diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs index 26f7ee2881d..f48a8038428 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(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelHelper(); } - public Task GetChannelAsync(CancellationToken cancellationToken) + 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 81173ad3639..63dab353cf4 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(OperationContext operationContext) { ThrowIfDisposed(); return GetReadChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetReadChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSourceAsync(cancellationToken); + 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 71a8e76c429..17ae75966bc 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(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetWriteChannelSource(cancellationToken); + return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(mayUseSecondary, cancellationToken); + return GetWriteChannelSource(operationContext, mayUseSecondary); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetWriteChannelSourceAsync(cancellationToken); + return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + return GetWriteChannelSourceAsync(operationContext, mayUseSecondary); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs index c7c04912d7b..3b08ff9da33 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(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetChannel(cancellationToken); + return _reference.Instance.GetChannel(operationContext); } - public Task GetChannelAsync(CancellationToken cancellationToken) + public Task GetChannelAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetChannelAsync(cancellationToken); + 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 c6fef30f1e6..e0c4772d23f 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(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetWriteChannelSource(cancellationToken); + return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(mayUseSecondary, cancellationToken); + return GetWriteChannelSource(operationContext, mayUseSecondary); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetWriteChannelSourceAsync(cancellationToken); + return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + 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 66fa294a14f..073492ea4da 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -155,7 +157,7 @@ public bool IsInTransaction try { var firstAttempt = CreateAbortTransactionOperation(); - ExecuteEndTransactionOnPrimary(firstAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(operationContext, firstAttempt); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -173,7 +175,7 @@ public bool IsInTransaction try { var secondAttempt = CreateAbortTransactionOperation(); - ExecuteEndTransactionOnPrimary(secondAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(operationContext, secondAttempt); } catch { @@ -194,6 +196,8 @@ public bool IsInTransaction { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(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(operationContext, firstAttempt).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(operationContext, secondAttempt).ConfigureAwait(false); } catch { @@ -292,6 +296,8 @@ public long AdvanceTransactionNumber() { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -303,7 +309,7 @@ public long AdvanceTransactionNumber() try { var firstAttempt = CreateCommitTransactionOperation(IsFirstCommitAttemptRetry()); - ExecuteEndTransactionOnPrimary(firstAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(operationContext, firstAttempt); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -313,7 +319,7 @@ public long AdvanceTransactionNumber() } var secondAttempt = CreateCommitTransactionOperation(isCommitRetry: true); - ExecuteEndTransactionOnPrimary(secondAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(operationContext, secondAttempt); } finally { @@ -327,6 +333,8 @@ public long AdvanceTransactionNumber() { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(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(operationContext, firstAttempt).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(operationContext, secondAttempt).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(OperationContext operationContext, IReadOperation operation) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return operation.Execute(binding, cancellationToken); + return operation.Execute(operationContext, binding); } } - private async Task ExecuteEndTransactionOnPrimaryAsync(IReadOperation operation, CancellationToken cancellationToken) + 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, cancellationToken).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 304796f1a9b..275131043ba 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(OperationContext operationContext); + Task GetReadChannelSourceAsync(OperationContext operationContext); - IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken); - Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken); + IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); + Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); } 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(OperationContext operationContext); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary); - 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(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/IChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs index 8582a50e7b8..c9bd90ec61b 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(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 63605e4b6c3..99dfa24212d 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(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(cancellationToken); + return _reference.Instance.GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSource(operationContext, deprioritizedServers); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationToken); + 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 54cd2faf4a2..32106f0efcd 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(OperationContext operationContext) { - return GetReadChannelSource(null, cancellationToken); + return GetReadChannelSource(operationContext, null); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { - return GetReadChannelSourceAsync(null, cancellationToken); + return GetReadChannelSourceAsync(operationContext, null); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, _serverSelector, deprioritizedServers, cancellationToken); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, _serverSelector, deprioritizedServers); return GetChannelSourceHelper(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public async Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, _serverSelector, deprioritizedServers, cancellationToken).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 7a298b3af60..0409d3ae844 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(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(cancellationToken); + return _reference.Instance.GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSource(operationContext, deprioritizedServers); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(operationContext, deprioritizedServers); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(cancellationToken); + return _reference.Instance.GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, cancellationToken); + return _reference.Instance.GetWriteChannelSource(operationContext, deprioritizedServers); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSource(operationContext, mayUseSecondary); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSource(operationContext, deprioritizedServers, mayUseSecondary); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext, deprioritizedServers); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext, mayUseSecondary); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext, deprioritizedServers, mayUseSecondary); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs index a4cadb0001f..c5fbc55cea1 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(OperationContext operationContext) { ThrowIfDisposed(); - return _server.GetChannel(cancellationToken); + return _server.GetChannel(operationContext); } - public Task GetChannelAsync(CancellationToken cancellationToken) + public Task GetChannelAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _server.GetChannelAsync(cancellationToken); + 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 6bd5b858021..04a65fbd4b3 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(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSourceAsync(cancellationToken); + 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 4f7756a1d7d..5113baa09c0 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(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetWriteChannelSource(cancellationToken); + return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(mayUseSecondary, cancellationToken); + return GetWriteChannelSource(operationContext, mayUseSecondary); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { - return GetWriteChannelSourceAsync(cancellationToken); + return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + 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 27ea948577e..764bdc0e0ae 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(OperationContext operationContext) { - return GetReadChannelSource(null, cancellationToken); + return GetReadChannelSource(operationContext, null); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { - return GetReadChannelSourceAsync(null, cancellationToken); + return GetReadChannelSourceAsync(operationContext, null); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers); return CreateServerChannelSource(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public async Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { - return GetWriteChannelSource(deprioritizedServers: null, cancellationToken); + return GetWriteChannelSource(operationContext, deprioritizedServers: null); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(null, mayUseSecondary, cancellationToken); + return GetWriteChannelSource(operationContext, null, mayUseSecondary); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { if (IsSessionPinnedToServer()) { @@ -102,28 +101,28 @@ public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { - return GetWriteChannelSourceAsync(deprioritizedServers: null, cancellationToken); + return GetWriteChannelSourceAsync(operationContext, deprioritizedServers: null); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public async Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); return CreateServerChannelSource(server); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(null, mayUseSecondary, cancellationToken); + return GetWriteChannelSourceAsync(operationContext, null, mayUseSecondary); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public async Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { 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(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 f1031387530..fbf9cfe7ac5 100644 --- a/src/MongoDB.Driver/Core/Clusters/Cluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/Cluster.cs @@ -217,10 +217,13 @@ protected void OnDescriptionChanged(ClusterDescription oldDescription, ClusterDe DescriptionChanged?.Invoke(this, new ClusterDescriptionChangedEventArgs(oldDescription, newDescription)); } - public IServer SelectServer(IServerSelector selector, CancellationToken cancellationToken) + public IServer SelectServer(OperationContext operationContext, IServerSelector selector) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); + + var serverSelectionOperationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -228,16 +231,23 @@ public IServer SelectServer(IServerSelector selector, CancellationToken cancella { while (true) { - var server = helper.SelectServer(); + var server = helper.SelectServer(serverSelectionOperationContext); if (server != null) { return server; } - helper.WaitingForDescriptionToChange(); - WaitForDescriptionChanged(helper.Selector, helper.Description, helper.DescriptionChangedTask, helper.TimeoutRemaining, cancellationToken); + helper.WaitForDescriptionChanged(serverSelectionOperationContext); } } + 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 +256,13 @@ public IServer SelectServer(IServerSelector selector, CancellationToken cancella } } - public async Task SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken) + public async Task SelectServerAsync(OperationContext operationContext, IServerSelector selector) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); + + var serverSelectionOperationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -257,16 +270,23 @@ public async Task SelectServerAsync(IServerSelector selector, Cancellat { while (true) { - var server = helper.SelectServer(); + var server = helper.SelectServer(serverSelectionOperationContext); if (server != null) { return server; } - helper.WaitingForDescriptionToChange(); - await WaitForDescriptionChangedAsync(helper.Selector, helper.Description, helper.DescriptionChangedTask, helper.TimeoutRemaining, cancellationToken).ConfigureAwait(false); + await helper.WaitForDescriptionChangedAsync(serverSelectionOperationContext).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 +340,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 { @@ -375,19 +371,16 @@ private class SelectServerHelper : IDisposable 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; + _selector = DecorateSelector(selector); } public ClusterDescription Description @@ -405,11 +398,6 @@ public IServerSelector Selector get { return _selector; } } - public TimeSpan TimeoutRemaining - { - get { return _timeoutAt - DateTime.UtcNow; } - } - public void Dispose() { if (_serverSelectionWaitQueueEntered) @@ -428,7 +416,7 @@ public void HandleException(Exception exception) EventContext.OperationName)); } - public IServer SelectServer() + public IServer SelectServer(OperationContext operationContext) { var clusterDescription = _cluster._descriptionWithChangedTaskCompletionSource; _descriptionChangedTask = clusterDescription.Changed; @@ -490,19 +478,27 @@ public IServer SelectServer() return selectedServer; } - public void WaitingForDescriptionToChange() + public void WaitForDescriptionChanged(OperationContext operationContext) { - if (!_serverSelectionWaitQueueEntered) - { - _cluster.EnterServerSelectionWaitQueue(_selector, _description, EventContext.OperationId, _timeoutAt - DateTime.UtcNow); - _serverSelectionWaitQueueEntered = true; - } + EnsureEnteredServerSelectionQueue(operationContext); + operationContext.WaitTask(DescriptionChangedTask); + } - var timeoutRemaining = _timeoutAt - DateTime.UtcNow; - if (timeoutRemaining <= TimeSpan.Zero) + public Task WaitForDescriptionChangedAsync(OperationContext operationContext) + { + EnsureEnteredServerSelectionQueue(operationContext); + return operationContext.WaitTaskAsync(DescriptionChangedTask); + } + + private void EnsureEnteredServerSelectionQueue(OperationContext operationContext) + { + if (_serverSelectionWaitQueueEntered) { - _cluster.ThrowTimeoutException(_selector, _description); + return; } + + _cluster.EnterServerSelectionWaitQueue(_selector, _description, EventContext.OperationId, operationContext.RemainingTimeout); + _serverSelectionWaitQueueEntered = true; } private IServerSelector DecorateSelector(IServerSelector selector) @@ -529,67 +525,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..ea31d13bc12 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(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 245ba8a48a3..e8060a75a07 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; @@ -26,10 +25,10 @@ internal static class IClusterExtensions { public static IServer SelectServerAndPinIfNeeded( this IClusterInternal cluster, + OperationContext operationContext, ICoreSessionHandle session, IServerSelector selector, - IReadOnlyCollection deprioritizedServers, - CancellationToken cancellationToken) + IReadOnlyCollection deprioritizedServers) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -41,19 +40,19 @@ 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, cancellationToken); + 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, - CancellationToken cancellationToken) + IReadOnlyCollection deprioritizedServers) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -65,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, cancellationToken).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 712d9f52fc7..c77d2d45241 100644 --- a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs @@ -170,30 +170,39 @@ public void Initialize() } } - public IServer SelectServer(IServerSelector selector, CancellationToken cancellationToken) + public IServer SelectServer(OperationContext operationContext, IServerSelector selector) { + Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); ThrowIfDisposed(); + var serverSelectionOperationContext = operationContext.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) + var stopwatch = Stopwatch.StartNew(); + try + { + serverSelectionOperationContext.WaitTask(_serverReadyTaskCompletionSource.Task); + } + catch (TimeoutException) { - cancellationToken.ThrowIfCancellationRequested(); throw CreateTimeoutException(_description); // _description will contain dnsException } if (_server != null) { + stopwatch.Stop(); + _serverSelectionEventLogger.LogAndPublish(new ClusterSelectedServerEvent( _description, selector, _server.Description, - TimeSpan.FromSeconds(1), + stopwatch.Elapsed, null, EventContext.OperationName)); } @@ -202,31 +211,38 @@ 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(OperationContext operationContext, IServerSelector selector) { + Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); ThrowIfDisposed(); + var serverSelectionOperationContext = operationContext.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) + var stopwatch = Stopwatch.StartNew(); + try + { + await serverSelectionOperationContext.WaitTaskAsync(_serverReadyTaskCompletionSource.Task).ConfigureAwait(false); + } + catch (TimeoutException) { - cancellationToken.ThrowIfCancellationRequested(); throw CreateTimeoutException(_description); // _description will contain dnsException } if (_server != null) { + stopwatch.Stop(); _serverSelectionEventLogger.LogAndPublish(new ClusterSelectedServerEvent( _description, selector, _server.Description, - TimeSpan.FromSeconds(1), + 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 77895ed99a4..b4adb83a8db 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(TimeSpan elapsed, 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 {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,32 +174,31 @@ private sealed class AcquireConnectionHelper : IDisposable public AcquireConnectionHelper(ExclusiveConnectionPool pool) { _pool = pool; - _timeout = pool._settings.WaitQueueTimeout; } - public IConnectionHandle AcquireConnection(CancellationToken cancellationToken) + public IConnectionHandle AcquireConnection(OperationContext operationContext) { var stopwatch = new Stopwatch(); try { StartCheckingOut(stopwatch); - _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(_timeout, cancellationToken); + _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(operationContext.RemainingTimeout, operationContext.CancellationToken); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - var timeout = EnsureTimeout(stopwatch); + ThrowIfTimedOut(operationContext, stopwatch); - using (var connectionCreator = new ConnectionCreator(_pool, timeout)) + using (var connectionCreator = new ConnectionCreator(_pool)) { - pooledConnection = connectionCreator.CreateOpenedOrReuse(cancellationToken); + pooledConnection = connectionCreator.CreateOpenedOrReuse(operationContext); } return EndCheckingOut(pooledConnection, stopwatch); } stopwatch.Stop(); - throw CreateException(stopwatch); + throw CreateException(stopwatch.Elapsed); } catch (Exception ex) { @@ -210,29 +208,29 @@ public IConnectionHandle AcquireConnection(CancellationToken cancellationToken) } } - public async Task AcquireConnectionAsync(CancellationToken cancellationToken) + public async Task AcquireConnectionAsync(OperationContext operationContext) { var stopwatch = new Stopwatch(); try { StartCheckingOut(stopwatch); - _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(_timeout, cancellationToken).ConfigureAwait(false); + _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - var timeout = EnsureTimeout(stopwatch); + ThrowIfTimedOut(operationContext, stopwatch); - using (var connectionCreator = new ConnectionCreator(_pool, timeout)) + using (var connectionCreator = new ConnectionCreator(_pool)) { - pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(cancellationToken).ConfigureAwait(false); + pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(operationContext).ConfigureAwait(false); } return EndCheckingOut(pooledConnection, stopwatch); } stopwatch.Stop(); - throw CreateException(stopwatch); + throw CreateException(stopwatch.Elapsed); } catch (Exception ex) { @@ -281,13 +279,21 @@ private void AcquireWaitQueueSlot() _enteredWaitQueue = true; } + private void ThrowIfTimedOut(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)); - stopwatch.Start(); - _pool._poolState.ThrowIfNotReady(); + _pool._poolState.ThrowIfNotReady(); AcquireWaitQueueSlot(); } @@ -296,7 +302,6 @@ private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Stop 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)); // no need to release the semaphore @@ -305,26 +310,13 @@ private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Stop return connectionHandle; } - private TimeSpan EnsureTimeout(Stopwatch stopwatch) - { - var timeSpentInWaitQueue = stopwatch.Elapsed; - var timeout = _timeout - timeSpentInWaitQueue; - - if (timeout < TimeSpan.Zero) - { - throw _pool.CreateTimeoutException(stopwatch, $"Timed out waiting for a connection after {timeSpentInWaitQueue.TotalMilliseconds}ms."); - } - - return timeout; - } - - private Exception CreateException(Stopwatch stopwatch) => + private Exception CreateException(TimeSpan elapsed) => _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(elapsed, $"Timed out waiting for a connection after {elapsed.TotalMilliseconds}ms."), // should not be reached _ => new InvalidOperationException($"Invalid {_poolQueueWaitResult}.") }; @@ -846,41 +838,35 @@ 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(TimeSpan maxConnectingQueueTimeout, CancellationToken cancellationToken) { try { var stopwatch = Stopwatch.StartNew(); - _connectingWaitStatus = _pool._maxConnectingQueue.Wait(_connectingTimeout, cancellationToken); + _connectingWaitStatus = _pool._maxConnectingQueue.Wait(maxConnectingQueueTimeout, cancellationToken); stopwatch.Stop(); - _pool._poolState.ThrowIfNotReady(); if (_connectingWaitStatus == SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut) { - _pool.CreateTimeoutException(stopwatch, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); + _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); } - return CreateOpenedInternal(cancellationToken); + return CreateOpenedInternal(new(Timeout.InfiniteTimeSpan, cancellationToken)); } catch (Exception ex) { @@ -889,12 +875,11 @@ public PooledConnection CreateOpened(CancellationToken cancellationToken) } } - public PooledConnection CreateOpenedOrReuse(CancellationToken cancellationToken) + public PooledConnection CreateOpenedOrReuse(OperationContext operationContext) { try { var connection = _pool._connectionHolder.Acquire(); - var waitTimeout = _connectingTimeout; var stopwatch = Stopwatch.StartNew(); while (connection == null) @@ -905,21 +890,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(operationContext.RemainingTimeout, operationContext.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(operationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(stopwatch.Elapsed), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - waitTimeout = _connectingTimeout - stopwatch.Elapsed; - - if (connection == null && waitTimeout <= TimeSpan.Zero) + if (connection == null && operationContext.IsTimedOut()) { - throw CreateTimeoutException(stopwatch); + throw CreateTimeoutException(stopwatch.Elapsed); } } @@ -932,13 +915,11 @@ public PooledConnection CreateOpenedOrReuse(CancellationToken cancellationToken) } } - public async Task CreateOpenedOrReuseAsync(CancellationToken cancellationToken) + public async Task CreateOpenedOrReuseAsync(OperationContext operationContext) { try { var connection = _pool._connectionHolder.Acquire(); - - var waitTimeout = _connectingTimeout; var stopwatch = Stopwatch.StartNew(); while (connection == null) @@ -949,21 +930,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(operationContext.RemainingTimeout, operationContext.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(operationContext).ConfigureAwait(false), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(stopwatch.Elapsed), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - waitTimeout = _connectingTimeout - stopwatch.Elapsed; - - if (connection == null && waitTimeout <= TimeSpan.Zero) + if (connection == null && operationContext.IsTimedOut()) { - throw CreateTimeoutException(stopwatch); + throw CreateTimeoutException(stopwatch.Elapsed); } } @@ -991,54 +970,55 @@ public void Dispose() } // private methods - private PooledConnection CreateOpenedInternal(CancellationToken cancellationToken) + private PooledConnection CreateOpenedInternal(OperationContext operationContext) { - StartCreating(cancellationToken); + var stopwatch = StartCreating(operationContext); - _connection.Open(cancellationToken); + // TODO: CSOT add support of CSOT timeout in connection open code too. + _connection.Open(operationContext.CancellationToken); - FinishCreating(_connection.Description); + FinishCreating(_connection.Description, stopwatch); return _connection; } - private async Task CreateOpenedInternalAsync(CancellationToken cancellationToken) + private async Task CreateOpenedInternalAsync(OperationContext operationContext) { - StartCreating(cancellationToken); + var stopwatch = StartCreating(operationContext); - await _connection.OpenAsync(cancellationToken).ConfigureAwait(false); + // TODO: CSOT add support of CSOT timeout in connection open code too. + await _connection.OpenAsync(operationContext.CancellationToken).ConfigureAwait(false); - FinishCreating(_connection.Description); + FinishCreating(_connection.Description, stopwatch); return _connection; } - private void StartCreating(CancellationToken cancellationToken) + private Stopwatch StartCreating(OperationContext operationContext) { _pool._eventLogger.LogAndPublish(new ConnectionPoolAddingConnectionEvent(_pool._serverId, EventContext.OperationId)); - cancellationToken.ThrowIfCancellationRequested(); - - _stopwatch = Stopwatch.StartNew(); + operationContext.ThrowIfTimedOutOrCanceled(); + var stopwatch = Stopwatch.StartNew(); _connection = _pool.CreateNewConnection(); + return stopwatch; } - private void FinishCreating(ConnectionDescription description) + private void FinishCreating(ConnectionDescription description, Stopwatch stopwatch) { - _stopwatch.Stop(); - - _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, _stopwatch.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; _pool._serviceStates.IncrementConnectionCount(description?.ServiceId); } - private Exception CreateTimeoutException(Stopwatch stopwatch) + private Exception CreateTimeoutException(TimeSpan elapsed) { - 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 {elapsed.TotalMilliseconds}ms."; + return _pool.CreateTimeoutException(elapsed, message); } } } diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs index 8490bba1b07..7489d714081 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(OperationContext operationContext) { + operationContext = operationContext.WithTimeout(Settings.WaitQueueTimeout); using var helper = new AcquireConnectionHelper(this); - return helper.AcquireConnection(cancellationToken); + return helper.AcquireConnection(operationContext); } - public async Task AcquireConnectionAsync(CancellationToken cancellationToken) + public async Task AcquireConnectionAsync(OperationContext operationContext) { + operationContext = operationContext.WithTimeout(Settings.WaitQueueTimeout); using var helper = new AcquireConnectionHelper(this); - return await helper.AcquireConnectionAsync(cancellationToken).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 24f2ff48e4e..599185c797a 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(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 a8f2bdfa12f..568ed1933c3 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs @@ -125,9 +125,9 @@ private void EnsureMinSize(CancellationToken cancellationToken) return; } - using (var connectionCreator = new ConnectionCreator(_connectionPool, minTimeout)) + using (var connectionCreator = new ConnectionCreator(_connectionPool)) { - var connection = connectionCreator.CreateOpened(cancellationToken); + var connection = connectionCreator.CreateOpened(minTimeout, cancellationToken); _connectionPool.ConnectionHolder.Return(connection); } } diff --git a/src/MongoDB.Driver/Core/Misc/Feature.cs b/src/MongoDB.Driver/Core/Misc/Feature.cs index 506e28de10c..762b7d0591e 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 operationContext + var operationContext = new OperationContext(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(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) { // 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 operationContext + var operationContext = new OperationContext(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(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 a66161543a9..86eae237593 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } /// - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { 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(operationContext, context); 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } /// - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { 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(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 88bc86f854c..79c684d9752 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(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + 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, cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).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, cancellationToken).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 1f0e4e46138..bb0b2daa92a 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) - using (var channel = _channelSource.GetChannel(cancellationToken)) + using (var channel = _channelSource.GetChannel(operationContext)) { 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) - using (var channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channel = await _channelSource.GetChannelAsync(operationContext).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 operationContext + var operationContext = new OperationContext(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(operationContext.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 operationContext + var operationContext = new OperationContext(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(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 c529c2ebc56..efe28a3f4af 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(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationToken)) + 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, cancellationToken); + batch.Result = ExecuteBatch(operationContext, context, batch); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationToken).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, cancellationToken).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(operationContext, context, batch).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(OperationContext operationContext, RetryableWriteContext context, Batch batch) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = operation.Execute(context, cancellationToken); + result = operation.Execute(operationContext, context); } 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(OperationContext operationContext, RetryableWriteContext context, Batch batch) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = await operation.ExecuteAsync(context, cancellationToken).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 616b150b155..03ad4ad3e3c 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(OperationContext operationContext, RetryableWriteContext context) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatches(context, cancellationToken); + return ExecuteBatches(operationContext, context); } - public BulkWriteOperationResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BulkWriteOperationResult Execute(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(operationContext, binding, _retryRequested)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } - public Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) + public Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatchesAsync(context, cancellationToken); + return ExecuteBatchesAsync(operationContext, context); } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } @@ -190,14 +189,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) + private BulkWriteBatchResult ExecuteBatch(OperationContext operationContext, RetryableWriteContext context, Batch batch) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = RetryableWriteOperationExecutor.Execute(operation, context, cancellationToken); + operationResult = RetryableWriteOperationExecutor.Execute(operationContext, operation, context); } 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(OperationContext operationContext, RetryableWriteContext context, Batch batch) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operation, context, cancellationToken).ConfigureAwait(false); + operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operationContext, operation, context).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(OperationContext operationContext, RetryableWriteContext context) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, cancellationToken); + batch.Result = ExecuteBatch(operationContext, context, batch); } return helper.CreateFinalResultOrThrow(context.Channel); } - private async Task ExecuteBatchesAsync(RetryableWriteContext context, CancellationToken cancellationToken) + 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, cancellationToken).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 4dfabd9a026..afd01623847 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + return _changeStreamOperation.Resume(operationContext, _binding); } private async Task> ResumeAsync(CancellationToken cancellationToken) { ReconfigureOperationResumeValues(); - return await _changeStreamOperation.ResumeAsync(_binding, cancellationToken).ConfigureAwait(false); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + 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 b9ed21931b0..ed08f1c85e5 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(OperationContext operationContext, IReadBinding binding); + Task> ResumeAsync(OperationContext operationContext, IReadBinding binding); } internal sealed class ChangeStreamOperation : IChangeStreamOperation @@ -250,7 +249,7 @@ public BsonTimestamp StartAtOperationTime // public methods /// - public IChangeStreamCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IChangeStreamCursor Execute(OperationContext operationContext, IReadBinding binding) { 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(operationContext, binding, _retryRequested)) { - cursor = ExecuteAggregateOperation(context, cancellationToken); + cursor = ExecuteAggregateOperation(operationContext, context); 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(OperationContext operationContext, IReadBinding binding) { 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(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - cursor = await ExecuteAggregateOperationAsync(context, cancellationToken).ConfigureAwait(false); + cursor = await ExecuteAggregateOperationAsync(operationContext, context).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(OperationContext operationContext, IReadBinding binding) { - using (var context = RetryableReadContext.Create(binding, retryRequested: false, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, retryRequested: false)) { - return ExecuteAggregateOperation(context, cancellationToken); + return ExecuteAggregateOperation(operationContext, context); } } /// - public async Task> ResumeAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ResumeAsync(OperationContext operationContext, IReadBinding binding) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested: false, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, retryRequested: false).ConfigureAwait(false)) { - return await ExecuteAggregateOperationAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAggregateOperationAsync(operationContext, context).ConfigureAwait(false); } } @@ -392,16 +391,16 @@ private List CreateCombinedPipeline(BsonDocument changeStreamStage return combinedPipeline; } - private IAsyncCursor ExecuteAggregateOperation(RetryableReadContext context, CancellationToken cancellationToken) + private IAsyncCursor ExecuteAggregateOperation(OperationContext operationContext, RetryableReadContext context) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.Execute(context, cancellationToken); + return aggregateOperation.Execute(operationContext, context); } - private Task> ExecuteAggregateOperationAsync(RetryableReadContext context, CancellationToken cancellationToken) + private Task> ExecuteAggregateOperationAsync(OperationContext operationContext, RetryableReadContext context) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.ExecuteAsync(context, cancellationToken); + 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 b994a95388d..2416fd0aff3 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(OperationContext operationContext, IWriteBinding binding) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationToken); + using var context = RetryableWriteContext.Create(operationContext, binding, GetEffectiveRetryRequested()); BsonDocument serverResponse = null; try { - serverResponse = base.Execute(context, cancellationToken); + serverResponse = base.Execute(operationContext, context); } catch (MongoWriteConcernException concernException) { @@ -124,7 +123,8 @@ protected override IEnumerable CreateCommandPayl { try { - while (individualResults.MoveNext(cancellationToken)) + // TODO: CSOT implement a way to support timeout in cursor methods + while (individualResults.MoveNext(operationContext.CancellationToken)) { PopulateIndividualResponses(individualResults.Current, bulkWriteResults); } @@ -146,17 +146,17 @@ protected override IEnumerable CreateCommandPayl } } - public new async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + 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(), cancellationToken); + using var context = RetryableWriteContext.Create(operationContext, binding, GetEffectiveRetryRequested()); BsonDocument serverResponse = null; try { - serverResponse = await base.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + serverResponse = await base.ExecuteAsync(operationContext, context).ConfigureAwait(false); } catch (MongoWriteConcernException concernException) { @@ -181,7 +181,8 @@ protected override IEnumerable CreateCommandPayl { try { - while (await individualResults.MoveNextAsync(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 18f18b14b6d..62eca2d6992 100644 --- a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs @@ -105,14 +105,14 @@ protected TCommandResult ExecuteProtocol(IChannelHandle channel, ICoreSessionHan } protected TCommandResult ExecuteProtocol( + OperationContext operationContext, IChannelSource channelSource, ICoreSessionHandle session, - ReadPreference readPreference, - CancellationToken cancellationToken) + ReadPreference readPreference) { - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channel = channelSource.GetChannel(operationContext)) { - return ExecuteProtocol(channel, session, readPreference, cancellationToken); + return ExecuteProtocol(channel, session, readPreference, operationContext.CancellationToken); } } @@ -136,14 +136,14 @@ protected Task ExecuteProtocolAsync(IChannelHandle channel, ICor } protected async Task ExecuteProtocolAsync( + OperationContext operationContext, IChannelSource channelSource, ICoreSessionHandle session, - ReadPreference readPreference, - CancellationToken cancellationToken) + ReadPreference readPreference) { - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channel, session, readPreference, 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 64a270c4486..68e6964d994 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(OperationContext operationContext, IWriteBinding binding) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = operationInfo.Operation.Execute(binding, cancellationToken); + var itemResult = operationInfo.Operation.Execute(operationContext, binding); 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(OperationContext operationContext, IWriteBinding binding) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = await operationInfo.Operation.ExecuteAsync(binding, cancellationToken).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 2871029e2a1..6bcc00d33db 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(OperationContext operationContext, IReadBinding binding) { 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(operationContext, binding); + var result = cursor.ToList(operationContext.CancellationToken); return ExtractCountFromResult(result); } } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { 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(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 dc33440c61f..cd83e1d374d 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } - public long Execute(RetryableReadContext context, CancellationToken cancellationToken) + public long Execute(OperationContext operationContext, RetryableReadContext context) { var operation = CreateOperation(context); - var document = operation.Execute(context, cancellationToken); + var document = operation.Execute(operationContext, context); return document["n"].ToInt64(); } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { var operation = CreateOperation(context); - var document = await operation.ExecuteAsync(context, cancellationToken).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 9f9923a5c75..31b2f7be994 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 1a19dc5787a..f4e071950ad 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(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding 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(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, cancellationToken).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 bb96493a076..edc8ae04f77 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(OperationContext operationContext, IWriteBinding binding) { using (EventContext.BeginOperation("createSearchIndexes")) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } /// - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 cd291bfbf19..64a5d954bc2 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, CancellationToken cancellationToken) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 ec4b4a42e4a..9b6f4cdca4d 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, cancellationToken); - var list = result.ToList(cancellationToken); + 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, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { 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(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 441996f2889..0e25eb3d097 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateOperation(context); - var result = operation.Execute(context, cancellationToken); + var result = operation.Execute(operationContext, context); 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, cancellationToken).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 fa7e11f8c70..d667367575a 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + result = operation.Execute(operationContext, channelBinding); } 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(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 315a5307409..39be674d49c 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 577ed62e448..ef68ad071c5 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + result = operation.Execute(operationContext, channelBinding); } 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(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).ConfigureAwait(false); + result = await operation.ExecuteAsync(operationContext, channelBinding).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..aff890be381 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(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } 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(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 90e5f44c882..0544b2498c3 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public virtual async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public virtual async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { 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(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, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).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(OperationContext operationContext, IReadBinding binding) { try { - return base.Execute(binding, cancellationToken); + return base.Execute(operationContext, binding); } 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(OperationContext operationContext, IReadBinding binding) { try { - return await base.ExecuteAsync(binding, cancellationToken).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 27958d906f4..eac2d1a32a1 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateCountOperation(); - return operation.Execute(context, cancellationToken); + return operation.Execute(operationContext, context); } } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateCountOperation(); - return await operation.ExecuteAsync(context, cancellationToken).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 218d4b91e11..b8bb23cfce5 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, cancellationToken); + var result = operation.Execute(operationContext, binding); return result["retval"]; } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, cancellationToken).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 8bad1138f40..d32198f81af 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(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, binding, _retryRequested, cancellationToken); + return RetryableWriteOperationExecutor.Execute(operationContext, this, binding, _retryRequested); } } - public TResult Execute(RetryableWriteContext context, CancellationToken cancellationToken) + public TResult Execute(OperationContext operationContext, RetryableWriteContext context) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, context, cancellationToken); + return RetryableWriteOperationExecutor.Execute(operationContext, this, context); } } - public Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - { - return RetryableWriteOperationExecutor.ExecuteAsync(this, binding, _retryRequested, cancellationToken); + { + return RetryableWriteOperationExecutor.ExecuteAsync(operationContext, this, binding, _retryRequested); } } - public Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) + public Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationToken); + return RetryableWriteOperationExecutor.ExecuteAsync(operationContext, this, context); } } - public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public TResult ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { 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(operationContext, channelBinding)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } } } - public async Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { 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(operationContext, channelBinding).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..7ebc524b81e 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken = default(CancellationToken)) + 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, cancellationToken); + var commandResult = operation.Execute(operationContext, context); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken = default(CancellationToken)) + 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, cancellationToken).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 7ae72c2444b..4c987e09300 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { 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(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, cancellationToken).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 06fa1fbabbf..1ccd8dcb2ad 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(OperationContext operationContext, IReadBinding binding); + Task ExecuteAsync(OperationContext operationContext, IReadBinding binding); } internal interface IWriteOperation { - TResult Execute(IWriteBinding binding, CancellationToken cancellationToken); - Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken); + 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 efa510c1553..d29a8948477 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(OperationContext operationContext, RetryableReadContext context); + Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context); } internal interface IExecutableInRetryableWriteContext { - TResult Execute(RetryableWriteContext context, CancellationToken cancellationToken); - Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken); + TResult Execute(OperationContext operationContext, RetryableWriteContext context); + Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context); } 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(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, CancellationToken cancellationToken); - Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken); + 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 e25b97bbbd7..320c1c3ea71 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } } - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = operation.Execute(context, cancellationToken); + var result = operation.Execute(operationContext, context); return CreateCursor(context.ChannelSource, context.Channel, result); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } } - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = await operation.ExecuteAsync(context, cancellationToken).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 fb9ec4fbfa5..e55151e5b5c 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = operation.Execute(binding, cancellationToken); + var reply = operation.Execute(operationContext, binding); return CreateCursor(reply); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = await operation.ExecuteAsync(binding, cancellationToken).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 1bd4fb40102..b91633c4716 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateOperation(); - return operation.Execute(context, cancellationToken); + return operation.Execute(operationContext, context); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { var operation = CreateOperation(); - return await operation.ExecuteAsync(context, cancellationToken).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 a16ba814dbc..290bbbf00e5 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { 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(operationContext, context); 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { 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(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 a509cfd33ed..a68b2227278 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + var result = operation.Execute(operationContext, channelBinding); return new SingleBatchAsyncCursor(result); } } /// - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { 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(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, cancellationToken).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 53e787daf15..99e32b1adcd 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } /// - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 bf9fe96b58b..fe54eb7d637 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; @@ -24,55 +23,55 @@ internal static class OperationExtensionMethods { public static TResult Execute( this IReadOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, ReadPreference readPreference, - ICoreSessionHandle session, - CancellationToken cancellationToken) + ICoreSessionHandle session) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return operation.Execute(readBinding, cancellationToken); + return operation.Execute(operationContext, readBinding); } } public static TResult Execute( this IWriteOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, - ICoreSessionHandle session, - CancellationToken cancellationToken) + ICoreSessionHandle session) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return operation.Execute(writeBinding, cancellationToken); + return operation.Execute(operationContext, writeBinding); } } public static async Task ExecuteAsync( this IReadOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, ReadPreference readPreference, - ICoreSessionHandle session, - CancellationToken cancellationToken) + ICoreSessionHandle session) { 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(operationContext, readBinding).ConfigureAwait(false); } } public static async Task ExecuteAsync( this IWriteOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, - ICoreSessionHandle session, - CancellationToken cancellationToken) + ICoreSessionHandle session) { 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(operationContext, writeBinding).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..84305df6f25 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(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } - public TCommandResult Execute(RetryableReadContext context, CancellationToken cancellationToken) + public TCommandResult Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return RetryableReadOperationExecutor.Execute(this, context, cancellationToken); + return RetryableReadOperationExecutor.Execute(operationContext, this, context); } } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return await RetryableReadOperationExecutor.ExecuteAsync(this, context, cancellationToken).ConfigureAwait(false); + return await RetryableReadOperationExecutor.ExecuteAsync(operationContext, this, context).ConfigureAwait(false); } } - public TCommandResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public TCommandResult ExecuteAttempt(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber) { - return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationToken); + return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, operationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public Task ExecuteAttemptAsync(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber) { - return ExecuteProtocolAsync(context.Channel, context.Binding.Session, context.Binding.ReadPreference, 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 7f5fb113da5..aee3f2fed1c 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).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..18d62e4b4a5 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(OperationContext operationContext, IReadBinding binding, bool retryRequested) { var context = new RetryableReadContext(binding, retryRequested); try { - context.Initialize(cancellationToken); + context.Initialize(operationContext); 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(OperationContext operationContext, IReadBinding binding, bool retryRequested) { var context = new RetryableReadContext(binding, retryRequested); try { - await context.InitializeAsync(cancellationToken).ConfigureAwait(false); + await context.InitializeAsync(operationContext).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(OperationContext operationContext) { - _channelSource = _binding.GetReadChannelSource(cancellationToken); + _channelSource = _binding.GetReadChannelSource(operationContext); try { - _channel = _channelSource.GetChannel(cancellationToken); + _channel = _channelSource.GetChannel(operationContext); } catch (Exception ex) when (RetryableReadOperationExecutor.ShouldConnectionAcquireBeRetried(this, ex)) { - ReplaceChannelSource(_binding.GetReadChannelSource(cancellationToken)); - ReplaceChannel(_channelSource.GetChannel(cancellationToken)); + ReplaceChannelSource(_binding.GetReadChannelSource(operationContext)); + ReplaceChannel(_channelSource.GetChannel(operationContext)); } } - private async Task InitializeAsync(CancellationToken cancellationToken) + private async Task InitializeAsync(OperationContext operationContext) { - _channelSource = await _binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false); + _channelSource = await _binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false); try { - _channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false); + _channel = await _channelSource.GetChannelAsync(operationContext).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(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 cdb74827dc0..d628382e264 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(OperationContext operationContext, IRetryableReadOperation operation, IReadBinding binding, bool retryRequested) { - using (var context = RetryableReadContext.Create(binding, retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(operationContext, binding, retryRequested)) { - return Execute(operation, context, cancellationToken); + return Execute(operationContext, operation, context); } } - public static TResult Execute(IRetryableReadOperation operation, RetryableReadContext context, CancellationToken cancellationToken) + public static TResult Execute(OperationContext operationContext, IRetryableReadOperation operation, RetryableReadContext context) { if (!ShouldReadBeRetried(context)) { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationToken); + return operation.ExecuteAttempt(operationContext, context, attempt: 1, transactionNumber: null); } Exception originalException; try { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationToken); + return operation.ExecuteAttempt(operationContext, context, attempt: 1, transactionNumber: null); } 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(operationContext, new[] { context.ChannelSource.ServerDescription })); + context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch { @@ -61,7 +60,7 @@ public static TResult Execute(IRetryableReadOperation operatio try { - return operation.ExecuteAttempt(context, attempt: 2, transactionNumber: null, cancellationToken); + return operation.ExecuteAttempt(operationContext, context, attempt: 2, transactionNumber: null); } 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(OperationContext operationContext, IRetryableReadOperation operation, IReadBinding binding, bool retryRequested) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, operation, context).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, RetryableReadContext context, CancellationToken cancellationToken) + public static async Task ExecuteAsync(OperationContext operationContext, IRetryableReadOperation operation, RetryableReadContext context) { if (!ShouldReadBeRetried(context)) { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationToken).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, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, attempt: 1, transactionNumber: null).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(operationContext, new[] { context.ChannelSource.ServerDescription })); + context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } 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(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 cd5e3e87dc9..bb3ec94e32d 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(OperationContext operationContext, IWriteBinding binding) { - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, cancellationToken); + return Execute(operationContext, context); } } - public virtual BsonDocument Execute(RetryableWriteContext context, CancellationToken cancellationToken) + public virtual BsonDocument Execute(OperationContext operationContext, RetryableWriteContext context) { - return RetryableWriteOperationExecutor.Execute(this, context, cancellationToken); + return RetryableWriteOperationExecutor.Execute(operationContext, this, context); } - public virtual async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public virtual async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public virtual Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) + public virtual Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationToken); + return RetryableWriteOperationExecutor.ExecuteAsync(operationContext, this, context); } - public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { 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); + operationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { 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); + 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 4aa1a3eb9fd..9c15d1e9bfc 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(OperationContext operationContext, IWriteBinding binding, bool retryRequested) { var context = new RetryableWriteContext(binding, retryRequested); try { - context.Initialize(cancellationToken); + context.Initialize(operationContext); 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(OperationContext operationContext, IWriteBinding binding, bool retryRequested) { var context = new RetryableWriteContext(binding, retryRequested); try { - await context.InitializeAsync(cancellationToken).ConfigureAwait(false); + await context.InitializeAsync(operationContext).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(OperationContext operationContext) { - _channelSource = _binding.GetWriteChannelSource(cancellationToken); + _channelSource = _binding.GetWriteChannelSource(operationContext); var serverDescription = _channelSource.ServerDescription; try { - _channel = _channelSource.GetChannel(cancellationToken); + _channel = _channelSource.GetChannel(operationContext); } catch (Exception ex) when (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription, ex)) { - ReplaceChannelSource(_binding.GetWriteChannelSource(cancellationToken)); - ReplaceChannel(_channelSource.GetChannel(cancellationToken)); + ReplaceChannelSource(_binding.GetWriteChannelSource(operationContext)); + ReplaceChannel(_channelSource.GetChannel(operationContext)); } } - private async Task InitializeAsync(CancellationToken cancellationToken) + private async Task InitializeAsync(OperationContext operationContext) { - _channelSource = await _binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false); + _channelSource = await _binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false); var serverDescription = _channelSource.ServerDescription; try { - _channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false); + _channel = await _channelSource.GetChannelAsync(operationContext).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(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 6e73af1e758..f654d614260 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(OperationContext operationContext, IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested) { - using (var context = RetryableWriteContext.Create(binding, retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(operationContext, binding, retryRequested)) { - return Execute(operation, context, cancellationToken); + return Execute(operationContext, operation, context); } } - public static TResult Execute(IRetryableWriteOperation operation, RetryableWriteContext context, CancellationToken cancellationToken) + public static TResult Execute(OperationContext operationContext, IRetryableWriteOperation operation, RetryableWriteContext context) { if (!AreRetriesAllowed(operation, context)) { - return operation.ExecuteAttempt(context, 1, null, cancellationToken); + return operation.ExecuteAttempt(operationContext, context, 1, null); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return operation.ExecuteAttempt(context, 1, transactionNumber, cancellationToken); + return operation.ExecuteAttempt(operationContext, context, 1, transactionNumber); } 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(operationContext, new[] { context.ChannelSource.ServerDescription })); + context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch { @@ -68,7 +67,7 @@ public static TResult Execute(IRetryableWriteOperation operati try { - return operation.ExecuteAttempt(context, 2, transactionNumber, cancellationToken); + return operation.ExecuteAttempt(operationContext, context, 2, transactionNumber); } 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(OperationContext operationContext, IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested) { - using (var context = await RetryableWriteContext.CreateAsync(binding, retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operationContext, operation, context).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableWriteOperation operation, RetryableWriteContext context, CancellationToken cancellationToken) + public static async Task ExecuteAsync(OperationContext operationContext, IRetryableWriteOperation operation, RetryableWriteContext context) { if (!AreRetriesAllowed(operation, context)) { - return await operation.ExecuteAttemptAsync(context, 1, null, cancellationToken).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, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, 1, transactionNumber).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(operationContext, new[] { context.ChannelSource.ServerDescription }).ConfigureAwait(false)); + context.ReplaceChannel(await context.ChannelSource.GetChannelAsync(operationContext).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(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 90657153792..09496dd9d3b 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(OperationContext operationContext, IWriteBinding binding) { using (EventContext.BeginOperation("updateSearchIndex")) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + 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, cancellationToken); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { 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(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, cancellationToken).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 183efdf9888..033db2d0eae 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(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) { - return ExecuteProtocol(channelSource, binding.Session, _readPreference, cancellationToken); + return ExecuteProtocol(operationContext, channelSource, binding.Session, _readPreference); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channelSource, binding.Session, _readPreference, cancellationToken).ConfigureAwait(false); + return await ExecuteProtocolAsync(operationContext, channelSource, binding.Session, _readPreference).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Servers/IServer.cs b/src/MongoDB.Driver/Core/Servers/IServer.cs index bbd9e0cbb80..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(CancellationToken cancellationToken); - Task GetChannelAsync(CancellationToken cancellationToken); + 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 e428c50212c..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(CancellationToken cancellationToken) + public IChannelHandle GetChannel(OperationContext operationContext) { ThrowIfNotOpen(); @@ -115,7 +115,7 @@ public IChannelHandle GetChannel(CancellationToken cancellationToken) { Interlocked.Increment(ref _outstandingOperationsCount); - var connection = _connectionPool.AcquireConnection(cancellationToken); + var connection = _connectionPool.AcquireConnection(operationContext); 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(OperationContext operationContext) { ThrowIfNotOpen(); try { Interlocked.Increment(ref _outstandingOperationsCount); - var connection = await _connectionPool.AcquireConnectionAsync(cancellationToken).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 262939e4f85..7bd029044b8 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(binding, cancellationToken); + var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(operationContext, binding); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - chunksDeleteOperation.Execute(binding, cancellationToken); + chunksDeleteOperation.Execute(operationContext, binding); 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 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, cancellationToken).ConfigureAwait(false); + var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - await chunksDeleteOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await chunksDeleteOperation.ExecuteAsync(operationContext, binding).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, cancellationToken); + var fileInfo = GetFileInfo(operationContext, binding, id); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(operationContext, binding, id).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, cancellationToken); + var fileInfo = GetFileInfoByName(operationContext, binding, filename, options.Revision); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(operationContext, binding, filename, options.Revision).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, cancellationToken); + var fileInfo = GetFileInfo(operationContext, binding, id); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(operationContext, binding, id).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, cancellationToken); + var fileInfo = GetFileInfoByName(operationContext, binding, filename, options.Revision); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(operationContext, binding, filename, options.Revision).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - filesCollectionDropOperation.Execute(binding, cancellationToken); + filesCollectionDropOperation.Execute(operationContext, binding); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - chunksCollectionDropOperation.Execute(binding, cancellationToken); + chunksCollectionDropOperation.Execute(operationContext, binding); } } /// public async Task DropAsync(CancellationToken cancellationToken = default(CancellationToken)) { + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(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(operationContext).ConfigureAwait(false)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - await filesCollectionDropOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await filesCollectionDropOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - await chunksCollectionDropOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await chunksCollectionDropOperation.ExecuteAsync(operationContext, binding).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 operationContext + 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(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - return operation.Execute(binding, cancellationToken); + return operation.Execute(operationContext, binding); } } @@ -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 operationContext + 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(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, binding).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, cancellationToken); + var fileInfo = GetFileInfo(operationContext, binding, id); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(operationContext, binding, id).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, cancellationToken); + var fileInfo = GetFileInfoByName(operationContext, binding, filename, options.Revision); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(operationContext, binding, filename, options.Revision).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { - EnsureIndexes(binding, cancellationToken); + EnsureIndexes(operationContext, binding); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); - using (var binding = await GetSingleServerReadWriteBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { - await EnsureIndexesAsync(binding, cancellationToken).ConfigureAwait(false); + await EnsureIndexesAsync(operationContext, binding).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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { - var result = renameOperation.Execute(binding, cancellationToken); + var result = renameOperation.Execute(operationContext, binding); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); - using (var binding = await GetSingleServerReadWriteBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { - var result = await renameOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + var result = await renameOperation.ExecuteAsync(operationContext, binding).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 operationContext + var operationContext = new OperationContext(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 operationContext + var operationContext = new OperationContext(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(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = ListIndexes(binding, this.GetChunksCollectionNamespace(), cancellationToken); + var indexes = ListIndexes(operationContext, binding, this.GetChunksCollectionNamespace()); return ChunksCollectionIndexesExist(indexes); } - private async Task ChunksCollectionIndexesExistAsync(IReadBindingHandle binding, CancellationToken cancellationToken) + private async Task ChunksCollectionIndexesExistAsync(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = await ListIndexesAsync(binding, this.GetChunksCollectionNamespace(), cancellationToken).ConfigureAwait(false); + var indexes = await ListIndexesAsync(operationContext, binding, this.GetChunksCollectionNamespace()).ConfigureAwait(false); return ChunksCollectionIndexesExist(indexes); } - private void CreateChunksCollectionIndexes(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private void CreateChunksCollectionIndexes(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateChunksCollectionIndexesOperation(); - operation.Execute(binding, cancellationToken); + operation.Execute(operationContext, binding); } - private async Task CreateChunksCollectionIndexesAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task CreateChunksCollectionIndexesAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateChunksCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await operation.ExecuteAsync(operationContext, binding).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(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateFilesCollectionIndexesOperation(); - operation.Execute(binding, cancellationToken); + operation.Execute(operationContext, binding); } - private async Task CreateFilesCollectionIndexesAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task CreateFilesCollectionIndexesAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateFilesCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } private FindOperation> CreateFindOperation( @@ -810,23 +858,23 @@ private GridFSUploadStream CreateUploadStream(IReadWriteBindingHandle b } } - private void EnsureIndexes(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private void EnsureIndexes(OperationContext operationContext, IReadWriteBindingHandle binding) { - _ensureIndexesSemaphore.Wait(cancellationToken); + _ensureIndexesSemaphore.Wait(operationContext.RemainingTimeout, operationContext.CancellationToken); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = IsFilesCollectionEmpty(binding, cancellationToken); + var isFilesCollectionEmpty = IsFilesCollectionEmpty(operationContext, binding); if (isFilesCollectionEmpty) { - if (!FilesCollectionIndexesExist(binding, cancellationToken)) + if (!FilesCollectionIndexesExist(operationContext, binding)) { - CreateFilesCollectionIndexes(binding, cancellationToken); + CreateFilesCollectionIndexes(operationContext, binding); } - if (!ChunksCollectionIndexesExist(binding, cancellationToken)) + if (!ChunksCollectionIndexesExist(operationContext, binding)) { - CreateChunksCollectionIndexes(binding, cancellationToken); + CreateChunksCollectionIndexes(operationContext, binding); } } @@ -839,23 +887,23 @@ private void EnsureIndexes(IReadWriteBindingHandle binding, CancellationToken ca } } - private async Task EnsureIndexesAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task EnsureIndexesAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { - await _ensureIndexesSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + await _ensureIndexesSemaphore.WaitAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(binding, cancellationToken).ConfigureAwait(false); + var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(operationContext, binding).ConfigureAwait(false); if (isFilesCollectionEmpty) { - if (!(await FilesCollectionIndexesExistAsync(binding, cancellationToken).ConfigureAwait(false))) + if (!(await FilesCollectionIndexesExistAsync(operationContext, binding).ConfigureAwait(false))) { - await CreateFilesCollectionIndexesAsync(binding, cancellationToken).ConfigureAwait(false); + await CreateFilesCollectionIndexesAsync(operationContext, binding).ConfigureAwait(false); } - if (!(await ChunksCollectionIndexesExistAsync(binding, cancellationToken).ConfigureAwait(false))) + if (!(await ChunksCollectionIndexesExistAsync(operationContext, binding).ConfigureAwait(false))) { - await CreateChunksCollectionIndexesAsync(binding, cancellationToken).ConfigureAwait(false); + await CreateChunksCollectionIndexesAsync(operationContext, binding).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(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = ListIndexes(binding, this.GetFilesCollectionNamespace(), cancellationToken); + var indexes = ListIndexes(operationContext, binding, this.GetFilesCollectionNamespace()); return FilesCollectionIndexesExist(indexes); } - private async Task FilesCollectionIndexesExistAsync(IReadBindingHandle binding, CancellationToken cancellationToken) + private async Task FilesCollectionIndexesExistAsync(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = await ListIndexesAsync(binding, this.GetFilesCollectionNamespace(), cancellationToken).ConfigureAwait(false); + var indexes = await ListIndexesAsync(operationContext, binding, this.GetFilesCollectionNamespace()).ConfigureAwait(false); return FilesCollectionIndexesExist(indexes); } - private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId id, CancellationToken cancellationToken) + private GridFSFileInfo GetFileInfo(OperationContext operationContext, IReadBindingHandle binding, TFileId id) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = operation.Execute(binding, cancellationToken)) + using (var cursor = operation.Execute(operationContext, binding)) { - var fileInfo = cursor.FirstOrDefault(cancellationToken); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var fileInfo = cursor.FirstOrDefault(operationContext.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(OperationContext operationContext, IReadBindingHandle binding, TFileId id) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, binding).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(operationContext.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(OperationContext operationContext, IReadBindingHandle binding, string filename, int revision) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = operation.Execute(binding, cancellationToken)) + using (var cursor = operation.Execute(operationContext, binding)) { - var fileInfo = cursor.FirstOrDefault(cancellationToken); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var fileInfo = cursor.FirstOrDefault(operationContext.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(OperationContext operationContext, IReadBindingHandle binding, string filename, int revision) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, binding).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(operationContext.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(OperationContext operationContext) { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = _cluster.SelectServer(selector, cancellationToken); + var server = _cluster.SelectServer(operationContext, selector); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } - private async Task GetSingleServerReadBindingAsync(CancellationToken cancellationToken) + private async Task GetSingleServerReadBindingAsync(OperationContext operationContext) { 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(operationContext, selector).ConfigureAwait(false); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } - private IReadWriteBindingHandle GetSingleServerReadWriteBinding(CancellationToken cancellationToken) + private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationContext operationContext) { var selector = WritableServerSelector.Instance; - var server = _cluster.SelectServer(selector, cancellationToken); + var server = _cluster.SelectServer(operationContext, selector); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } - private async Task GetSingleServerReadWriteBindingAsync(CancellationToken cancellationToken) + private async Task GetSingleServerReadWriteBindingAsync(OperationContext operationContext) { var selector = WritableServerSelector.Instance; - var server = await _cluster.SelectServerAsync(selector, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(operationContext, selector).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(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = operation.Execute(binding, cancellationToken)) + using (var cursor = operation.Execute(operationContext, binding)) { - var firstOrDefault = cursor.FirstOrDefault(cancellationToken); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var firstOrDefault = cursor.FirstOrDefault(operationContext.CancellationToken); return firstOrDefault == null; } } - private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task IsFilesCollectionEmptyAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, binding).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(operationContext.CancellationToken).ConfigureAwait(false); return firstOrDefault == null; } } - private List ListIndexes(IReadBinding binding, CollectionNamespace collectionNamespace, CancellationToken cancellationToken) + private List ListIndexes(OperationContext operationContext, IReadBinding binding, CollectionNamespace collectionNamespace) { var operation = CreateListIndexesOperation(collectionNamespace); - return operation.Execute(binding, cancellationToken).ToList(); + return operation.Execute(operationContext, binding).ToList(); } - private async Task> ListIndexesAsync(IReadBinding binding, CollectionNamespace collectionNamespace, CancellationToken cancellationToken) + private async Task> ListIndexesAsync(OperationContext operationContext, IReadBinding binding, CollectionNamespace collectionNamespace) { 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(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 0f9c09b96fe..23f5e48f877 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + _cursor = operation.Execute(operationContext, Binding); 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + _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 388b60e1fe8..f77fc81f56f 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + operation.Execute(operationContext, _binding); } 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + 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 afbe4a0b6b6..843412df7ef 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var cursor = operation.Execute(operationContext, Binding)) { 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 operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + 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/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/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs new file mode 100644 index 00000000000..d9c25405e24 --- /dev/null +++ b/src/MongoDB.Driver/OperationContext.cs @@ -0,0 +1,161 @@ +/* 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; +#if !NET6_0_OR_GREATER +using MongoDB.Driver.Core.Misc; +#endif + +namespace MongoDB.Driver +{ + 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); + + public OperationContext(TimeSpan timeout, CancellationToken cancellationToken) + : this(Stopwatch.StartNew(), timeout, cancellationToken) + { + } + + internal OperationContext(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) + { + Stopwatch = stopwatch; + Timeout = timeout; + CancellationToken = cancellationToken; + } + + public CancellationToken CancellationToken { get; } + + public OperationContext ParentContext { get; private init; } + + public TimeSpan RemainingTimeout + { + get + { + if (Timeout == System.Threading.Timeout.InfiniteTimeSpan) + { + return System.Threading.Timeout.InfiniteTimeSpan; + } + + return Timeout - Stopwatch.Elapsed; + } + } + + private Stopwatch Stopwatch { get; } + + public TimeSpan Timeout { get; } + + public bool IsTimedOut() + { + var remainingTimeout = RemainingTimeout; + if (remainingTimeout == System.Threading.Timeout.InfiniteTimeSpan) + { + return false; + } + + return remainingTimeout < TimeSpan.Zero; + } + + public void ThrowIfTimedOutOrCanceled() + { + CancellationToken.ThrowIfCancellationRequested(); + if (IsTimedOut()) + { + throw new TimeoutException(); + } + } + + public void WaitTask(Task task) + { + if (task.IsCompleted) + { + task.GetAwaiter().GetResult(); // re-throws exception if any + return; + } + + var timeout = RemainingTimeout; + if (timeout != System.Threading.Timeout.InfiniteTimeSpan && timeout < TimeSpan.Zero) + { + throw new TimeoutException(); + } + + try + { + 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 != System.Threading.Timeout.InfiniteTimeSpan && timeout < TimeSpan.Zero) + { + throw new TimeoutException(); + } + + try + { + await task.WaitAsync(timeout, CancellationToken).ConfigureAwait(false); + } + catch (TaskCanceledException) + { + CancellationToken.ThrowIfCancellationRequested(); + 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 295d136bd09..7025097de70 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 operationContext = options.ToOperationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return operation.Execute(binding, cancellationToken); + return operation.Execute(operationContext, binding); } public async Task ExecuteReadOperationAsync( @@ -67,9 +68,10 @@ public async Task ExecuteReadOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var operationContext = options.ToOperationContext(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(operationContext, binding).ConfigureAwait(false); } public TResult ExecuteWriteOperation( @@ -84,8 +86,9 @@ public TResult ExecuteWriteOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var operationContext = options.ToOperationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return operation.Execute(binding, cancellationToken); + return operation.Execute(operationContext, binding); } public async Task ExecuteWriteOperationAsync( @@ -100,8 +103,9 @@ public async Task ExecuteWriteOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var operationContext = options.ToOperationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, binding).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..5f564ca1b27 --- /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 OperationContext ToOperationContext(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..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, CancellationToken.None); + 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, CancellationToken.None); + 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, CancellationToken.None); + 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, CancellationToken.None); + 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, CancellationToken.None).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, CancellationToken.None); + 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 c9f6c9f9a4e..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, CancellationToken.None); + 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, CancellationToken.None); + operation.Execute(OperationContext.NoTimeout, _binding); } } } diff --git a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs index d865da3f833..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(CancellationToken.None)); + 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 a0d0a2a8a4c..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(default)) - using (var channel = channelSource.GetChannel(default)) + 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 f60b30c80c5..0ad423e16eb 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(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 1852264edc3..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(WritableServerSelector.Instance, default); - var fastServer = client.GetClusterInternal().SelectServer(new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId)), default); + 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); @@ -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(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 76a12582048..650f074169d 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(OperationContext.NoTimeout) : + subject.GetChannel(OperationContext.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(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 121011542cb..1d6f317e611 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(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.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(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 15c900f87d3..acc8fdfa4ad 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(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(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 212ca5f46d9..37031583a76 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.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(OperationContext.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(OperationContext.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..fbac6fc6c7b 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.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(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 d26b05ff749..070b01d7e48 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout); - _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(CancellationToken.None), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(OperationContext.NoTimeout), Times.Once); } else { - subject.GetReadChannelSource(CancellationToken.None); + subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockReadBinding.Verify(b => b.GetReadChannelSource(CancellationToken.None), 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 744241191af..c3486f158e5 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(OperationContext.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(OperationContext.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(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 33f36397c1b..7549be8c4c8 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(OperationContext.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(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.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(OperationContext.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(OperationContext.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..62bd5cfd535 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.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(OperationContext.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(OperationContext.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..ab0fae6858c 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(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.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(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 1087d544760..2efd25ca017 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(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationContext.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(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 a5796c5e5a0..f16dc755894 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.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(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); - subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); - subject.GetReadChannelSource(CancellationToken.None); + subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, 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 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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.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(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); - subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); - subject.GetWriteChannelSource(CancellationToken.None); + subject.GetWriteChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny()), 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(OperationContext.NoTimeout, It.Is(cp => cp.ToString().Contains("PriorityServerSelector")))).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(deprioritizedServers, CancellationToken.None); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, deprioritizedServers); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), CancellationToken.None), 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")), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.Is(cp => cp.ToString().Contains("PriorityServerSelector")))).Returns(selectedServer); - subject.GetWriteChannelSource(deprioritizedServers, CancellationToken.None); + subject.GetWriteChannelSource(OperationContext.NoTimeout, deprioritizedServers); - _mockCluster.Verify(c => c.SelectServer(It.Is(c => c.ToString().Contains("PriorityServerSelector")), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.Is(c => c.ToString().Contains("PriorityServerSelector"))), 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(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); - subject.GetWriteChannelSourceAsync(mayUseSecondary, CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, mayUseSecondary); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(s => s.MayUseSecondary == mayUseSecondary), CancellationToken.None), 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(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); - subject.GetWriteChannelSource(mayUseSecondary, CancellationToken.None); + subject.GetWriteChannelSource(OperationContext.NoTimeout, mayUseSecondary); - _mockCluster.Verify(c => c.SelectServer(It.Is(s => s.MayUseSecondary == mayUseSecondary), CancellationToken.None), 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 0d2b8bd2d20..7a3244b229d 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(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); - 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(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); - 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(OperationContext.NoTimeout, null)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, null)); - 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(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); 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(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); + 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(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); - 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(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); - 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(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); - 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(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); 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(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); 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(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); 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(OperationContext.NoTimeout, middleSelector) : + subject.SelectServer(OperationContext.NoTimeout, middleSelector); ((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(OperationContext.NoTimeout, selector): + subject.SelectServer(OperationContext.NoTimeout, selector); 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(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); 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..2c14c12f751 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(OperationContext.NoTimeout, Mock.Of()) : + subject.SelectServer(OperationContext.NoTimeout, Mock.Of()); 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(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 "); @@ -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 operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, Mock.Of())) : + Record.Exception(() => subject.SelectServer(operationContext, Mock.Of())); } 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..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(default)) + .Select(i => subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout); + connection2 = await _subject.AcquireConnectionAsync(OperationContext.NoTimeout); } else { - connection1 = _subject.AcquireConnection(CancellationToken.None); - connection2 = _subject.AcquireConnection(CancellationToken.None); + connection1 = _subject.AcquireConnection(OperationContext.NoTimeout); + connection2 = _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) : + subject.AcquireConnection(OperationContext.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(OperationContext.NoTimeout) .GetAwaiter() .GetResult(); } else { - return subject.AcquireConnection(CancellationToken.None); + 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 4e8a23a13fb..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(CancellationToken.None); + acquiredConnection = pool.AcquireConnection(OperationContext.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..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), CancellationToken.None); + var selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint1)); 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(OperationContext.NoTimeout).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => selectedServer.GetChannel(CancellationToken.None)); + 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, CancellationToken.None); + selectedServer = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); // 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..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 - var _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None); + _ = 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), CancellationToken.None); + 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), CancellationToken.None); + selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint2)); 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..a433e87fa5e 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(OperationContext.NoTimeout, context).GetAwaiter().GetResult(); } else { - return bulkInsertOperation.Execute(context, CancellationToken.None); + return bulkInsertOperation.Execute(OperationContext.NoTimeout, context); } } @@ -635,19 +634,19 @@ private IAsyncCursor CreateAndRunFindOperation(RetryableReadContex if (async) { - return findOperation.ExecuteAsync(context, CancellationToken.None).GetAwaiter().GetResult(); + return findOperation.ExecuteAsync(OperationContext.NoTimeout, context).GetAwaiter().GetResult(); } else { - return findOperation.Execute(context, CancellationToken.None); + return findOperation.Execute(OperationContext.NoTimeout, context); } } 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(OperationContext.NoTimeout, readBindingHandle, retryRequested: false).GetAwaiter().GetResult() + : RetryableReadContext.Create(OperationContext.NoTimeout, readBindingHandle, retryRequested: false); } 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(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/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..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)); @@ -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(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.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..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(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + 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(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + 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(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + 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(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + 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 f2661693749..4e11447d94c 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(It.IsAny(), mockBinding.Object)).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(It.IsAny(), mockBinding.Object), 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(It.IsAny(), mockBinding.Object)).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(It.IsAny(), mockBinding.Object), 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..3dcc8a36cfc 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(OperationContext.NoTimeout, Mock.Of())) + : Record.Exception(() => subject.Execute(OperationContext.NoTimeout, Mock.Of())); 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(OperationContext.NoTimeout, Mock.Of()).GetAwaiter().GetResult() + : subject.Execute(OperationContext.NoTimeout, Mock.Of()); 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..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, CancellationToken.None).GetAwaiter().GetResult(); + return subject.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return subject.Execute(binding, CancellationToken.None); + 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, CancellationToken.None).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 ef72d20e5fa..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, CancellationToken.None).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 64080a96efa..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, CancellationToken.None).GetAwaiter().GetResult(); + return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, CancellationToken.None); + return operation.Execute(OperationContext.NoTimeout, binding); } } } 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..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, CancellationToken.None); + return operation.Execute(OperationContext.NoTimeout, bindingHandle); } } @@ -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(OperationContext.NoTimeout, bindingHandle) : + operation.Execute(OperationContext.NoTimeout, bindingHandle); } } @@ -178,11 +173,11 @@ private protected TResult ExecuteOperation(IReadOperation oper { if (async) { - return operation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult(); + return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, CancellationToken.None); + return operation.Execute(OperationContext.NoTimeout, binding); } } @@ -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(OperationContext.NoTimeout, bindingHandle); } } @@ -220,11 +215,11 @@ private protected TResult ExecuteOperation(IWriteOperation ope { if (async) { - return operation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult(); + return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, CancellationToken.None); + return operation.Execute(OperationContext.NoTimeout, binding); } } @@ -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(OperationContext.NoTimeout, binding); } 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(OperationContext.NoTimeout, bindingHandle); } } @@ -258,18 +253,23 @@ private protected async Task ExecuteOperationAsync(IWriteOpera { if (async) { - return await operation.ExecuteAsync(bindingHandle, CancellationToken.None); + return await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle); } else { - return operation.Execute(bindingHandle, CancellationToken.None); + return operation.Execute(OperationContext.NoTimeout, bindingHandle); } } } + private protected TResult ExecuteOperation(IWriteOperation operation, IWriteBinding binding, bool async) + => async ? + 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, CancellationToken.None); + 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,16 +534,16 @@ 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); } 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, OperationContext.NoTimeout).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => execute(binding, cancellationToken)); + 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 e66a2fa67d1..f866f268877 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..471c4a0a931 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(OperationContext.NoTimeout, binding, retryRequested); } 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..bc44255fa2c 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..16709b65bf3 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(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => server.GetChannel(OperationContext.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(OperationContext.NoTimeout) : + _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.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..cd564ab9773 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(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => server.GetChannel(OperationContext.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(OperationContext.NoTimeout) : + _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.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(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.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,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 cancellationToken = CancellationToken.None; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationToken); - using (var channel = server.GetChannel(cancellationToken)) + var server = (Server)cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); + using (var channel = server.GetChannel(OperationContext.NoTimeout)) { session.AdvanceClusterTime(sessionClusterTime); server.ClusterClock.AdvanceClusterTime(clusterClusterTime); @@ -922,7 +874,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 +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 cancellationToken = CancellationToken.None; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationToken); - using (var channel = server.GetChannel(cancellationToken)) + var server = (Server)cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); + using (var channel = server.GetChannel(OperationContext.NoTimeout)) { var command = BsonDocument.Parse("{ ping : 1 }"); channel.Command( @@ -965,7 +916,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 +929,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 +943,13 @@ 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 server = (Server)cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); + using (var channel = server.GetChannel(OperationContext.NoTimeout)) { var command = BsonDocument.Parse("{ ping : 1 }"); if (async) { - channel + await channel .CommandAsync( session, ReadPreference.Primary, @@ -1012,9 +962,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 +978,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..fb09f34e818 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..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, CancellationToken.None); + 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, CancellationToken.None).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 44f2e342395..8a34e83638d 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(OperationContext.NoTimeout, pinnedServerSelector); } 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(OperationContext.NoTimeout, pinnedServerSelector).ConfigureAwait(false); } - // private methods + // private methods private IServerSelector CreateServerSelector(EndPoint endpoint) { return new CompositeServerSelector(new IServerSelector[] diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs new file mode 100644 index 00000000000..9b253837d8a --- /dev/null +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -0,0 +1,281 @@ +/* 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 System.Threading.Tasks; +using FluentAssertions; +using MongoDB.TestHelpers.XunitExtensions; +using Xunit; + +namespace MongoDB.Driver.Tests +{ + public class OperationContextTests + { + [Fact] + 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(stopwatch, timeout, cancellationToken); + + operationContext.Timeout.Should().Be(timeout); + operationContext.RemainingTimeout.Should().Be(timeout); + operationContext.CancellationToken.Should().Be(cancellationToken); + operationContext.ParentContext.Should().BeNull(); + } + + [Fact] + public void RemainingTimeout_should_calculate() + { + var timeout = TimeSpan.FromMilliseconds(500); + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(10); + stopwatch.Stop(); + + var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); + + operationContext.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 operationContext = new OperationContext(stopwatch, Timeout.InfiniteTimeSpan, CancellationToken.None); + + operationContext.RemainingTimeout.Should().Be(Timeout.InfiniteTimeSpan); + } + + [Fact] + public void RemainingTimeout_could_be_negative() + { + var timeout = TimeSpan.FromMilliseconds(5); + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(10); + stopwatch.Stop(); + + var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); + + operationContext.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 operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); + var result = operationContext.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)], + ]; + + [Fact] + public void ThrowIfTimedOutOrCanceled_should_not_throw_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(); + } + + [Fact] + public void ThrowIfTimedOutOrCanceled_throws_CancelledException_when_timedout_and_cancelled() + { + using var cancellationSource = new CancellationTokenSource(); + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(10), cancellationSource.Token); + Thread.Sleep(20); + cancellationSource.Cancel(); + + var exception = Record.Exception(() => operationContext.ThrowIfTimedOutOrCanceled()); + + exception.Should().BeOfType(); + } + + [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(); + } + + + [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); + } + } +} + 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..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, CancellationToken.None); + _failPointServer = cluster.SelectServer(OperationContext.NoTimeout, selector); } else { - _failPointServer = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); + _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 ceafb5aeae4..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, CancellationToken.None); + 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 626ef59450a..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 @@ -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(OperationContext.NoTimeout).GetAwaiter().GetResult() : + cp.AcquireConnection(OperationContext.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(OperationContext.NoTimeout, WritableServerSelector.Instance); 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(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 f4aa9cc83ac..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, default); + 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), default); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), default); + 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), default); + 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 9054e532708..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 @@ -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(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 75f89943f40..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), default); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), default); + 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), default); + 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 cebdf47395f..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)), default); + 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, CancellationToken.None); + 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)), default); + 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 84abad019de..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, default).GetAwaiter().GetResult() - : cluster.SelectServer(readPreferenceSelector, default); + ? cluster.SelectServerAsync(OperationContext.NoTimeout, readPreferenceSelector).GetAwaiter().GetResult() + : cluster.SelectServer(OperationContext.NoTimeout, readPreferenceSelector); 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..97463a719b0 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(OperationContext.NoTimeout, new EndPointServerSelector(pinnedServer)); var session = NoCoreSession.NewHandle();