diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs index f48a8038428..c71d3e327e6 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs @@ -26,14 +26,12 @@ internal sealed class ChannelChannelSource : IChannelSource private readonly IChannelHandle _channel; private bool _disposed; private readonly IServer _server; - private readonly ICoreSessionHandle _session; // constructors - public ChannelChannelSource(IServer server, IChannelHandle channel, ICoreSessionHandle session) + public ChannelChannelSource(IServer server, IChannelHandle channel) { _server = Ensure.IsNotNull(server, nameof(server)); _channel = Ensure.IsNotNull(channel, nameof(channel)); - _session = Ensure.IsNotNull(session, nameof(session)); } // properties @@ -47,18 +45,12 @@ public ServerDescription ServerDescription get { return _server.Description; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - // methods public void Dispose() { if (!_disposed) { _channel.Dispose(); - _session.Dispose(); _disposed = true; } } diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs index 63dab353cf4..6d4b1fe464a 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -27,14 +27,12 @@ internal sealed class ChannelReadBinding : IReadBinding private bool _disposed; private readonly ReadPreference _readPreference; private readonly IServer _server; - private readonly ICoreSessionHandle _session; - public ChannelReadBinding(IServer server, IChannelHandle channel, ReadPreference readPreference, ICoreSessionHandle session) + public ChannelReadBinding(IServer server, IChannelHandle channel, ReadPreference readPreference) { _server = Ensure.IsNotNull(server, nameof(server)); _channel = Ensure.IsNotNull(channel, nameof(channel)); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); - _session = Ensure.IsNotNull(session, nameof(session)); } public ReadPreference ReadPreference @@ -42,17 +40,11 @@ public ReadPreference ReadPreference get { return _readPreference; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - public void Dispose() { if (!_disposed) { _channel.Dispose(); - _session.Dispose(); _disposed = true; } } @@ -81,7 +73,7 @@ public Task GetReadChannelSourceAsync(OperationContext ope private IChannelSourceHandle GetReadChannelSourceHelper() { - return new ChannelSourceHandle(new ChannelChannelSource(_server, _channel.Fork(), _session.Fork())); + return new ChannelSourceHandle(new ChannelChannelSource(_server, _channel.Fork())); } private void ThrowIfDisposed() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs index 17ae75966bc..997d9997519 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -26,13 +26,11 @@ internal sealed class ChannelReadWriteBinding : IReadWriteBinding private readonly IChannelHandle _channel; private bool _disposed; private readonly IServer _server; - private readonly ICoreSessionHandle _session; - public ChannelReadWriteBinding(IServer server, IChannelHandle channel, ICoreSessionHandle session) + public ChannelReadWriteBinding(IServer server, IChannelHandle channel) { _server = Ensure.IsNotNull(server, nameof(server)); _channel = Ensure.IsNotNull(channel, nameof(channel)); - _session = Ensure.IsNotNull(session, nameof(session)); } public ReadPreference ReadPreference @@ -40,17 +38,11 @@ public ReadPreference ReadPreference get { return ReadPreference.Primary; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - public void Dispose() { if (!_disposed) { _channel.Dispose(); - _session.Dispose(); _disposed = true; } } @@ -121,7 +113,7 @@ public Task GetWriteChannelSourceAsync(OperationContext op private IChannelSourceHandle GetChannelSourceHelper() { - return new ChannelSourceHandle(new ChannelChannelSource(_server, _channel.Fork(), _session.Fork())); + return new ChannelSourceHandle(new ChannelChannelSource(_server, _channel.Fork())); } private void ThrowIfDisposed() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs index 3b08ff9da33..081bc0858c0 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -48,11 +48,6 @@ public ServerDescription ServerDescription get { return _reference.Instance.ServerDescription; } } - public ICoreSessionHandle Session - { - get { return _reference.Instance.Session; } - } - // methods public IChannelHandle GetChannel(OperationContext operationContext) { diff --git a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs index 1e20bb94c7e..99072dc84a2 100644 --- a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs +++ b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs @@ -151,7 +151,14 @@ void ICoreSessionInternal.AbortTransaction(AbortTransactionOptions options, Canc { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); - using var operationContext = new OperationContext(GetTimeout(options?.Timeout), "abortTransaction", "admin", null, _currentTransaction.IsTracingEnabled, cancellationToken); + using var sessionHandle = new NonDisposingCoreSessionHandle(this); + using var operationContext = new OperationContext(sessionHandle, GetTimeout(options?.Timeout), cancellationToken) + { + IsTracingEnabled = _currentTransaction.IsTracingEnabled, + OperationName = "abortTransaction", + DatabaseName = "admin", + CollectionName = null + }; try { if (_currentTransaction.IsEmpty) @@ -189,7 +196,14 @@ async Task ICoreSessionInternal.AbortTransactionAsync(AbortTransactionOptions op { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); - using var operationContext = new OperationContext(GetTimeout(options?.Timeout), "abortTransaction", "admin", null, _currentTransaction.IsTracingEnabled, cancellationToken); + using var sessionHandle = new NonDisposingCoreSessionHandle(this); + using var operationContext = new OperationContext(sessionHandle, GetTimeout(options?.Timeout), cancellationToken) + { + IsTracingEnabled = _currentTransaction.IsTracingEnabled, + OperationName = "abortTransaction", + DatabaseName = "admin", + CollectionName = null + }; try { if (_currentTransaction.IsEmpty) @@ -275,8 +289,14 @@ public void CommitTransaction(CancellationToken cancellationToken = default) void ICoreSessionInternal.CommitTransaction(CommitTransactionOptions options, CancellationToken cancellationToken) { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); - - using var operationContext = new OperationContext(GetTimeout(options?.Timeout), "commitTransaction", "admin", null, _currentTransaction.IsTracingEnabled, cancellationToken); + using var sessionHandle = new NonDisposingCoreSessionHandle(this); + using var operationContext = new OperationContext(sessionHandle, GetTimeout(options?.Timeout), cancellationToken) + { + IsTracingEnabled = _currentTransaction.IsTracingEnabled, + OperationName = "commitTransaction", + DatabaseName = "admin", + CollectionName = null + }; try { _isCommitTransactionInProgress = true; @@ -304,8 +324,14 @@ public Task CommitTransactionAsync(CancellationToken cancellationToken = default async Task ICoreSessionInternal.CommitTransactionAsync(CommitTransactionOptions options, CancellationToken cancellationToken) { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); - - using var operationContext = new OperationContext(GetTimeout(options?.Timeout), "commitTransaction", "admin", null, _currentTransaction.IsTracingEnabled, cancellationToken); + using var sessionHandle = new NonDisposingCoreSessionHandle(this); + using var operationContext = new OperationContext(sessionHandle, GetTimeout(options?.Timeout), cancellationToken) + { + IsTracingEnabled = _currentTransaction.IsTracingEnabled, + OperationName = "commitTransaction", + DatabaseName = "admin", + CollectionName = null + }; try { _isCommitTransactionInProgress = true; @@ -560,7 +586,7 @@ private IReadWriteBinding CreateEndTransactionBinding(ICoreSessionHandle session // otherwise the captured pinned-channel fork goes stale after UnpinAll. if (_cluster.Description.Type == ClusterType.LoadBalanced) { - return new EndTransactionReadWriteBinding(_cluster, session); + return new EndTransactionReadWriteBinding(_cluster); } return ChannelPinningHelper.CreateReadWriteBinding(_cluster, session); diff --git a/src/MongoDB.Driver/Core/Bindings/EndTransactionReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/EndTransactionReadWriteBinding.cs index ddc39e93e1f..f1537925bd7 100644 --- a/src/MongoDB.Driver/Core/Bindings/EndTransactionReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/EndTransactionReadWriteBinding.cs @@ -31,72 +31,110 @@ internal sealed class EndTransactionReadWriteBinding : IReadWriteBinding #pragma warning restore CA2213 // Disposable fields should be disposed private bool _disposed; private IReadWriteBindingHandle _innerBinding; - private readonly ICoreSessionHandle _session; - public EndTransactionReadWriteBinding(IClusterInternal cluster, ICoreSessionHandle session) + public EndTransactionReadWriteBinding(IClusterInternal cluster) { _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); - _session = Ensure.IsNotNull(session, nameof(session)); - _innerBinding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, _session.Fork()); } public ReadPreference ReadPreference => ReadPreference.Primary; - public ICoreSessionHandle Session => _session; - // Called by EndTransactionOperation.OnRetry between attempts. public void RebuildInnerBinding() { ThrowIfDisposed(); - _innerBinding.Dispose(); - _innerBinding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, _session.Fork()); + _innerBinding?.Dispose(); + _innerBinding = null; } public void Dispose() { if (!_disposed) { - _innerBinding.Dispose(); - _session.Dispose(); + _innerBinding?.Dispose(); _disposed = true; } } public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) - => _innerBinding.GetReadChannelSource(operationContext); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetReadChannelSource(operationContext); + } public Task GetReadChannelSourceAsync(OperationContext operationContext) - => _innerBinding.GetReadChannelSourceAsync(operationContext); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetReadChannelSourceAsync(operationContext); + } public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) - => _innerBinding.GetReadChannelSource(operationContext, deprioritizedServers); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetReadChannelSource(operationContext, deprioritizedServers); + } public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) - => _innerBinding.GetReadChannelSourceAsync(operationContext, deprioritizedServers); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetReadChannelSourceAsync(operationContext, deprioritizedServers); + } public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) - => _innerBinding.GetWriteChannelSource(operationContext); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSource(operationContext); + } public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) - => _innerBinding.GetWriteChannelSource(operationContext, deprioritizedServers); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSource(operationContext, deprioritizedServers); + } public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) - => _innerBinding.GetWriteChannelSource(operationContext, mayUseSecondary); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSource(operationContext, mayUseSecondary); + } public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) - => _innerBinding.GetWriteChannelSource(operationContext, deprioritizedServers, mayUseSecondary); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSource(operationContext, deprioritizedServers, mayUseSecondary); + } public Task GetWriteChannelSourceAsync(OperationContext operationContext) - => _innerBinding.GetWriteChannelSourceAsync(operationContext); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSourceAsync(operationContext); + } public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) - => _innerBinding.GetWriteChannelSourceAsync(operationContext, deprioritizedServers); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSourceAsync(operationContext, deprioritizedServers); + } public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) - => _innerBinding.GetWriteChannelSourceAsync(operationContext, mayUseSecondary); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSourceAsync(operationContext, mayUseSecondary); + } public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) - => _innerBinding.GetWriteChannelSourceAsync(operationContext, deprioritizedServers, mayUseSecondary); + { + EnsureInnerBinding(operationContext); + return _innerBinding.GetWriteChannelSourceAsync(operationContext, deprioritizedServers, mayUseSecondary); + } + + private void EnsureInnerBinding(OperationContext operationContext) + { + if (_innerBinding == null) + { + _innerBinding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, operationContext.Session); + } + } private void ThrowIfDisposed() { diff --git a/src/MongoDB.Driver/Core/Bindings/IBinding.cs b/src/MongoDB.Driver/Core/Bindings/IBinding.cs index 0b2d0456a36..712453e7cb0 100644 --- a/src/MongoDB.Driver/Core/Bindings/IBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/IBinding.cs @@ -22,7 +22,6 @@ namespace MongoDB.Driver.Core.Bindings { internal interface IBinding : IDisposable { - ICoreSessionHandle Session { get; } } internal interface IReadBinding : IBinding diff --git a/src/MongoDB.Driver/Core/Bindings/IChannel.cs b/src/MongoDB.Driver/Core/Bindings/IChannel.cs index 3a1dca12020..9314b93befe 100644 --- a/src/MongoDB.Driver/Core/Bindings/IChannel.cs +++ b/src/MongoDB.Driver/Core/Bindings/IChannel.cs @@ -33,7 +33,6 @@ internal interface IChannel : IDisposable TResult Command( OperationContext operationContext, - ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, @@ -47,7 +46,6 @@ TResult Command( Task CommandAsync( OperationContext operationContext, - ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, diff --git a/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs index c9bd90ec61b..92dddc2367f 100644 --- a/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs @@ -23,7 +23,6 @@ internal interface IChannelSource : IDisposable { IServer Server { get; } ServerDescription ServerDescription { get; } - ICoreSessionHandle Session { get; } IChannelHandle GetChannel(OperationContext operationContext); Task GetChannelAsync(OperationContext operationContext); diff --git a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs index 99dfa24212d..9d3b048a85f 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs @@ -41,11 +41,6 @@ public ReadPreference ReadPreference get { return _reference.Instance.ReadPreference; } } - public ICoreSessionHandle Session - { - get { return _reference.Instance.Session; } - } - public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); diff --git a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs index 32106f0efcd..508671d70a0 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs @@ -31,13 +31,11 @@ internal sealed class ReadPreferenceBinding : IReadBinding private bool _disposed; private readonly ReadPreference _readPreference; private readonly IServerSelector _serverSelector; - private readonly ICoreSessionHandle _session; - public ReadPreferenceBinding(IClusterInternal cluster, ReadPreference readPreference, ICoreSessionHandle session) + public ReadPreferenceBinding(IClusterInternal cluster, ReadPreference readPreference) { _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); - _session = Ensure.IsNotNull(session, nameof(session)); _serverSelector = new ReadPreferenceServerSelector(readPreference); } @@ -46,11 +44,6 @@ public ReadPreference ReadPreference get { return _readPreference; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { return GetReadChannelSource(operationContext, null); @@ -64,27 +57,26 @@ public Task GetReadChannelSourceAsync(OperationContext ope public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, _serverSelector, deprioritizedServers); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, operationContext.Session, _serverSelector, deprioritizedServers); return GetChannelSourceHelper(server); } public async Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, _serverSelector, deprioritizedServers).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, operationContext.Session, _serverSelector, deprioritizedServers).ConfigureAwait(false); return GetChannelSourceHelper(server); } private IChannelSourceHandle GetChannelSourceHelper(IServer server) { - return new ChannelSourceHandle(new ServerChannelSource(server, _session.Fork())); + return new ChannelSourceHandle(new ServerChannelSource(server)); } public void Dispose() { if (!_disposed) { - _session.Dispose(); _disposed = true; } } diff --git a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs index 0409d3ae844..ebd7f08a281 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs @@ -41,11 +41,6 @@ public ReadPreference ReadPreference get { return _reference.Instance.ReadPreference; } } - public ICoreSessionHandle Session - { - get { return _reference.Instance.Session; } - } - public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); diff --git a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs index bd8080404ca..26bbb5b1928 100644 --- a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs @@ -25,13 +25,11 @@ internal sealed class ServerChannelSource : IChannelSource // fields private bool _disposed; private readonly IServer _server; - private readonly ICoreSessionHandle _session; // constructors - public ServerChannelSource(IServer server, ICoreSessionHandle session) + public ServerChannelSource(IServer server) { _server = Ensure.IsNotNull(server, nameof(server)); - _session = Ensure.IsNotNull(session, nameof(session)); } // properties @@ -39,14 +37,12 @@ public ServerChannelSource(IServer server, ICoreSessionHandle session) public ServerDescription ServerDescription => _server.Description; - public ICoreSessionHandle Session => _session; // methods public void Dispose() { if (!_disposed) { - _session.Dispose(); _disposed = true; } } diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs index 2e76e42a093..a28cf794823 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs @@ -31,15 +31,13 @@ internal sealed class SingleServerReadBinding : IReadBinding private bool _disposed; private readonly ReadPreference _readPreference; private readonly IServerSelector _serverSelector; - private readonly ICoreSessionHandle _session; - public SingleServerReadBinding(IClusterInternal cluster, IServer server, ReadPreference readPreference, ICoreSessionHandle session) + public SingleServerReadBinding(IClusterInternal cluster, IServer server, ReadPreference readPreference) { _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); Ensure.IsNotNull(server, nameof(server)); _serverSelector = new EndPointServerSelector(server.EndPoint); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); - _session = Ensure.IsNotNull(session, nameof(session)); } public ReadPreference ReadPreference @@ -47,23 +45,18 @@ public ReadPreference ReadPreference get { return _readPreference; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); var server = _cluster.SelectServer(operationContext, _serverSelector); - return new ChannelSourceHandle(new ServerChannelSource(server, _session.Fork())); + return new ChannelSourceHandle(new ServerChannelSource(server)); } public async Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); var server = await _cluster.SelectServerAsync(operationContext, _serverSelector).ConfigureAwait(false); - return new ChannelSourceHandle(new ServerChannelSource(server, _session.Fork())); + return new ChannelSourceHandle(new ServerChannelSource(server)); } public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) => @@ -76,7 +69,6 @@ public void Dispose() { if (!_disposed) { - _session.Dispose(); _disposed = true; } } diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs index 5113baa09c0..fdfff7a0422 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs @@ -25,12 +25,10 @@ internal sealed class SingleServerReadWriteBinding : IReadWriteBinding { private bool _disposed; private readonly IServer _server; - private readonly ICoreSessionHandle _session; - public SingleServerReadWriteBinding(IServer server, ICoreSessionHandle session) + public SingleServerReadWriteBinding(IServer server) { _server = Ensure.IsNotNull(server, nameof(server)); - _session = Ensure.IsNotNull(session, nameof(session)); } public ReadPreference ReadPreference @@ -38,16 +36,10 @@ public ReadPreference ReadPreference get { return ReadPreference.Primary; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - public void Dispose() { if (!_disposed) { - _session.Dispose(); _disposed = true; } } @@ -118,7 +110,7 @@ public Task GetWriteChannelSourceAsync(OperationContext op private IChannelSourceHandle GetChannelSourceHelper() { - return new ChannelSourceHandle(new ServerChannelSource(_server, _session.Fork())); + return new ChannelSourceHandle(new ServerChannelSource(_server)); } private void ThrowIfDisposed() diff --git a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs index cbf9c7a7649..6b5a7ca3035 100644 --- a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs @@ -29,12 +29,10 @@ internal sealed class WritableServerBinding : IReadWriteBinding private readonly IClusterInternal _cluster; #pragma warning restore CA2213 // Disposable fields should be disposed private bool _disposed; - private readonly ICoreSessionHandle _session; - public WritableServerBinding(IClusterInternal cluster, ICoreSessionHandle session) + public WritableServerBinding(IClusterInternal cluster) { _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); - _session = Ensure.IsNotNull(session, nameof(session)); } public ReadPreference ReadPreference @@ -42,11 +40,6 @@ public ReadPreference ReadPreference get { return ReadPreference.Primary; } } - public ICoreSessionHandle Session - { - get { return _session; } - } - public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { return GetReadChannelSource(operationContext, null); @@ -60,14 +53,14 @@ public Task GetReadChannelSourceAsync(OperationContext ope public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, operationContext.Session, WritableServerSelector.Instance, deprioritizedServers); return CreateServerChannelSource(server); } public async Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, operationContext.Session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); return CreateServerChannelSource(server); } @@ -79,7 +72,7 @@ public IChannelSourceHandle GetWriteChannelSource(OperationContext operationCont public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, operationContext.Session, WritableServerSelector.Instance, deprioritizedServers); return CreateServerChannelSource(server); } @@ -90,7 +83,7 @@ public IChannelSourceHandle GetWriteChannelSource(OperationContext operationCont public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - if (IsSessionPinnedToServer()) + if (IsSessionPinnedToServer(operationContext)) { throw new InvalidOperationException($"This overload of {nameof(GetWriteChannelSource)} cannot be called when pinned to a server."); } @@ -113,7 +106,7 @@ public Task GetWriteChannelSourceAsync(OperationContext op public async Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, operationContext.Session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); return CreateServerChannelSource(server); } @@ -124,7 +117,7 @@ public Task GetWriteChannelSourceAsync(OperationContext op public async Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - if (IsSessionPinnedToServer()) + if (IsSessionPinnedToServer(operationContext)) { throw new InvalidOperationException($"This overload of {nameof(GetWriteChannelSource)} cannot be called when pinned to a server."); } @@ -141,21 +134,20 @@ public async Task GetWriteChannelSourceAsync(OperationCont private IChannelSourceHandle CreateServerChannelSource(IServer server) { - return new ChannelSourceHandle(new ServerChannelSource(server, _session.Fork())); + return new ChannelSourceHandle(new ServerChannelSource(server)); } public void Dispose() { if (!_disposed) { - _session.Dispose(); _disposed = true; } } - private bool IsSessionPinnedToServer() + private bool IsSessionPinnedToServer(OperationContext operationContext) { - return _session.IsInTransaction && _session.CurrentTransaction.PinnedServer != null; + return operationContext.Session.IsInTransaction && operationContext.Session.CurrentTransaction.PinnedServer != null; } private void ThrowIfDisposed() diff --git a/src/MongoDB.Driver/Core/ChannelPinningHelper.cs b/src/MongoDB.Driver/Core/ChannelPinningHelper.cs index 740ffef8fa4..60fb361a9c4 100644 --- a/src/MongoDB.Driver/Core/ChannelPinningHelper.cs +++ b/src/MongoDB.Driver/Core/ChannelPinningHelper.cs @@ -32,8 +32,7 @@ public static IReadBindingHandle CreateReadBinding(IClusterInternal cluster, ICo { readBinding = new ChannelReadWriteBinding( session.CurrentTransaction.PinnedServer, - session.CurrentTransaction.PinnedChannel.Fork(), - session); + session.CurrentTransaction.PinnedChannel.Fork()); } else { @@ -42,7 +41,7 @@ public static IReadBindingHandle CreateReadBinding(IClusterInternal cluster, ICo // unpin if the next operation is not under transaction session.CurrentTransaction.UnpinAll(); } - readBinding = new ReadPreferenceBinding(cluster, readPreference, session); + readBinding = new ReadPreferenceBinding(cluster, readPreference); } return new ReadBindingHandle(readBinding); @@ -57,8 +56,7 @@ public static IReadWriteBindingHandle CreateReadWriteBinding(IClusterInternal cl { readWriteBinding = new ChannelReadWriteBinding( session.CurrentTransaction.PinnedServer, - session.CurrentTransaction.PinnedChannel.Fork(), - session); + session.CurrentTransaction.PinnedChannel.Fork()); } else { @@ -67,7 +65,7 @@ public static IReadWriteBindingHandle CreateReadWriteBinding(IClusterInternal cl // unpin if the next operation is not under transaction session.CurrentTransaction.UnpinAll(); } - readWriteBinding = new WritableServerBinding(cluster, session); + readWriteBinding = new WritableServerBinding(cluster); } return new ReadWriteBindingHandle(readWriteBinding); @@ -85,12 +83,11 @@ internal static IChannelSourceHandle CreateGetMoreChannelSource(IChannelSourceHa effectiveChannelSource = new ChannelChannelSource( channelSource.Server, - channel.Fork(), - channelSource.Session.Fork()); + channel.Fork()); } else { - effectiveChannelSource = new ServerChannelSource(channelSource.Server, channelSource.Session.Fork()); + effectiveChannelSource = new ServerChannelSource(channelSource.Server); } return new ChannelSourceHandle(effectiveChannelSource); @@ -99,7 +96,7 @@ internal static IChannelSourceHandle CreateGetMoreChannelSource(IChannelSourceHa internal static void PinChannellIfRequired( IChannelSourceHandle channelSource, IChannelHandle channel, - ICoreSessionHandle session) + ICoreSession session) { if (IsInLoadBalancedMode(channel.ConnectionDescription) && session.IsInTransaction && diff --git a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs index 8634d9afe6c..bcbd05c1c37 100644 --- a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs +++ b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs @@ -26,7 +26,7 @@ internal static class IClusterExtensions public static IServer SelectServerAndPinIfNeeded( this IClusterInternal cluster, OperationContext operationContext, - ICoreSessionHandle session, + ICoreSession session, IServerSelector selector, IReadOnlyCollection deprioritizedServers) { @@ -51,7 +51,7 @@ public static IServer SelectServerAndPinIfNeeded( public static async Task SelectServerAndPinIfNeededAsync( this IClusterInternal cluster, OperationContext operationContext, - ICoreSessionHandle session, + ICoreSession session, IServerSelector selector, IReadOnlyCollection deprioritizedServers) { @@ -74,7 +74,7 @@ public static async Task SelectServerAndPinIfNeededAsync( return server; } - private static void PinServerIfNeeded(ICluster cluster, ICoreSessionHandle session, IServer server) + private static void PinServerIfNeeded(ICluster cluster, ICoreSession session, IServer server) { if (cluster.Description.Type == ClusterType.Sharded && session.IsInTransaction) { @@ -82,7 +82,7 @@ private static void PinServerIfNeeded(ICluster cluster, ICoreSessionHandle sessi } } - private static IServer GetPinnedServerIfValid(ICluster cluster, ICoreSessionHandle session) + private static IServer GetPinnedServerIfValid(ICluster cluster, ICoreSession session) { if (cluster.Description.Type == ClusterType.Sharded && session.IsInTransaction diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 507c8d0adbf..8aa491ced5e 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -20,6 +20,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Events; @@ -899,7 +900,7 @@ public PooledConnection CreateOpened(TimeSpan maxConnectingQueueTimeout, Cancell throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); } - return CreateOpenedInternal(new(Timeout.InfiniteTimeSpan, cancellationToken)); + return CreateOpenedInternal(new(NoCoreSession.NewHandle(), Timeout.InfiniteTimeSpan, cancellationToken)); } catch (Exception ex) { diff --git a/src/MongoDB.Driver/Core/Misc/Feature.cs b/src/MongoDB.Driver/Core/Misc/Feature.cs index f9cce0eb4f5..59d957d8068 100644 --- a/src/MongoDB.Driver/Core/Misc/Feature.cs +++ b/src/MongoDB.Driver/Core/Misc/Feature.cs @@ -666,15 +666,13 @@ 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(null, cancellationToken); - using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - 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); - } + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session, cancellationToken: cancellationToken); + using var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster)); + 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); } /// @@ -685,15 +683,13 @@ 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(null, cancellationToken); - using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - 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); - } + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session, cancellationToken: cancellationToken); + using var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster)); + 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); } internal bool IsSupported(int wireVersion) diff --git a/src/MongoDB.Driver/Core/Misc/IDictionaryExtensions.cs b/src/MongoDB.Driver/Core/Misc/IDictionaryExtensions.cs deleted file mode 100644 index 9a99976f2d9..00000000000 --- a/src/MongoDB.Driver/Core/Misc/IDictionaryExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -/* 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.Collections.Generic; - -namespace MongoDB.Driver.Core -{ - internal static class IDictionaryExtensions - { - public static void AddRange(this IDictionary dictionary, IEnumerable> values) - { - foreach (var p in values) - { - dictionary.Add(p); - } - } - } -} diff --git a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs index d54caad6271..8b11b541461 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs @@ -312,9 +312,9 @@ public IAsyncCursor Execute(OperationContext operationContext, Retryabl var operation = CreateOperation(operationContext, context); var result = operation.Execute(operationContext, context); - context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); + operationContext.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); - return CreateCursor(context.ChannelSource, context.Channel, result); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, result); } } @@ -341,15 +341,15 @@ public async Task> ExecuteAsync(OperationContext operation var operation = CreateOperation(operationContext, context); var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); - context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); + operationContext.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); - return CreateCursor(context.ChannelSource, context.Channel, result); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, result); } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription) { - var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern); + var readConcern = ReadConcernHelper.GetReadConcernForCommand(operationContext.Session, connectionDescription, _readConcern); var command = new BsonDocument { { "aggregate", _collectionNamespace == null ? (BsonValue)1 : _collectionNamespace.CollectionName }, @@ -392,25 +392,23 @@ private ReadCommandOperation CreateOperation(OperationContext o }; } - private AsyncCursor CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, AggregateResult result) + private IAsyncCursor CreateCursor(OperationContext operationContext, IChannelSourceHandle channelSource, IChannelHandle channel, AggregateResult result) { if (result.CursorId.HasValue) { - return CreateCursorFromCursorResult(channelSource, channel, result); - } - else - { - // don't need connection pinning - return CreateCursorFromInlineResult(result); + return CreateCursorFromCursorResult(operationContext, channelSource, channel, result); } + + return new SingleBatchAsyncCursor(result.Results); } - private AsyncCursor CreateCursorFromCursorResult(IChannelSourceHandle channelSource, IChannelHandle channel, AggregateResult result) + private AsyncCursor CreateCursorFromCursorResult(OperationContext operationContext, IChannelSourceHandle channelSource, IChannelHandle channel, AggregateResult result) { var cursorId = result.CursorId.GetValueOrDefault(0); var getMoreChannelSource = ChannelPinningHelper.CreateGetMoreChannelSource(channelSource, channel, cursorId); return new AsyncCursor( getMoreChannelSource, + operationContext.Session.Fork(), result.CollectionNamespace, _comment, result.Results, @@ -426,25 +424,6 @@ private AsyncCursor CreateCursorFromCursorResult(IChannelSourceHandle c enableOverloadRetargeting: _enableOverloadRetargeting); } - private AsyncCursor CreateCursorFromInlineResult(AggregateResult result) - { - return new AsyncCursor( - null, // channelSource - CollectionNamespace, - _comment, - result.Results, - 0, // cursorId - null, // postBatchResumeToken - null, // batchSize - null, // limit - _resultSerializer, - MessageEncoderSettings, - _maxAwaitTime, - _retryRequested, - maxAdaptiveRetries: _maxAdaptiveRetries, - enableOverloadRetargeting: _enableOverloadRetargeting); - } - private void EnsureIsReadOnlyPipeline() { if (Pipeline.Any(s => { var n = s.GetElement(0).Name; return n == "$out" || n == "$merge"; })) diff --git a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs index 5fb22414afb..12a4bc3fab6 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs @@ -206,36 +206,34 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, context.MayUseSecondaryCriteria.EffectiveReadPreference, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, context.MayUseSecondaryCriteria.EffectiveReadPreference, transactionNumber); return operation.Execute(operationContext, channelBinding); } } public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, context.MayUseSecondaryCriteria.EffectiveReadPreference, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, context.MayUseSecondaryCriteria.EffectiveReadPreference, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { var readConcern = _readConcern != null - ? ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern) + ? ReadConcernHelper.GetReadConcernForCommand(operationContext.Session, connectionDescription, _readConcern) : null; - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "aggregate", _collectionNamespace == null ? (BsonValue)1 : _collectionNamespace.CollectionName }, @@ -255,9 +253,9 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation(OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, ReadPreference effectiveReadPreference, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, ReadPreference effectiveReadPreference, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); var operation = new WriteCommandOperation(_databaseNamespace, command, BsonDocumentSerializer.Instance, MessageEncoderSettings, OperationName); if (effectiveReadPreference != null) { diff --git a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs index a95d8feefe4..d46459d64a9 100644 --- a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs @@ -42,6 +42,7 @@ internal class AsyncCursor : IAsyncCursor, ICursorBatchInf private readonly int? _batchSize; private readonly CollectionNamespace _collectionNamespace; + private ICoreSessionHandle _session; private IChannelSource _channelSource; private bool _closed; private readonly BsonValue _comment; @@ -63,6 +64,7 @@ internal class AsyncCursor : IAsyncCursor, ICursorBatchInf public AsyncCursor( IChannelSource channelSource, + ICoreSessionHandle session, CollectionNamespace collectionNamespace, BsonValue comment, IReadOnlyList firstBatch, @@ -77,6 +79,7 @@ public AsyncCursor( bool enableOverloadRetargeting) : this( channelSource, + session, collectionNamespace, comment, firstBatch, @@ -95,6 +98,7 @@ public AsyncCursor( public AsyncCursor( IChannelSource channelSource, + ICoreSessionHandle session, CollectionNamespace collectionNamespace, BsonValue comment, IReadOnlyList firstBatch, @@ -111,6 +115,7 @@ public AsyncCursor( { _operationId = EventContext.OperationId; _channelSource = channelSource; + _session = Ensure.IsNotNull(session, nameof(session)); _comment = comment; _collectionNamespace = Ensure.IsNotNull(collectionNamespace, nameof(collectionNamespace)); _firstBatch = Ensure.IsNotNull(firstBatch, nameof(firstBatch)); @@ -228,15 +233,12 @@ private BsonDocument CreateKillCursorsCommand() return command; } - private CursorBatch ExecuteGetMoreCommand(IChannelHandle channel, CancellationToken cancellationToken) + private CursorBatch ExecuteGetMoreCommand(OperationContext operationContext, IChannelHandle channel) { var command = CreateGetMoreCommand(channel.ConnectionDescription); BsonDocument result; try { - // TODO: CSOT: Implement operation context support for Cursors - var operationContext = new OperationContext(null, cancellationToken); - var operation = new ReadCommandOperation( _collectionNamespace.DatabaseNamespace, command, @@ -251,8 +253,7 @@ private CursorBatch ExecuteGetMoreCommand(IChannelHandle channel, Can using var channelBinding = new ChannelReadWriteBinding( _channelSource.Server, - channel, - _channelSource.Session.Fork()); + channel); result = operation.Execute(operationContext, channelBinding); } catch (MongoCommandException ex) when (IsMongoCursorNotFoundException(ex)) @@ -263,15 +264,12 @@ private CursorBatch ExecuteGetMoreCommand(IChannelHandle channel, Can return CreateCursorBatch(result); } - private async Task> ExecuteGetMoreCommandAsync(IChannelHandle channel, CancellationToken cancellationToken) + private async Task> ExecuteGetMoreCommandAsync(OperationContext operationContext, IChannelHandle channel) { var command = CreateGetMoreCommand(channel.ConnectionDescription); BsonDocument result; try { - // TODO: CSOT: Implement operation context support for Cursors - var operationContext = new OperationContext(null, cancellationToken); - var operation = new ReadCommandOperation( _collectionNamespace.DatabaseNamespace, command, @@ -286,8 +284,7 @@ private async Task> ExecuteGetMoreCommandAsync(IChannelHa using var channelBinding = new ChannelReadWriteBinding( _channelSource.Server, - channel, - _channelSource.Session.Fork()); + channel); result = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } catch (MongoCommandException ex) when (IsMongoCursorNotFoundException(ex)) @@ -298,14 +295,11 @@ private async Task> ExecuteGetMoreCommandAsync(IChannelHa return CreateCursorBatch(result); } - private void ExecuteKillCursorsCommand(IChannelHandle channel, CancellationToken cancellationToken) + private void ExecuteKillCursorsCommand(OperationContext operationContext, IChannelHandle channel) { - // TODO: CSOT: Implement operation context support for Cursors - var operationContext = new OperationContext(null, cancellationToken); var command = CreateKillCursorsCommand(); var result = channel.Command( operationContext, - _channelSource.Session, null, // readPreference _collectionNamespace.DatabaseNamespace, command, @@ -320,14 +314,11 @@ private void ExecuteKillCursorsCommand(IChannelHandle channel, CancellationToken ThrowIfKillCursorsCommandFailed(result, channel.ConnectionDescription.ConnectionId); } - private async Task ExecuteKillCursorsCommandAsync(IChannelHandle channel, CancellationToken cancellationToken) + private async Task ExecuteKillCursorsCommandAsync(OperationContext operationContext, IChannelHandle channel) { - // TODO: CSOT: Implement operation context support for Cursors - var operationContext = new OperationContext(null, cancellationToken); var command = CreateKillCursorsCommand(); var result = await channel.CommandAsync( operationContext, - _channelSource.Session, null, // readPreference _collectionNamespace.DatabaseNamespace, command, @@ -356,11 +347,8 @@ protected virtual void Dispose(bool disposing) if (!_disposed) { CloseIfNotAlreadyClosedFromDispose(); - - if (_channelSource != null) - { - _channelSource.Dispose(); - } + _channelSource?.Dispose(); + _session?.Dispose(); _disposed = true; } } @@ -376,7 +364,8 @@ private void CloseIfNotAlreadyClosed(CancellationToken cancellationToken) { try { - KillCursors(cancellationToken); + using var operationContext = new OperationContext(_session, cancellationToken: cancellationToken); + KillCursors(operationContext); } catch { @@ -401,7 +390,8 @@ private async Task CloseIfNotAlreadyClosedAsync(CancellationToken cancellationTo { try { - await KillCursorsAsync(cancellationToken).ConfigureAwait(false); + using var operationContext = new OperationContext(_session, cancellationToken: cancellationToken); + await KillCursorsAsync(operationContext).ConfigureAwait(false); } catch { @@ -420,10 +410,7 @@ private void CloseIfNotAlreadyClosedFromDispose() { try { - using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(10))) - { - CloseIfNotAlreadyClosed(source.Token); - } + CloseIfNotAlreadyClosed(CancellationToken.None); } catch { @@ -438,27 +425,29 @@ private void DisposeChannelSourceIfNoLongerNeeded() _channelSource.Dispose(); _channelSource = null; } + + if (_session != null && _cursorId == 0) + { + _session.Dispose(); + _session = null; + } } - private CursorBatch GetNextBatch(CancellationToken cancellationToken) + private CursorBatch GetNextBatch(OperationContext operationContext) { - // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (var channel = _channelSource.GetChannel(operationContext)) { - return ExecuteGetMoreCommand(channel, cancellationToken); + return ExecuteGetMoreCommand(operationContext, channel); } } - private async Task> GetNextBatchAsync(CancellationToken cancellationToken) + private async Task> GetNextBatchAsync(OperationContext operationContext) { - // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (var channel = await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteGetMoreCommandAsync(channel, cancellationToken).ConfigureAwait(false); + return await ExecuteGetMoreCommandAsync(operationContext, channel).ConfigureAwait(false); } } @@ -467,32 +456,28 @@ private bool IsMongoCursorNotFoundException(MongoCommandException exception) return exception.Code == (int)ServerErrorCode.CursorNotFound; } - private void KillCursors(CancellationToken cancellationToken) + private void KillCursors(OperationContext operationContext) { - // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) using (var channel = _channelSource.GetChannel(operationContext.WithTimeout(TimeSpan.FromSeconds(10)))) { if (!channel.Connection.IsExpired) { - ExecuteKillCursorsCommand(channel, cancellationToken); + ExecuteKillCursorsCommand(operationContext, channel); } } } - private async Task KillCursorsAsync(CancellationToken cancellationToken) + private async Task KillCursorsAsync(OperationContext operationContext) { - // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) using (var channel = await _channelSource.GetChannelAsync(operationContext.WithTimeout(TimeSpan.FromSeconds(10))).ConfigureAwait(false)) { if (!channel.Connection.IsExpired) { - await ExecuteKillCursorsCommandAsync(channel, cancellationToken).ConfigureAwait(false); + await ExecuteKillCursorsCommandAsync(operationContext, channel).ConfigureAwait(false); } } } @@ -508,7 +493,8 @@ public bool MoveNext(CancellationToken cancellationToken) return hasMore; } - var batch = GetNextBatch(cancellationToken); + using var operationContext = new OperationContext(_session, cancellationToken: cancellationToken); + var batch = GetNextBatch(operationContext); SaveBatch(batch); return true; } @@ -524,7 +510,8 @@ public async Task MoveNextAsync(CancellationToken cancellationToken) return hasMore; } - var batch = await GetNextBatchAsync(cancellationToken).ConfigureAwait(false); + using var operationContext = new OperationContext(_session, cancellationToken: cancellationToken); + var batch = await GetNextBatchAsync(operationContext).ConfigureAwait(false); SaveBatch(batch); return true; } diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs index f43cb30a168..61c10b450ff 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs @@ -41,6 +41,7 @@ internal sealed class ChangeStreamCursor : IChangeStreamCursor _documentSerializer; private readonly BsonTimestamp _initialOperationTime; + private readonly ICoreSessionHandle _session; private BsonDocument _postBatchResumeToken; private readonly BsonDocument _initialResumeAfter; private readonly BsonDocument _initialStartAfter; @@ -58,6 +59,7 @@ internal sealed class ChangeStreamCursor : IChangeStreamCursorThe cursor. /// The document serializer. /// The binding. + /// The session. /// The change stream operation. /// The post batch resume token from an aggregate command. /// The initial operation time. @@ -69,6 +71,7 @@ public ChangeStreamCursor( IAsyncCursor cursor, IBsonSerializer documentSerializer, IReadBinding binding, + ICoreSessionHandle session, IChangeStreamOperation changeStreamOperation, BsonDocument aggregatePostBatchResumeToken, BsonTimestamp initialOperationTime, @@ -81,6 +84,7 @@ public ChangeStreamCursor( _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); _binding = Ensure.IsNotNull(binding, nameof(binding)); _changeStreamOperation = Ensure.IsNotNull(changeStreamOperation, nameof(changeStreamOperation)); + _session = Ensure.IsNotNull(session, nameof(session)); _postBatchResumeToken = aggregatePostBatchResumeToken; _initialOperationTime = initialOperationTime; @@ -99,6 +103,7 @@ public void Dispose() _disposed = true; _cursor.Dispose(); _binding.Dispose(); + _session.Dispose(); } } @@ -262,7 +267,7 @@ private IAsyncCursor Resume(CancellationToken cancellationToken { ReconfigureOperationResumeValues(); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(_session, null, cancellationToken); return _changeStreamOperation.Resume(operationContext, _binding); } @@ -270,7 +275,7 @@ private async Task> ResumeAsync(CancellationToken { ReconfigureOperationResumeValues(); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(_session, null, cancellationToken); return await _changeStreamOperation.ResumeAsync(operationContext, _binding).ConfigureAwait(false); } diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs index f40e4faa45d..021f796e239 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs @@ -287,7 +287,7 @@ public IChangeStreamCursor Execute(OperationContext operationContext, I { cursor = ExecuteAggregateOperation(operationContext, context); cursorBatchInfo = (ICursorBatchInfo)cursor; - initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); + initialOperationTime = GetInitialOperationTimeIfRequired(operationContext, context, cursorBatchInfo); var postBatchResumeToken = GetInitialPostBatchResumeTokenIfRequired(cursorBatchInfo); @@ -295,6 +295,7 @@ public IChangeStreamCursor Execute(OperationContext operationContext, I cursor, _resultSerializer, bindingHandle.Fork(), + operationContext.Session.Fork(), this, postBatchResumeToken, initialOperationTime, @@ -322,7 +323,7 @@ public async Task> ExecuteAsync(OperationContext op { cursor = await ExecuteAggregateOperationAsync(operationContext, context).ConfigureAwait(false); cursorBatchInfo = (ICursorBatchInfo)cursor; - initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); + initialOperationTime = GetInitialOperationTimeIfRequired(operationContext, context, cursorBatchInfo); var postBatchResumeToken = GetInitialPostBatchResumeTokenIfRequired(cursorBatchInfo); @@ -330,6 +331,7 @@ public async Task> ExecuteAsync(OperationContext op cursor, _resultSerializer, bindingHandle.Fork(), + operationContext.Session.Fork(), this, postBatchResumeToken, initialOperationTime, @@ -435,7 +437,7 @@ private BsonDocument GetInitialPostBatchResumeTokenIfRequired(ICursorBatchInfo c return cursorBatchInfo.WasFirstBatchEmpty ? cursorBatchInfo.PostBatchResumeToken : null; } - private BsonTimestamp GetInitialOperationTimeIfRequired(RetryableReadContext context, ICursorBatchInfo cursorBatchInfo) + private BsonTimestamp GetInitialOperationTimeIfRequired(OperationContext operationContext, RetryableReadContext context, ICursorBatchInfo cursorBatchInfo) { if (_startAtOperationTime == null && _resumeAfter == null && _startAfter == null) { @@ -444,7 +446,7 @@ private BsonTimestamp GetInitialOperationTimeIfRequired(RetryableReadContext con { if (cursorBatchInfo.PostBatchResumeToken == null && cursorBatchInfo.WasFirstBatchEmpty) { - return context.Binding.Session.OperationTime; + return operationContext.Session.OperationTime; } } } diff --git a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs index f0a60072608..846aa18ac95 100644 --- a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs @@ -58,9 +58,9 @@ public ClientBulkWriteOperation( public override string OperationName => "bulkWrite"; - protected override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, long? transactionNumber) + protected override BsonDocument CreateCommand(OperationContext operationContext, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "bulkWrite", 1 }, @@ -121,7 +121,7 @@ protected override IEnumerable CreateCommandPayl if (serverResponse != null) { PopulateBulkWriteResponse(serverResponse, bulkWriteResults); - using var individualResults = GetIndividualResultsCursor(context, serverResponse); + using var individualResults = GetIndividualResultsCursor(operationContext, context, serverResponse); if (individualResults != null && bulkWriteResults.TopLevelException == null) { try @@ -179,7 +179,7 @@ protected override IEnumerable CreateCommandPayl if (serverResponse != null) { PopulateBulkWriteResponse(serverResponse, bulkWriteResults); - using var individualResults = GetIndividualResultsCursor(context, serverResponse); + using var individualResults = GetIndividualResultsCursor(operationContext, context, serverResponse); if (individualResults != null && bulkWriteResults.TopLevelException == null) { try @@ -270,7 +270,7 @@ private ClientBulkWriteResult ToFinalResultsOrThrow(ConnectionId connectionId, B return result; } - private IAsyncCursor GetIndividualResultsCursor(RetryableWriteContext context, BsonDocument bulkWriteResponse) + private IAsyncCursor GetIndividualResultsCursor(OperationContext operationContext, RetryableWriteContext context, BsonDocument bulkWriteResponse) { if (!bulkWriteResponse.TryGetElement("cursor", out var cursorElement)) { @@ -280,6 +280,7 @@ private IAsyncCursor GetIndividualResultsCursor(RetryableWriteCont var cursorDocument = cursorElement.Value.AsBsonDocument; return new AsyncCursor( context.ChannelSource, + operationContext.Session.Fork(), CollectionNamespace.FromFullName(cursorDocument["ns"].AsString), null, cursorDocument["firstBatch"].AsBsonArray.Cast().ToList(), diff --git a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs index 39f2afc8606..35111445036 100644 --- a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs @@ -75,13 +75,12 @@ public IBsonSerializer ResultSerializer get { return _resultSerializer; } } - protected TCommandResult ExecuteProtocol(OperationContext operationContext, IChannelHandle channel, ICoreSessionHandle session, ReadPreference readPreference, BsonDocument command) + protected TCommandResult ExecuteProtocol(OperationContext operationContext, IChannelHandle channel, ReadPreference readPreference, BsonDocument command) { var additionalOptions = GetEffectiveAdditionalOptions(); return channel.Command( operationContext, - session, readPreference, _databaseNamespace, command, @@ -97,23 +96,21 @@ protected TCommandResult ExecuteProtocol(OperationContext operationContext, ICha protected TCommandResult ExecuteProtocol( OperationContext operationContext, IChannelSource channelSource, - ICoreSessionHandle session, ReadPreference readPreference, BsonDocument command) { using (var channel = channelSource.GetChannel(operationContext)) { - return ExecuteProtocol(operationContext, channel, session, readPreference, command); + return ExecuteProtocol(operationContext, channel, readPreference, command); } } - protected Task ExecuteProtocolAsync(OperationContext operationContext, IChannelHandle channel, ICoreSessionHandle session, ReadPreference readPreference, BsonDocument command) + protected Task ExecuteProtocolAsync(OperationContext operationContext, IChannelHandle channel, ReadPreference readPreference, BsonDocument command) { var additionalOptions = GetEffectiveAdditionalOptions(); return channel.CommandAsync( operationContext, - session, readPreference, _databaseNamespace, command, @@ -129,13 +126,12 @@ protected Task ExecuteProtocolAsync(OperationContext operationCo protected async Task ExecuteProtocolAsync( OperationContext operationContext, IChannelSource channelSource, - ICoreSessionHandle session, ReadPreference readPreference, BsonDocument command) { using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(operationContext, channel, session, readPreference, command).ConfigureAwait(false); + return await ExecuteProtocolAsync(operationContext, channel, readPreference, command).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CountOperation.cs b/src/MongoDB.Driver/Core/Operations/CountOperation.cs index edf42f23d73..a74d182acfd 100644 --- a/src/MongoDB.Driver/Core/Operations/CountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountOperation.cs @@ -127,9 +127,9 @@ public long? Skip set { _skip = value; } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription) { - var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern); + var readConcern = ReadConcernHelper.GetReadConcernForCommand(operationContext.Session, connectionDescription, _readConcern); return new BsonDocument { { "count", _collectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs index 7b666dc369d..44f2a456da4 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs @@ -238,9 +238,9 @@ public BsonDocument ClusteredIndex set => _clusteredIndex = value; } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "create", _collectionNamespace.CollectionName }, @@ -297,37 +297,35 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; EnsureServerIsValid(channel.ConnectionDescription.MaxWireVersion); - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; EnsureServerIsValid(channel.ConnectionDescription.MaxWireVersion); - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation("create"); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings, OperationName); } diff --git a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs index 404a2fbe9a7..982bef00b11 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs @@ -145,34 +145,32 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { var maxWireVersion = connectionDescription.MaxWireVersion; - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); if (_commitQuorum != null) { Feature.CreateIndexCommitQuorum.ThrowIfNotSupported(maxWireVersion); @@ -191,10 +189,10 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess private EventContext.OperationIdDisposer BeginOperation() => EventContext.BeginOperation(null, OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { var databaseNamespace = _collectionNamespace.DatabaseNamespace; - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); var resultSerializer = BsonDocumentSerializer.Instance; return new WriteCommandOperation(databaseNamespace, command, resultSerializer, _messageEncoderSettings, OperationName); } diff --git a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs index ee391ef538e..68102ee8529 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs @@ -127,31 +127,29 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { return new BsonDocument { @@ -163,9 +161,9 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess // private methods private IDisposable BeginOperation() => EventContext.BeginOperation("createSearchIndexes"); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs index 0a93511f425..1f45cf6efd0 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs @@ -147,33 +147,31 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "create", _viewName }, @@ -186,9 +184,9 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess private IDisposable BeginOperation() => EventContext.BeginOperation("create"); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); } } diff --git a/src/MongoDB.Driver/Core/Operations/DelayedEvaluationWriteConcernSerializer.cs b/src/MongoDB.Driver/Core/Operations/DelayedEvaluationWriteConcernSerializer.cs deleted file mode 100644 index 237fb1988b7..00000000000 --- a/src/MongoDB.Driver/Core/Operations/DelayedEvaluationWriteConcernSerializer.cs +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright 2017-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 MongoDB.Bson.Serialization; -using MongoDB.Bson.Serialization.Serializers; - -namespace MongoDB.Driver.Core.Operations -{ - internal class DelayedEvaluationWriteConcernSerializer : SealedClassSerializerBase> - { - // protected methods - protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, Func value) - { - var writeConcern = value(); - var writeConcernDocument = writeConcern.ToBsonDocument(); - BsonDocumentSerializer.Instance.Serialize(context, args, writeConcernDocument); - } - } -} diff --git a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs index 7216a058e52..db5a55d2fbe 100644 --- a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs @@ -132,7 +132,7 @@ public IAsyncCursor Execute(OperationContext operationContext, IReadBind var operation = CreateOperation(operationContext); var result = operation.Execute(operationContext, context); - binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); + operationContext.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); return new SingleBatchAsyncCursor(result.Values); } @@ -148,15 +148,15 @@ public async Task> ExecuteAsync(OperationContext operationC var operation = CreateOperation(operationContext); var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); - binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); + operationContext.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); return new SingleBatchAsyncCursor(result.Values); } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription) { - var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern); + var readConcern = ReadConcernHelper.GetReadConcernForCommand(operationContext.Session, connectionDescription, _readConcern); return new BsonDocument { { "distinct", _collectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs index da9792744c3..30ac0fac6b3 100644 --- a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs @@ -156,13 +156,12 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); BsonDocument result; try { @@ -182,13 +181,12 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); BsonDocument result; try { @@ -206,9 +204,9 @@ public async Task ExecuteAttemptAsync(OperationContext operationCo } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "drop", _collectionNamespace.CollectionName }, @@ -218,9 +216,9 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation("drop"); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings, OperationName); } diff --git a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs index fd91b4438d9..9edac09ac73 100644 --- a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -80,9 +79,9 @@ public bool RetryRequested set { _retryRequested = value; } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "dropDatabase", 1 }, @@ -124,35 +123,33 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation(OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings, OperationName); } } diff --git a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs index 07146685c77..179e317678c 100644 --- a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs @@ -110,9 +110,9 @@ public TimeSpan? MaxTime set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "dropIndexes", _collectionNamespace.CollectionName }, @@ -157,13 +157,12 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); BsonDocument result; try { @@ -183,13 +182,12 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); BsonDocument result; try { @@ -209,9 +207,9 @@ public async Task ExecuteAttemptAsync(OperationContext operationCo private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation(OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings, OperationName); } diff --git a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs index 5564ee5b014..f3051201e79 100644 --- a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs @@ -125,13 +125,12 @@ public Task ExecuteAsync(OperationContext operationContext, Retrya public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); try { return operation.Execute(operationContext, channelBinding); @@ -145,13 +144,12 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); try { return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); @@ -163,7 +161,7 @@ public async Task ExecuteAttemptAsync(OperationContext operationCo } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { return new BsonDocument { @@ -174,9 +172,9 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess private IDisposable BeginOperation() => EventContext.BeginOperation(OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); } diff --git a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs index 28712942f54..12ef135e7a0 100644 --- a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs @@ -70,7 +70,7 @@ public virtual BsonDocument ExecuteAttempt(OperationContext operationContext, Re var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, context.Binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { var operation = CreateWriteOperation(operationContext, GetEffectiveWriteConcern(operationContext, attempt)); return operation.Execute(operationContext, channelBinding); @@ -82,14 +82,14 @@ public virtual async Task ExecuteAttemptAsync(OperationContext ope var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, context.Binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { var operation = CreateWriteOperation(operationContext, GetEffectiveWriteConcern(operationContext, attempt)); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } - internal virtual void OnRetry(RetryableWriteContext context, Exception exception) + internal virtual void OnRetry(OperationContext operationContext, RetryableWriteContext context, Exception exception) { if (context.Binding is EndTransactionReadWriteBinding endTransactionBinding) { @@ -139,10 +139,10 @@ public AbortTransactionOperation(WriteConcern writeConcern) protected override string CommandName => "abortTransaction"; - internal override void OnRetry(RetryableWriteContext context, Exception exception) + internal override void OnRetry(OperationContext operationContext, RetryableWriteContext context, Exception exception) { - context.Binding.Session.CurrentTransaction?.UnpinAll(); - base.OnRetry(context, exception); + operationContext.Session.CurrentTransaction?.UnpinAll(); + base.OnRetry(operationContext, context, exception); } } @@ -175,16 +175,16 @@ public TimeSpan? MaxCommitTime protected override string CommandName => "commitTransaction"; - internal override void OnRetry(RetryableWriteContext context, Exception exception) + internal override void OnRetry(OperationContext operationContext, RetryableWriteContext context, Exception exception) { - TransactionHelper.UnpinServerIfNeededOnRetryableCommitException(context.Binding.Session.CurrentTransaction, exception); + TransactionHelper.UnpinServerIfNeededOnRetryableCommitException(operationContext.Session.CurrentTransaction, exception); if (!RetryabilityHelper.IsSystemOverloadedException(exception)) { RequiresMajorityWriteConcern = true; } - base.OnRetry(context, exception); + base.OnRetry(operationContext, context, exception); } public override BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) diff --git a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs index 4f76c0fc53d..e20bf8bca2c 100644 --- a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; @@ -136,13 +135,12 @@ public Task ExecuteAsync(OperationContext operationContext, RetryableWr public TResult ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { - var binding = context.Binding; var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); using (var rawBsonDocument = operation.Execute(operationContext, channelBinding)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); @@ -156,9 +154,9 @@ public async Task ExecuteAttemptAsync(OperationContext operationContext var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); using (var rawBsonDocument = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); @@ -166,15 +164,15 @@ public async Task ExecuteAttemptAsync(OperationContext operationContext } } - public abstract BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber); + public abstract BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber); protected abstract IElementNameValidator GetCommandValidator(); private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation(OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, RawBsonDocumentSerializer.Instance, _messageEncoderSettings, OperationName) { CommandValidator = GetCommandValidator() diff --git a/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs index 7af4bc6b05b..dd276deea8f 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs @@ -17,7 +17,6 @@ using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; @@ -74,7 +73,7 @@ public BsonDocument Sort set { _sort = value; } } - public override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + public override BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { var wireVersion = connectionDescription.MaxWireVersion; FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion); @@ -87,7 +86,7 @@ public override BsonDocument CreateCommand(OperationContext operationContext, IC } } - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "findAndModify", CollectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs index 6ddb3a9df04..954d58ea083 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs @@ -17,7 +17,6 @@ using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; @@ -103,7 +102,7 @@ public BsonDocument Sort set { _sort = value; } } - public override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + public override BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { var wireVersion = connectionDescription.MaxWireVersion; FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion); @@ -116,7 +115,7 @@ public override BsonDocument CreateCommand(OperationContext operationContext, IC } } - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "findAndModify", CollectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs index 7c4281b74f6..0c6a2ff14b7 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs @@ -18,7 +18,6 @@ using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Operations.ElementNameValidators; @@ -112,7 +111,7 @@ public BsonValue Update get { return _update; } } - public override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + public override BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { var wireVersion = connectionDescription.MaxWireVersion; FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion); @@ -125,7 +124,7 @@ public override BsonDocument CreateCommand(OperationContext operationContext, IC } } - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "findAndModify", CollectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/FindOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOperation.cs index 9255b10ce2b..dd96e66ac9e 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOperation.cs @@ -255,7 +255,7 @@ public BsonDocument Sort set { _sort = value; } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription) { var wireVersion = connectionDescription.MaxWireVersion; FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion); @@ -268,7 +268,7 @@ public BsonDocument CreateCommand(OperationContext operationContext, ICoreSessio } var isShardRouter = connectionDescription.HelloResult.ServerType == ServerType.ShardRouter; - var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern); + var readConcern = ReadConcernHelper.GetReadConcernForCommand(operationContext.Session, connectionDescription, _readConcern); return new BsonDocument { { "find", _collectionNamespace.CollectionName }, @@ -315,9 +315,9 @@ public IAsyncCursor Execute(OperationContext operationContext, Retrya using (EventContext.BeginFind(_batchSize, _limit)) { - var operation = CreateOperation(operationContext); + var operation = CreateOperation(); var commandResult = operation.Execute(operationContext, context); - return CreateCursor(context.ChannelSource, context.Channel, commandResult); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, commandResult); } } @@ -338,13 +338,13 @@ public async Task> ExecuteAsync(OperationContext operati using (EventContext.BeginFind(_batchSize, _limit)) { - var operation = CreateOperation(operationContext); + var operation = CreateOperation(); var commandResult = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); - return CreateCursor(context.ChannelSource, context.Channel, commandResult); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, commandResult); } } - private AsyncCursor CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult) + private AsyncCursor CreateCursor(OperationContext operationContext, IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult) { var cursorDocument = commandResult["cursor"].AsBsonDocument; var collectionNamespace = CollectionNamespace.FromFullName(cursorDocument["ns"].AsString); @@ -353,11 +353,12 @@ private AsyncCursor CreateCursor(IChannelSourceHandle channelSource, if (cursorDocument.TryGetValue("atClusterTime", out var atClusterTime)) { - channelSource.Session.SetSnapshotTimeIfNeeded(atClusterTime.AsBsonTimestamp); + operationContext.Session.SetSnapshotTimeIfNeeded(atClusterTime.AsBsonTimestamp); } return new AsyncCursor( getMoreChannelSource, + operationContext.Session.Fork(), collectionNamespace, _comment, firstBatch.Documents, @@ -386,7 +387,7 @@ private CursorBatch CreateFirstCursorBatch(BsonDocument cursorDocumen private EventContext.OperationIdDisposer BeginOperation() => EventContext.BeginOperation(null, OperationName); - private ReadCommandOperation CreateOperation(OperationContext operationContext) + private ReadCommandOperation CreateOperation() { var operation = new ReadCommandOperation( _collectionNamespace.DatabaseNamespace, diff --git a/src/MongoDB.Driver/Core/Operations/ICommandCreator.cs b/src/MongoDB.Driver/Core/Operations/ICommandCreator.cs index 44e541893fc..a2241858849 100644 --- a/src/MongoDB.Driver/Core/Operations/ICommandCreator.cs +++ b/src/MongoDB.Driver/Core/Operations/ICommandCreator.cs @@ -14,7 +14,6 @@ */ using MongoDB.Bson; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; namespace MongoDB.Driver.Core.Operations @@ -28,12 +27,10 @@ internal interface ICommandCreator /// Creates a command to be executed. /// /// The operation context. - /// The session. /// The connection description. /// The command document. BsonDocument CreateCommand( OperationContext operationContext, - ICoreSession session, ConnectionDescription connectionDescription); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs index 9473d9e161d..4e6202346ee 100644 --- a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Linq; using System.Threading.Tasks; using MongoDB.Bson; @@ -129,7 +128,7 @@ public IAsyncCursor Execute(OperationContext operationContext, Ret { var operation = CreateOperation(); var result = operation.Execute(operationContext, context); - return CreateCursor(context.ChannelSource, context.Channel, result); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, result); } } @@ -154,7 +153,7 @@ public async Task> ExecuteAsync(OperationContext oper { var operation = CreateOperation(); var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); - return CreateCursor(context.ChannelSource, context.Channel, result); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, result); } } @@ -179,13 +178,14 @@ private ReadCommandOperation CreateOperation() }; } - private IAsyncCursor CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument result) + private IAsyncCursor CreateCursor(OperationContext operationContext, IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument result) { var cursorDocument = result["cursor"].AsBsonDocument; var cursorId = cursorDocument["id"].ToInt64(); var getMoreChannelSource = ChannelPinningHelper.CreateGetMoreChannelSource(channelSource, channel, cursorId); var cursor = new AsyncCursor( getMoreChannelSource, + operationContext.Session.Fork(), CollectionNamespace.FromFullName(cursorDocument["ns"].AsString), _comment, cursorDocument["firstBatch"].AsBsonArray.OfType().ToList(), diff --git a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs index 70ade357305..5134aac479c 100644 --- a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Linq; using System.Threading.Tasks; using MongoDB.Bson; diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs index a0494cfe2e4..788fa865291 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs index d94273e80f9..c1c75a3522b 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs @@ -107,7 +107,7 @@ public IAsyncCursor Execute(OperationContext operationContext, Ret try { var result = operation.Execute(operationContext, context); - return CreateCursor(context.ChannelSource, context.Channel, result); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) { @@ -136,7 +136,7 @@ public async Task> ExecuteAsync(OperationContext oper try { var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); - return CreateCursor(context.ChannelSource, context.Channel, result); + return CreateCursor(operationContext, context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) { @@ -162,13 +162,14 @@ private ReadCommandOperation CreateOperation() }; } - private IAsyncCursor CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument result) + private IAsyncCursor CreateCursor(OperationContext operationContext, IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument result) { var cursorDocument = result["cursor"].AsBsonDocument; var cursorId = cursorDocument["id"].ToInt64(); var getMoreChannelSource = ChannelPinningHelper.CreateGetMoreChannelSource(channelSource, channel, cursorId); var cursor = new AsyncCursor( getMoreChannelSource, + operationContext.Session.Fork(), CollectionNamespace.FromFullName(cursorDocument["ns"].AsString), _comment, cursorDocument["firstBatch"].AsBsonArray.OfType().ToList(), diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs index 21544cbf9d2..a6b013f8924 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs @@ -98,9 +98,9 @@ public IAsyncCursor Execute(OperationContext operationContext, IReadBin 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())) + using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription); + var operation = CreateOperation(operationContext, channel.ConnectionDescription); var result = operation.Execute(operationContext, channelBinding); return new SingleBatchAsyncCursor(result); } @@ -113,20 +113,20 @@ public async Task> ExecuteAsync(OperationContext operation 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())) + using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription); + var operation = CreateOperation(operationContext, channel.ConnectionDescription); var result = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); return new SingleBatchAsyncCursor(result); } } /// - protected internal override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber = null) + protected internal override BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber = null) { - var command = base.CreateCommand(operationContext, session, connectionDescription); + var command = base.CreateCommand(operationContext, connectionDescription); - var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern); + var readConcern = ReadConcernHelper.GetReadConcernForCommand(operationContext.Session, connectionDescription, _readConcern); if (readConcern != null) { command.Add("readConcern", readConcern); @@ -135,9 +135,9 @@ protected internal override BsonDocument CreateCommand(OperationContext operatio return command; } - private ReadCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription) + private ReadCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription) { - var command = CreateCommand(operationContext, session, connectionDescription); + var command = CreateCommand(operationContext, connectionDescription); var resultArraySerializer = new ArraySerializer(_resultSerializer); var resultSerializer = new ElementDeserializer("results", resultArraySerializer); return new ReadCommandOperation(CollectionNamespace.DatabaseNamespace, command, resultSerializer, MessageEncoderSettings, OperationName) diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs index 864d1c9fe75..5fcdb9d9826 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs @@ -15,7 +15,6 @@ using System; using MongoDB.Bson; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; @@ -221,7 +220,7 @@ public bool? Verbose } // methods - protected internal virtual BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber = null) + protected internal virtual BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber = null) { return new BsonDocument { diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs index c980c7ac140..92654b46412 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs @@ -183,15 +183,15 @@ public WriteConcern WriteConcern // methods /// - protected internal override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber = null) + protected internal override BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber = null) { - var command = base.CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = base.CreateCommand(operationContext, connectionDescription, transactionNumber); if (_bypassDocumentValidation.HasValue) { command.Add("bypassDocumentValidation", _bypassDocumentValidation.Value); } - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); if (writeConcern != null) { command.Add("writeConcern", writeConcern.ToBsonDocument()); @@ -255,9 +255,9 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } @@ -269,18 +269,18 @@ public async Task ExecuteAttemptAsync(OperationContext operationCo var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } private IDisposable BeginOperation() => EventContext.BeginOperation("mapReduce"); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(CollectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, MessageEncoderSettings, OperationName); } } diff --git a/src/MongoDB.Driver/Core/Operations/QueryHelper.cs b/src/MongoDB.Driver/Core/Operations/QueryHelper.cs index a0c894840c2..fffd1adea12 100644 --- a/src/MongoDB.Driver/Core/Operations/QueryHelper.cs +++ b/src/MongoDB.Driver/Core/Operations/QueryHelper.cs @@ -22,36 +22,6 @@ namespace MongoDB.Driver.Core.Operations { internal static class QueryHelper { - public static int CalculateFirstBatchSize(int? limit, int? batchSize) - { - int firstBatchSize; - - int nonNullLimit = limit ?? 0; - int nonNullBatchSize = batchSize ?? 0; - if (nonNullLimit < 0) - { - firstBatchSize = nonNullLimit; - } - else if (nonNullLimit == 0) - { - firstBatchSize = nonNullBatchSize; - } - else if (nonNullBatchSize == 0) - { - firstBatchSize = nonNullLimit; - } - else if (nonNullLimit < nonNullBatchSize) - { - firstBatchSize = nonNullLimit; - } - else - { - firstBatchSize = nonNullBatchSize; - } - - return firstBatchSize; - } - public static BsonDocument CreateReadPreferenceDocument(ServerType serverType, ReadPreference readPreference, out bool secondaryOk) { secondaryOk = readPreference != null && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary; diff --git a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs index 0fb9a9e085f..090e1ff53a5 100644 --- a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs @@ -123,19 +123,19 @@ public async Task ExecuteAsync(OperationContext operationContext public TCommandResult ExecuteAttempt(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber) { var command = _commandCreator != null - ? _commandCreator.CreateCommand(operationContext, context.Binding.Session, context.Channel.ConnectionDescription) + ? _commandCreator.CreateCommand(operationContext, context.Channel.ConnectionDescription) : _command; - return ExecuteProtocol(operationContext, context.Channel, context.Binding.Session, context.Binding.ReadPreference, command); + return ExecuteProtocol(operationContext, context.Channel, context.Binding.ReadPreference, command); } public Task ExecuteAttemptAsync(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber) { var command = _commandCreator != null - ? _commandCreator.CreateCommand(operationContext, context.Binding.Session, context.Channel.ConnectionDescription) + ? _commandCreator.CreateCommand(operationContext, context.Channel.ConnectionDescription) : _command; - return ExecuteProtocolAsync(operationContext, context.Channel, context.Binding.Session, context.Binding.ReadPreference, command); + return ExecuteProtocolAsync(operationContext, context.Channel, context.Binding.ReadPreference, command); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs index 0b16121bdd2..0a59d699a26 100644 --- a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs @@ -95,9 +95,9 @@ public bool RetryRequested set { _retryRequested = value; } } - public BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + public BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, _writeConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, _writeConcern); return new BsonDocument { { "renameCollection", _collectionNamespace.FullName }, @@ -145,9 +145,9 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } @@ -158,18 +158,18 @@ public async Task ExecuteAttemptAsync(OperationContext operationCo var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } private EventContext.OperationNameDisposer BeginOperation() => EventContext.BeginOperation(OperationName); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableDeleteCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/RetryableDeleteCommandOperation.cs index 2ee8aa9fb4d..b7122905ea3 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableDeleteCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableDeleteCommandOperation.cs @@ -62,7 +62,7 @@ public BatchableSource Deletes get { return _deletes; } } - protected override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, long? transactionNumber) + protected override BsonDocument CreateCommand(OperationContext operationContext, long? transactionNumber) { if (WriteConcern != null && !WriteConcern.IsAcknowledged) { @@ -72,7 +72,7 @@ protected override BsonDocument CreateCommand(OperationContext operationContext, } } - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "delete", _collectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/RetryableInsertCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/RetryableInsertCommandOperation.cs index 15973a027c5..7274971690a 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableInsertCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableInsertCommandOperation.cs @@ -68,9 +68,9 @@ public IBsonSerializer DocumentSerializer get { return _documentSerializer; } } - protected override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, long? transactionNumber) + protected override BsonDocument CreateCommand(OperationContext operationContext, long? transactionNumber) { - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "insert", _collectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs index 76abed61341..f9fc7484d1d 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs @@ -108,7 +108,7 @@ public void AcquireChannel(OperationContext operationContext) } operationContext.ThrowIfTimedOutOrCanceled(); ReplaceChannel(ChannelSource.GetChannel(operationContext)); - ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, Binding.Session); + ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, operationContext.Session); } catch { @@ -127,7 +127,7 @@ public async Task AcquireChannelAsync(OperationContext operationContext) } operationContext.ThrowIfTimedOutOrCanceled(); ReplaceChannel(await ChannelSource.GetChannelAsync(operationContext).ConfigureAwait(false)); - ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, Binding.Session); + ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, operationContext.Session); } catch { diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs index 64d9c581d0a..2f5557f4d41 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs @@ -45,10 +45,10 @@ public static TResult Execute(OperationContext operationContext, IRetry var operationResult = operation.ExecuteAttempt(operationContext, context, totalAttempts, transactionNumber: null); - if (context.Binding.Session.Id != null && - context.Binding.Session.IsInTransaction) + if (operationContext.Session.Id != null && + operationContext.Session.IsInTransaction) { - context.Binding.Session.CurrentTransaction.HasCompletedCommand = true; + operationContext.Session.CurrentTransaction.HasCompletedCommand = true; } return operationResult; @@ -96,10 +96,10 @@ public static async Task ExecuteAsync(OperationContext operati var operationResult = await operation.ExecuteAttemptAsync(operationContext, context, totalAttempts, transactionNumber: null).ConfigureAwait(false); - if (context.Binding.Session.Id != null && - context.Binding.Session.IsInTransaction) + if (operationContext.Session.Id != null && + operationContext.Session.IsInTransaction) { - context.Binding.Session.CurrentTransaction.HasCompletedCommand = true; + operationContext.Session.CurrentTransaction.HasCompletedCommand = true; } return operationResult; @@ -121,7 +121,8 @@ public static async Task ExecuteAsync(OperationContext operati } // private static methods - private static bool ShouldRetry(OperationContext operationContext, + private static bool ShouldRetry( + OperationContext operationContext, RetryableReadContext context, bool isOperationRetryable, Exception exception, @@ -144,7 +145,7 @@ private static bool ShouldRetry(OperationContext operationContext, var isRetryableException = RetryabilityHelper.IsRetryableException(exception); var isSystemOverloadedException = RetryabilityHelper.IsSystemOverloadedException(exception); - var isRetryableRead = isOperationRetryable && !context.Binding.Session.IsInTransaction && isRetryableReadException; + var isRetryableRead = isOperationRetryable && !operationContext.Session.IsInTransaction && isRetryableReadException; var isBackpressureRetry = isSystemOverloadedException && isRetryableException; @@ -157,9 +158,9 @@ private static bool ShouldRetry(OperationContext operationContext, if (isSystemOverloadedException) { // If the first command in a transaction was rejected due to overload, reset to Starting so the retry re-sends startTransaction:true. - if (context.Binding.Session.Id != null - && context.Binding.Session.IsInTransaction - && context.Binding.Session.CurrentTransaction is { HasCompletedCommand: false } currentTransaction) + if (operationContext.Session.Id != null + && operationContext.Session.IsInTransaction + && operationContext.Session.CurrentTransaction is { HasCompletedCommand: false } currentTransaction) { currentTransaction.ResetState(); } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableUpdateCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/RetryableUpdateCommandOperation.cs index 40f25de3b03..3831654c874 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableUpdateCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableUpdateCommandOperation.cs @@ -69,7 +69,7 @@ public BatchableSource Updates get { return _updates; } } - protected override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, long? transactionNumber) + protected override BsonDocument CreateCommand(OperationContext operationContext, long? transactionNumber) { if (WriteConcern != null && !WriteConcern.IsAcknowledged) { @@ -79,7 +79,7 @@ protected override BsonDocument CreateCommand(OperationContext operationContext, } } - var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, WriteConcern); + var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, WriteConcern); return new BsonDocument { { "update", _collectionNamespace.CollectionName }, diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs index c44b7af7cb5..2e44e7190dd 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs @@ -140,7 +140,6 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW var args = GetCommandArgs(operationContext, context, attempt, transactionNumber); return context.Channel.Command( operationContext, - context.ChannelSource.Session, ReadPreference.Primary, _databaseNamespace, args.Command, @@ -158,7 +157,6 @@ public Task ExecuteAttemptAsync(OperationContext operationContext, var args = GetCommandArgs(operationContext, context, attempt, transactionNumber); return context.Channel.CommandAsync( operationContext, - context.ChannelSource.Session, ReadPreference.Primary, _databaseNamespace, args.Command, @@ -171,7 +169,7 @@ public Task ExecuteAttemptAsync(OperationContext operationContext, args.MessageEncoderSettings); } - protected abstract BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, long? transactionNumber); + protected abstract BsonDocument CreateCommand(OperationContext operationContext, long? transactionNumber); protected abstract IEnumerable CreateCommandPayloads(IChannelHandle channel, int attempt); @@ -187,7 +185,7 @@ private MessageEncoderSettings CreateMessageEncoderSettings(IChannelHandle chann private CommandArgs GetCommandArgs(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { var args = new CommandArgs(); - args.Command = CreateCommand(operationContext, context.Binding.Session, transactionNumber); + args.Command = CreateCommand(operationContext, transactionNumber); args.CommandPayloads = CreateCommandPayloads(context.Channel, attempt).ToList(); args.PostWriteAction = GetPostWriteAction(args.CommandPayloads); args.ResponseHandling = GetResponseHandling(); diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs index 4bcdb7034f0..c1069a6a2cd 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs @@ -114,7 +114,7 @@ public void AcquireChannel(OperationContext operationContext) } operationContext.ThrowIfTimedOutOrCanceled(); ReplaceChannel(ChannelSource.GetChannel(operationContext)); - ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, Binding.Session); + ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, operationContext.Session); } catch { @@ -133,7 +133,7 @@ public async Task AcquireChannelAsync(OperationContext operationContext) } operationContext.ThrowIfTimedOutOrCanceled(); ReplaceChannel(await ChannelSource.GetChannelAsync(operationContext).ConfigureAwait(false)); - ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, Binding.Session); + ChannelPinningHelper.PinChannellIfRequired(ChannelSource, Channel, operationContext.Session); } catch { diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs index fa6e38c5994..77734be69c2 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs @@ -54,16 +54,16 @@ public static TResult Execute(OperationContext operationContext, IRetry server = context.SelectServer(operationContext, deprioritizedServers); context.AcquireChannel(operationContext); - transactionNumber ??= AreRetriesAllowed(operation.WriteConcern, operation.IsOperationRetryable, context, context.ChannelSource.ServerDescription) ? context.Binding.Session.AdvanceTransactionNumber() : null; + transactionNumber ??= AreRetriesAllowed(operationContext, operation.WriteConcern, operation.IsOperationRetryable, context, context.ChannelSource.ServerDescription) ? operationContext.Session.AdvanceTransactionNumber() : null; operationExecutionAttempts++; var operationResult = operation.ExecuteAttempt(operationContext, context, operationExecutionAttempts, transactionNumber); - if (context.Binding.Session.Id != null && - context.Binding.Session.IsInTransaction) + if (operationContext.Session.Id != null && + operationContext.Session.IsInTransaction) { - context.Binding.Session.CurrentTransaction.HasCompletedCommand = true; + operationContext.Session.CurrentTransaction.HasCompletedCommand = true; } return operationResult; @@ -84,7 +84,7 @@ public static TResult Execute(OperationContext operationContext, IRetry if (operation is EndTransactionOperation endTransactionOperation) { - endTransactionOperation.OnRetry(context, ex); + endTransactionOperation.OnRetry(operationContext, context, ex); } // We bail early if the backoff would exceed the CSOT deadline. @@ -128,14 +128,14 @@ public static async Task ExecuteAsync(OperationContext operati await context.AcquireChannelAsync(operationContext).ConfigureAwait(false); operationExecutionAttempts++; - transactionNumber ??= AreRetriesAllowed(operation.WriteConcern, operation.IsOperationRetryable, context, context.ChannelSource.ServerDescription) ? context.Binding.Session.AdvanceTransactionNumber() : null; + transactionNumber ??= AreRetriesAllowed(operationContext, operation.WriteConcern, operation.IsOperationRetryable, context, context.ChannelSource.ServerDescription) ? operationContext.Session.AdvanceTransactionNumber() : null; var operationResult = await operation.ExecuteAttemptAsync(operationContext, context, operationExecutionAttempts, transactionNumber).ConfigureAwait(false); - if (context.Binding.Session.Id != null && - context.Binding.Session.IsInTransaction) + if (operationContext.Session.Id != null && + operationContext.Session.IsInTransaction) { - context.Binding.Session.CurrentTransaction.HasCompletedCommand = true; + operationContext.Session.CurrentTransaction.HasCompletedCommand = true; } return operationResult; @@ -156,7 +156,7 @@ public static async Task ExecuteAsync(OperationContext operati if (operation is EndTransactionOperation endTransactionOperation) { - endTransactionOperation.OnRetry(context, ex); + endTransactionOperation.OnRetry(operationContext, context, ex); } await Task.Delay(backoff, operationContext.CancellationToken).ConfigureAwait(false); @@ -166,7 +166,8 @@ public static async Task ExecuteAsync(OperationContext operati } // private static methods - private static bool ShouldRetry(OperationContext operationContext, + private static bool ShouldRetry( + OperationContext operationContext, bool errorDuringChannelAcquisition, ServerDescription server, WriteConcern writeConcern, @@ -193,7 +194,7 @@ private static bool ShouldRetry(OperationContext operationContext, var exceptionToAnalyze = exception is MongoAuthenticationException mongoAuthenticationException ? mongoAuthenticationException.InnerException : exception; var isRetryableReadException = RetryabilityHelper.IsRetryableReadException(exceptionToAnalyze); - isRetryableRead = isOperationRetryable && !context.Binding.Session.IsInTransaction && isRetryableReadException; + isRetryableRead = isOperationRetryable && !operationContext.Session.IsInTransaction && isRetryableReadException; } else { @@ -206,7 +207,7 @@ private static bool ShouldRetry(OperationContext operationContext, var isRetryableWrites = isRetryableWriteException && (isEndTransactionOperation ? IsOperationAcknowledged(writeConcern) - : AreRetriesAllowed(writeConcern, isOperationRetryable, context, server)); + : AreRetriesAllowed(operationContext, writeConcern, isOperationRetryable, context, server)); var isRetryableReadOrWrite = isRetryableRead || isRetryableWrites; @@ -224,9 +225,9 @@ private static bool ShouldRetry(OperationContext operationContext, if (isSystemOverloadedException) { // If the first command in a transaction was rejected due to overload, reset to Starting so the retry re-sends startTransaction:true. - if (context.Binding.Session.Id != null - && context.Binding.Session.IsInTransaction - && context.Binding.Session.CurrentTransaction is { HasCompletedCommand: false } currentTransaction) + if (operationContext.Session.Id != null + && operationContext.Session.IsInTransaction + && operationContext.Session.CurrentTransaction is { HasCompletedCommand: false } currentTransaction) { currentTransaction.ResetState(); } @@ -246,8 +247,8 @@ private static bool ShouldRetry(OperationContext operationContext, return operationContext.IsRootContextTimeoutConfigured() || attempt < 2; } - private static bool AreRetriesAllowed(WriteConcern writeConcern, bool isOperationRetryable, RetryableWriteContext context, ServerDescription server) - => IsOperationAcknowledged(writeConcern) && isOperationRetryable && DoesContextAllowRetries(context, server); + private static bool AreRetriesAllowed(OperationContext operationContext, WriteConcern writeConcern, bool isOperationRetryable, RetryableWriteContext context, ServerDescription server) + => IsOperationAcknowledged(writeConcern) && isOperationRetryable && DoesContextAllowRetries(operationContext, context, server); private static bool AreRetryableWritesSupported(ServerDescription serverDescription) { @@ -255,11 +256,11 @@ private static bool AreRetryableWritesSupported(ServerDescription serverDescript (serverDescription.LogicalSessionTimeout != null && serverDescription.Type != ServerType.Standalone); } - private static bool DoesContextAllowRetries(RetryableWriteContext context, ServerDescription server) + private static bool DoesContextAllowRetries(OperationContext operationContext, RetryableWriteContext context, ServerDescription server) => context.RetryRequested && AreRetryableWritesSupported(server) && - context.Binding.Session.Id != null && - !context.Binding.Session.IsInTransaction; + operationContext.Session.Id != null && + !operationContext.Session.IsInTransaction; private static bool WritesWereAttempted(Exception exception, bool channelAcquisitionSuccessful) => channelAcquisitionSuccessful && !RetryabilityHelper.IsNoWritesPerformedException(exception); diff --git a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs index ed2cb639f75..b77ebf3761c 100644 --- a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs @@ -115,9 +115,9 @@ public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableW var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return operation.Execute(operationContext, channelBinding); } } @@ -128,14 +128,14 @@ public async Task ExecuteAttemptAsync(OperationContext operationCo var channelSource = context.ChannelSource; var channel = context.Channel; - using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber); + var operation = CreateOperation(operationContext, channel.ConnectionDescription, transactionNumber); return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } - internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + internal BsonDocument CreateCommand(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { return new BsonDocument { @@ -147,9 +147,9 @@ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSess private IDisposable BeginOperation() => EventContext.BeginOperation("updateSearchIndex"); - private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) + private WriteCommandOperation CreateOperation(OperationContext operationContext, ConnectionDescription connectionDescription, long? transactionNumber) { - var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber); + var command = CreateCommand(operationContext, connectionDescription, transactionNumber); return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings, OperationName); } } diff --git a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs index fc8c2d515fa..01876b14536 100644 --- a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs @@ -53,7 +53,7 @@ public TCommandResult Execute(OperationContext operationContext, IWriteBinding b using (EventContext.BeginOperation()) using (var channelSource = binding.GetWriteChannelSource(operationContext)) { - return ExecuteProtocol(operationContext, channelSource, binding.Session, _readPreference, _command); + return ExecuteProtocol(operationContext, channelSource, _readPreference, _command); } } @@ -64,7 +64,7 @@ public async Task ExecuteAsync(OperationContext operationContext using (EventContext.BeginOperation()) using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(operationContext, channelSource, binding.Session, _readPreference, _command).ConfigureAwait(false); + return await ExecuteProtocolAsync(operationContext, channelSource, _readPreference, _command).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/WriteConcernHelper.cs b/src/MongoDB.Driver/Core/Operations/WriteConcernHelper.cs index 345effcfc5d..3d2c8960e94 100644 --- a/src/MongoDB.Driver/Core/Operations/WriteConcernHelper.cs +++ b/src/MongoDB.Driver/Core/Operations/WriteConcernHelper.cs @@ -14,13 +14,12 @@ */ using MongoDB.Bson; -using MongoDB.Driver.Core.Bindings; namespace MongoDB.Driver.Core.Operations { internal static class WriteConcernHelper { - public static BsonDocument GetEffectiveWriteConcern(OperationContext operationContext, ICoreSession session, WriteConcern writeConcern) + public static BsonDocument GetEffectiveWriteConcern(OperationContext operationContext, WriteConcern writeConcern) { if (writeConcern != null) { @@ -29,7 +28,7 @@ public static BsonDocument GetEffectiveWriteConcern(OperationContext operationCo writeConcern = writeConcern.With(wTimeout: null); } - if (!session.IsInTransaction && !writeConcern.IsServerDefault) + if (!operationContext.Session.IsInTransaction && !writeConcern.IsServerDefault) { return writeConcern.ToBsonDocument(); } diff --git a/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs b/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs index 0521743d5ae..da193b838ef 100644 --- a/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs +++ b/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs @@ -18,6 +18,7 @@ using System.Net; using System.Threading; using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Misc; @@ -125,7 +126,7 @@ private void MonitorServer() _logger?.LogDebug(_serverId, "Monitoring started"); var helloOk = false; - using var operationContext = new OperationContext(null, _cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, _cancellationToken); while (!operationContext.IsCancelledOrTimedOut()) { try diff --git a/src/MongoDB.Driver/Core/Servers/ServerChannel.cs b/src/MongoDB.Driver/Core/Servers/ServerChannel.cs index bf0ce569e87..db00ad04bc0 100644 --- a/src/MongoDB.Driver/Core/Servers/ServerChannel.cs +++ b/src/MongoDB.Driver/Core/Servers/ServerChannel.cs @@ -53,7 +53,6 @@ public ServerChannel(IServer server, IConnectionHandle connection, bool decremen // methods public TResult Command( OperationContext operationContext, - ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, @@ -72,7 +71,7 @@ public TResult Command( } var protocol = new CommandWireProtocol( - CreateClusterClockAdvancingCoreSession(session), + CreateClusterClockAdvancingCoreSession(operationContext.Session), readPreference, databaseNamespace, command, @@ -86,12 +85,11 @@ public TResult Command( _server.ServerApi, roundTripTime); - return ExecuteProtocol(operationContext, protocol, session); + return ExecuteProtocol(operationContext, protocol, operationContext.Session); } public Task CommandAsync( OperationContext operationContext, - ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, @@ -110,7 +108,7 @@ public Task CommandAsync( } var protocol = new CommandWireProtocol( - CreateClusterClockAdvancingCoreSession(session), + CreateClusterClockAdvancingCoreSession(operationContext.Session), readPreference, databaseNamespace, command, @@ -124,7 +122,7 @@ public Task CommandAsync( _server.ServerApi, roundTripTime); - return ExecuteProtocolAsync(operationContext, protocol, session); + return ExecuteProtocolAsync(operationContext, protocol, operationContext.Session); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Servers/ServerMonitor.cs b/src/MongoDB.Driver/Core/Servers/ServerMonitor.cs index a70572a70e0..d56649e6f2d 100644 --- a/src/MongoDB.Driver/Core/Servers/ServerMonitor.cs +++ b/src/MongoDB.Driver/Core/Servers/ServerMonitor.cs @@ -19,6 +19,7 @@ using System.Threading; using Microsoft.Extensions.Logging; using MongoDB.Bson; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Logging; @@ -321,7 +322,7 @@ private HelloResult GetHelloResult( private void Heartbeat(CancellationToken cancellationToken) { - using var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); CommandWireProtocol helloProtocol = null; bool processAnother = true; while (processAnother && !cancellationToken.IsCancellationRequested) diff --git a/src/MongoDB.Driver/GridFS/GridFSBucket.cs b/src/MongoDB.Driver/GridFS/GridFSBucket.cs index 0299e0ab237..cd1c18dd3bb 100644 --- a/src/MongoDB.Driver/GridFS/GridFSBucket.cs +++ b/src/MongoDB.Driver/GridFS/GridFSBucket.cs @@ -84,7 +84,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); @@ -105,7 +105,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); @@ -126,7 +126,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { @@ -140,7 +140,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { @@ -154,7 +154,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) @@ -169,7 +169,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) @@ -185,7 +185,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { @@ -200,7 +200,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { @@ -215,7 +215,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) @@ -231,7 +231,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) @@ -245,7 +245,7 @@ public ImmutableGridFSBucketOptions Options public void Drop(CancellationToken cancellationToken = default(CancellationToken)) { // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); @@ -264,7 +264,7 @@ public ImmutableGridFSBucketOptions Options public async Task DropAsync(CancellationToken cancellationToken = default(CancellationToken)) { // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); @@ -284,7 +284,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filter, nameof(filter)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSFindOptions(); var translationOptions = _database.Client.Settings.TranslationOptions; @@ -300,7 +300,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filter, nameof(filter)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSFindOptions(); var translationOptions = _database.Client.Settings.TranslationOptions; @@ -316,7 +316,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { @@ -330,7 +330,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { @@ -344,7 +344,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) @@ -359,7 +359,7 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) @@ -375,7 +375,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var binding = GetSingleServerReadWriteBinding(operationContext)) @@ -391,7 +391,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) @@ -407,7 +407,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); using (var binding = GetSingleServerReadWriteBinding(operationContext)) { @@ -426,7 +426,7 @@ 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(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { @@ -446,7 +446,7 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var sourceStream = new MemoryStream(source)) @@ -462,7 +462,7 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var sourceStream = new MemoryStream(source)) @@ -1041,7 +1041,7 @@ private IReadBindingHandle GetSingleServerReadBinding(OperationContext operation var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); var server = _cluster.SelectServer(operationContext, selector); - var binding = new SingleServerReadBinding(_cluster, server, readPreference, NoCoreSession.NewHandle()); + var binding = new SingleServerReadBinding(_cluster, server, readPreference); return new ReadBindingHandle(binding); } @@ -1050,7 +1050,7 @@ private async Task GetSingleServerReadBindingAsync(Operation var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); var server = await _cluster.SelectServerAsync(operationContext, selector).ConfigureAwait(false); - var binding = new SingleServerReadBinding(_cluster, server, readPreference, NoCoreSession.NewHandle()); + var binding = new SingleServerReadBinding(_cluster, server, readPreference); return new ReadBindingHandle(binding); } @@ -1058,7 +1058,7 @@ private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationContext { var selector = WritableServerSelector.Instance; var server = _cluster.SelectServer(operationContext, selector); - var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); + var binding = new SingleServerReadWriteBinding(server); return new ReadWriteBindingHandle(binding); } @@ -1066,7 +1066,7 @@ private async Task GetSingleServerReadWriteBindingAsync { var selector = WritableServerSelector.Instance; var server = await _cluster.SelectServerAsync(operationContext, selector).ConfigureAwait(false); - var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); + var binding = new SingleServerReadWriteBinding(server); return new ReadWriteBindingHandle(binding); } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs index ce74de8fa0a..b332cf89682 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs @@ -213,7 +213,7 @@ private void GetFirstBatch(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); _cursor = operation.Execute(operationContext, Binding); GetNextBatch(cancellationToken); } @@ -222,7 +222,7 @@ private async Task GetFirstBatchAsync(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, 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 e929211de54..5d03c1480f6 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs @@ -123,7 +123,7 @@ public override long Position var operation = CreateAbortOperation(); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); operation.Execute(operationContext, _binding); } @@ -138,7 +138,7 @@ public override long Position var operation = CreateAbortOperation(); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); await operation.ExecuteAsync(operationContext, _binding).ConfigureAwait(false); } diff --git a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs index f815d4386c4..9db97dff00e 100644 --- a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs @@ -189,7 +189,7 @@ private void GetChunk(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); using (var cursor = operation.Execute(operationContext, Binding)) { var documents = cursor.ToList(); @@ -202,7 +202,7 @@ private async Task GetChunkAsync(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); // TODO: CSOT implement proper way to obtain the operationContext - var operationContext = new OperationContext(null, cancellationToken); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), null, cancellationToken); using (var cursor = await operation.ExecuteAsync(operationContext, Binding).ConfigureAwait(false)) { var documents = await cursor.ToListAsync().ConfigureAwait(false); diff --git a/src/MongoDB.Driver/IOperationExecutor.cs b/src/MongoDB.Driver/IOperationExecutor.cs index 6dfd8e741c5..0b682c85d82 100644 --- a/src/MongoDB.Driver/IOperationExecutor.cs +++ b/src/MongoDB.Driver/IOperationExecutor.cs @@ -23,27 +23,23 @@ internal interface IOperationExecutor : IDisposable { TResult ExecuteReadOperation( OperationContext operationContext, - IClientSessionHandle session, IReadOperation operation, ReadPreference readPreference, bool allowChannelPinning); Task ExecuteReadOperationAsync( OperationContext operationContext, - IClientSessionHandle session, IReadOperation operation, ReadPreference readPreference, bool allowChannelPinning); TResult ExecuteWriteOperation( OperationContext operationContext, - IClientSessionHandle session, IWriteOperation operation, bool allowChannelPinning); Task ExecuteWriteOperationAsync( OperationContext operationContext, - IClientSessionHandle session, IWriteOperation operation, bool allowChannelPinning); diff --git a/src/MongoDB.Driver/MongoClient.cs b/src/MongoDB.Driver/MongoClient.cs index 4b6ce9090f3..6fec807df4c 100644 --- a/src/MongoDB.Driver/MongoClient.cs +++ b/src/MongoDB.Driver/MongoClient.cs @@ -590,35 +590,39 @@ private OperationContext CreateOperationContext(IClientSessionHandle session, Ti : operationContext.Fork(); } - return isTracingEnabled - ? new OperationContext(timeout ?? _settings.Timeout, operationName, "admin", null, isTracingEnabled, cancellationToken) - : new OperationContext(timeout ?? _settings.Timeout, cancellationToken); + return new OperationContext(session.WrappedCoreSession, timeout ?? _settings.Timeout, cancellationToken) + { + IsTracingEnabled = isTracingEnabled, + OperationName = isTracingEnabled ? operationName : null, + DatabaseName = isTracingEnabled ? "admin" : null, + CollectionName = null, + }; } private TResult ExecuteReadOperation(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) { var readPreference = session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return _operationExecutor.ExecuteReadOperation(operationContext, session, operation, readPreference, false); + return _operationExecutor.ExecuteReadOperation(operationContext, operation, readPreference, false); } private async Task ExecuteReadOperationAsync(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) { var readPreference = session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return await _operationExecutor.ExecuteReadOperationAsync(operationContext, session, operation, readPreference, false).ConfigureAwait(false); + return await _operationExecutor.ExecuteReadOperationAsync(operationContext, operation, readPreference, false).ConfigureAwait(false); } private TResult ExecuteWriteOperation(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return _operationExecutor.ExecuteWriteOperation(operationContext, session, operation, false); + return _operationExecutor.ExecuteWriteOperation(operationContext, operation, false); } private async Task ExecuteWriteOperationAsync(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, session, operation, false).ConfigureAwait(false); + return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, operation, false).ConfigureAwait(false); } private MessageEncoderSettings GetMessageEncoderSettings() diff --git a/src/MongoDB.Driver/MongoCollectionImpl.cs b/src/MongoDB.Driver/MongoCollectionImpl.cs index 4a53cb7f451..d232ea79ffe 100644 --- a/src/MongoDB.Driver/MongoCollectionImpl.cs +++ b/src/MongoDB.Driver/MongoCollectionImpl.cs @@ -1282,15 +1282,13 @@ private OperationContext CreateOperationContext(IClientSessionHandle session, Ti : operationContext.Fork(); } - return isTracingEnabled - ? new OperationContext( - timeout ?? _settings.Timeout, - operationName, - _collectionNamespace.DatabaseNamespace.DatabaseName, - _collectionNamespace.CollectionName, - isTracingEnabled, - cancellationToken) - : new OperationContext(timeout ?? _settings.Timeout, cancellationToken); + return new OperationContext(session.WrappedCoreSession, timeout ?? _settings.Timeout, cancellationToken) + { + IsTracingEnabled = isTracingEnabled, + OperationName = isTracingEnabled ? operationName : null, + DatabaseName = isTracingEnabled ? _collectionNamespace.DatabaseNamespace.DatabaseName : null, + CollectionName = isTracingEnabled ? _collectionNamespace.CollectionName : null, + }; } private TResult ExecuteReadOperation(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) @@ -1300,7 +1298,7 @@ private TResult ExecuteReadOperation(IClientSessionHandle session, IRea { var readPreference = explicitReadPreference ?? session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return _operationExecutor.ExecuteReadOperation(operationContext, session, operation, readPreference, true); + return _operationExecutor.ExecuteReadOperation(operationContext, operation, readPreference, true); } private Task ExecuteReadOperationAsync(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) @@ -1310,19 +1308,19 @@ private async Task ExecuteReadOperationAsync(IClientSessionHan { var readPreference = explicitReadPreference ?? session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return await _operationExecutor.ExecuteReadOperationAsync(operationContext, session, operation, readPreference, true).ConfigureAwait(false); + return await _operationExecutor.ExecuteReadOperationAsync(operationContext, operation, readPreference, true).ConfigureAwait(false); } private TResult ExecuteWriteOperation(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return _operationExecutor.ExecuteWriteOperation(operationContext, session, operation, true); + return _operationExecutor.ExecuteWriteOperation(operationContext, operation, true); } private async Task ExecuteWriteOperationAsync(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, cancellationToken); - return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, session, operation, true).ConfigureAwait(false); + return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, operation, true).ConfigureAwait(false); } private MessageEncoderSettings GetMessageEncoderSettings() diff --git a/src/MongoDB.Driver/MongoDB.Driver.csproj b/src/MongoDB.Driver/MongoDB.Driver.csproj index 8c21f5daac8..10a3ccffc87 100644 --- a/src/MongoDB.Driver/MongoDB.Driver.csproj +++ b/src/MongoDB.Driver/MongoDB.Driver.csproj @@ -17,6 +17,7 @@ + diff --git a/src/MongoDB.Driver/MongoDatabase.cs b/src/MongoDB.Driver/MongoDatabase.cs index 6bd2344a9e0..76e9034af45 100644 --- a/src/MongoDB.Driver/MongoDatabase.cs +++ b/src/MongoDB.Driver/MongoDatabase.cs @@ -796,9 +796,13 @@ private OperationContext CreateOperationContext(IClientSessionHandle session, Ti : operationContext.Fork(); } - return isTracingEnabled - ? new OperationContext(timeout ?? _settings.Timeout, operationName, _databaseNamespace.DatabaseName, collectionName, isTracingEnabled, cancellationToken) - : new OperationContext(timeout ?? _settings.Timeout, cancellationToken); + return new OperationContext(session.WrappedCoreSession, timeout ?? _settings.Timeout, cancellationToken) + { + IsTracingEnabled = isTracingEnabled, + OperationName = isTracingEnabled ? operationName : null, + DatabaseName = isTracingEnabled ? _databaseNamespace.DatabaseName : null, + CollectionName = isTracingEnabled ? collectionName : null, + }; } private TResult ExecuteReadOperation(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) @@ -808,7 +812,7 @@ private TResult ExecuteReadOperation(IClientSessionHandle session, IRea { var readPreference = explicitReadPreference ?? session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, null, cancellationToken); - return _operationExecutor.ExecuteReadOperation(operationContext, session, operation, readPreference, true); + return _operationExecutor.ExecuteReadOperation(operationContext, operation, readPreference, true); } private Task ExecuteReadOperationAsync(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken) @@ -818,19 +822,19 @@ private async Task ExecuteReadOperationAsync(IClientSessionHan { var readPreference = explicitReadPreference ?? session.GetEffectiveReadPreference(_settings.ReadPreference); using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, null, cancellationToken); - return await _operationExecutor.ExecuteReadOperationAsync(operationContext, session, operation, readPreference, true).ConfigureAwait(false); + return await _operationExecutor.ExecuteReadOperationAsync(operationContext, operation, readPreference, true).ConfigureAwait(false); } private TResult ExecuteWriteOperation(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, string collectionName, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, collectionName, cancellationToken); - return _operationExecutor.ExecuteWriteOperation(operationContext, session, operation, true); + return _operationExecutor.ExecuteWriteOperation(operationContext, operation, true); } private async Task ExecuteWriteOperationAsync(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, string collectionName, CancellationToken cancellationToken) { using var operationContext = CreateOperationContext(session, timeout, operation.OperationName, collectionName, cancellationToken); - return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, session, operation, true).ConfigureAwait(false); + return await _operationExecutor.ExecuteWriteOperationAsync(operationContext, operation, true).ConfigureAwait(false); } private IEnumerable ExtractCollectionNames(IEnumerable collections) diff --git a/src/MongoDB.Driver/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs index 22b78dda255..5de0cbc7572 100644 --- a/src/MongoDB.Driver/OperationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -16,45 +16,29 @@ using System; using System.Threading; using System.Threading.Tasks; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver { internal sealed class OperationContext : IDisposable { - // 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(null, CancellationToken.None); - private CancellationTokenSource _remainingTimeoutCancellationTokenSource; private CancellationTokenSource _combinedCancellationTokenSource; - public OperationContext(TimeSpan? timeout, CancellationToken cancellationToken) - : this(SystemClock.Instance, SystemClock.Instance.GetTimestamp(), timeout, cancellationToken) + public OperationContext(ICoreSessionHandle session, TimeSpan? timeout = null, CancellationToken cancellationToken = default) + : this(session, SystemClock.Instance, SystemClock.Instance.GetTimestamp(), timeout, cancellationToken) { } - internal OperationContext( - TimeSpan? timeout, - string operationName, - string databaseName, - string collectionName, - bool isTracingEnabled, - CancellationToken cancellationToken) - : this(timeout, cancellationToken) + internal OperationContext(ICoreSessionHandle session, IClock clock, TimeSpan? timeout, CancellationToken cancellationToken) + : this(session, clock, clock.GetTimestamp(), timeout, cancellationToken) { - OperationName = operationName; - DatabaseName = databaseName; - CollectionName = collectionName; - IsTracingEnabled = isTracingEnabled; } - internal OperationContext(IClock clock, TimeSpan? timeout, CancellationToken cancellationToken) - : this(clock, clock.GetTimestamp(), timeout, cancellationToken) - { - } - - internal OperationContext(IClock clock, long initialTimestamp, TimeSpan? timeout, CancellationToken cancellationToken) + internal OperationContext(ICoreSessionHandle session, IClock clock, long initialTimestamp, TimeSpan? timeout, CancellationToken cancellationToken) { + Session = Ensure.IsNotNull(session, nameof(session)); Clock = Ensure.IsNotNull(clock, nameof(clock)); InitialTimestamp = initialTimestamp; Timeout = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(timeout, nameof(timeout)); @@ -91,6 +75,8 @@ public TimeSpan RemainingTimeout } } + public ICoreSessionHandle Session { get; } + [Obsolete("Do not use this property, unless it's needed to avoid breaking changes in public API")] public CancellationToken CombinedCancellationToken { @@ -133,13 +119,13 @@ public void Dispose() } public OperationContext Fork() => - new (Clock, InitialTimestamp, Timeout, CancellationToken) + new (Session, Clock, InitialTimestamp, Timeout, CancellationToken) { RootContext = RootContext }; internal OperationContext ForkWithOperationMetadata(string operationName, string databaseName, string collectionName, bool isTracingEnabled) => - new (Clock, InitialTimestamp, Timeout, CancellationToken) + new (Session, Clock, InitialTimestamp, Timeout, CancellationToken) { RootContext = RootContext, OperationName = operationName, @@ -211,13 +197,13 @@ public OperationContext WithTimeout(TimeSpan timeout) timeout = remainingTimeout; } - return new OperationContext(Clock, timeout, CancellationToken) + return new OperationContext(Session, Clock, timeout, CancellationToken) { RootContext = RootContext, OperationName = OperationName, DatabaseName = DatabaseName, CollectionName = CollectionName, - IsTracingEnabled = IsTracingEnabled + IsTracingEnabled = IsTracingEnabled, }; } diff --git a/src/MongoDB.Driver/OperationExecutor.cs b/src/MongoDB.Driver/OperationExecutor.cs index 5e12f5dcb4e..c96e4bbabe0 100644 --- a/src/MongoDB.Driver/OperationExecutor.cs +++ b/src/MongoDB.Driver/OperationExecutor.cs @@ -40,23 +40,21 @@ public void Dispose() public TResult ExecuteReadOperation( OperationContext operationContext, - IClientSessionHandle session, IReadOperation operation, ReadPreference readPreference, bool allowChannelPinning) { Ensure.IsNotNull(operationContext, nameof(operationContext)); - Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(operation, nameof(operation)); Ensure.IsNotNull(readPreference, nameof(readPreference)); ThrowIfDisposed(); - using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(session.WrappedCoreSession.CurrentTransaction); + using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(operationContext.Session.CurrentTransaction); using var activity = MongoTelemetry.StartOperationActivity(operationContext); try { - using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); + using var binding = CreateReadBinding(operationContext.Session, readPreference, allowChannelPinning); var result = operation.Execute(operationContext, binding); activity?.SetStatus(ActivityStatusCode.Ok); return result; @@ -70,23 +68,21 @@ public TResult ExecuteReadOperation( public async Task ExecuteReadOperationAsync( OperationContext operationContext, - IClientSessionHandle session, IReadOperation operation, ReadPreference readPreference, bool allowChannelPinning) { Ensure.IsNotNull(operationContext, nameof(operationContext)); - Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(operation, nameof(operation)); Ensure.IsNotNull(readPreference, nameof(readPreference)); ThrowIfDisposed(); - using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(session.WrappedCoreSession.CurrentTransaction); + using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(operationContext.Session.CurrentTransaction); using var activity = MongoTelemetry.StartOperationActivity(operationContext); try { - using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); + using var binding = CreateReadBinding(operationContext.Session, readPreference, allowChannelPinning); var result = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); activity?.SetStatus(ActivityStatusCode.Ok); return result; @@ -100,21 +96,19 @@ public async Task ExecuteReadOperationAsync( public TResult ExecuteWriteOperation( OperationContext operationContext, - IClientSessionHandle session, IWriteOperation operation, bool allowChannelPinning) { Ensure.IsNotNull(operationContext, nameof(operationContext)); - Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(operation, nameof(operation)); ThrowIfDisposed(); - using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(session.WrappedCoreSession.CurrentTransaction); + using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(operationContext.Session.CurrentTransaction); using var activity = MongoTelemetry.StartOperationActivity(operationContext); try { - using var binding = CreateReadWriteBinding(session, allowChannelPinning); + using var binding = CreateReadWriteBinding(operationContext.Session, allowChannelPinning); var result = operation.Execute(operationContext, binding); activity?.SetStatus(ActivityStatusCode.Ok); return result; @@ -128,21 +122,19 @@ public TResult ExecuteWriteOperation( public async Task ExecuteWriteOperationAsync( OperationContext operationContext, - IClientSessionHandle session, IWriteOperation operation, bool allowChannelPinning) { Ensure.IsNotNull(operationContext, nameof(operationContext)); - Ensure.IsNotNull(session, nameof(session)); Ensure.IsNotNull(operation, nameof(operation)); ThrowIfDisposed(); - using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(session.WrappedCoreSession.CurrentTransaction); + using var transactionActivityScope = TransactionActivityScope.CreateIfNeeded(operationContext.Session.CurrentTransaction); using var activity = MongoTelemetry.StartOperationActivity(operationContext); try { - using var binding = CreateReadWriteBinding(session, allowChannelPinning); + using var binding = CreateReadWriteBinding(operationContext.Session, allowChannelPinning); var result = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); activity?.SetStatus(ActivityStatusCode.Ok); return result; @@ -165,7 +157,7 @@ public IClientSessionHandle StartImplicitSession() return new ClientSessionHandle(_client, options, coreSession); } - private IReadBindingHandle CreateReadBinding(IClientSessionHandle session, ReadPreference readPreference, bool allowChannelPinning) + private IReadBindingHandle CreateReadBinding(ICoreSessionHandle session, ReadPreference readPreference, bool allowChannelPinning) { if (session.IsInTransaction && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary) { @@ -174,21 +166,21 @@ private IReadBindingHandle CreateReadBinding(IClientSessionHandle session, ReadP if (allowChannelPinning) { - return ChannelPinningHelper.CreateReadBinding(_client.GetClusterInternal(), session.WrappedCoreSession.Fork(), readPreference); + return ChannelPinningHelper.CreateReadBinding(_client.GetClusterInternal(), session, readPreference); } - var binding = new ReadPreferenceBinding(_client.GetClusterInternal(), readPreference, session.WrappedCoreSession.Fork()); + var binding = new ReadPreferenceBinding(_client.GetClusterInternal(), readPreference); return new ReadBindingHandle(binding); } - private IReadWriteBindingHandle CreateReadWriteBinding(IClientSessionHandle session, bool allowChannelPinning) + private IReadWriteBindingHandle CreateReadWriteBinding(ICoreSessionHandle session, bool allowChannelPinning) { if (allowChannelPinning) { - return ChannelPinningHelper.CreateReadWriteBinding(_client.GetClusterInternal(), session.WrappedCoreSession.Fork()); + return ChannelPinningHelper.CreateReadWriteBinding(_client.GetClusterInternal(), session); } - var binding = new WritableServerBinding(_client.GetClusterInternal(), session.WrappedCoreSession.Fork()); + var binding = new WritableServerBinding(_client.GetClusterInternal()); return new ReadWriteBindingHandle(binding); } diff --git a/src/MongoDB.Driver/TransactionExecutor.cs b/src/MongoDB.Driver/TransactionExecutor.cs index 2bc26f942f9..f5647f76a76 100644 --- a/src/MongoDB.Driver/TransactionExecutor.cs +++ b/src/MongoDB.Driver/TransactionExecutor.cs @@ -39,7 +39,7 @@ public static TResult ExecuteWithRetries( { var attempt = 0; var transactionTimeout = transactionOptions?.Timeout ?? clientSession.Options.DefaultTransactionOptions?.Timeout; - using var operationContext = new OperationContext(clock, transactionTimeout, cancellationToken); + using var operationContext = new OperationContext(clientSession.WrappedCoreSession, clock, transactionTimeout, cancellationToken); while (true) { @@ -85,7 +85,7 @@ public static async Task ExecuteWithRetriesAsync( { var attempt = 0; var transactionTimeout = transactionOptions?.Timeout ?? clientSession.Options.DefaultTransactionOptions?.Timeout; - using var operationContext = new OperationContext(clock, transactionTimeout, cancellationToken); + using var operationContext = new OperationContext(clientSession.WrappedCoreSession, clock, transactionTimeout, cancellationToken); while (true) { diff --git a/tests/MongoDB.Bson.TestHelpers/Reflector.cs b/tests/MongoDB.Bson.TestHelpers/Reflector.cs index a08dd6f8c69..ca458cb921a 100644 --- a/tests/MongoDB.Bson.TestHelpers/Reflector.cs +++ b/tests/MongoDB.Bson.TestHelpers/Reflector.cs @@ -162,6 +162,22 @@ public static object Invoke(object obj, string name, T1 arg1, T2 arg } } + public static object Invoke(object obj, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4) + { + var parameterTypes = new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }; + var methodInfo = obj.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) + .Where(m => m.Name == name && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)) + .Single(); + try + { + return methodInfo.Invoke(obj, new object[] { arg1, arg2, arg3, arg4 }); + } + catch (TargetInvocationException exception) + { + throw exception.InnerException; + } + } + public static object InvokeStatic(Type type, string name, BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static) { var methodInfo = type.GetMethods(flags) diff --git a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs index 9ced9397892..e6aae35fb8a 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs @@ -306,11 +306,12 @@ public static DatabaseNamespace GetDatabaseNamespaceForTestClass(Type testClassT private static int GetMaxWireVersion() { using (var session = StartSession()) - using (var binding = CreateReadBinding(session)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadBinding()) { var command = new BsonDocument("hello", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(OperationContext.NoTimeout, binding); + var response = operation.Execute(operationContext, binding); return response["maxWireVersion"].AsInt32; } } @@ -318,11 +319,12 @@ private static int GetMaxWireVersion() private static SemanticVersion GetServerVersion() { using (var session = StartSession()) - using (var binding = CreateReadBinding(session)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadBinding()) { var command = new BsonDocument("buildinfo", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(OperationContext.NoTimeout, binding); + var response = operation.Execute(operationContext, binding); return SemanticVersion.Parse(response["version"].AsString); } } @@ -330,11 +332,12 @@ private static SemanticVersion GetServerVersion() public static BsonDocument GetServerParameters() { using (var session = StartSession()) - using (var binding = CreateReadBinding(session)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadBinding()) { var command = new BsonDocument("getParameter", new BsonString("*")); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var serverParameters = operation.Execute(OperationContext.NoTimeout, binding); + var serverParameters = operation.Execute(operationContext, binding); return serverParameters; } @@ -384,47 +387,37 @@ private static bool AreSessionsSupported(ClusterDescription clusterDescription) (clusterDescription.LogicalSessionTimeout.HasValue || clusterDescription.Type == ClusterType.LoadBalanced); } - private static IReadBindingHandle CreateReadBinding(ICoreSessionHandle session) + private static IReadBindingHandle CreateReadBinding() { - return CreateReadBinding(ReadPreference.Primary, session); + return CreateReadBinding(ReadPreference.Primary); } - private static IReadBindingHandle CreateReadBinding(ReadPreference readPreference, ICoreSessionHandle session) + private static IReadBindingHandle CreateReadBinding(ReadPreference readPreference) { - return CreateReadBinding(__cluster.Value, readPreference, session); + return CreateReadBinding(__cluster.Value, readPreference); } - private static IReadBindingHandle CreateReadBinding(IClusterInternal cluster, ReadPreference readPreference, ICoreSessionHandle session) + private static IReadBindingHandle CreateReadBinding(IClusterInternal cluster, ReadPreference readPreference) { - var binding = new ReadPreferenceBinding(cluster, readPreference, session.Fork()); + var binding = new ReadPreferenceBinding(cluster, readPreference); return new ReadBindingHandle(binding); } private static IReadWriteBindingHandle CreateReadWriteBinding(ICoreSessionHandle session) { - var binding = new WritableServerBinding(__cluster.Value, session.Fork()); + var binding = new WritableServerBinding(__cluster.Value); return new ReadWriteBindingHandle(binding); } - private static void DropDatabase() - { - var operation = new DropDatabaseOperation(__databaseNamespace.Value, __messageEncoderSettings); - - using (var session = StartSession()) - using (var binding = CreateReadWriteBinding(session)) - { - operation.Execute(OperationContext.NoTimeout, binding); - } - } - private static IEnumerable FindDocuments(IClusterInternal cluster, CollectionNamespace collectionNamespace) { using (var session = StartSession(cluster)) - using (var binding = CreateReadBinding(cluster, ReadPreference.Primary, session)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadBinding(cluster, ReadPreference.Primary)) { var operation = new FindOperation(collectionNamespace, BsonDocumentSerializer.Instance, __messageEncoderSettings); - return operation.Execute(OperationContext.NoTimeout, binding).ToList(); + return operation.Execute(operationContext, binding).ToList(); } } @@ -499,11 +492,12 @@ string GetStorageEngineForCluster(IClusterInternal cluster) { var command = new BsonDocument("serverStatus", 1); using (var session = StartSession(cluster)) - using (var binding = CreateReadBinding(cluster, ReadPreference.PrimaryPreferred, session)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadBinding(cluster, ReadPreference.PrimaryPreferred)) { var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(OperationContext.NoTimeout, binding); + var response = operation.Execute(operationContext, 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 5f3f0244c63..8f04e105141 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs @@ -48,8 +48,9 @@ public static FailPoint Configure(IServerSelector serverSelector, BsonDocument c { cluster ??= DriverTestConfiguration.Client.GetClusterInternal(); DriverTestConfiguration.WaitForAllServersToBeConnected(cluster); - var server = cluster.SelectServer(OperationContext.NoTimeout, serverSelector); - var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var server = cluster.SelectServer(operationContext, serverSelector); + var binding = new SingleServerReadWriteBinding(server); if (withAsync.HasValue) { MakeFailPointApplicationNameTestableIfConfigured(command, withAsync.Value); @@ -58,7 +59,7 @@ public static FailPoint Configure(IServerSelector serverSelector, BsonDocument c var failpoint = new FailPoint(server, binding, command); try { - failpoint.Configure(); + failpoint.Configure(operationContext); return failpoint; } catch @@ -139,8 +140,8 @@ public void Dispose() } // private methods - private void Configure() - => ExecuteCommand(_command, false); + private void Configure(OperationContext operationContext) + => ExecuteCommand(operationContext, _command, false); private void ConfigureOff() { @@ -150,10 +151,11 @@ private void ConfigureOff() { "configureFailPoint", name }, { "mode", "off" } }; - ExecuteCommand(command, true); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + ExecuteCommand(operationContext, command, true); } - private void ExecuteCommand(BsonDocument command, bool waitForConnected) + private void ExecuteCommand(OperationContext operationContext, BsonDocument command, bool waitForConnected) { if (waitForConnected) { @@ -171,7 +173,7 @@ private void ExecuteCommand(BsonDocument command, bool waitForConnected) BsonDocumentSerializer.Instance, new MessageEncoderSettings()); - operation.Execute(OperationContext.NoTimeout, _binding); + operation.Execute(operationContext, _binding); } } } diff --git a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs index cc51f98a8a6..46ad8413ea0 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs @@ -186,7 +186,8 @@ 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(OperationContext.NoTimeout)); + + var mockConnection = Mock.Get(server._connectionPool().AcquireConnection(It.IsAny())); 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 0717a5af8c1..1d93b2cbae3 100644 --- a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs @@ -207,9 +207,10 @@ public static MongoClientSettings GetClientSettings() public static ConnectionDescription GetConnectionDescription() { var cluster = Client.GetClusterInternal(); - using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = binding.GetWriteChannelSource(OperationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) + using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster))) + using (var operationContext = new OperationContext(NoCoreSession.NewHandle())) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) { return channel.ConnectionDescription; } diff --git a/tests/MongoDB.Driver.Tests/Authentication/AuthenticationHelperTests.cs b/tests/MongoDB.Driver.Tests/Authentication/AuthenticationHelperTests.cs index 90938099faf..db9d8d5f402 100644 --- a/tests/MongoDB.Driver.Tests/Authentication/AuthenticationHelperTests.cs +++ b/tests/MongoDB.Driver.Tests/Authentication/AuthenticationHelperTests.cs @@ -19,6 +19,7 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver.Authentication; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -66,15 +67,16 @@ public async Task Authenticate_should_invoke_authenticators_when_they_exist( mockConnection.SetupGet(c => c.Description).Returns(description); mockConnection.SetupGet(c => c.Settings).Returns(settings); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await AuthenticationHelper.AuthenticateAsync(OperationContext.NoTimeout, mockConnection.Object, description, authenticator); + await AuthenticationHelper.AuthenticateAsync(operationContext, mockConnection.Object, description, authenticator); mockAuthenticator.Verify(a => a.AuthenticateAsync(It.IsAny(), mockConnection.Object, description), Times.Once); } else { - AuthenticationHelper.Authenticate(OperationContext.NoTimeout, mockConnection.Object, description, authenticator); + AuthenticationHelper.Authenticate(operationContext, mockConnection.Object, description, authenticator); mockAuthenticator.Verify(a => a.Authenticate(It.IsAny(), mockConnection.Object, description), Times.Once); } @@ -98,15 +100,16 @@ public async Task Authenticate_should_not_invoke_authenticator_when_connected_to mockConnection.SetupGet(c => c.Description).Returns(description); mockConnection.SetupGet(c => c.Settings).Returns(settings); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await AuthenticationHelper.AuthenticateAsync(OperationContext.NoTimeout, mockConnection.Object, description, authenticator); + await AuthenticationHelper.AuthenticateAsync(operationContext, mockConnection.Object, description, authenticator); mockAuthenticator.Verify(a => a.AuthenticateAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } else { - AuthenticationHelper.Authenticate(OperationContext.NoTimeout, mockConnection.Object, description, authenticator); + AuthenticationHelper.Authenticate(operationContext, mockConnection.Object, description, authenticator); mockAuthenticator.Verify(a => a.Authenticate(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } diff --git a/tests/MongoDB.Driver.Tests/Authentication/MongoAWSAuthenticatorTests.cs b/tests/MongoDB.Driver.Tests/Authentication/MongoAWSAuthenticatorTests.cs index b0a84d4d31e..79002dbacdd 100644 --- a/tests/MongoDB.Driver.Tests/Authentication/MongoAWSAuthenticatorTests.cs +++ b/tests/MongoDB.Driver.Tests/Authentication/MongoAWSAuthenticatorTests.cs @@ -22,6 +22,7 @@ using MongoDB.Bson; using MongoDB.Driver.Authentication; using MongoDB.Driver.Authentication.AWS; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -114,13 +115,14 @@ public async Task Authenticate_should_have_expected_result( connection.EnqueueCommandResponseMessage(saslContinueCommandResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -194,13 +196,14 @@ public async Task Authenticate_should_send_serverApi_with_command_wire_protocol( connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -270,13 +273,14 @@ public async Task Authenticate_with_loadBalancedConnection_should_use_command_wi connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = null; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -304,9 +308,10 @@ public async Task Authenticate_should_throw_an_AuthenticationException_when_auth connection.EnqueueCommandResponseMessage(commandResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) ; + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)) ; exception.Should().BeOfType(); } @@ -341,9 +346,10 @@ public async Task Authenticate_should_throw_when_server_provides_invalid_host( connection.EnqueueCommandResponseMessage(saslContinueCommandResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) ; + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)) ; exception.Should().BeOfType(); exception.Message.Should().Be("Server returned an invalid sts host."); @@ -376,9 +382,10 @@ public async Task Authenticate_should_throw_when_server_provides_invalid_nonce( connection.EnqueueCommandResponseMessage(saslStartCommandResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) ; + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)) ; exception.Should().BeOfType(); exception.Message.Should().Be("Server sent an invalid nonce."); @@ -415,9 +422,10 @@ public async Task Authenticate_should_throw_when_server_provides_unexpected_fiel connection.EnqueueCommandResponseMessage(saslContinueCommandResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) ; + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)) ; exception.Should().BeOfType(); exception.Message.Should().Be("Server returned unexpected fields: u."); @@ -480,13 +488,14 @@ public async Task Authenticate_with_session_token_should_have_expected_result( connection.EnqueueCommandResponseMessage(saslContinueCommandResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); diff --git a/tests/MongoDB.Driver.Tests/Authentication/MongoDBX509AuthenticatorTests.cs b/tests/MongoDB.Driver.Tests/Authentication/MongoDBX509AuthenticatorTests.cs index 4a093dc1492..2c57123c3e7 100644 --- a/tests/MongoDB.Driver.Tests/Authentication/MongoDBX509AuthenticatorTests.cs +++ b/tests/MongoDB.Driver.Tests/Authentication/MongoDBX509AuthenticatorTests.cs @@ -20,6 +20,7 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver.Authentication; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -69,14 +70,14 @@ public async Task Authenticate_should_send_serverApi_with_command_wire_protocol( connection.Description = __descriptionCommandWireProtocol; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -104,14 +105,14 @@ public async Task Authenticate_with_loadBalancedConnection_should_use_command_wi connection.Description = null; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -140,9 +141,10 @@ public async Task Authenticate_should_throw_an_AuthenticationException_when_auth connection.Description = CreateConnectionDescription(maxWireVersion: WireVersion.Server36); connection.EnqueueCommandResponseMessage(response); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -161,9 +163,10 @@ public async Task Authenticate_should_not_throw_when_authentication_succeeds( connection.Description = CreateConnectionDescription(maxWireVersion: WireVersion.Server36); connection.EnqueueCommandResponseMessage(response); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeNull(); } @@ -184,9 +187,10 @@ public async Task Authenticate_should_not_throw_when_username_is_null( var description = CreateConnectionDescription(maxWireVersion: WireVersion.Server36); connection.Description = description; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, description)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, description)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, description)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, description)); exception.Should().BeNull(); } diff --git a/tests/MongoDB.Driver.Tests/Authentication/PlainAuthenticatorTests.cs b/tests/MongoDB.Driver.Tests/Authentication/PlainAuthenticatorTests.cs index 86100b111c7..977036ae4ee 100644 --- a/tests/MongoDB.Driver.Tests/Authentication/PlainAuthenticatorTests.cs +++ b/tests/MongoDB.Driver.Tests/Authentication/PlainAuthenticatorTests.cs @@ -21,6 +21,7 @@ using MongoDB.Bson; using MongoDB.Driver.Authentication; using MongoDB.Driver.Authentication.Plain; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -62,9 +63,10 @@ public async Task Authenticate_should_throw_an_AuthenticationException_when_auth connection.EnqueueCommandResponseMessage(response); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -84,14 +86,14 @@ public async Task Authenticate_should_not_throw_when_authentication_succeeds( connection.Description = __descriptionCommandWireProtocol; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -121,14 +123,14 @@ public async Task Authenticate_should_send_serverApi_with_command_wire_protocol( connection.Description = __descriptionCommandWireProtocol; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -156,14 +158,14 @@ public async Task Authenticate_with_loadBalancedConnection_should_use_command_wi connection.Description = null; var expectedRequestId = RequestMessage.CurrentGlobalRequestId + 1; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(5)).Should().BeTrue(); diff --git a/tests/MongoDB.Driver.Tests/Authentication/ScramSha1AuthenticatorTests.cs b/tests/MongoDB.Driver.Tests/Authentication/ScramSha1AuthenticatorTests.cs index c1a4254aadf..5e2688ed21c 100644 --- a/tests/MongoDB.Driver.Tests/Authentication/ScramSha1AuthenticatorTests.cs +++ b/tests/MongoDB.Driver.Tests/Authentication/ScramSha1AuthenticatorTests.cs @@ -23,6 +23,7 @@ using MongoDB.Bson; using MongoDB.Driver.Authentication; using MongoDB.Driver.Authentication.ScramSha; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -68,13 +69,14 @@ public async Task Authenticate_should_send_serverApi_with_command_wire_protocol( connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -103,13 +105,14 @@ public async Task Authenticate_with_loadBalancedConnection_should_use_command_wi connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = null; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -137,9 +140,10 @@ public async Task Authenticate_should_throw_an_AuthenticationException_when_auth connection.EnqueueCommandResponseMessage(responseException); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -159,9 +163,10 @@ public async Task Authenticate_should_throw_when_server_provides_invalid_r_value connection.EnqueueCommandResponseMessage(saslStartResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -184,9 +189,10 @@ public async Task Authenticate_should_throw_when_server_provides_invalid_serverS connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -223,11 +229,12 @@ public async Task Authenticate_should_not_throw_when_authentication_succeeds( connection.Description = new ConnectionDescription(__descriptionCommandWireProtocol.ConnectionId, new HelloResult(helloResult)); BsonDocument helloCommand = null; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (useSpeculativeAuthenticate) { // Call CustomizeInitialHelloCommand so that the authenticator thinks its started to speculatively // authenticate - helloCommand = subject.CustomizeInitialHelloCommand(OperationContext.NoTimeout, new BsonDocument { { OppressiveLanguageConstants.LegacyHelloCommandName, 1 } }); + helloCommand = subject.CustomizeInitialHelloCommand(operationContext, new BsonDocument { { OppressiveLanguageConstants.LegacyHelloCommandName, 1 } }); } else { @@ -242,11 +249,11 @@ public async Task Authenticate_should_not_throw_when_authentication_succeeds( if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, connection.Description); + await subject.AuthenticateAsync(operationContext, connection, connection.Description); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, connection.Description); + subject.Authenticate(operationContext, connection, connection.Description); } var expectedSentMessageCount = 3 - (useLongAuthentication ? 0 : 1) - (useSpeculativeAuthenticate ? 1 : 0); @@ -357,13 +364,14 @@ public async Task Authenticate_should_use_cache( connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)) diff --git a/tests/MongoDB.Driver.Tests/Authentication/ScramSha256AuthenticatorTests.cs b/tests/MongoDB.Driver.Tests/Authentication/ScramSha256AuthenticatorTests.cs index 027ef3e7874..751be0334ca 100644 --- a/tests/MongoDB.Driver.Tests/Authentication/ScramSha256AuthenticatorTests.cs +++ b/tests/MongoDB.Driver.Tests/Authentication/ScramSha256AuthenticatorTests.cs @@ -24,6 +24,7 @@ using MongoDB.Bson.TestHelpers; using MongoDB.Driver.Authentication; using MongoDB.Driver.Authentication.ScramSha; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -118,13 +119,14 @@ public async Task Authenticate_should_send_serverApi_with_command_wire_protocol( connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -153,13 +155,14 @@ public async Task Authenticate_with_loadBalancedConnection_should_use_command_wi connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = null; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)).Should().BeTrue(); @@ -187,9 +190,10 @@ public async Task Authenticate_should_throw_an_AuthenticationException_when_auth connection.EnqueueCommandResponseMessage(responseException); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -212,9 +216,10 @@ public async Task Authenticate_should_throw_when_server_provides_invalid_r_value connection.EnqueueCommandResponseMessage(poisonedSaslStartResponseMessage); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -244,9 +249,10 @@ public async Task Authenticate_should_throw_when_server_provides_invalid_serverS connection.EnqueueCommandResponseMessage(poisonedSaslContinueResponseMessage); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol)) : + Record.Exception(() => subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol)); exception.Should().BeOfType(); } @@ -284,13 +290,13 @@ public async Task Authenticate_should_not_throw_when_authentication_succeeds( } connection.Description = new ConnectionDescription(__descriptionCommandWireProtocol.ConnectionId, new HelloResult(helloResult)); - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); BsonDocument helloCommand = null; if (useSpeculativeAuthenticate) { // We must call CustomizeInitialHelloCommand so that the authenticator thinks its started to speculatively // authenticate - helloCommand = subject.CustomizeInitialHelloCommand(OperationContext.NoTimeout, new BsonDocument { { OppressiveLanguageConstants.LegacyHelloCommandName, 1 } }); + helloCommand = subject.CustomizeInitialHelloCommand(operationContext, new BsonDocument { { OppressiveLanguageConstants.LegacyHelloCommandName, 1 } }); } else { @@ -307,11 +313,11 @@ public async Task Authenticate_should_not_throw_when_authentication_succeeds( if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, connection.Description); + await subject.AuthenticateAsync(operationContext, connection, connection.Description); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, connection.Description); + subject.Authenticate(operationContext, connection, connection.Description); } var expectedSentMessageCount = 3 - (useLongAuthentication ? 0 : 1) - (useSpeculativeAuthenticate ? 1 : 0); @@ -432,13 +438,14 @@ public async Task Authenticate_should_use_cache( connection.EnqueueCommandResponseMessage(saslContinueResponse); connection.Description = __descriptionCommandWireProtocol; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, connection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, connection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, connection, __descriptionCommandWireProtocol); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 2, TimeSpan.FromSeconds(5)) @@ -477,14 +484,14 @@ public Task Authenticate_should_work_regardless_of_culture( mockConnection.EnqueueCommandResponseMessage(serverResponseMessage2); mockConnection.Description = __descriptionCommandWireProtocol; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.AuthenticateAsync(OperationContext.NoTimeout, mockConnection, __descriptionCommandWireProtocol); + await subject.AuthenticateAsync(operationContext, mockConnection, __descriptionCommandWireProtocol); } else { - subject.Authenticate(OperationContext.NoTimeout, mockConnection, __descriptionCommandWireProtocol); + subject.Authenticate(operationContext, mockConnection, __descriptionCommandWireProtocol); } }); diff --git a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs index ae96102e662..20034611f79 100644 --- a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs +++ b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs @@ -18,6 +18,7 @@ using System.Security.Cryptography.X509Certificates; using FluentAssertions; using MongoDB.Bson; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; @@ -338,8 +339,9 @@ private void AssertAuthenticationSucceeds( speculativeAuthenticatationShouldSucceedIfPossible) { var serverSelector = new ReadPreferenceServerSelector(settings.ReadPreference); - var server = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, serverSelector); - var channel = server.GetChannel(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var server = client.GetClusterInternal().SelectServer(operationContext, serverSelector); + var channel = server.GetChannel(operationContext); 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 683fa0ccaeb..fdabf99cb43 100644 --- a/tests/MongoDB.Driver.Tests/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterTests.cs @@ -89,7 +89,7 @@ public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool asy { using var failPoint = FailPoint.Configure(WritableServerSelector.Instance, failCommand, async, client.GetClusterInternal()); var slowServer = failPoint.Server; - var fastServer = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId))); + var fastServer = client.GetClusterInternal().Servers.First(s => s.ServerId != slowServer.ServerId); var database = client.GetDatabase(_databaseName); CreateCollection(); @@ -99,8 +99,9 @@ public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool asy var channels = new ConcurrentBag(); ThreadingUtilities.ExecuteOnNewThreads(threadsCount, i => { - channels.Add(slowServer.GetChannel(OperationContext.NoTimeout)); - channels.Add(fastServer.GetChannel(OperationContext.NoTimeout)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + channels.Add(slowServer.GetChannel(operationContext)); + channels.Add(fastServer.GetChannel(operationContext)); }); 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 650f074169d..05a00ea8fc4 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2017-present MongoDB Inc. +/* 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. @@ -31,23 +31,20 @@ public void constructor_should_initialize_instance() { var server = new Mock().Object; var channel = new Mock().Object; - var session = new Mock().Object; - var result = new ChannelChannelSource(server, channel, session); + var result = new ChannelChannelSource(server, channel); result._channel().Should().BeSameAs(channel); result._disposed().Should().BeFalse(); result.Server.Should().BeSameAs(server); - result.Session.Should().BeSameAs(session); } [Fact] public void constructor_should_throw_when_server_is_null() { var channel = new Mock().Object; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelChannelSource(null, channel, session)); + var exception = Record.Exception(() => new ChannelChannelSource(null, channel)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("server"); @@ -57,26 +54,13 @@ public void constructor_should_throw_when_server_is_null() public void constructor_should_throw_when_channel_is_null() { var server = new Mock().Object; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelChannelSource(server, null, session)); + var exception = Record.Exception(() => new ChannelChannelSource(server, null)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("channel"); } - [Fact] - public void constructor_should_throw_when_session_is_null() - { - var server = new Mock().Object; - var channel = new Mock().Object; - - var exception = Record.Exception(() => new ChannelChannelSource(server, channel, null)); - - var e = exception.Should().BeOfType().Subject; - e.ParamName.Should().Be("session"); - } - [Fact] public void Server_should_return_expected_result() { @@ -94,48 +78,33 @@ public void ServerDescription_should_call_server() var mockServer = new Mock(); var subject = CreateSubject(server: mockServer.Object); - var result = subject.ServerDescription; + _ = subject.ServerDescription; mockServer.VerifyGet(m => m.Description, Times.Once); } - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = CreateSubject(session: session); - - var result = subject.Session; - - result.Should().BeSameAs(session); - } - [Fact] public void Dispose_should_have_expected_result() { var mockChannel = new Mock(); - var mockSession = new Mock(); - var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); + var subject = CreateSubject(channel: mockChannel.Object); subject.Dispose(); subject._disposed().Should().BeTrue(); mockChannel.Verify(m => m.Dispose(), Times.Once); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Fact] public void Dispose_can_be_called_more_than_once() { var mockChannel = new Mock(); - var mockSession = new Mock(); - var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); + var subject = CreateSubject(channel: mockChannel.Object); subject.Dispose(); subject.Dispose(); mockChannel.Verify(m => m.Dispose(), Times.Once); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Theory] @@ -148,9 +117,10 @@ public async Task GetChannel_should_return_expected_result( var expectedResult = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(expectedResult); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetChannelAsync(OperationContext.NoTimeout) : - subject.GetChannel(OperationContext.NoTimeout); + await subject.GetChannelAsync(operationContext) : + subject.GetChannel(operationContext); result.Should().BeSameAs(expectedResult); mockChannel.Verify(m => m.Fork(), Times.Once); @@ -163,9 +133,10 @@ public async Task GetChannel_should_throw_when_disposed( { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(operationContext)) : + Record.Exception(() => subject.GetChannel(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -179,13 +150,8 @@ private ChannelChannelSource CreateDisposedSubject() return subject; } - private ChannelChannelSource CreateSubject(IServer server = null, IChannelHandle channel = null, ICoreSessionHandle session = null) - { - return new ChannelChannelSource( - server ?? new Mock().Object, - channel ?? new Mock().Object, - session ?? new Mock().Object); - } + private ChannelChannelSource CreateSubject(IServer server = null, IChannelHandle channel = null) => + new(server ?? new Mock().Object, channel ?? new Mock().Object); } internal static class ChannelChannelSourceReflector diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs index 1d6f317e611..ba11ba0aaa1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2017-present MongoDB Inc. +/* 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. @@ -32,15 +32,13 @@ public void constructor_should_initialize_instance() var server = new Mock().Object; var channel = new Mock().Object; var readPreference = ReadPreference.Primary; - var session = new Mock().Object; - var result = new ChannelReadBinding(server, channel, readPreference, session); + var result = new ChannelReadBinding(server, channel, readPreference); result._channel().Should().BeSameAs(channel); result._disposed().Should().BeFalse(); result.ReadPreference.Should().BeSameAs(readPreference); result._server().Should().BeSameAs(server); - result.Session.Should().BeSameAs(session); } [Fact] @@ -48,9 +46,8 @@ public void constructor_should_throw_when_server_is_null() { var channel = new Mock().Object; var readPreference = ReadPreference.Primary; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelReadBinding(null, channel, readPreference, session)); + var exception = Record.Exception(() => new ChannelReadBinding(null, channel, readPreference)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("server"); @@ -61,9 +58,8 @@ public void constructor_should_throw_when_channel_is_null() { var server = new Mock().Object; var readPreference = ReadPreference.Primary; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelReadBinding(server, null, readPreference, session)); + var exception = Record.Exception(() => new ChannelReadBinding(server, null, readPreference)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("channel"); @@ -74,27 +70,13 @@ public void constructor_should_throw_when_readPreference_is_null() { var server = new Mock().Object; var channel = new Mock().Object; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelReadBinding(server, channel, null, session)); + var exception = Record.Exception(() => new ChannelReadBinding(server, channel, null)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("readPreference"); } - [Fact] - public void constructor_should_throw_when_session_is_null() - { - var server = new Mock().Object; - var channel = new Mock().Object; - var readPreference = ReadPreference.Primary; - - var exception = Record.Exception(() => new ChannelReadBinding(server, channel, readPreference, null)); - - var e = exception.Should().BeOfType().Subject; - e.ParamName.Should().Be("session"); - } - [Fact] public void ReadPreference_should_return_expected_result() { @@ -106,43 +88,28 @@ public void ReadPreference_should_return_expected_result() result.Should().BeSameAs(readPreference); } - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = CreateSubject(session: session); - - var result = subject.Session; - - result.Should().BeSameAs(session); - } - [Fact] public void Dispose_should_have_expected_result() { var mockChannel = new Mock(); - var mockSession = new Mock(); - var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); + var subject = CreateSubject(channel: mockChannel.Object); subject.Dispose(); subject._disposed().Should().BeTrue(); mockChannel.Verify(m => m.Dispose(), Times.Once); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Fact] public void Dispose_can_be_called_more_than_once() { var mockChannel = new Mock(); - var mockSession = new Mock(); - var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); + var subject = CreateSubject(channel: mockChannel.Object); subject.Dispose(); subject.Dispose(); mockChannel.Verify(m => m.Dispose(), Times.Once); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Theory] @@ -151,23 +118,20 @@ 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); + var subject = CreateSubject(channel: mockChannel.Object); var forkedChannel = new Mock().Object; - var forkedSession = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(forkedChannel); - mockSession.Setup(m => m.Fork()).Returns(forkedSession); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : - subject.GetReadChannelSource(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext) : + subject.GetReadChannelSource(operationContext); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); var newSource = referenceCounted.Instance.Should().BeOfType().Subject; newSource._channel().Should().Be(forkedChannel); - newSource.Session.Should().Be(forkedSession); } [Theory] @@ -176,9 +140,10 @@ public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -192,13 +157,12 @@ private ChannelReadBinding CreateDisposedSubject() return subject; } - private ChannelReadBinding CreateSubject(IServer server = null, IChannelHandle channel = null, ReadPreference readPreference = null, ICoreSessionHandle session = null) + private ChannelReadBinding CreateSubject(IServer server = null, IChannelHandle channel = null, ReadPreference readPreference = null) { return new ChannelReadBinding( server ?? new Mock().Object, channel ?? new Mock().Object, - readPreference ?? ReadPreference.Primary, - session ?? new Mock().Object); + readPreference ?? ReadPreference.Primary); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs index acc8fdfa4ad..7158cb5e53c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2017-present MongoDB Inc. +/* 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. @@ -31,23 +31,20 @@ public void constructor_should_initialize_instance() { var server = new Mock().Object; var channel = new Mock().Object; - var session = new Mock().Object; - var result = new ChannelReadWriteBinding(server, channel, session); + var result = new ChannelReadWriteBinding(server, channel); result._channel().Should().BeSameAs(channel); result._disposed().Should().BeFalse(); result._server().Should().BeSameAs(server); - result.Session.Should().BeSameAs(session); } [Fact] public void constructor_should_throw_when_server_is_null() { var channel = new Mock().Object; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelReadWriteBinding(null, channel, session)); + var exception = Record.Exception(() => new ChannelReadWriteBinding(null, channel)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("server"); @@ -57,26 +54,13 @@ public void constructor_should_throw_when_server_is_null() public void constructor_should_throw_when_channel_is_null() { var server = new Mock().Object; - var session = new Mock().Object; - var exception = Record.Exception(() => new ChannelReadWriteBinding(server, null, session)); + var exception = Record.Exception(() => new ChannelReadWriteBinding(server, null)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("channel"); } - [Fact] - public void constructor_should_throw_when_session_is_null() - { - var server = new Mock().Object; - var channel = new Mock().Object; - - var exception = Record.Exception(() => new ChannelReadWriteBinding(server, channel, null)); - - var e = exception.Should().BeOfType().Subject; - e.ParamName.Should().Be("session"); - } - [Fact] public void ReadPreference_should_return_expected_result() { @@ -87,43 +71,28 @@ public void ReadPreference_should_return_expected_result() result.Should().Be(ReadPreference.Primary); } - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = CreateSubject(session: session); - - var result = subject.Session; - - result.Should().Be(session); - } - [Fact] public void Dispose_should_have_expected_result() { var mockChannel = new Mock(); - var mockSession = new Mock(); - var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); + var subject = CreateSubject(channel: mockChannel.Object); subject.Dispose(); subject._disposed().Should().BeTrue(); mockChannel.Verify(m => m.Dispose(), Times.Once); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Fact] public void Dispose_can_be_called_more_than_once() { var mockChannel = new Mock(); - var mockSession = new Mock(); - var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); + var subject = CreateSubject(channel: mockChannel.Object); subject.Dispose(); subject.Dispose(); mockChannel.Verify(m => m.Dispose(), Times.Once); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Theory] @@ -132,23 +101,20 @@ 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); + var subject = CreateSubject(channel: mockChannel.Object); var forkedChannel = new Mock().Object; - var forkedSession = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(forkedChannel); - mockSession.Setup(m => m.Fork()).Returns(forkedSession); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : - subject.GetReadChannelSource(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext) : + subject.GetReadChannelSource(operationContext); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); var newSource = referenceCounted.Instance.Should().BeOfType().Subject; newSource._channel().Should().Be(forkedChannel); - newSource.Session.Should().Be(forkedSession); } [Theory] @@ -157,23 +123,20 @@ 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); + var subject = CreateSubject(channel: mockChannel.Object); var forkedChannel = new Mock().Object; - var forkedSession = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(forkedChannel); - mockSession.Setup(m => m.Fork()).Returns(forkedSession); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout) : - subject.GetWriteChannelSource(OperationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(operationContext) : + subject.GetWriteChannelSource(operationContext); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); var newSource = referenceCounted.Instance.Should().BeOfType().Subject; newSource._channel().Should().Be(forkedChannel); - newSource.Session.Should().Be(forkedSession); } [Theory] @@ -182,9 +145,10 @@ public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -196,9 +160,10 @@ public async Task GetWriteChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetWriteChannelSource(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -212,12 +177,11 @@ private ChannelReadWriteBinding CreateDisposedSubject() return subject; } - private ChannelReadWriteBinding CreateSubject(IServer server = null, IChannelHandle channel = null, ICoreSessionHandle session = null) + private ChannelReadWriteBinding CreateSubject(IServer server = null, IChannelHandle channel = null) { return new ChannelReadWriteBinding( server ?? new Mock().Object, - channel ?? new Mock().Object, - session ?? new Mock().Object); + channel ?? new Mock().Object); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs index 37031583a76..03a2c7fee30 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson.TestHelpers; @@ -42,16 +41,6 @@ public void Constructor_should_throw_if_channelSource_is_null() act.ShouldThrow(); } - [Fact] - public void Session_should_delegate_to_reference() - { - var subject = new ChannelSourceHandle(_mockChannelSource.Object); - - var result = subject.Session; - - _mockChannelSource.Verify(m => m.Session, Times.Once); - } - [Theory] [ParameterAttributeData] public async Task GetChannel_should_throw_if_disposed( @@ -61,9 +50,10 @@ public async Task GetChannel_should_throw_if_disposed( var subject = new ChannelSourceHandle(_mockChannelSource.Object); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(operationContext)) : + Record.Exception(() => subject.GetChannel(operationContext)); exception.Should().BeOfType(); } @@ -75,16 +65,16 @@ public async Task GetChannel_should_delegate_to_reference( bool async) { var subject = new ChannelSourceHandle(_mockChannelSource.Object); - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.GetChannelAsync(OperationContext.NoTimeout); + await subject.GetChannelAsync(operationContext); _mockChannelSource.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.GetChannel(OperationContext.NoTimeout); + subject.GetChannel(operationContext); _mockChannelSource.Verify(s => s.GetChannel(It.IsAny()), Times.Once); } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs index 070b01d7e48..59e808be9c6 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -39,16 +39,6 @@ public void Constructor_should_throw_if_readWriteBinding_is_null() act.ShouldThrow(); } - [Fact] - public void Session_should_delegate_to_reference() - { - var subject = new ReadBindingHandle(_mockReadBinding.Object); - - var result = subject.Session; - - _mockReadBinding.Verify(m => m.Session, Times.Once); - } - [Theory] [ParameterAttributeData] public async Task GetReadChannelSource_should_throw_if_disposed( @@ -58,9 +48,10 @@ public async Task GetReadChannelSource_should_throw_if_disposed( var subject = new ReadBindingHandle(_mockReadBinding.Object); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); exception.Should().BeOfType(); } @@ -73,17 +64,18 @@ public async Task GetReadChannelSource_should_delegate_to_reference( { var subject = new ReadBindingHandle(_mockReadBinding.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext); - _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(OperationContext.NoTimeout), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetReadChannelSource(OperationContext.NoTimeout); + subject.GetReadChannelSource(operationContext); - _mockReadBinding.Verify(b => b.GetReadChannelSource(OperationContext.NoTimeout), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSource(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs index c3486f158e5..f4b84819a26 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2013-present MongoDB Inc. +/* 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. @@ -40,7 +40,7 @@ public ReadPreferenceBindingTests() [Fact] public void Constructor_should_throw_if_cluster_is_null() { - Action act = () => new ReadPreferenceBinding(null, ReadPreference.Primary, NoCoreSession.NewHandle()); + Action act = () => new ReadPreferenceBinding(null, ReadPreference.Primary); act.ShouldThrow(); } @@ -48,42 +48,24 @@ public void Constructor_should_throw_if_cluster_is_null() [Fact] public void Constructor_should_throw_if_readPreference_is_null() { - Action act = () => new ReadPreferenceBinding(_mockCluster.Object, null, NoCoreSession.NewHandle()); + Action act = () => new ReadPreferenceBinding(_mockCluster.Object, null); act.ShouldThrow(); } - [Fact] - public void Constructor_should_throw_if_session_is_null() - { - Action act = () => new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, null); - - act.ShouldThrow(); - } - - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, session); - - var result = subject.Session; - - result.Should().BeSameAs(session); - } - [Theory] [ParameterAttributeData] public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { - var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); + var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); exception.Should().BeOfType(); } @@ -94,7 +76,7 @@ public async Task GetReadChannelSource_should_use_a_read_preference_server_selec [Values(false, true)] bool async) { - var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); + var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary); var selectedServer = new Mock().Object; var clusterId = new ClusterId(); @@ -109,11 +91,12 @@ public async Task GetReadChannelSource_should_use_a_read_preference_server_selec var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone); _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext); _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } @@ -121,7 +104,7 @@ public async Task GetReadChannelSource_should_use_a_read_preference_server_selec { _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetReadChannelSource(OperationContext.NoTimeout); + subject.GetReadChannelSource(operationContext); _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } @@ -132,13 +115,10 @@ public async Task GetReadChannelSource_should_use_a_read_preference_server_selec 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); + var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary); var selectedServer = new Mock().Object; _mockCluster.Setup(m => m.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - var forkedSession = new Mock().Object; - mockSession.Setup(m => m.Fork()).Returns(forkedSession); var clusterId = new ClusterId(); var endPoint = new DnsEndPoint("localhost", 27017); @@ -152,36 +132,24 @@ public async Task GetReadChannelSource_should_fork_the_session( var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone); _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : - subject.GetReadChannelSource(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext) : + subject.GetReadChannelSource(operationContext); var handle = result.Should().BeOfType().Subject; - var referenceCounted = handle._reference().Should().BeOfType>().Subject; - var source = referenceCounted.Instance; - source.Session.Should().BeSameAs(forkedSession); + handle._reference().Should().BeOfType>(); } [Fact] public void Dispose_should_not_call_dispose_on_the_cluster() { - var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); + var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary); subject.Dispose(); _mockCluster.Verify(c => c.Dispose(), Times.Never); } - - [Fact] - public void Dispose_should_call_dispose_on_the_session() - { - var mockSession = new Mock(); - var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, mockSession.Object); - - subject.Dispose(); - - mockSession.Verify(c => c.Dispose(), Times.Once); - } } internal static class ReadPreferenceBindingReflector diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs index 7549be8c4c8..e7f5fad0f44 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs @@ -24,29 +24,12 @@ namespace MongoDB.Driver.Core.Bindings { public class ReadWriteBindingHandleTests { - private Mock _mockReadWriteBinding; - - public ReadWriteBindingHandleTests() - { - _mockReadWriteBinding = new Mock(); - } - [Fact] public void Constructor_should_throw_if_readWriteBinding_is_null() { - Action act = () => new ReadWriteBindingHandle(null); - - act.ShouldThrow(); - } - - [Fact] - public void Session_should_delegate_to_reference() - { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); - - var result = subject.Session; + var exception = Record.Exception(() => new ReadWriteBindingHandle(null)); - _mockReadWriteBinding.Verify(m => m.Session, Times.Once); + exception.Should().BeOfType(); } [Theory] @@ -55,12 +38,13 @@ public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var subject = new ReadWriteBindingHandle(Mock.Of()); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); exception.Should().BeOfType(); } @@ -71,19 +55,21 @@ public async Task GetReadChannelSource_should_delegate_to_reference( [Values(false, true)] bool async) { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var mockReadWriteBinding = new Mock(); + var subject = new ReadWriteBindingHandle(mockReadWriteBinding.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext); - _mockReadWriteBinding.Verify(b => b.GetReadChannelSourceAsync(It.IsAny()), Times.Once); + mockReadWriteBinding.Verify(b => b.GetReadChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetReadChannelSource(OperationContext.NoTimeout); + subject.GetReadChannelSource(operationContext); - _mockReadWriteBinding.Verify(b => b.GetReadChannelSource(It.IsAny()), Times.Once); + mockReadWriteBinding.Verify(b => b.GetReadChannelSource(It.IsAny()), Times.Once); } } @@ -93,12 +79,13 @@ public async Task GetWriteChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var subject = new ReadWriteBindingHandle(Mock.Of()); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetWriteChannelSource(operationContext)); exception.Should().BeOfType(); } @@ -109,26 +96,28 @@ public async Task GetWriteChannelSource_should_delegate_to_reference( [Values(false, true)] bool async) { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var mockReadWriteBinding = new Mock(); + var subject = new ReadWriteBindingHandle(mockReadWriteBinding.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(operationContext); - _mockReadWriteBinding.Verify(b => b.GetWriteChannelSourceAsync(It.IsAny()), Times.Once); + mockReadWriteBinding.Verify(b => b.GetWriteChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetWriteChannelSource(OperationContext.NoTimeout); + subject.GetWriteChannelSource(operationContext); - _mockReadWriteBinding.Verify(b => b.GetWriteChannelSource(It.IsAny()), Times.Once); + mockReadWriteBinding.Verify(b => b.GetWriteChannelSource(It.IsAny()), Times.Once); } } [Fact] public void Fork_should_throw_if_disposed() { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var subject = new ReadWriteBindingHandle(Mock.Of()); subject.Dispose(); Action act = () => subject.Fork(); @@ -139,46 +128,49 @@ public void Fork_should_throw_if_disposed() [Fact] public void Disposing_of_handle_after_fork_should_not_dispose_of_channelSource() { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var mockReadWriteBinding = new Mock(); + var subject = new ReadWriteBindingHandle(mockReadWriteBinding.Object); var forked = subject.Fork(); subject.Dispose(); - _mockReadWriteBinding.Verify(b => b.Dispose(), Times.Never); + mockReadWriteBinding.Verify(b => b.Dispose(), Times.Never); forked.Dispose(); - _mockReadWriteBinding.Verify(b => b.Dispose(), Times.Once); + mockReadWriteBinding.Verify(b => b.Dispose(), Times.Once); } [Fact] public void Disposing_of_fork_before_disposing_of_subject_hould_not_dispose_of_channelSource() { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var mockReadWriteBinding = new Mock(); + var subject = new ReadWriteBindingHandle(mockReadWriteBinding.Object); var forked = subject.Fork(); forked.Dispose(); - _mockReadWriteBinding.Verify(b => b.Dispose(), Times.Never); + mockReadWriteBinding.Verify(b => b.Dispose(), Times.Never); subject.Dispose(); - _mockReadWriteBinding.Verify(b => b.Dispose(), Times.Once); + mockReadWriteBinding.Verify(b => b.Dispose(), Times.Once); } [Fact] public void Disposing_of_last_handle_should_dispose_of_connectioSource() { - var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); + var mockReadWriteBinding = new Mock(); + var subject = new ReadWriteBindingHandle(mockReadWriteBinding.Object); var forked = subject.Fork(); subject.Dispose(); forked.Dispose(); - _mockReadWriteBinding.Verify(b => b.Dispose(), Times.Once); + mockReadWriteBinding.Verify(b => b.Dispose(), Times.Once); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs index bd6737efdb1..8b9bddff2b7 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs @@ -30,62 +30,38 @@ public class ServerChannelSourceTests [Fact] public void Constructor_should_throw_when_server_is_null() { - var session = new Mock().Object; - var exception = Record.Exception(() => new ServerChannelSource(null, session)); + var exception = Record.Exception(() => new ServerChannelSource(null)); exception.Should().BeOfType() .Subject.ParamName.Should().Be("server"); } - [Fact] - public void Constructor_should_throw_when_session_is_null() - { - var server = Mock.Of(); - - var exception = Record.Exception(() => new ServerChannelSource(server, null)); - - exception.Should().BeOfType() - .Subject.ParamName.Should().Be("session"); - } - [Fact] public void ServerDescription_should_return_description_of_server() { - var session = new Mock().Object; var desc = ServerDescriptionHelper.Disconnected(new ClusterId()); var serverMock = new Mock(); serverMock.SetupGet(s => s.Description).Returns(desc); - var subject = new ServerChannelSource(serverMock.Object, session); + var subject = new ServerChannelSource(serverMock.Object); var result = subject.ServerDescription; result.Should().BeSameAs(desc); } - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = new ServerChannelSource(Mock.Of(), session); - - var result = subject.Session; - - result.Should().BeSameAs(session); - } - [Theory] [ParameterAttributeData] public async Task GetChannel_should_throw_if_disposed( [Values(false, true)] bool async) { - var session = new Mock().Object; - var subject = new ServerChannelSource(Mock.Of(), session); + var subject = new ServerChannelSource(Mock.Of()); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(operationContext)) : + Record.Exception(() => subject.GetChannel(operationContext)); exception.Should().BeOfType(); } @@ -97,18 +73,18 @@ public async Task GetChannel_should_get_connection_from_server( bool async) { var serverMock = new Mock(); - var session = new Mock().Object; - var subject = new ServerChannelSource(serverMock.Object, session); + var subject = new ServerChannelSource(serverMock.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.GetChannelAsync(OperationContext.NoTimeout); + await subject.GetChannelAsync(operationContext); serverMock.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.GetChannel(OperationContext.NoTimeout); + subject.GetChannel(operationContext); serverMock.Verify(s => s.GetChannel(It.IsAny()), Times.Once); } @@ -117,12 +93,9 @@ public async Task GetChannel_should_get_connection_from_server( [Fact] public void Dispose_should_dispose_session() { - var mockSession = new Mock(); - var subject = new ServerChannelSource(Mock.Of(), mockSession.Object); + var subject = new ServerChannelSource(Mock.Of()); subject.Dispose(); - - mockSession.Verify(m => m.Dispose(), Times.Once); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs index 27bb8dcb760..77dc6ac534d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs @@ -35,14 +35,12 @@ public void constructor_should_initialize_instance() var cluster = new Mock().Object; var server = CreateMockServer().Object; var readPreference = ReadPreference.Primary; - var session = new Mock().Object; - var result = new SingleServerReadBinding(cluster, server, readPreference, session); + var result = new SingleServerReadBinding(cluster, server, readPreference); result._cluster().Should().BeSameAs(cluster); result._disposed().Should().BeFalse(); result.ReadPreference.Should().BeSameAs(readPreference); - result.Session.Should().BeSameAs(session); } [Fact] @@ -50,9 +48,8 @@ public void constructor_should_throw_when_cluster_is_null() { var server = CreateMockServer().Object; var readPreference = ReadPreference.Primary; - var session = new Mock().Object; - var exception = Record.Exception(() => new SingleServerReadBinding(null, server, readPreference, session)); + var exception = Record.Exception(() => new SingleServerReadBinding(null, server, readPreference)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("cluster"); @@ -63,9 +60,8 @@ public void constructor_should_throw_when_server_is_null() { var cluster = new Mock().Object; var readPreference = ReadPreference.Primary; - var session = new Mock().Object; - var exception = Record.Exception(() => new SingleServerReadBinding(cluster, null, readPreference, session)); + var exception = Record.Exception(() => new SingleServerReadBinding(cluster, null, readPreference)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("server"); @@ -76,27 +72,13 @@ public void constructor_should_throw_when_readPreference_is_null() { var cluster = new Mock().Object; var server = CreateMockServer().Object; - var session = new Mock().Object; - var exception = Record.Exception(() => new SingleServerReadBinding(cluster, server, null, session)); + var exception = Record.Exception(() => new SingleServerReadBinding(cluster, server, null)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("readPreference"); } - [Fact] - public void constructor_should_throw_when_session_is_null() - { - var cluster = new Mock().Object; - var server = CreateMockServer().Object; - var readPreference = ReadPreference.Primary; - - var exception = Record.Exception(() => new SingleServerReadBinding(cluster, server, readPreference, null)); - - var e = exception.Should().BeOfType().Subject; - e.ParamName.Should().Be("session"); - } - [Fact] public void ReadPreference_should_return_expected_result() { @@ -108,39 +90,23 @@ public void ReadPreference_should_return_expected_result() result.Should().BeSameAs(readPreference); } - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = CreateSubject(session: session); - - var result = subject.Session; - - result.Should().BeSameAs(session); - } - [Fact] public void Dispose_should_have_expected_result() { - var mockSession = new Mock(); - var subject = CreateSubject(session: mockSession.Object); + var subject = CreateSubject(); subject.Dispose(); subject._disposed().Should().BeTrue(); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Fact] public void Dispose_can_be_called_more_than_once() { - var mockSession = new Mock(); - var subject = CreateSubject(session: mockSession.Object); + var subject = CreateSubject(); subject.Dispose(); subject.Dispose(); - - mockSession.Verify(m => m.Dispose(), Times.Once); } [Theory] @@ -150,9 +116,10 @@ public async Task GetReadChannelSource_should_throw_when_disposed( { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -172,14 +139,15 @@ public async Task GetReadChannelSource_should_call_cluster_SelectServer( serverMock.Setup(s => s.EndPoint).Returns(endpoint); var subject = CreateSubject(cluster: clusterMock.Object, server: serverMock.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - _ = await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); + _ = await subject.GetReadChannelSourceAsync(operationContext); clusterMock.Verify(c => c.SelectServerAsync(It.IsAny(), It.Is(s => s.EndPoint == endpoint))); } else { - _ = subject.GetReadChannelSource(OperationContext.NoTimeout); + _ = subject.GetReadChannelSource(operationContext); clusterMock.Verify(c => c.SelectServer(It.IsAny(), It.Is(s => s.EndPoint == endpoint))); } } @@ -192,21 +160,11 @@ private SingleServerReadBinding CreateDisposedSubject() return subject; } - private SingleServerReadBinding CreateSubject(IClusterInternal cluster = null, IServer server = null, ReadPreference readPreference = null, ICoreSessionHandle session = null) - { - if (session == null) - { - var sessionMock = new Mock(); - sessionMock.Setup(m => m.Fork()).Returns(sessionMock.Object); - session = sessionMock.Object; - } - - return new SingleServerReadBinding( + private SingleServerReadBinding CreateSubject(IClusterInternal cluster = null, IServer server = null, ReadPreference readPreference = null) => + new( cluster ?? new Mock().Object, server ?? CreateMockServer().Object, - readPreference ?? ReadPreference.Primary, - session); - } + readPreference ?? ReadPreference.Primary); private Mock CreateMockServer() { diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs index 2efd25ca017..1413db50b91 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs @@ -30,37 +30,22 @@ public class SingleServerReadWriteBindingTests public void constructor_should_initialize_instance() { var server = new Mock().Object; - var session = new Mock().Object; - var result = new SingleServerReadWriteBinding(server, session); + var result = new SingleServerReadWriteBinding(server); result._disposed().Should().BeFalse(); result._server().Should().BeSameAs(server); - result.Session.Should().BeSameAs(session); } [Fact] public void constructor_should_throw_when_server_is_null() { - var session = new Mock().Object; - - var exception = Record.Exception(() => new SingleServerReadWriteBinding(null, session)); + var exception = Record.Exception(() => new SingleServerReadWriteBinding(null)); var e = exception.Should().BeOfType().Subject; e.ParamName.Should().Be("server"); } - [Fact] - public void constructor_should_throw_when_session_is_null() - { - var server = new Mock().Object; - - var exception = Record.Exception(() => new SingleServerReadWriteBinding(server, null)); - - var e = exception.Should().BeOfType().Subject; - e.ParamName.Should().Be("session"); - } - [Fact] public void ReadPreference_should_return_expected_result() { @@ -71,39 +56,23 @@ public void ReadPreference_should_return_expected_result() result.Should().Be(ReadPreference.Primary); } - [Fact] - public void Session_should_return_expected_result() - { - var session = new Mock().Object; - var subject = CreateSubject(session: session); - - var result = subject.Session; - - result.Should().Be(session); - } - [Fact] public void Dispose_should_have_expected_result() { - var mockSession = new Mock(); - var subject = CreateSubject(session: mockSession.Object); + var subject = CreateSubject(); subject.Dispose(); subject._disposed().Should().BeTrue(); - mockSession.Verify(m => m.Dispose(), Times.Once); } [Fact] public void Dispose_can_be_called_more_than_once() { - var mockSession = new Mock(); - var subject = CreateSubject(session: mockSession.Object); + var subject = CreateSubject(); subject.Dispose(); subject.Dispose(); - - mockSession.Verify(m => m.Dispose(), Times.Once); } [Theory] @@ -111,19 +80,16 @@ public void Dispose_can_be_called_more_than_once() public async Task GetReadChannelSource_should_return_expected_result( [Values(false, true)] bool async) { - var mockSession = new Mock(); - var subject = CreateSubject(session: mockSession.Object); - var forkedSession = new Mock().Object; - mockSession.Setup(m => m.Fork()).Returns(forkedSession); + var subject = CreateSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : - subject.GetReadChannelSource(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext) : + subject.GetReadChannelSource(operationContext); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); - var source = referenceCounted.Instance.Should().BeOfType().Subject; - source.Session.Should().BeSameAs(forkedSession); + referenceCounted.Instance.Should().BeOfType(); } [Theory] @@ -132,9 +98,10 @@ public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -145,19 +112,16 @@ await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCon public async Task GetWriteChannelSource_should_return_expected_result( [Values(false, true)] bool async) { - var mockSession = new Mock(); - var subject = CreateSubject(session: mockSession.Object); - var forkedSession = new Mock().Object; - mockSession.Setup(m => m.Fork()).Returns(forkedSession); + var subject = CreateSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout) : - subject.GetWriteChannelSource(OperationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(operationContext) : + subject.GetWriteChannelSource(operationContext); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); - var source = referenceCounted.Instance.Should().BeOfType().Subject; - source.Session.Should().BeSameAs(forkedSession); + referenceCounted.Instance.Should().BeOfType(); } [Theory] @@ -166,9 +130,10 @@ public async Task GetWriteChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -182,12 +147,8 @@ private SingleServerReadWriteBinding CreateDisposedSubject() return subject; } - private SingleServerReadWriteBinding CreateSubject(IServer server = null, ICoreSessionHandle session = null) - { - return new SingleServerReadWriteBinding( - server ?? new Mock().Object, - session ?? new Mock().Object); - } + private SingleServerReadWriteBinding CreateSubject(IServer server = null) => + new(server ?? new Mock().Object); } internal static class SingleServerReadWriteBindingReflector diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs index f7b84ee0923..3ffae8def3d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs @@ -39,17 +39,7 @@ public WritableServerBindingTests() [Fact] public void Constructor_should_throw_if_cluster_is_null() { - Action act = () => new WritableServerBinding(null, NoCoreSession.NewHandle()); - - act.ShouldThrow(); - } - - [Fact] - public void Constructor_should_throw_if_session_is_null() - { - var cluster = new Mock().Object; - - Action act = () => new WritableServerBinding(cluster, null); + Action act = () => new WritableServerBinding(null); act.ShouldThrow(); } @@ -57,35 +47,25 @@ public void Constructor_should_throw_if_session_is_null() [Fact] public void ReadPreference_should_be_primary() { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); subject.ReadPreference.Should().Be(ReadPreference.Primary); } - [Fact] - public void Session_should_return_expected_result() - { - var cluster = new Mock().Object; - var session = new Mock().Object; - var subject = new WritableServerBinding(cluster, session); - - var result = subject.Session; - - result.Should().BeSameAs(session); - } - [Theory] [ParameterAttributeData] public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetReadChannelSource(operationContext)); exception.Should().BeOfType(); } @@ -96,7 +76,7 @@ public async Task GetReadChannelSource_should_use_a_writable_server_selector_to_ [Values(false, true)] bool async) { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); var selectedServer = new Mock().Object; var clusterId = new ClusterId(); @@ -112,22 +92,22 @@ public async Task GetReadChannelSource_should_use_a_writable_server_selector_to_ var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone); _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(operationContext); - _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetReadChannelSource(OperationContext.NoTimeout); + subject.GetReadChannelSource(operationContext); - _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } } @@ -137,12 +117,13 @@ public async Task GetWriteChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(operationContext)) : + Record.Exception(() => subject.GetWriteChannelSource(operationContext)); exception.Should().BeOfType(); } @@ -153,7 +134,7 @@ public async Task GetWriteChannelSourceAsync_should_use_a_writable_server_select [Values(false, true)] bool async) { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); var selectedServer = new Mock().Object; var clusterId = new ClusterId(); @@ -169,21 +150,22 @@ public async Task GetWriteChannelSourceAsync_should_use_a_writable_server_select var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone); _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(operationContext); - _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetWriteChannelSource(OperationContext.NoTimeout); + subject.GetWriteChannelSource(operationContext); - _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } } @@ -193,7 +175,7 @@ public async Task GetWriteChannelSource_should_use_a_deprioritized_servers_serve [Values(false, true)] bool async) { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); var selectedServer = new Mock().Object; var clusterId = new ClusterId(); @@ -209,22 +191,22 @@ public async Task GetWriteChannelSource_should_use_a_deprioritized_servers_serve _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); var deprioritizedServers = new ServerDescription[] { server }; - + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, deprioritizedServers); + await subject.GetWriteChannelSourceAsync(operationContext, deprioritizedServers); - _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetWriteChannelSource(OperationContext.NoTimeout, deprioritizedServers); + subject.GetWriteChannelSource(operationContext, deprioritizedServers); - _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } } @@ -234,7 +216,7 @@ public async Task GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseS [Values(false, true)] bool async) { - var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); + var subject = new WritableServerBinding(_mockCluster.Object); var selectedServer = new Mock().Object; var clusterId = new ClusterId(); @@ -254,34 +236,33 @@ public async Task GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseS mockMayUseSecondary.Setup(x => x.CanUseSecondary(It.IsAny())).Returns(true); var mayUseSecondary = mockMayUseSecondary.Object; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, mayUseSecondary); + await subject.GetWriteChannelSourceAsync(operationContext, mayUseSecondary); - _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is(s => s.MayUseSecondary == mayUseSecondary)), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.Is(s => s.MayUseSecondary == mayUseSecondary)), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetWriteChannelSource(OperationContext.NoTimeout, mayUseSecondary); + subject.GetWriteChannelSource(operationContext, mayUseSecondary); - _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.Is(s => s.MayUseSecondary == mayUseSecondary)), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.Is(s => s.MayUseSecondary == mayUseSecondary)), Times.Once); } } [Fact] public void Dispose_should_call_dispose_on_owned_resources() { - var mockSession = new Mock(); - var subject = new WritableServerBinding(_mockCluster.Object, mockSession.Object); + var subject = new WritableServerBinding(_mockCluster.Object); subject.Dispose(); _mockCluster.Verify(c => c.Dispose(), Times.Never); - mockSession.Verify(m => m.Dispose(), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs index 8cd60f2ab46..9c7f3a3d145 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs @@ -126,10 +126,11 @@ public async Task SelectServer_should_throw_if_not_initialized( { var selector = new Mock().Object; var subject = CreateSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, selector)) : + Record.Exception(() => subject.SelectServer(operationContext, selector)); exception.Should().BeOfType(); } @@ -144,9 +145,10 @@ public async Task SelectServer_should_throw_if_disposed( var subject = CreateSubject(); subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, selector)) : + Record.Exception(() => subject.SelectServer(operationContext, selector)); exception.Should().BeOfType(); } @@ -160,9 +162,10 @@ public async Task SelectServer_should_throw_if_serverSelector_is_null( var subject = CreateSubject(); subject.Initialize(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, null)) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, null)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, null)) : + Record.Exception(() => subject.SelectServer(operationContext, null)); exception.Should().BeOfType(); } @@ -182,9 +185,10 @@ public async Task SelectServer_should_return_a_server_if_one_matches( var selector = new DelegateServerSelector((c, s) => s); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : - subject.SelectServer(OperationContext.NoTimeout, selector); + await subject.SelectServerAsync(operationContext, selector) : + subject.SelectServer(operationContext, selector); result.Should().NotBeNull(); @@ -212,9 +216,10 @@ public async Task SelectServer_should_return_second_server_if_first_cannot_be_fo var selector = new DelegateServerSelector((c, s) => s); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : - subject.SelectServer(OperationContext.NoTimeout, selector); + await subject.SelectServerAsync(operationContext, selector) : + subject.SelectServer(operationContext, selector); result.Should().NotBeNull(); @@ -240,9 +245,10 @@ public async Task SelectServer_should_throw_if_no_servers_match( var selector = new DelegateServerSelector((c, s) => Enumerable.Empty()); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, selector)) : + Record.Exception(() => subject.SelectServer(operationContext, selector)); exception.Should().BeOfType(); @@ -268,9 +274,10 @@ public async Task SelectServer_should_throw_if_the_matched_server_cannot_be_foun var selector = new DelegateServerSelector((c, s) => s); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, selector)) : + Record.Exception(() => subject.SelectServer(operationContext, selector)); exception.Should().BeOfType(); @@ -296,9 +303,10 @@ public async Task SelectServer_should_throw_if_any_servers_are_incompatible(int var selector = new DelegateServerSelector((c, s) => s); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, selector)) : + Record.Exception(() => subject.SelectServer(operationContext, selector)); exception.Should().BeOfType(); @@ -337,9 +345,10 @@ public async Task SelectServer_should_keep_trying_to_match_by_waiting_on_cluster var selector = new DelegateServerSelector((c, s) => s); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : - subject.SelectServer(OperationContext.NoTimeout, selector); + await subject.SelectServerAsync(operationContext, selector) : + subject.SelectServer(operationContext, selector); result.Should().NotBeNull(); @@ -421,9 +430,10 @@ public async Task SelectServer_should_apply_both_pre_and_post_server_selectors( ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27020))); _capturedEvents.Clear(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.SelectServerAsync(OperationContext.NoTimeout, middleSelector) : - subject.SelectServer(OperationContext.NoTimeout, middleSelector); + await subject.SelectServerAsync(operationContext, middleSelector) : + subject.SelectServer(operationContext, middleSelector); ((DnsEndPoint)result.EndPoint).Port.Should().Be(27020); _capturedEvents.Next().Should().BeOfType(); @@ -453,12 +463,13 @@ public async Task SelectServer_should_call_custom_selector( ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27020))); _capturedEvents.Clear(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (withEligibleServers) { var selector = new DelegateServerSelector((c, s) => s); var selectedServer = async ? - await subject.SelectServerAsync(OperationContext.NoTimeout, selector): - subject.SelectServer(OperationContext.NoTimeout, selector); + await subject.SelectServerAsync(operationContext, selector): + subject.SelectServer(operationContext, selector); var selectedServerPort = ((DnsEndPoint)selectedServer.EndPoint).Port; selectedServerPort.Should().Be(27020); @@ -469,8 +480,8 @@ await subject.SelectServerAsync(OperationContext.NoTimeout, selector): { 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)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, selector)) : + Record.Exception(() => subject.SelectServer(operationContext, selector)); exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs index 2c14c12f751..42de4374516 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs @@ -20,6 +20,7 @@ using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson.TestHelpers; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Configuration; @@ -327,9 +328,10 @@ public async Task SelectServer_should_return_expected_server( PublishDescription(_endPoint); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async ? - await subject.SelectServerAsync(OperationContext.NoTimeout, Mock.Of()) : - subject.SelectServer(OperationContext.NoTimeout, Mock.Of()); + await subject.SelectServerAsync(operationContext, Mock.Of()) : + subject.SelectServer(operationContext, Mock.Of()); result.EndPoint.Should().Be(_endPoint); } @@ -355,9 +357,10 @@ public async Task SelectServer_should_throw_server_selection_timeout_if_server_h PublishDnsException(subject, dnsException); } + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, Mock.Of())) : - Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, Mock.Of())); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, Mock.Of())) : + Record.Exception(() => subject.SelectServer(operationContext, 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 "); @@ -387,7 +390,7 @@ public async Task SelectServer_should_be_cancelled_by_cancellationToken( Exception exception; using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) { - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + var operationContext = new OperationContext(NoCoreSession.NewHandle(), Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); exception = async ? await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, Mock.Of())) : Record.Exception(() => subject.SelectServer(operationContext, Mock.Of())); diff --git a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs index 7720cf0e046..f01a06324be 100644 --- a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs @@ -22,6 +22,7 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.TestHelpers; +using MongoDB.Driver.Core.Bindings; using MongoDB.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; @@ -174,8 +175,9 @@ public void AcquireConnection_should_iterate_over_all_dormant_connections() subject.SetReady(); // acquire all connections and return them + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var allConnections = Enumerable.Range(0, connectionsCount) - .Select(i => subject.AcquireConnection(OperationContext.NoTimeout)) + .Select(i => subject.AcquireConnection(operationContext)) .ToArray(); var connectionNotToExpire = allConnections[allConnections.Length / 2].ConnectionId; @@ -222,9 +224,10 @@ public async Task AcquireConnection_should_throw_an_InvalidOperationException_if { _capturedEvents.Clear(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.AcquireConnection(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(operationContext)) : + Record.Exception(() => _subject.AcquireConnection(operationContext)); exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -243,9 +246,10 @@ public async Task AcquireConnection_should_throw_an_ObjectDisposedException_afte _capturedEvents.Clear(); _subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.AcquireConnection(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(operationContext)) : + Record.Exception(() => _subject.AcquireConnection(operationContext)); exception.Should().BeOfType(); @@ -267,9 +271,10 @@ public async Task AcquireConnection_should_return_a_connection( InitializeAndWait(); _capturedEvents.Clear(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - _subject.AcquireConnection(OperationContext.NoTimeout); + await _subject.AcquireConnectionAsync(operationContext) : + _subject.AcquireConnection(operationContext); connection.Should().NotBeNull(); _subject.AvailableCount.Should().Be(_settings.MaxConnections - 1); @@ -329,9 +334,10 @@ public async Task AcquireConnection_should_invoke_error_handling_before_releasin subject.Initialize(); subject.SetReady(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var resultException = async ? - await Record.ExceptionAsync(() => subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.AcquireConnection(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.AcquireConnectionAsync(operationContext)) : + Record.Exception(() => subject.AcquireConnection(operationContext)); resultException.Should().BeOfType(); subject.AvailableCount.Should().Be(maxConnections); @@ -365,9 +371,10 @@ internal async Task AcquireConnection_should_track_checked_out_reasons( List connections = new(); for (int attempt = 1; attempt <= attempts; attempt++) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - subject.AcquireConnection(OperationContext.NoTimeout); + await subject.AcquireConnectionAsync(operationContext) : + subject.AcquireConnection(operationContext); ((ICheckOutReasonTracker)connection).SetCheckOutReasonIfNotAlreadySet(reason); connections.Add(connection); @@ -426,11 +433,12 @@ public async Task AcquireConnection_should_increase_count_up_to_the_max_number_o var connections = new List(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); for (int i = 0; i < _settings.MaxConnections; i++) { var connection = async ? - await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - _subject.AcquireConnection(OperationContext.NoTimeout); + await _subject.AcquireConnectionAsync(operationContext) : + _subject.AcquireConnection(operationContext); connections.Add(connection); } @@ -463,9 +471,10 @@ public async Task AcquiredConnection_should_return_connections_to_the_pool_when_ { InitializeAndWait(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - _subject.AcquireConnection(OperationContext.NoTimeout); + await _subject.AcquireConnectionAsync(operationContext) : + _subject.AcquireConnection(operationContext); _capturedEvents.Clear(); @@ -495,9 +504,10 @@ public async Task AcquiredConnection_should_not_return_connections_to_the_pool_w InitializeAndWait(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - _subject.AcquireConnection(OperationContext.NoTimeout); + await _subject.AcquireConnectionAsync(operationContext) : + _subject.AcquireConnection(operationContext); _capturedEvents.Clear(); @@ -523,18 +533,19 @@ public async Task AcquireConnection_should_throw_a_TimeoutException_when_all_con { InitializeAndWait(); var connections = new List(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); for (int i = 0; i < _settings.MaxConnections; i++) { var connection = async ? - await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - _subject.AcquireConnection(OperationContext.NoTimeout); + await _subject.AcquireConnectionAsync(operationContext) : + _subject.AcquireConnection(operationContext); connections.Add(connection); } _capturedEvents.Clear(); var exception = async ? - await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.AcquireConnection(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(operationContext)) : + Record.Exception(() => _subject.AcquireConnection(operationContext)); exception.Should().BeOfType(); @@ -680,15 +691,16 @@ public async Task AcquiredConnection_should_not_throw_exceptions_when_disposed_a InitializeAndWait(); IConnectionHandle connection1; IConnectionHandle connection2; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - connection1 = await _subject.AcquireConnectionAsync(OperationContext.NoTimeout); - connection2 = await _subject.AcquireConnectionAsync(OperationContext.NoTimeout); + connection1 = await _subject.AcquireConnectionAsync(operationContext); + connection2 = await _subject.AcquireConnectionAsync(operationContext); } else { - connection1 = _subject.AcquireConnection(OperationContext.NoTimeout); - connection2 = _subject.AcquireConnection(OperationContext.NoTimeout); + connection1 = _subject.AcquireConnection(operationContext); + connection2 = _subject.AcquireConnection(operationContext); } _capturedEvents.Clear(); @@ -861,9 +873,10 @@ public async Task Clear_should_cause_existing_connections_to_be_expired( _subject.Initialize(); _subject.SetReady(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - _subject.AcquireConnection(OperationContext.NoTimeout); + await _subject.AcquireConnectionAsync(operationContext) : + _subject.AcquireConnection(operationContext); connection.IsExpired.Should().BeFalse(); _subject.Clear(closeInUseConnections: false); @@ -902,9 +915,10 @@ public async Task Clear_with_serviceId_should_cause_only_expected_connections_to subject.Initialize(); subject.SetReady(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await subject.AcquireConnectionAsync(OperationContext.NoTimeout) : - subject.AcquireConnection(OperationContext.NoTimeout); + await subject.AcquireConnectionAsync(operationContext) : + subject.AcquireConnection(operationContext); connection.IsExpired.Should().BeFalse(); var randomServiceId = ObjectId.GenerateNewId(); @@ -1604,16 +1618,17 @@ public void WaitQueue_should_release_slot_after_connection_checkout( // private methods private IConnection AcquireConnection(ExclusiveConnectionPool subject, bool async) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { return subject - .AcquireConnectionAsync(OperationContext.NoTimeout) + .AcquireConnectionAsync(operationContext) .GetAwaiter() .GetResult(); } else { - return subject.AcquireConnection(OperationContext.NoTimeout); + return subject.AcquireConnection(operationContext); } } diff --git a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs index 2b4970bd723..c1ee92a2fb9 100644 --- a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs @@ -20,6 +20,7 @@ using System.Threading; using FluentAssertions; using MongoDB.Bson.TestHelpers; +using MongoDB.Driver.Core.Bindings; using MongoDB.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; @@ -168,7 +169,8 @@ public void Stop_should_trigger_immediate_maintenance_call( IConnection acquiredConnection = null; if (checkOutConnection) { - acquiredConnection = pool.AcquireConnection(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + acquiredConnection = pool.AcquireConnection(operationContext); acquiredConnection.ConnectionId.LongLocalValue.Should().Be(1); } diff --git a/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnectionTests.cs b/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnectionTests.cs index bbbda4b357e..9d58f75daf7 100644 --- a/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnectionTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnectionTests.cs @@ -24,6 +24,7 @@ using MongoDB.Bson.Serialization.Serializers; using MongoDB.Bson.TestHelpers; using MongoDB.Driver.Authentication; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Events; @@ -134,9 +135,10 @@ public async Task Open_should_always_create_description_if_handshake_was_success .Setup(i => i.AuthenticateAsync(It.IsAny(), It.IsAny(), It.IsAny())) .ThrowsAsync(socketException); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.OpenAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.Open(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.OpenAsync(operationContext)) : + Record.Exception(() => _subject.Open(operationContext)); _subject.Description.Should().Be(connectionDescription); var ex = exception.Should().BeOfType().Subject; @@ -190,13 +192,14 @@ public async Task Open_should_create_authenticators_only_once( socketReadTimeout: Timeout.InfiniteTimeSpan, socketWriteTimeout: Timeout.InfiniteTimeSpan); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.OpenAsync(OperationContext.NoTimeout); + await subject.OpenAsync(operationContext); } else { - subject.Open(OperationContext.NoTimeout); + subject.Open(operationContext); } authenticatorFactoryMock.Verify(f => f.Create(), Times.Once()); @@ -219,9 +222,10 @@ public async Task Open_should_throw_an_ObjectDisposedException_if_the_connection { _subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.OpenAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.Open(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.OpenAsync(operationContext)) : + Record.Exception(() => _subject.Open(operationContext)); exception.Should().BeOfType(); } @@ -237,9 +241,10 @@ public async Task Open_should_raise_the_correct_events_upon_failure( _mockConnectionInitializer.Setup(i => i.SendHello(It.IsAny(), It.IsAny())) .Throws(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.OpenAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.Open(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.OpenAsync(operationContext)) : + Record.Exception(() => _subject.Open(operationContext)); exception.Should().BeOfType().Subject .ConnectionId.Should().Be(_subject.ConnectionId); @@ -256,13 +261,14 @@ public async Task Open_should_setup_the_description( [Values(false, true)] bool async) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await _subject.OpenAsync(OperationContext.NoTimeout); + await _subject.OpenAsync(operationContext); } else { - _subject.Open(OperationContext.NoTimeout); + _subject.Open(operationContext); } _subject.Description.Should().NotBeNull(); @@ -295,14 +301,15 @@ public void Open_should_not_complete_the_second_call_until_the_first_is_complete return completionSource.Task; }); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var openTask1 = async1 ? - _subject.OpenAsync(OperationContext.NoTimeout) : - Task.Run(() => _subject.Open(OperationContext.NoTimeout)); + _subject.OpenAsync(operationContext) : + Task.Run(() => _subject.Open(operationContext)); SpinWait.SpinUntil(() => task1IsBlocked, TimeSpan.FromSeconds(5)).Should().BeTrue(); var openTask2 = async2 ? - _subject.OpenAsync(OperationContext.NoTimeout) : - Task.Run(() => _subject.Open(OperationContext.NoTimeout)); + _subject.OpenAsync(operationContext) : + Task.Run(() => _subject.Open(operationContext)); openTask1.IsCompleted.Should().BeFalse(); openTask2.IsCompleted.Should().BeFalse(); @@ -325,26 +332,27 @@ public async Task Reauthentication_should_use_the_same_auth_context_as_in_initia { _subject._connectionInitializerContext().Should().BeNull(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await _subject.OpenAsync(OperationContext.NoTimeout); + await _subject.OpenAsync(operationContext); } else { - _subject.Open(OperationContext.NoTimeout); + _subject.Open(operationContext); } _subject._connectionInitializerContext().Should().Be(_connectionInitializerContextAfterAuthentication); if (async) { - await _subject.ReauthenticateAsync(OperationContext.NoTimeout); + await _subject.ReauthenticateAsync(operationContext); _mockConnectionInitializer.Verify(c => c.AuthenticateAsync(It.IsAny(), It.IsAny(), _connectionInitializerContext), Times.Once); _mockConnectionInitializer.Verify(c => c.AuthenticateAsync(It.IsAny(), It.IsAny(), _connectionInitializerContextAfterAuthentication), Times.Once); } else { - _subject.Reauthenticate(OperationContext.NoTimeout); + _subject.Reauthenticate(operationContext); _mockConnectionInitializer.Verify(c => c.Authenticate(It.IsAny(), It.IsAny(), _connectionInitializerContext), Times.Once); _mockConnectionInitializer.Verify(c => c.Authenticate(It.IsAny(), It.IsAny(), _connectionInitializerContextAfterAuthentication), Times.Once); } @@ -370,12 +378,13 @@ public async Task ReceiveMessage_should_throw_a_FormatException_when_message_is_ _mockStreamFactory.Setup(f => f.CreateStreamAsync(_endPoint, It.IsAny())).ReturnsAsync(stream); _mockStreamFactory.Setup(f => f.CreateStream(_endPoint, It.IsAny())).Returns(stream); - await _subject.OpenAsync(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + await _subject.OpenAsync(operationContext); var encoderSelector = new ReplyMessageEncoderSelector(BsonDocumentSerializer.Instance); var exception = async ? - await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)) : - Record.Exception(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 10, encoderSelector, _messageEncoderSettings)) : + Record.Exception(() => _subject.ReceiveMessage(operationContext, 10, encoderSelector, _messageEncoderSettings)); exception.Should().BeOfType(); var e = exception.InnerException.Should().BeOfType().Subject; @@ -389,9 +398,10 @@ public async Task ReceiveMessage_should_throw_an_ArgumentNullException_when_the_ [Values(false, true)] bool async) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 10, null, _messageEncoderSettings)) : - Record.Exception(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 10, null, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 10, null, _messageEncoderSettings)) : + Record.Exception(() => _subject.ReceiveMessage(operationContext, 10, null, _messageEncoderSettings)); exception.Should().BeOfType().Subject .ParamName.Should().Be("encoderSelector"); @@ -406,9 +416,10 @@ public async Task ReceiveMessage_should_throw_an_ObjectDisposedException_if_the_ var encoderSelector = new Mock().Object; _subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)) : - Record.Exception(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 10, encoderSelector, _messageEncoderSettings)) : + Record.Exception(() => _subject.ReceiveMessage(operationContext, 10, encoderSelector, _messageEncoderSettings)); exception.Should().BeOfType(); } @@ -421,9 +432,10 @@ public async Task ReceiveMessage_should_throw_an_InvalidOperationException_if_th { var encoderSelector = new Mock().Object; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)) : - Record.Exception(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 10, encoderSelector, _messageEncoderSettings)) : + Record.Exception(() => _subject.ReceiveMessage(operationContext, 10, encoderSelector, _messageEncoderSettings)); exception.Should().BeOfType(); } @@ -443,14 +455,15 @@ public async Task ReceiveMessage_should_complete_when_reply_is_already_on_the_st .ReturnsAsync(stream); _mockStreamFactory.Setup(f => f.CreateStream(_endPoint, It.IsAny())) .Returns(stream); - await _subject.OpenAsync(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + await _subject.OpenAsync(operationContext); _capturedEvents.Clear(); var encoderSelector = new ReplyMessageEncoderSelector(BsonDocumentSerializer.Instance); var received = async ? - await _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings) : - _subject.ReceiveMessage(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings); + await _subject.ReceiveMessageAsync(operationContext, 10, encoderSelector, _messageEncoderSettings) : + _subject.ReceiveMessage(operationContext, 10, encoderSelector, _messageEncoderSettings); var expected = MessageHelper.TranslateMessagesToBsonDocuments(new[] { messageToReceive }); var actual = MessageHelper.TranslateMessagesToBsonDocuments(new[] { received }); @@ -475,14 +488,15 @@ public async Task ReceiveMessage_should_complete_when_reply_is_not_already_on_th .ReturnsAsync(stream); _mockStreamFactory.Setup(f => f.CreateStream(_endPoint, It.IsAny())) .Returns(stream); - await _subject.OpenAsync(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + await _subject.OpenAsync(operationContext); _capturedEvents.Clear(); var encoderSelector = new ReplyMessageEncoderSelector(BsonDocumentSerializer.Instance); var receiveMessageTask = async ? - _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings) : - Task.Run(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 10, encoderSelector, _messageEncoderSettings)); + _subject.ReceiveMessageAsync(operationContext, 10, encoderSelector, _messageEncoderSettings) : + Task.Run(() => _subject.ReceiveMessage(operationContext, 10, encoderSelector, _messageEncoderSettings)); receiveMessageTask.IsCompleted.Should().BeFalse(); @@ -528,9 +542,10 @@ public async Task ReceiveMessage_should_not_produce_unobserved_task_exceptions_o tcs.SetException(new SocketException()); SetupStreamRead(mockStream, tcs); - _subject.Open(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + _subject.Open(operationContext); - var exception = await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 1, encoderSelector, _messageEncoderSettings)); + var exception = await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 1, encoderSelector, _messageEncoderSettings)); exception.Should().BeOfType(); GC.Collect(); // Collects the unobserved tasks @@ -569,9 +584,10 @@ public async Task ReceiveMessageAsync_should_not_produce_unobserved_task_excepti var tcs = new TaskCompletionSource(); SetupStreamRead(mockStream, tcs); - _subject.Open(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + _subject.Open(operationContext); - var exception = await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 1, encoderSelector, _messageEncoderSettings)); + var exception = await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 1, encoderSelector, _messageEncoderSettings)); exception.Should().BeOfType(); exception.InnerException.Should().BeOfType(); @@ -607,18 +623,19 @@ public async Task ReceiveMessage_should_throw_MongoConnectionClosedException_whe var readTcs = new TaskCompletionSource(); readTcs.SetException(new SocketException()); SetupStreamRead(mockStream, readTcs); - await _subject.OpenAsync(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + await _subject.OpenAsync(operationContext); _capturedEvents.Clear(); var encoderSelector = new ReplyMessageEncoderSelector(BsonDocumentSerializer.Instance); var exception1 = async1 ? - await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 1, encoderSelector, _messageEncoderSettings)) : - Record.Exception(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 1, encoderSelector, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 1, encoderSelector, _messageEncoderSettings)) : + Record.Exception(() => _subject.ReceiveMessage(operationContext, 1, encoderSelector, _messageEncoderSettings)); var exception2 = async2 ? - await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(OperationContext.NoTimeout, 2, encoderSelector, _messageEncoderSettings)) : - Record.Exception(() => _subject.ReceiveMessage(OperationContext.NoTimeout, 2, encoderSelector, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.ReceiveMessageAsync(operationContext, 2, encoderSelector, _messageEncoderSettings)) : + Record.Exception(() => _subject.ReceiveMessage(operationContext, 2, encoderSelector, _messageEncoderSettings)); exception1.Should().BeOfType().Subject .ConnectionId.Should().Be(_subject.ConnectionId); @@ -640,9 +657,10 @@ public async Task SendMessage_should_throw_an_ArgumentNullException_if_message_i [Values(false, true)] bool async) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.SendMessageAsync(OperationContext.NoTimeout, null, _messageEncoderSettings)) : - Record.Exception(() => _subject.SendMessage(OperationContext.NoTimeout, null, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.SendMessageAsync(operationContext, null, _messageEncoderSettings)) : + Record.Exception(() => _subject.SendMessage(operationContext, null, _messageEncoderSettings)); exception.Should().BeOfType(); } @@ -656,9 +674,10 @@ public async Task SendMessage_should_throw_an_ObjectDisposedException_if_the_con var message = MessageHelper.BuildQuery(); _subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.SendMessageAsync(OperationContext.NoTimeout, message, _messageEncoderSettings)) : - Record.Exception(() => _subject.SendMessage(OperationContext.NoTimeout, message, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.SendMessageAsync(operationContext, message, _messageEncoderSettings)) : + Record.Exception(() => _subject.SendMessage(operationContext, message, _messageEncoderSettings)); exception.Should().BeOfType(); } @@ -671,9 +690,10 @@ public async Task SendMessage_should_throw_an_InvalidOperationException_if_the_c { var message = MessageHelper.BuildQuery(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.SendMessageAsync(OperationContext.NoTimeout, message, _messageEncoderSettings)) : - Record.Exception(() => _subject.SendMessage(OperationContext.NoTimeout, message, _messageEncoderSettings)); + await Record.ExceptionAsync(() => _subject.SendMessageAsync(operationContext, message, _messageEncoderSettings)) : + Record.Exception(() => _subject.SendMessage(operationContext, message, _messageEncoderSettings)); exception.Should().BeOfType(); } @@ -688,18 +708,19 @@ public async Task SendMessage_should_put_the_message_on_the_stream_and_raise_the { _mockStreamFactory.Setup(f => f.CreateStreamAsync(_endPoint, It.IsAny())).ReturnsAsync(stream); _mockStreamFactory.Setup(f => f.CreateStream(_endPoint, It.IsAny())).Returns(stream); - _subject.OpenAsync(OperationContext.NoTimeout).GetAwaiter().GetResult(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + _subject.OpenAsync(operationContext).GetAwaiter().GetResult(); _capturedEvents.Clear(); var message = MessageHelper.BuildQuery(query: new BsonDocument("x", 1)); if (async) { - await _subject.SendMessageAsync(OperationContext.NoTimeout, message, _messageEncoderSettings); + await _subject.SendMessageAsync(operationContext, message, _messageEncoderSettings); } else { - _subject.SendMessage(OperationContext.NoTimeout, message, _messageEncoderSettings); + _subject.SendMessage(operationContext, message, _messageEncoderSettings); } var expectedRequests = MessageHelper.TranslateMessagesToBsonDocuments(new[] { message }); @@ -728,7 +749,8 @@ public void IsExpired_should_return_false_when_maxIdleTime_has_no_limit() socketReadTimeout: TimeSpan.FromMilliseconds(1000), socketWriteTimeout: TimeSpan.FromMilliseconds(1000)); - subject.Open(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + subject.Open(operationContext); subject.IsExpired.Should().BeFalse(); } @@ -747,7 +769,8 @@ public void IsExpired_should_return_true_when_maxIdleTime_is_positive_and_connec socketReadTimeout: TimeSpan.FromMilliseconds(1000), socketWriteTimeout: TimeSpan.FromMilliseconds(1000)); - subject.Open(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + subject.Open(operationContext); subject.IsExpired.Should().BeTrue(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnection_CommandEventTests.cs b/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnection_CommandEventTests.cs index 6c548608cfa..389ab1b36b6 100644 --- a/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnection_CommandEventTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Connections/BinaryConnection_CommandEventTests.cs @@ -22,6 +22,7 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Events; @@ -106,7 +107,8 @@ public BinaryConnection_CommandEventTests(ITestOutputHelper output) : base(outpu _stream = new BlockingMemoryStream(); _mockStreamFactory.Setup(f => f.CreateStreamAsync(_endPoint, It.IsAny())) .Returns(Task.FromResult(_stream)); - _subject.OpenAsync(OperationContext.NoTimeout).Wait(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + _subject.OpenAsync(operationContext).Wait(); _capturedEvents.Clear(); _operationIdDisposer = EventContext.BeginOperation(); @@ -486,14 +488,16 @@ public void Should_process_a_failed_query() private void SendMessage(RequestMessage message) { - _subject.SendMessageAsync(OperationContext.NoTimeout, message, _messageEncoderSettings).Wait(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + _subject.SendMessageAsync(operationContext, message, _messageEncoderSettings).Wait(); } private void ReceiveMessage(ReplyMessage message) { MessageHelper.WriteResponsesToStream(_stream, message); var encoderSelector = new ReplyMessageEncoderSelector(BsonDocumentSerializer.Instance); - _subject.ReceiveMessageAsync(OperationContext.NoTimeout, message.ResponseTo, encoderSelector, _messageEncoderSettings).Wait(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + _subject.ReceiveMessageAsync(operationContext, message.ResponseTo, encoderSelector, _messageEncoderSettings).Wait(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Connections/ConnectionInitializerTests.cs b/tests/MongoDB.Driver.Tests/Core/Connections/ConnectionInitializerTests.cs index d86d925434a..f9fbbaa7262 100644 --- a/tests/MongoDB.Driver.Tests/Core/Connections/ConnectionInitializerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Connections/ConnectionInitializerTests.cs @@ -22,6 +22,7 @@ using MongoDB.Bson.TestHelpers; using MongoDB.Driver.Authentication; using MongoDB.Driver.Authentication.ScramSha; +using MongoDB.Driver.Core.Bindings; using MongoDB.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Compression; @@ -63,9 +64,10 @@ public async Task ConnectionAuthentication_should_throw_if_connection_is_null( { var connectionInitializerContext = new ConnectionInitializerContext(__emptyConnectionDescription, null); var subject = CreateSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, null, connectionInitializerContext)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, null, connectionInitializerContext)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, null, connectionInitializerContext)) : + Record.Exception(() => subject.Authenticate(operationContext, null, connectionInitializerContext)); exception.Should().BeOfType() .Subject.ParamName.Should().Be("connection"); @@ -77,9 +79,10 @@ public async Task ConnectionAuthentication_should_throw_if_connectionInitializer [Values(false, true)] bool async) { var subject = CreateSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.AuthenticateAsync(OperationContext.NoTimeout, Mock.Of(), null)) : - Record.Exception(() => subject.Authenticate(OperationContext.NoTimeout, Mock.Of(), null)); + await Record.ExceptionAsync(() => subject.AuthenticateAsync(operationContext, Mock.Of(), null)) : + Record.Exception(() => subject.Authenticate(operationContext, Mock.Of(), null)); exception.Should().BeOfType() .Subject.ParamName.Should().Be("connectionInitializerContext"); @@ -143,9 +146,10 @@ public async Task Handshake_should_throw_if_connection_is_null( [Values(false, true)] bool async) { var subject = CreateSubject(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.SendHelloAsync(OperationContext.NoTimeout, null)) : - Record.Exception(() => subject.SendHello(OperationContext.NoTimeout, null)); + await Record.ExceptionAsync(() => subject.SendHelloAsync(operationContext, null)) : + Record.Exception(() => subject.SendHello(operationContext, null)); exception.Should().BeOfType(); } @@ -406,18 +410,19 @@ private ConnectionInitializer CreateSubject(bool withServerApi = false) => private async Task InitializeConnection(ConnectionInitializer connectionInitializer, MockConnection connection, bool async) { ConnectionInitializerContext connectionInitializerContext; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - connectionInitializerContext = await connectionInitializer.SendHelloAsync(OperationContext.NoTimeout, connection); + connectionInitializerContext = await connectionInitializer.SendHelloAsync(operationContext, connection); connection.Description = connectionInitializerContext.Description; - connectionInitializerContext = await connectionInitializer.AuthenticateAsync(OperationContext.NoTimeout, connection, connectionInitializerContext); + connectionInitializerContext = await connectionInitializer.AuthenticateAsync(operationContext, connection, connectionInitializerContext); return connectionInitializerContext.Description; } else { - connectionInitializerContext = connectionInitializer.SendHello(OperationContext.NoTimeout, connection); + connectionInitializerContext = connectionInitializer.SendHello(operationContext, connection); connection.Description = connectionInitializerContext.Description; - connectionInitializerContext = connectionInitializer.Authenticate(OperationContext.NoTimeout, connection, connectionInitializerContext); + connectionInitializerContext = connectionInitializer.Authenticate(operationContext, connection, connectionInitializerContext); return connectionInitializerContext.Description; } } @@ -428,7 +433,10 @@ internal static class ConnectionInitializerReflector public static BsonDocument CreateInitialHelloCommand( this ConnectionInitializer initializer, IAuthenticator authenticator, - bool loadBalanced) => - (BsonDocument)Reflector.Invoke(initializer, nameof(CreateInitialHelloCommand), OperationContext.NoTimeout, authenticator, loadBalanced); + bool loadBalanced) + { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + return (BsonDocument)Reflector.Invoke(initializer, nameof(CreateInitialHelloCommand), operationContext, authenticator, loadBalanced); + } } } diff --git a/tests/MongoDB.Driver.Tests/Core/IAsyncCursorExtensionsTests.cs b/tests/MongoDB.Driver.Tests/Core/IAsyncCursorExtensionsTests.cs index c32b85b7e6c..66e9ed70ace 100644 --- a/tests/MongoDB.Driver.Tests/Core/IAsyncCursorExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/IAsyncCursorExtensionsTests.cs @@ -334,6 +334,7 @@ private IAsyncCursor CreateCursor(int count) return new AsyncCursor( channelSource: new Mock().Object, + session: new Mock().Object, collectionNamespace: new CollectionNamespace("foo", "bar"), comment: null, firstBatch: firstBatch, diff --git a/tests/MongoDB.Driver.Tests/Core/IAsyncCursorSourceExtensionsTests.cs b/tests/MongoDB.Driver.Tests/Core/IAsyncCursorSourceExtensionsTests.cs index 183a72a25c3..a7e351583f2 100644 --- a/tests/MongoDB.Driver.Tests/Core/IAsyncCursorSourceExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/IAsyncCursorSourceExtensionsTests.cs @@ -309,6 +309,7 @@ private IAsyncCursor CreateCursor(int count) return new AsyncCursor( channelSource: new Mock().Object, + session: new Mock().Object, collectionNamespace: new CollectionNamespace("foo", "bar"), comment: null, firstBatch: firstBatch, diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs index 92bac389e2b..a38aaf612bb 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs @@ -22,6 +22,7 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.TestHelpers; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Configuration; @@ -75,7 +76,8 @@ 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(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint1)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var selectedServer = cluster.SelectServer(operationContext, CreateWritableServerAndEndPointSelector(__endPoint1)); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); @@ -86,11 +88,11 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ Exception exception; if (async) { - exception = Record.Exception(() => selectedServer.GetChannelAsync(OperationContext.NoTimeout).GetAwaiter().GetResult()); + exception = Record.Exception(() => selectedServer.GetChannelAsync(operationContext).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => selectedServer.GetChannel(OperationContext.NoTimeout)); + exception = Record.Exception(() => selectedServer.GetChannel(operationContext)); } var e = exception.Should().BeOfType().Subject; @@ -107,7 +109,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ } // ensure that a new server can be selected - selectedServer = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); + selectedServer = cluster.SelectServer(operationContext, WritableServerSelector.Instance); // ensure that the selected server is not the same as the initial selectedServer.EndPoint.Should().Be(__endPoint2); diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs index fbd2a379525..74857dc617e 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs @@ -22,6 +22,7 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.TestHelpers; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Configuration; @@ -97,7 +98,7 @@ public async Task RapidHeartbeatTimerCallback_should_ignore_reentrant_calls() // Trigger Cluster._rapidHeartbeatTimer using var cancellationTokenSource = new CancellationTokenSource(); - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); cluster.SelectServerAsync(operationContext, CreateWritableServerAndEndPointSelector(__endPoint1)) .IgnoreExceptions(); @@ -147,13 +148,14 @@ public async Task Ensure_no_deadlock_after_primary_update() server.DescriptionChanged += ProcessServerDescriptionChanged; } - var selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint1)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle(), Timeout.InfiniteTimeSpan); + var selectedServer = cluster.SelectServer(operationContext, CreateWritableServerAndEndPointSelector(__endPoint1)); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); // Change primary currentPrimaries.Add(__serverId2); - selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint2)); + selectedServer = cluster.SelectServer(operationContext, CreateWritableServerAndEndPointSelector(__endPoint2)); selectedServer.EndPoint.Should().Be(__endPoint2); // Ensure stalling happened diff --git a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntegrationTests.cs b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntegrationTests.cs index c79ac85ddfb..2667e00081e 100644 --- a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntegrationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntegrationTests.cs @@ -612,13 +612,14 @@ private BulkWriteOperationResult CreateAndRunBulkOperation(RetryableWriteContext new[] { new InsertRequest(new BsonDocument()) }, _messageEncoderSettings); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - return bulkInsertOperation.ExecuteAsync(OperationContext.NoTimeout, context).GetAwaiter().GetResult(); + return bulkInsertOperation.ExecuteAsync(operationContext, context).GetAwaiter().GetResult(); } else { - return bulkInsertOperation.Execute(OperationContext.NoTimeout, context); + return bulkInsertOperation.Execute(operationContext, context); } } @@ -632,28 +633,30 @@ private IAsyncCursor CreateAndRunFindOperation(RetryableReadContex BatchSize = 1 }; + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - return findOperation.ExecuteAsync(OperationContext.NoTimeout, context).GetAwaiter().GetResult(); + return findOperation.ExecuteAsync(operationContext, context).GetAwaiter().GetResult(); } else { - return findOperation.Execute(OperationContext.NoTimeout, context); + return findOperation.Execute(operationContext, context); } } private RetryableReadContext CreateRetryableReadContext(IReadBindingHandle readBindingHandle, bool async) { var retryableContext = new RetryableReadContext(readBindingHandle, retryRequested: false, RetryabilityHelper.OperationRetryBackpressureConstants.DefaultMaxRetries, false); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - retryableContext.SelectServerAsync(OperationContext.NoTimeout, null).GetAwaiter().GetResult(); - retryableContext.AcquireChannelAsync(OperationContext.NoTimeout).GetAwaiter().GetResult(); + retryableContext.SelectServerAsync(operationContext, null).GetAwaiter().GetResult(); + retryableContext.AcquireChannelAsync(operationContext).GetAwaiter().GetResult(); } else { - retryableContext.SelectServer(OperationContext.NoTimeout, null); - retryableContext.AcquireChannel(OperationContext.NoTimeout); + retryableContext.SelectServer(operationContext, null); + retryableContext.AcquireChannel(operationContext); } return retryableContext; } @@ -671,15 +674,16 @@ private DisposableBindingBundle Create private RetryableWriteContext CreateRetryableWriteContext(IReadWriteBindingHandle readWriteBindingHandle, bool async) { var retryableContext = new RetryableWriteContext(readWriteBindingHandle, retryRequested: false, RetryabilityHelper.OperationRetryBackpressureConstants.DefaultMaxRetries, false); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - retryableContext.SelectServerAsync(OperationContext.NoTimeout, null).GetAwaiter().GetResult(); - retryableContext.AcquireChannelAsync(OperationContext.NoTimeout).GetAwaiter().GetResult(); + retryableContext.SelectServerAsync(operationContext, null).GetAwaiter().GetResult(); + retryableContext.AcquireChannelAsync(operationContext).GetAwaiter().GetResult(); } else { - retryableContext.SelectServer(OperationContext.NoTimeout, null); - retryableContext.AcquireChannel(OperationContext.NoTimeout); + retryableContext.SelectServer(operationContext, null); + retryableContext.AcquireChannel(operationContext); } return retryableContext; } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs index 8c43eff469e..281cfd83d23 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs @@ -15,7 +15,6 @@ using System; using System.Reflection; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -306,9 +305,10 @@ public void CreateCommand_should_return_the_expected_result() { var subject = new AggregateOperation(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -331,10 +331,10 @@ public void CreateCommand_should_return_the_expected_result_when_AllowDiskUse_is }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var session = OperationTestHelper.CreateSession(); - - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -357,9 +357,10 @@ public void CreateCommand_should_return_the_expected_result_when_BatchSize_is_se BatchSize = batchSize }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var cursor = new BsonDocument { @@ -387,9 +388,10 @@ public void CreateCommand_should_return_the_expected_result_when_Collation_is_se }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -413,9 +415,10 @@ public void CreateCommand_should_return_expected_result_when_Comment_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -440,9 +443,10 @@ public void CreateCommand_should_return_the_expected_result_when_Hint_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -467,9 +471,10 @@ public void CreateCommand_should_return_expected_result_when_Let_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.AggregateOptionsLet.FirstSupportedWireVersion); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -495,9 +500,10 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -520,10 +526,9 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout MaxTime = TimeSpan.FromTicks(10) }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); result.Should().NotContain("maxTimeMS"); } @@ -541,9 +546,10 @@ public void CreateCommand_should_return_the_expected_result_when_ReadConcern_is_ }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -568,9 +574,9 @@ public void CreateCommand_should_return_the_expected_result_when_using_causal_co }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true); - var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(true, new BsonTimestamp(100))); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedReadConcernDocument = readConcern.ToBsonDocument(); expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100); @@ -609,8 +615,10 @@ public void Execute_should_throw_when_binding_is_null( bool async) { var subject = new AggregateOperation(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var exception = Record.Exception(() => ExecuteOperation(subject, binding: null, async: async)); + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, binding: null, async: async)); var argumentNullException = exception.Should().BeOfType().Subject; argumentNullException.ParamName.Should().Be("binding"); } @@ -626,7 +634,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AggregateToCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AggregateToCollectionOperationTests.cs index 523d4886fcc..e0dc34bb18c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AggregateToCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AggregateToCollectionOperationTests.cs @@ -304,10 +304,11 @@ public void CanUseSecondary_should_return_expected_result(int maxWireVersion, bo public void CreateCommand_should_return_expected_result() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -328,10 +329,11 @@ public void CreateCommand_should_return_expected_result_when_AllowDiskUse_is_set { AllowDiskUse = allowDiskUse }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -353,10 +355,11 @@ public void CreateCommand_should_return_expected_result_when_BypassDocumentValid { BypassDocumentValidation = bypassDocumentValidation }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -379,10 +382,11 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( { Collation = collation }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -404,10 +408,11 @@ public void CreateCommand_should_return_expected_result_when_Comment_is_set( { Comment = comment, }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -430,10 +435,11 @@ public void CreateCommand_should_return_the_expected_result_when_Hint_is_set( { Hint = hint }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -456,10 +462,11 @@ public void CreateCommand_should_return_the_expected_result_when_Let_is_set( { Let = let }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -484,10 +491,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -509,11 +517,10 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); result.Should().NotContain("maxTimeMS"); } @@ -529,10 +536,11 @@ public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( { subject.ReadConcern = new ReadConcern(readConcernLevel); } - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -555,10 +563,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -753,7 +762,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorEnumeratorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorEnumeratorTests.cs index a653fb648b0..81823044d75 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorEnumeratorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorEnumeratorTests.cs @@ -241,6 +241,7 @@ private AsyncCursorEnumerator CreateSubject(int count) var cursor = new AsyncCursor( channelSource: new Mock().Object, + session: new Mock().Object, collectionNamespace: new CollectionNamespace("foo", "bar"), comment: null, firstBatch: firstBatch, diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorSourceEnumeratorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorSourceEnumeratorTests.cs index c95f4b64c38..a4b1bcc30b8 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorSourceEnumeratorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorSourceEnumeratorTests.cs @@ -171,6 +171,7 @@ private IAsyncCursor CreateCursor(int count) return new AsyncCursor( channelSource: new Mock().Object, + session: Mock.Of(), collectionNamespace: new CollectionNamespace("test", "collection"), comment: null, firstBatch: firstBatch, @@ -194,4 +195,4 @@ private IAsyncCursorSource CreateCursorSource(int count) return mockCursorSource.Object; } } -} \ No newline at end of file +} diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs index 8c562675807..c8301a47a74 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs @@ -181,6 +181,7 @@ public void constructor_should_dispose_channel_source_when_cursor_id_is_zero() public void constructor_should_initialize_instance() { var channelSource = new Mock().Object; + var session = new Mock().Object; var databaseNamespace = new DatabaseNamespace("test"); var collectionNamespace = new CollectionNamespace(databaseNamespace, "test"); var firstBatch = new BsonDocument[] { new BsonDocument("y", 2) }; @@ -193,6 +194,7 @@ public void constructor_should_initialize_instance() var result = new AsyncCursor( channelSource, + session, collectionNamespace, comment: null, firstBatch, @@ -407,21 +409,19 @@ public void GetMore_should_use_same_session( var mockChannel = new Mock(); var channel = mockChannel.Object; var mockSession = new Mock(); + mockSession.Setup(m => m.Fork()).Returns(mockSession.Object); var session = mockSession.Object; var databaseNamespace = new DatabaseNamespace("database"); var collectionNamespace = new CollectionNamespace(databaseNamespace, "collection"); var cursorId = 1; - var subject = CreateSubject(collectionNamespace: collectionNamespace, cursorId: cursorId, channelSource: Optional.Create(channelSource)); + var subject = CreateSubject(session: Optional.Create(session), collectionNamespace: collectionNamespace, cursorId: cursorId, channelSource: Optional.Create(channelSource)); var connectionDescription = CreateConnectionDescriptionSupportingSession(); - - mockSession.Setup(m => m.Fork()).Returns(mockSession.Object); mockChannel.Setup(m => m.Fork()).Returns(mockChannel.Object); var mockServer = new Mock(); var serverId = new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27017)); mockServer.SetupGet(m => m.Description).Returns(new ServerDescription(serverId, serverId.EndPoint)); mockChannelSource.SetupGet(m => m.Server).Returns(mockServer.Object); - mockChannelSource.SetupGet(m => m.Session).Returns(session); mockChannel.SetupGet(m => m.ConnectionDescription).Returns(connectionDescription); var nextBatchBytes = new byte[] { 5, 0, 0, 0, 0 }; var nextBatchSlice = new ByteArrayBuffer(nextBatchBytes, isReadOnly: true); @@ -442,8 +442,7 @@ public void GetMore_should_use_same_session( mockChannelSource.Setup(m => m.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockChannel .Setup(m => m.CommandAsync( - It.IsAny(), - session, + It.Is(c => c.Session == session), ReadPreference.Primary, databaseNamespace, It.IsAny(), @@ -464,8 +463,7 @@ public void GetMore_should_use_same_session( mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); mockChannel .Setup(m => m.Command( - It.IsAny(), - session, + It.Is(c => c.Session == session), ReadPreference.Primary, databaseNamespace, It.IsAny(), @@ -503,6 +501,7 @@ private ConnectionDescription CreateConnectionDescriptionSupportingSession(int m private AsyncCursor CreateSubject( Optional channelSource = default(Optional), + Optional session = default(Optional), Optional collectionNamespace = default(Optional), Optional> serializer = default(Optional>), Optional> firstBatch = default(Optional>), @@ -513,8 +512,16 @@ private AsyncCursor CreateSubject( Optional comment = default(Optional), Optional retryRequested = default(Optional)) { + if (!session.HasValue) + { + var sessionMock = new Mock(); + sessionMock.Setup(s => s.Fork()).Returns(Mock.Of()); + session = Optional.Create(sessionMock.Object); + } + return new AsyncCursor( channelSource.WithDefault(new Mock().Object), + session.Value, collectionNamespace.WithDefault(new CollectionNamespace("test", "test")), comment: comment.WithDefault(null), firstBatch.WithDefault(new List()), @@ -558,7 +565,6 @@ private void SetupChannelMocks(Mock mockChannelSource, Mock c.CommandAsync( It.IsAny(), - It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), @@ -585,7 +591,6 @@ private void SetupChannelMocks(Mock mockChannelSource, Mock c.Command( It.IsAny(), - It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), @@ -611,7 +616,6 @@ private void VerifyHowManyTimesKillCursorsCommandWasCalled(Mock mockChannelHandle.Verify( s => s.CommandAsync( It.IsAny(), - It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), @@ -629,7 +633,6 @@ private void VerifyHowManyTimesKillCursorsCommandWasCalled(Mock mockChannelHandle.Verify( s => s.Command( It.IsAny(), - It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), @@ -662,15 +665,17 @@ public void Session_reference_count_should_be_decremented_as_soon_as_possible(in Insert(documents); _session.ReferenceCount().Should().Be(1); - using (var binding = new ReadPreferenceBinding(CoreTestConfiguration.Cluster, ReadPreference.Primary, _session.Fork())) - using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(OperationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) + using (var session = _session.Fork()) + using (var operationContext = new OperationContext(session)) + using (var binding = new ReadPreferenceBinding(CoreTestConfiguration.Cluster, ReadPreference.Primary)) + using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) { var query = new BsonDocument(); long cursorId; - var firstBatch = GetFirstBatch(channel, query, batchSize, CancellationToken.None, out cursorId); + var firstBatch = GetFirstBatch(operationContext, channel, query, batchSize, CancellationToken.None, out cursorId); - using (var cursor = new AsyncCursor(channelSource, _collectionNamespace, comment: null, firstBatch, cursorId, batchSize, null, BsonDocumentSerializer.Instance, new MessageEncoderSettings(), maxTime: null, retryRequested: false, maxAdaptiveRetries: RetryabilityHelper.OperationRetryBackpressureConstants.DefaultMaxRetries, enableOverloadRetargeting: false)) + using (var cursor = new AsyncCursor(channelSource, session, _collectionNamespace, comment: null, firstBatch, cursorId, batchSize, null, BsonDocumentSerializer.Instance, new MessageEncoderSettings(), maxTime: null, retryRequested: false, maxAdaptiveRetries: RetryabilityHelper.OperationRetryBackpressureConstants.DefaultMaxRetries, enableOverloadRetargeting: false)) { AssertExpectedSessionReferenceCount(_session, cursor); while (cursor.MoveNext(CancellationToken.None)) @@ -688,16 +693,11 @@ private void AssertExpectedSessionReferenceCount(ICoreSessionHandle session, IAs { var cursorImplementation = (AsyncCursor)cursor; var cursorId = cursorImplementation._cursorId(); - var expectedReferenceCount = cursorId == 0 ? 2 : 3; // one from the session, one from the binding, and maybe one from the cursor + var expectedReferenceCount = cursorId == 0 ? 1 : 2; // one from the session, and one from the cursor session.ReferenceCount().Should().Be(expectedReferenceCount); } - private IReadOnlyList GetFirstBatch(IChannelHandle channel, BsonDocument query, int batchSize, CancellationToken cancellationToken, out long cursorId) - { - return GetFirstBatchUsingFindCommand(channel, query, batchSize, cancellationToken, out cursorId); - } - - private IReadOnlyList GetFirstBatchUsingFindCommand(IChannelHandle channel, BsonDocument query, int batchSize, CancellationToken cancellationToken, out long cursorId) + private IReadOnlyList GetFirstBatch(OperationContext operationContext, IChannelHandle channel, BsonDocument query, int batchSize, CancellationToken cancellationToken, out long cursorId) { var command = new BsonDocument { @@ -706,8 +706,7 @@ private IReadOnlyList GetFirstBatchUsingFindCommand(IChannelHandle { "batchSize", batchSize } }; var result = channel.Command( - new OperationContext(null, cancellationToken), - _session, + operationContext, ReadPreference.Primary, _databaseNamespace, command, diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs index c14714121a3..fa1aad7b213 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -1375,17 +1374,19 @@ public void Execute_unacknowledged_with_an_error_in_the_first_batch_and_ordered_ WriteConcern = WriteConcern.Unacknowledged }; - using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - 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())) + using (var readWriteBinding = CreateReadWriteBinding()) + using (var session = CreateSession(useImplicitSession: true)) + using (var operationContext = new OperationContext(session)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var result = ExecuteOperation(subject, channelBinding, async); + var result = ExecuteOperation(operationContext, subject, channelBinding, async); result.ProcessedRequests.Should().HaveCount(5); result.RequestCount.Should().Be(5); - var list = ReadAllFromCollection(channelBinding); + var list = ReadAllFromCollection(operationContext, channelBinding); list.Should().HaveCount(3); } } @@ -1422,16 +1423,18 @@ public void Execute_unacknowledged_with_an_error_in_the_first_batch_and_ordered_ WriteConcern = WriteConcern.Unacknowledged }; - using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - 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())) + using (var readWriteBinding = CreateReadWriteBinding()) + using (var session = CreateSession(useImplicitSession: true)) + using (var operationContext = new OperationContext(session)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var result = ExecuteOperation(subject, channelBinding, async); + var result = ExecuteOperation(operationContext, subject, channelBinding, async); result.ProcessedRequests.Should().HaveCount(5); result.RequestCount.Should().Be(5); - var list = ReadAllFromCollection(channelBinding); + var list = ReadAllFromCollection(operationContext, channelBinding); list.Should().HaveCount(1); } } @@ -1463,16 +1466,18 @@ public void Execute_unacknowledged_with_an_error_in_the_second_batch_and_ordered WriteConcern = WriteConcern.Unacknowledged }; - using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - 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())) + using (var readWriteBinding = CreateReadWriteBinding()) + using (var session = CreateSession(useImplicitSession: true)) + using (var operationContext = new OperationContext(session)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var result = ExecuteOperation(subject, channelBinding, async); + var result = ExecuteOperation(operationContext, subject, channelBinding, async); result.ProcessedRequests.Should().HaveCount(5); result.RequestCount.Should().Be(5); - var list = ReadAllFromCollection(channelBinding); + var list = ReadAllFromCollection(operationContext, channelBinding); list.Should().HaveCount(4); } } @@ -1504,16 +1509,18 @@ public void Execute_unacknowledged_with_an_error_in_the_second_batch_and_ordered WriteConcern = WriteConcern.Unacknowledged }; - using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - 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())) + using (var readWriteBinding = CreateReadWriteBinding()) + using (var session = CreateSession(useImplicitSession: true)) + using (var operationContext = new OperationContext(session)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) + using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel)) { - var result = ExecuteOperation(subject, channelBinding, async); + var result = ExecuteOperation(operationContext, subject, channelBinding, async); result.ProcessedRequests.Should().HaveCount(4); result.RequestCount.Should().Be(5); - var list = ReadAllFromCollection(channelBinding); + var list = ReadAllFromCollection(operationContext, channelBinding); list.Should().HaveCount(3); } } @@ -1643,12 +1650,13 @@ public void Execute_with_multiple_deletes_should_split_batches_as_expected_when_ var eventCapturer = new EventCapturer().Capture(e => e.CommandName == "delete" && e.OperationId == EventContext.OperationId); using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = NoCoreSession.NewHandle()) - using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, session.Fork()))) + using (var operationContext = new OperationContext(session)) + using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster))) { var requests = requestSizes.Select(size => CreateDeleteRequest(size)); var operation = new BulkMixedWriteOperation(_collectionNamespace, requests, _messageEncoderSettings); - var result = ExecuteOperation(operation, binding, async: false); + var result = ExecuteOperation(operationContext, operation, binding, async: false); var commandStartedEvents = eventCapturer.Events.OfType().ToList(); var actualBatchCounts = commandStartedEvents.Select(e => e.Command["deletes"].AsBsonArray.Count).ToList(); @@ -1681,13 +1689,14 @@ public void Execute_with_multiple_inserts_should_split_batches_as_expected_when_ var eventCapturer = new EventCapturer().Capture(e => e.CommandName == "insert" && e.OperationId == EventContext.OperationId); using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = NoCoreSession.NewHandle()) - using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, session.Fork()))) + using (var operationContext = new OperationContext(session)) + using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster))) { var documents = documentSizes.Select((size, index) => CreateDocument(index + 1, size)).ToList(); var requests = documents.Select(d => new InsertRequest(d)).ToList(); var operation = new BulkMixedWriteOperation(_collectionNamespace, requests, _messageEncoderSettings); - var result = ExecuteOperation(operation, binding, async: false); + var result = ExecuteOperation(operationContext, operation, binding, async: false); result.InsertedCount.Should().Be(documents.Count); var commandStartedEvents = eventCapturer.Events.OfType().ToList(); @@ -1721,12 +1730,13 @@ public void Execute_with_multiple_updates_should_split_batches_as_expected_when_ var eventCapturer = new EventCapturer().Capture(e => e.CommandName == "update" && e.OperationId == EventContext.OperationId); using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = NoCoreSession.NewHandle()) - using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, session.Fork()))) + using (var operationContext = new OperationContext(session)) + using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster))) { var requests = requestSizes.Select(size => CreateUpdateRequest(size)); var operation = new BulkMixedWriteOperation(_collectionNamespace, requests, _messageEncoderSettings); - var result = ExecuteOperation(operation, binding, async: false); + var result = ExecuteOperation(operationContext, operation, binding, async: false); var commandStartedEvents = eventCapturer.Events.OfType().ToList(); var actualBatchCounts = commandStartedEvents.Select(e => e.Command["updates"].AsBsonArray.Count).ToList(); @@ -1792,10 +1802,10 @@ private void EnsureTestData() BsonDocument.Parse("{_id: 6, x: 3 }")); } - private List ReadAllFromCollection(IReadBinding binding) + private List ReadAllFromCollection(OperationContext operationContext, IReadBinding binding) { var operation = new FindOperation(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings); - var cursor = ExecuteOperation(operation, binding, false); + var cursor = ExecuteOperation(operationContext, operation, binding, false); return ReadCursorToEnd(cursor); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs index 4e11447d94c..67300d725b4 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs @@ -89,6 +89,7 @@ public void constructor_should_initialize_instance() var cursor = new Mock>().Object; var documentSerializer = new Mock>().Object; var binding = new Mock().Object; + var session = new Mock().Object; var initialOperationTime = new BsonTimestamp(3L); var postBatchResumeToken = new BsonDocument("c", 3); var changeStreamOperation = CreateChangeStreamOperation(); @@ -100,6 +101,7 @@ public void constructor_should_initialize_instance() cursor, documentSerializer, binding, + session, changeStreamOperation, postBatchResumeToken, initialOperationTime, @@ -120,6 +122,7 @@ public void constructor_should_initialize_instance() subject._initialResumeAfter().Should().Be(resumeAfter); subject._initialStartAtOperationTime().Should().Be(startAtOperationTime); subject._maxWireVersion().Should().Be(__dummyMaxWireVersion); + subject._session().Should().Be(session); } [Fact] @@ -127,11 +130,12 @@ public void constructor_should_throw_when_cursor_is_null() { var documentSerializer = new Mock>().Object; var binding = new Mock().Object; + var session = new Mock().Object; var initialOperationTime = new BsonTimestamp(3L); var postBatchResumeToken = Mock.Of(); var changeStreamOperation = CreateChangeStreamOperation(); - var exception = Record.Exception(() => new ChangeStreamCursor(null, documentSerializer, binding, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); + var exception = Record.Exception(() => new ChangeStreamCursor(null, documentSerializer, binding, session, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); var argumnetNullException = exception.Should().BeOfType().Subject; argumnetNullException.ParamName.Should().Be("cursor"); @@ -142,11 +146,12 @@ public void constructor_should_throw_when_documentSerializer_is_null() { var cursor = new Mock>().Object; var binding = new Mock().Object; + var session = new Mock().Object; var initialOperationTime = new BsonTimestamp(3L); var postBatchResumeToken = Mock.Of(); var changeStreamOperation = CreateChangeStreamOperation(); - var exception = Record.Exception(() => new ChangeStreamCursor(cursor, null, binding, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); + var exception = Record.Exception(() => new ChangeStreamCursor(cursor, null, binding, session, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); var argumnetNullException = exception.Should().BeOfType().Subject; argumnetNullException.ParamName.Should().Be("documentSerializer"); @@ -157,11 +162,12 @@ public void constructor_should_throw_when_binding_is_null() { var cursor = new Mock>().Object; var documentSerializer = new Mock>().Object; + var session = new Mock().Object; var initialOperationTime = new BsonTimestamp(3L); var postBatchResumeToken = Mock.Of(); var changeStreamOperation = CreateChangeStreamOperation(); - var exception = Record.Exception(() => new ChangeStreamCursor(cursor, documentSerializer, null, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); + var exception = Record.Exception(() => new ChangeStreamCursor(cursor, documentSerializer, null, session, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); var argumnetNullException = exception.Should().BeOfType().Subject; argumnetNullException.ParamName.Should().Be("binding"); @@ -175,8 +181,9 @@ public void constructor_should_throw_when_changeStreamOperation_is_null() var initialOperationTime = new BsonTimestamp(3L); var postBatchResumeToken = Mock.Of(); var binding = new Mock().Object; + var session = new Mock().Object; - var exception = Record.Exception(() => new ChangeStreamCursor(cursor, documentSerializer, binding, null, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); + var exception = Record.Exception(() => new ChangeStreamCursor(cursor, documentSerializer, binding, session, null, postBatchResumeToken, initialOperationTime, null, null, null, __dummyMaxWireVersion)); var argumnetNullException = exception.Should().BeOfType().Subject; argumnetNullException.ParamName.Should().Be("changeStreamOperation"); @@ -190,9 +197,10 @@ public void constructor_should_throw_when_maxWireVersion_is_negative() var initialOperationTime = new BsonTimestamp(3L); var postBatchResumeToken = Mock.Of(); var binding = new Mock().Object; + var session = new Mock().Object; var changeStreamOperation = CreateChangeStreamOperation(); - var exception = Record.Exception(() => new ChangeStreamCursor(cursor, documentSerializer, binding, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, -1)); + var exception = Record.Exception(() => new ChangeStreamCursor(cursor, documentSerializer, binding, session, changeStreamOperation, postBatchResumeToken, initialOperationTime, null, null, null, -1)); var argumnetNullException = exception.Should().BeOfType().Subject; argumnetNullException.ParamName.Should().Be("maxWireVersion"); @@ -640,6 +648,7 @@ private ChangeStreamCursor CreateSubject( IAsyncCursor cursor = null, IBsonSerializer documentSerializer = null, IReadBinding binding = null, + ICoreSessionHandle session = null, IChangeStreamOperation changeStreamOperation = null, BsonDocument postBatchResumeToken = null, BsonDocument startAfter = null, @@ -647,11 +656,12 @@ private ChangeStreamCursor CreateSubject( BsonTimestamp startAtOperationTime = null, BsonTimestamp initialOperationTime = null) { - cursor = cursor ?? new Mock>().Object; - documentSerializer = documentSerializer ?? new Mock>().Object; - binding = binding ?? new Mock().Object; - changeStreamOperation = changeStreamOperation ?? Mock.Of>(); - return new ChangeStreamCursor(cursor, documentSerializer, binding, changeStreamOperation, postBatchResumeToken, initialOperationTime, startAfter, resumeAfter, startAtOperationTime, __dummyMaxWireVersion); + cursor ??= new Mock>().Object; + documentSerializer ??= new Mock>().Object; + binding ??= new Mock().Object; + session ??= new Mock().Object; + changeStreamOperation ??= Mock.Of>(); + return new ChangeStreamCursor(cursor, documentSerializer, binding, session, changeStreamOperation, postBatchResumeToken, initialOperationTime, startAfter, resumeAfter, startAtOperationTime, __dummyMaxWireVersion); } private BsonDocument GenerateResumeAfterToken(bool async, bool shouldBeEmpty = false) @@ -693,79 +703,52 @@ private RawBsonDocument ToRawDocument(BsonDocument document) internal static class ChangeStreamCursorReflector { - public static IReadBinding _binding(this ChangeStreamCursor cursor) - { - return (IReadBinding)Reflector.GetFieldValue(cursor, nameof(_binding)); - } + public static IReadBinding _binding(this ChangeStreamCursor cursor) => + (IReadBinding)Reflector.GetFieldValue(cursor, nameof(_binding)); - public static IChangeStreamOperation _changeStreamOperation(this ChangeStreamCursor cursor) - { - return (IChangeStreamOperation)Reflector.GetFieldValue(cursor, nameof(_changeStreamOperation)); - } + public static IChangeStreamOperation _changeStreamOperation(this ChangeStreamCursor cursor) => + (IChangeStreamOperation)Reflector.GetFieldValue(cursor, nameof(_changeStreamOperation)); - public static IEnumerable _current(this ChangeStreamCursor cursor) - { - return (IEnumerable)Reflector.GetFieldValue(cursor, nameof(_current)); - } + public static IEnumerable _current(this ChangeStreamCursor cursor) => + (IEnumerable)Reflector.GetFieldValue(cursor, nameof(_current)); - public static IAsyncCursor _cursor(this ChangeStreamCursor cursor) - { - return (IAsyncCursor)Reflector.GetFieldValue(cursor, nameof(_cursor)); - } + public static IAsyncCursor _cursor(this ChangeStreamCursor cursor) => + (IAsyncCursor)Reflector.GetFieldValue(cursor, nameof(_cursor)); - public static bool _disposed(this ChangeStreamCursor cursor) - { - return (bool)Reflector.GetFieldValue(cursor, nameof(_disposed)); - } + public static bool _disposed(this ChangeStreamCursor cursor) => + (bool)Reflector.GetFieldValue(cursor, nameof(_disposed)); - public static IBsonSerializer _documentSerializer(this ChangeStreamCursor cursor) - { - return (IBsonSerializer)Reflector.GetFieldValue(cursor, nameof(_documentSerializer)); - } + public static IBsonSerializer _documentSerializer(this ChangeStreamCursor cursor) => + (IBsonSerializer)Reflector.GetFieldValue(cursor, nameof(_documentSerializer)); - public static BsonDocument _documentResumeToken(this IChangeStreamCursor cursor) - { - return (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_documentResumeToken)); - } + public static BsonDocument _documentResumeToken(this IChangeStreamCursor cursor) => + (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_documentResumeToken)); - public static void _documentResumeToken(this IChangeStreamCursor cursor, BsonDocument value) - { + public static void _documentResumeToken(this IChangeStreamCursor cursor, BsonDocument value) => Reflector.SetFieldValue(cursor, nameof(_documentResumeToken), value); - } - public static ChangeStreamCursor.ResumeValues GetResumeValues(this IChangeStreamCursor cursor) - { - return (ChangeStreamCursor.ResumeValues)Reflector.Invoke(cursor, nameof(GetResumeValues)); - } + public static ChangeStreamCursor.ResumeValues GetResumeValues(this IChangeStreamCursor cursor) => + (ChangeStreamCursor.ResumeValues)Reflector.Invoke(cursor, nameof(GetResumeValues)); - public static BsonTimestamp _initialOperationTime(this IChangeStreamCursor cursor) - { - return (BsonTimestamp)Reflector.GetFieldValue(cursor, nameof(_initialOperationTime)); - } + public static BsonTimestamp _initialOperationTime(this IChangeStreamCursor cursor) => + (BsonTimestamp)Reflector.GetFieldValue(cursor, nameof(_initialOperationTime)); - public static BsonDocument _postBatchResumeToken(this IChangeStreamCursor cursor) - { - return (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_postBatchResumeToken)); - } + public static BsonDocument _postBatchResumeToken(this IChangeStreamCursor cursor) => + (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_postBatchResumeToken)); - public static BsonDocument _initialResumeAfter(this IChangeStreamCursor cursor) - { - return (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_initialResumeAfter)); - } + public static BsonDocument _initialResumeAfter(this IChangeStreamCursor cursor) => + (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_initialResumeAfter)); - public static BsonDocument _initialStartAfter(this IChangeStreamCursor cursor) - { - return (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_initialStartAfter)); - } + public static BsonDocument _initialStartAfter(this IChangeStreamCursor cursor) => + (BsonDocument)Reflector.GetFieldValue(cursor, nameof(_initialStartAfter)); - public static BsonTimestamp _initialStartAtOperationTime(this IChangeStreamCursor cursor) - { - return (BsonTimestamp)Reflector.GetFieldValue(cursor, nameof(_initialStartAtOperationTime)); - } + public static BsonTimestamp _initialStartAtOperationTime(this IChangeStreamCursor cursor) => + (BsonTimestamp)Reflector.GetFieldValue(cursor, nameof(_initialStartAtOperationTime)); - public static int _maxWireVersion(this IChangeStreamCursor cursor) - { - return (int)Reflector.GetFieldValue(cursor, nameof(_maxWireVersion)); - } + public static int _maxWireVersion(this IChangeStreamCursor cursor) => + (int)Reflector.GetFieldValue(cursor, nameof(_maxWireVersion)); + + public static ICoreSessionHandle _session(this IChangeStreamCursor cursor) => + (ICoreSessionHandle)Reflector.GetFieldValue(cursor, nameof(_session)); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs index 394685a8807..3d48f0408be 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs @@ -635,8 +635,10 @@ public void Execute_should_throw_when_binding_does_not_implement_IReadBindingHan { var subject = CreateSubject(); var binding = new Mock().Object; + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var exception = Record.Exception(() => ExecuteOperation(subject, binding, async)); + var exception = Record.Exception(() => ExecuteOperation(operationContext, 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 3dcc8a36cfc..d40945556d6 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs @@ -68,9 +68,10 @@ 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)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var resultedException = async - ? await Record.ExceptionAsync(() => subject.ExecuteAsync(OperationContext.NoTimeout, Mock.Of())) - : Record.Exception(() => subject.Execute(OperationContext.NoTimeout, Mock.Of())); + ? await Record.ExceptionAsync(() => subject.ExecuteAsync(operationContext, Mock.Of())) + : Record.Exception(() => subject.Execute(operationContext, Mock.Of())); resultedException.Should().Be(testException); @@ -91,9 +92,10 @@ 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)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var result = async - ? subject.ExecuteAsync(OperationContext.NoTimeout, Mock.Of()).GetAwaiter().GetResult() - : subject.Execute(OperationContext.NoTimeout, Mock.Of()); + ? subject.ExecuteAsync(operationContext, Mock.Of()).GetAwaiter().GetResult() + : subject.Execute(operationContext, Mock.Of()); result.Should().Be(operation2Result); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CountDocumentsOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CountDocumentsOperationTests.cs index 671a49aacfb..a3cb5557ffd 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CountDocumentsOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CountDocumentsOperationTests.cs @@ -259,7 +259,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CountOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CountOperationTests.cs index b97cdc3f117..7b4acfc7147 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CountOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CountOperationTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -201,9 +200,10 @@ public void CreateCommand_should_return_expected_result() var subject = new CountOperation(_collectionNamespace, _messageEncoderSettings); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -224,9 +224,10 @@ public void CreateCommand_should_return_expected_result_when_Comment_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -249,9 +250,10 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -274,9 +276,10 @@ public void CreateCommand_should_return_expected_result_when_Filter_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -299,9 +302,10 @@ public void CreateCommand_should_return_expected_result_when_Hint_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -323,9 +327,10 @@ public void CreateCommand_should_return_expected_result_when_Limit_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -349,9 +354,10 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -372,10 +378,9 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout MaxTime = TimeSpan.FromTicks(10) }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); result.Should().NotContain("maxTimeMS"); } @@ -393,9 +398,10 @@ public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -418,9 +424,10 @@ public void CreateCommand_should_return_the_expected_result_when_using_causal_co }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true); - var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedReadConcernDocument = readConcern.ToBsonDocument(); expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100); @@ -445,9 +452,10 @@ public void CreateCommand_should_return_expected_result_when_Skip_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -514,7 +522,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs index 031fbb3c012..268411405ed 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs @@ -96,9 +96,10 @@ public void constructor_should_throw_when_collectionNamespace_is_null() public void CreateCommand_should_return_expected_result() { var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -117,9 +118,10 @@ public void CreateCommand_should_return_expected_result_when_Capped_is_set( { Capped = capped }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -140,9 +142,10 @@ public void CreateCommand_should_return_expected_result_when_ChangeStreamsPreAnd } }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -162,9 +165,10 @@ public void CreateCommand_should_return_expected_result_when_ClusteredIndex_is_s { ClusteredIndex = clusteredIndex != null ? BsonDocument.Parse(clusteredIndex) : null }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -185,9 +189,10 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( { Collation = collation }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -208,9 +213,10 @@ public void CreateCommand_should_return_expected_result_when_IndexOptionDefaults { IndexOptionDefaults = indexOptionDefaults }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -230,9 +236,10 @@ public void CreateCommand_should_return_expected_result_when_MaxDocuments_is_set { MaxDocuments = maxDocuments }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -252,9 +259,10 @@ public void CreateCommand_should_return_expected_result_when_MaxSize_is_set( { MaxSize = maxSize }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -275,9 +283,10 @@ public void CreateCommand_should_return_expected_result_when_StorageEngine_is_se { StorageEngine = storageEngine }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -297,9 +306,10 @@ public void CreateCommand_should_return_expected_result_when_ValidationAction_is { ValidationAction = validationAction }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -319,9 +329,10 @@ public void CreateCommand_should_return_expected_result_when_ValidationLevel_is_ { ValidationLevel = validationLevel }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -342,9 +353,10 @@ public void CreateCommand_should_return_expected_result_when_Validator_is_set( { Validator = validator }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -372,10 +384,10 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = hasOperationTimeout ? new OperationContext(session, TimeSpan.FromSeconds(42), CancellationToken.None) : new OperationContext(session); - var result = subject.CreateCommand(operationContext, session, OperationTestHelper.CreateConnectionDescription(), null); + var result = subject.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -395,11 +407,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set public void CreateEncryptedCreateCollectionOperationIfConfigured_should_return_expected_result_when_EncryptedFields_is_null() { var subject = CreateCollectionOperation.CreateEncryptedCreateCollectionOperationIfConfigured(_collectionNamespace, encryptedFields: null, _messageEncoderSettings, null); - var session = OperationTestHelper.CreateSession(); - var s = subject.Should().BeOfType().Subject; + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var command = s.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null); + var command = s.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null); var expectedResult = new BsonDocument { @@ -432,7 +444,8 @@ public void CreateEncryptedCreateCollectionOperationIfConfigured_should_return_e }}"); var subject = CreateCollectionOperation.CreateEncryptedCreateCollectionOperationIfConfigured(_collectionNamespace, encryptedFields, _messageEncoderSettings, null); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); var operations = ((CompositeWriteOperation)subject)._operations(); @@ -489,8 +502,8 @@ void AssertCommand((IWriteOperation Operation, bool IsMainOperatio var result = operation switch { - CreateCollectionOperation createCollectionOperation => createCollectionOperation.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null), - CreateIndexesOperation createIndexesOperation => createIndexesOperation.CreateCommand(OperationContext.NoTimeout, session, OperationTestHelper.CreateConnectionDescription(), null), + CreateCollectionOperation createCollectionOperation => createCollectionOperation.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null), + CreateIndexesOperation createIndexesOperation => createIndexesOperation.CreateCommand(operationContext, OperationTestHelper.CreateConnectionDescription(), null), _ => throw new Exception($"Unexpected operation {operation}."), }; result.Should().Be(expectedResult); @@ -524,9 +537,11 @@ public void Execute_should_create_collection( var subject = new CreateCollectionOperation(_collectionNamespace, _messageEncoderSettings); BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -551,9 +566,11 @@ public void Execute_should_create_collection_when_Capped_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -578,9 +595,11 @@ public void Execute_should_create_collection_when_Collation_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -606,9 +625,11 @@ public void Execute_should_create_collection_when_IndexOptionDefaults_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -633,9 +654,11 @@ public void Execute_should_create_collection_when_MaxDocuments_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -659,9 +682,11 @@ public void Execute_should_create_collection_when_MaxSize_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -688,9 +713,11 @@ public void Execute_should_create_collection_when_StorageEngine_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -714,9 +741,11 @@ public void Execute_should_create_collection_when_Validator_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); info = GetCollectionInfo(binding); } @@ -740,9 +769,11 @@ public void Execute_should_throw_when_a_write_concern_error_occurs( var exception = Record.Exception(() => { + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, false); + ExecuteOperation(operationContext, subject, binding, false); } }); @@ -917,25 +948,15 @@ public void WriteConcern_get_and_set_should_work( } // helper methods - private BsonDocument ExecuteOperation(CreateCollectionOperation subject, IWriteBinding binding, bool async) - { - if (async) - { - return subject.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); - } - else - { - return subject.Execute(OperationContext.NoTimeout, binding); - } - } - private BsonDocument GetCollectionInfo(IReadBinding binding) { var listCollectionsOperation = new ListCollectionsOperation(_collectionNamespace.DatabaseNamespace, _messageEncoderSettings) { Filter = new BsonDocument("name", _collectionNamespace.CollectionName) }; - return listCollectionsOperation.Execute(OperationContext.NoTimeout, binding).Single(); + using var session = CreateSession(); + using var operationContext = new OperationContext(session); + return listCollectionsOperation.Execute(operationContext, binding).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateIndexesOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateIndexesOperationTests.cs index 8c83c811077..80911f5817f 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateIndexesOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateIndexesOperationTests.cs @@ -20,6 +20,7 @@ using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.TestHelpers; @@ -90,10 +91,11 @@ public void CreateCommand_should_return_expected_result_when_creating_one_index( { var requests = new[] { new CreateIndexRequest(new BsonDocument("x", 1)) }; var subject = new CreateIndexesOperation(_collectionNamespace, requests, _messageEncoderSettings); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -112,10 +114,11 @@ public void CreateCommand_should_return_expected_result_when_creating_two_indexe new CreateIndexRequest(new BsonDocument("y", 1)) }; var subject = new CreateIndexesOperation(_collectionNamespace, requests, _messageEncoderSettings); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -136,10 +139,11 @@ public void CreateCommand_should_return_expected_result_when_CommitQuorum_with_m { CommitQuorum = commitQuorum }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.CreateIndexCommitQuorum.FirstSupportedWireVersion); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -162,10 +166,11 @@ public void CreateCommand_should_return_expected_result_when_CommitQuorum_with_w { CommitQuorum = commitQuorum }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.CreateIndexCommitQuorum.FirstSupportedWireVersion); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -191,10 +196,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_Set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -216,11 +222,11 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session, TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().NotContain("maxTimeMS"); } @@ -237,10 +243,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -260,10 +267,11 @@ public void CreateCommand_should_throw_when_commitQuorum_is_specified_and_not_su { CommitQuorum = commitQuorum }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.CreateIndexCommitQuorum.LastNotSupportedWireVersion); + using var operationContext = new OperationContext(session); - var exception = Record.Exception(() => subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null)); + var exception = Record.Exception(() => subject.CreateCommand(operationContext, connectionDescription, null)); exception.Should().BeOfType(); } @@ -279,7 +287,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs index c949818fc00..25b019245ed 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs @@ -15,7 +15,6 @@ using System; using System.Linq; -using System.Threading; using FluentAssertions; using MongoDB.Bson; using MongoDB.TestHelpers.XunitExtensions; @@ -136,10 +135,12 @@ public void Execute_should_create_view( var subject = new CreateViewOperation(_databaseNamespace, viewName, _collectionNamespace.CollectionName, _pipeline, _messageEncoderSettings); BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); - info = GetViewInfo(binding, viewName); + ExecuteOperation(operationContext, subject, binding, async); + info = GetViewInfo(operationContext, binding, viewName); } var options = info["options"].AsBsonDocument; @@ -164,10 +165,12 @@ public void Execute_should_create_view_when_Collation_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); - info = GetViewInfo(binding, _viewName); + ExecuteOperation(operationContext, subject, binding, async); + info = GetViewInfo(operationContext, binding, _viewName); } var options = info["options"].AsBsonDocument; @@ -199,10 +202,12 @@ public void Execute_should_create_view_when_WriteConcern_is_set( }; BsonDocument info; + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); - info = GetViewInfo(binding, viewName); + ExecuteOperation(operationContext, subject, binding, async); + info = GetViewInfo(operationContext, binding, viewName); } var options = info["options"].AsBsonDocument; @@ -248,10 +253,11 @@ public void CreateCommand_should_return_expected_result( string viewName) { var subject = new CreateViewOperation(_databaseNamespace, viewName, _collectionNamespace.CollectionName, _pipeline, _messageEncoderSettings); - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -273,10 +279,11 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( { Collation = collation }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedResult = new BsonDocument { @@ -305,11 +312,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session, timeout: hasOperationTimeout ? TimeSpan.FromSeconds(42) : null); - var result = subject.CreateCommand(operationContext, session, connectionDescription, transactionNumber: null); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber: null); var expectedConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -335,13 +342,13 @@ private void DropView(string viewName) ExecuteOperation(operation); } - private BsonDocument GetViewInfo(IReadBinding binding, string viewName) + private BsonDocument GetViewInfo(OperationContext operationContext, IReadBinding binding, string viewName) { var listCollectionsOperation = new ListCollectionsOperation(_collectionNamespace.DatabaseNamespace, _messageEncoderSettings) { Filter = new BsonDocument("name", viewName) }; - return listCollectionsOperation.Execute(OperationContext.NoTimeout, binding).Single(); + return listCollectionsOperation.Execute(operationContext, binding).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CursorTests.cs index 432ea2710e9..f8b31b99043 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CursorTests.cs @@ -29,8 +29,10 @@ public class CursorTests public void Constructor_should_call_Dispose_on_channelSource_if_cursorId_is_zero(int cursorId, bool shouldCallDispose) { var mockChannelSource = new Mock(); + var session = Mock.Of(); new AsyncCursor( mockChannelSource.Object, + session, new CollectionNamespace("databaseName", "collectionName"), comment: null, new BsonDocument[0], // firstBatch diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/DistinctOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/DistinctOperationTests.cs index d57e9fc04f8..56085cc07b1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/DistinctOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/DistinctOperationTests.cs @@ -185,9 +185,10 @@ public void CreateCommand_should_return_expected_result() var subject = new DistinctOperation(_collectionNamespace, _valueSerializer, _fieldName, _messageEncoderSettings); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -210,9 +211,10 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -236,9 +238,10 @@ public void CreateCommand_should_return_expected_result_when_Filter_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -264,9 +267,10 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -287,11 +291,12 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); + var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session, timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); result.Should().NotContain("maxTimeMS"); } @@ -309,9 +314,10 @@ public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -335,9 +341,10 @@ public void CreateCommand_should_return_the_expected_result_when_using_causal_co }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true); - var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedReadConcernDocument = readConcern.ToBsonDocument(); expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100); @@ -464,7 +471,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/DropCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/DropCollectionOperationTests.cs index 0545ffbd844..0da113efca6 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/DropCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/DropCollectionOperationTests.cs @@ -68,10 +68,11 @@ public void CreateCommand_should_return_expected_result() { { "drop", _collectionNamespace.CollectionName } }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().Be(expectedResult); } @@ -94,11 +95,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = hasOperationTimeout ? new OperationContext(session, TimeSpan.FromSeconds(42), CancellationToken.None) : new OperationContext(session); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -118,12 +119,12 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set public void CreateEncryptedDropCollectionOperationIfConfigured_should_return_expected_result_when_EncryptedFields_is_null() { var subject = DropCollectionOperation.CreateEncryptedDropCollectionOperationIfConfigured(_collectionNamespace, encryptedFields: null, _messageEncoderSettings, null); - var session = OperationTestHelper.CreateSession(); - var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var s = subject.Should().BeOfType().Subject; + using var session = OperationTestHelper.CreateSession(); + var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var command = s.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var command = s.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -156,7 +157,8 @@ public void CreateEncryptedDropCollectionOperationIfConfigured_should_return_exp }}"); var subject = DropCollectionOperation.CreateEncryptedDropCollectionOperationIfConfigured(_collectionNamespace, encryptedFields, _messageEncoderSettings, null); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); var operations = ((CompositeWriteOperation)subject)._operations(); @@ -185,7 +187,7 @@ void AssertDropCollectionCommand((IWriteOperation Operation, bool operationInfo.IsMainOperation.Should().Be(isMainOperation); var operation = operationInfo.Operation.Should().BeOfType().Subject; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var result = operation.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = operation.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { { "drop", collectionNamespace.CollectionName }, diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/DropDatabaseOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/DropDatabaseOperationTests.cs index 005f5cd6f47..987581db7f9 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/DropDatabaseOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/DropDatabaseOperationTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -54,10 +53,11 @@ public void CreateCommand_should_return_expected_result() { { "dropDatabase", 1 } }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().Be(expectedResult); } @@ -80,11 +80,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); + var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: hasOperationTimeout ? TimeSpan.FromSeconds(42) : null); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedWriteConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -109,11 +109,13 @@ public void Execute_should_return_expected_result( RequireServer.Check(); EnsureDatabaseExists(); + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { var subject = new DropDatabaseOperation(_databaseNamespace, _messageEncoderSettings); - var result = ExecuteOperation(subject, binding, async); + var result = ExecuteOperation(operationContext, subject, binding, async); result["ok"].ToBoolean().Should().BeTrue(); } @@ -136,8 +138,10 @@ public void Execute_should_throw_when_binding_is_null( bool async) { var subject = new DropDatabaseOperation(_databaseNamespace, _messageEncoderSettings); + using var session = CreateSession(); + using var operationContext = new OperationContext(session); - Action action = () => ExecuteOperation(subject, null, async); + Action action = () => ExecuteOperation(operationContext, subject, null, async); action.ShouldThrow().And.ParamName.Should().Be("binding"); } @@ -156,9 +160,11 @@ public void Execute_should_throw_when_a_write_concern_error_occurs( var exception = Record.Exception(() => { + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding()) { - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); } }); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/DropIndexOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/DropIndexOperationTests.cs index 366ca3450a6..d8d302d2501 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/DropIndexOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/DropIndexOperationTests.cs @@ -15,7 +15,6 @@ using System; using System.Linq; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -138,10 +137,11 @@ public void CreateCommand_should_return_expectedResult() { "dropIndexes", _collectionNamespace.CollectionName }, { "index", indexName } }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().Be(expectedResult); } @@ -167,10 +167,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_Set(long { "index", indexName }, { "maxTimeMS", expectedMaxTimeMS } }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().Be(expectedResult); result["maxTimeMS"].BsonType.Should().Be(BsonType.Int32); @@ -186,11 +187,10 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromSeconds(10) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().NotContain("maxTimeMS"); } @@ -214,11 +214,10 @@ public void CreateCommand_should_return_expectedResult_when_WriteConcern_is_set( { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: hasOperationTimeout ? TimeSpan.FromSeconds(42) : null); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedWriteConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -276,8 +275,10 @@ public void Execute_should_throw_when_binding_is_null( { var indexName = "x_1"; var subject = new DropIndexOperation(_collectionNamespace, indexName, _messageEncoderSettings); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - Action action = () => ExecuteOperation(subject, null, async); + Action action = () => ExecuteOperation(operationContext, subject, null, async); var ex = action.ShouldThrow().Subject.Single(); ex.ParamName.Should().Be("binding"); @@ -294,7 +295,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/EndTransactionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/EndTransactionOperationTests.cs index ac4df1bc728..b2f49679851 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/EndTransactionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/EndTransactionOperationTests.cs @@ -223,7 +223,9 @@ internal static class EndTransactionOperationReflector public static BsonDocument CreateCommand(this EndTransactionOperation obj) { var methodInfo = typeof(EndTransactionOperation).GetMethod("CreateCommand", BindingFlags.NonPublic | BindingFlags.Instance, null, [typeof(OperationContext), typeof(WriteConcern)], null); - return (BsonDocument)methodInfo.Invoke(obj, [OperationContext.NoTimeout, obj.WriteConcern]); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); + return (BsonDocument)methodInfo.Invoke(obj, [operationContext, obj.WriteConcern]); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/EstimatedDocumentCountOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/EstimatedDocumentCountOperationTests.cs index 2f620fb0808..3e2653c7c3b 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/EstimatedDocumentCountOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/EstimatedDocumentCountOperationTests.cs @@ -18,7 +18,6 @@ using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.TestHelpers; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.TestHelpers; @@ -149,9 +148,10 @@ public void CreateCommand_should_return_expected_result() { var subject = new EstimatedDocumentCountOperation(_collectionNamespace, _messageEncoderSettings); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = CreateCommand(subject, connectionDescription, session); + var result = CreateCommand(operationContext, subject, connectionDescription); AssertCommandDocument(result); } @@ -170,9 +170,10 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = CreateCommand(subject, connectionDescription, session); + var result = CreateCommand(operationContext, subject, connectionDescription); AssertCommandDocument(result, expectedMaxTimeMS: expectedMaxTimeMS); } @@ -189,9 +190,10 @@ public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = CreateCommand(subject, connectionDescription, session); + var result = CreateCommand(operationContext, subject, connectionDescription); AssertCommandDocument(result, readConcern: readConcern.IsServerDefault ? null : readConcern.ToBsonDocument()); } @@ -208,9 +210,10 @@ public void CreateCommand_should_return_the_expected_result_when_using_causal_co }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true); - var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var operationContext = new OperationContext(session); - var result = CreateCommand(subject, connectionDescription, session); + var result = CreateCommand(operationContext, subject, connectionDescription); var expectedReadConcernDocument = readConcern.ToBsonDocument(); expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100); @@ -242,7 +245,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded([Values(false, true)] using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } @@ -325,10 +331,10 @@ private void AssertCommandDocument(BsonDocument actualResult, int? expectedMaxTi } } - private BsonDocument CreateCommand(EstimatedDocumentCountOperation subject, ConnectionDescription connectionDescription, ICoreSession session) + private BsonDocument CreateCommand(OperationContext operationContext, EstimatedDocumentCountOperation subject, ConnectionDescription connectionDescription) { var countOperation = (CountOperation)subject.CreateCountOperation(); - return countOperation.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + return countOperation.CreateCommand(operationContext, connectionDescription); } private void EnsureTestData() diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndDeleteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndDeleteOperationTests.cs index c5138fd7149..a469b3171d8 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndDeleteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndDeleteOperationTests.cs @@ -119,10 +119,11 @@ public void CreateCommand_should_return_expected_result_when_Hint_is_set( { Hint = hint }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.HintForFindAndModifyFeature.FirstSupportedWireVersion); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -291,10 +292,11 @@ public void CreateCommand_should_return_the_expected_result( { Let = letDocument }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber); var expectedResult = new BsonDocument { @@ -318,10 +320,11 @@ public void CreateCommand_should_return_the_expected_result_when_Collation_is_se { Collation = collation }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -346,10 +349,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -371,11 +375,10 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().NotContain("maxTimeMS"); } @@ -391,10 +394,11 @@ public void CreateCommand_should_return_the_expected_result_when_Projection_is_s { Projection = projection }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -417,10 +421,11 @@ public void CreateCommand_should_return_the_expected_result_when_Sort_is_set( { Sort = sort }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -450,11 +455,10 @@ public void CreateCommand_should_return_the_expected_result_when_WriteConcern_is { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: hasOperationTimeout ? TimeSpan.FromSeconds(42) : null); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedWriteConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -483,7 +487,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndReplaceOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndReplaceOperationTests.cs index 6a5b187be61..6704596503f 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndReplaceOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndReplaceOperationTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -278,10 +277,11 @@ public void CreateCommand_should_return_expected_result( { Let = letDocument }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber); var expectedResult = new BsonDocument { @@ -304,10 +304,11 @@ public void CreateCommand_should_return_expected_result_when_BypassDocumentValid { BypassDocumentValidation = value }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -330,10 +331,11 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( { Collation = collation }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -355,10 +357,11 @@ public void CreateCommand_should_return_expected_result_when_Hint_is_set( { Hint = hint }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.HintForFindAndModifyFeature.FirstSupportedWireVersion); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -380,10 +383,11 @@ public void CreateCommand_should_return_expected_result_when_IsUpsert_is_set( { IsUpsert = value }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -408,10 +412,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -433,11 +438,10 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().NotContain("maxTimeMS"); } @@ -453,10 +457,11 @@ public void CreateCommand_should_return_expected_result_when_Projection_is_set( { Projection = projection }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -478,10 +483,11 @@ public void CreateCommand_should_return_expected_result_when_ReturnDocument_is_s { ReturnDocument = value }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -504,10 +510,11 @@ public void CreateCommand_should_return_expected_result_when_Sort_is_set( { Sort = sort }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -537,11 +544,10 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: hasOperationTimeout ? TimeSpan.FromSeconds(42) : null); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedWriteConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -723,7 +729,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndUpdateOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndUpdateOperationTests.cs index aa28977363b..55531c022cf 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndUpdateOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/FindOneAndUpdateOperationTests.cs @@ -272,10 +272,11 @@ public void CreateCommand_should_return_expected_result( { Let = letDocument }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, transactionNumber); + var result = subject.CreateCommand(operationContext, connectionDescription, transactionNumber); var expectedResult = new BsonDocument { @@ -298,10 +299,11 @@ public void CreateCommand_should_return_expected_result_when_BypassDocumentValid { BypassDocumentValidation = bypassDocumentValidation }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -324,10 +326,11 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( { Collation = collation }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -349,10 +352,11 @@ public void CreateCommand_should_return_expected_result_when_Hint_is_set( { Hint = hint }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(Feature.HintForFindAndModifyFeature.FirstSupportedWireVersion); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -374,10 +378,11 @@ public void CreateCommand_should_return_expected_result_when_IsUpsert_is_set( { IsUpsert = value }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -402,10 +407,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -427,12 +433,11 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session, TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().NotContain("maxTimeMS"); } @@ -448,10 +453,11 @@ public void CreateCommand_should_return_expected_result_when_Projection_is_set( { Projection = projection }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -473,10 +479,11 @@ public void CreateCommand_should_return_expected_result_when_ReturnDocument_is_s { ReturnDocument = value }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -499,10 +506,11 @@ public void CreateCommand_should_return_expected_result_when_Sort_is_set( { Sort = sort }; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedResult = new BsonDocument { @@ -532,11 +540,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = hasOperationTimeout ? new OperationContext(session, TimeSpan.FromSeconds(42), CancellationToken.None) : new OperationContext(session); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedWriteConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -725,7 +733,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/FindOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/FindOperationTests.cs index 22d960799d1..5ca73e05f5f 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/FindOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/FindOperationTests.cs @@ -189,10 +189,11 @@ public void CreateCommand_should_return_expected_result() { var subject = new FindOperation(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings); + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -214,10 +215,11 @@ public void CreateCommand_should_return_expected_result_when_AllowDiskUse_is_set AllowDiskUse = allowDiskUse }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(serverType: serverType); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -240,10 +242,11 @@ public void CreateCommand_should_return_expected_result_when_AllowPartialResults AllowPartialResults = allowPartialResults }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(serverType: serverType); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -265,10 +268,11 @@ public void CreateCommand_should_return_expected_result_when_Collation_is_set( Collation = collation }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -289,10 +293,11 @@ public void CreateCommand_should_return_expected_result_when_Comment_is_set( Comment = comment }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -313,10 +318,11 @@ public void CreateCommand_should_return_expected_result_when_CursorType_is_Set( CursorType = cursorType }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -339,10 +345,11 @@ public void CreateCommand_should_return_expected_result_when_Filter_is_set( Filter = filter }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -364,10 +371,11 @@ public void CreateCommand_should_return_expected_result_when_Hint_is_set( Hint = hint }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -391,10 +399,11 @@ public void CreateCommand_should_return_expected_result_when_Limit_is_set( SingleBatch = singleBatch }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -417,10 +426,11 @@ public void CreateCommand_should_return_expected_result_when_Max_is_set( Max = max }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -443,10 +453,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -466,11 +477,11 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session, TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); result.Should().NotContain("maxTimeMS"); } @@ -487,10 +498,11 @@ public void CreateCommand_should_return_expected_result_when_Min_is_set( Min = min }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -511,10 +523,11 @@ public void CreateCommand_should_return_expected_result_when_NoCursorTimeout_is_ NoCursorTimeout = noCursorTimeout }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -537,10 +550,11 @@ public void CreateCommand_should_return_expected_result_when_OplogReplay_is_set( #pragma warning restore 618 }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -562,10 +576,11 @@ public void CreateCommand_should_return_expected_result_when_Projection_is_set( Projection = projection }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -587,10 +602,11 @@ public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( ReadConcern = readConcern }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -611,10 +627,11 @@ public void CreateCommand_should_return_expected_result_when_ReturnKey_is_set( ReturnKey = returnKey }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -635,10 +652,11 @@ public void CreateCommand_should_return_expected_result_when_ShowRecordId_is_set ShowRecordId = showRecordId }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -659,10 +677,11 @@ public void CreateCommand_should_return_expected_result_when_Skip_is_set( Skip = skip }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -684,10 +703,11 @@ public void CreateCommand_should_return_expected_result_when_Sort_is_set( Sort = sort }; + using var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -709,10 +729,11 @@ public void CreateCommand_should_return_the_expected_result_when_using_causal_co ReadConcern = readConcern }; + using var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true); - var session = OperationTestHelper.CreateSession(true, new BsonTimestamp(100)); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedReadConcernDocument = readConcern.ToBsonDocument(); expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100); @@ -743,14 +764,15 @@ public void CreateCursor_should_use_ns_field_instead_of_namespace_passed_in_cons { "cursor", cursorDocument } }; var mockServer = new Mock(); + var mockChannelSource = new Mock(); + mockChannelSource.Setup(x => x.Server).Returns(mockServer.Object); var mockSession = new Mock(); var mockSessionFork = new Mock(); mockSession.Setup(x => x.Fork()).Returns(mockSessionFork.Object); - var mockChannelSource = new Mock(); - mockChannelSource.Setup(x => x.Server).Returns(mockServer.Object); - mockChannelSource.Setup(x => x.Session).Returns(mockSession.Object); - var cursor = subject.CreateCursor(mockChannelSource.Object, Mock.Of(), commandResult); + using var operationContext = new OperationContext(mockSession.Object); + + var cursor = subject.CreateCursor(operationContext, mockChannelSource.Object, Mock.Of(), commandResult); cursor._collectionNamespace().Should().Be(cursorCollectionNamespace); } @@ -881,8 +903,10 @@ public void Execute_should_throw_when_binding_is_null( bool async) { var subject = new FindOperation(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var exception = Record.Exception(() => ExecuteOperation(subject, (IReadBinding)null, async)); + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, (IReadBinding)null, async)); var argumentNullException = exception.Should().BeOfType().Subject; argumentNullException.ParamName.Should().Be("binding"); @@ -898,7 +922,10 @@ public void Execute_should_throw_when_maxTime_is_exceeded( using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); + + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } @@ -1237,11 +1264,12 @@ internal static class FindOperationReflector { public static AsyncCursor CreateCursor( this FindOperation obj, + OperationContext operationContext, IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult) { - return (AsyncCursor)Reflector.Invoke(obj, nameof(CreateCursor), channelSource, channel, commandResult); + return (AsyncCursor)Reflector.Invoke(obj, nameof(CreateCursor), operationContext, channelSource, channel, commandResult); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ListDatabasesOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ListDatabasesOperationTests.cs index ef27ae6bf5c..fe8b0fda8d3 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ListDatabasesOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ListDatabasesOperationTests.cs @@ -211,8 +211,10 @@ public void Execute_should_throw_when_binding_is_null( { var subject = new ListDatabasesOperation(_messageEncoderSettings); IReadBinding binding = null; + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - Action action = () => ExecuteOperation(subject, binding, async); + Action action = () => ExecuteOperation(operationContext, subject, binding, async); action.ShouldThrow().And.ParamName.Should().Be("binding"); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesOperationTests.cs index 8eb1bf087e4..21ee5a78e7e 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesOperationTests.cs @@ -155,8 +155,10 @@ public void Execute_should_throw_when_binding_is_null( { var subject = new ListIndexesOperation(_collectionNamespace, _messageEncoderSettings); IReadBinding binding = null; + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - Action action = () => ExecuteOperation(subject, binding, async); + Action action = () => ExecuteOperation(operationContext, subject, binding, async); action.ShouldThrow().And.ParamName.Should().Be("binding"); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesUsingCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesUsingCommandOperationTests.cs index 48384169736..09bb8b0ce3f 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesUsingCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesUsingCommandOperationTests.cs @@ -142,8 +142,10 @@ public void Execute_should_throw_when_binding_is_null( { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); IReadBinding binding = null; + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - Action action = () => ExecuteOperation(subject, binding, async); + Action action = () => ExecuteOperation(operationContext, subject, binding, async); action.ShouldThrow().And.ParamName.Should().Be("binding"); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationBaseTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationBaseTests.cs index 8840542784f..fe508c24344 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationBaseTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationBaseTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using FluentAssertions; using MongoDB.Bson; using MongoDB.TestHelpers.XunitExtensions; @@ -122,10 +121,11 @@ public void constructor_should_throw_when_reduceFunction_is_null() public void CreateCommand_should_return_the_expected_result() { var subject = new FakeMapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -148,11 +148,11 @@ public void CreateCommand_should_return_the_expected_result_when_Collation_is_pr { Collation = collation }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -176,10 +176,11 @@ public void CreateCommand_should_return_the_expected_result_when_Filter_is_provi { Filter = filter }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -203,10 +204,11 @@ public void CreateCommand_should_return_the_expected_result_when_FinalizeFunctio { FinalizeFunction = finalizeFunction }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -231,10 +233,11 @@ public void CreateCommand_should_return_the_expected_result_when_JavaScriptMode_ JavaScriptMode = javaScriptMode #pragma warning restore 618 }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -257,10 +260,11 @@ public void CreateCommand_should_return_the_expected_result_when_Limit_is_provid { Limit = limit }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -286,10 +290,11 @@ public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -312,11 +317,10 @@ public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeout { MaxTime = TimeSpan.FromTicks(10) }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession(), timeout: TimeSpan.FromMilliseconds(timeoutMs)); - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); - var result = subject.CreateCommand(operationContext, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); result.Should().NotContain("maxTimeMS"); } @@ -332,10 +336,11 @@ public void CreateCommand_should_return_the_expected_result_when_Scope_is_provid { Scope = scope }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -359,10 +364,11 @@ public void CreateCommand_should_return_the_expected_result_when_Sort_is_provide { Sort = sort }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -385,10 +391,11 @@ public void CreateCommand_should_return_the_expected_result_when_Verbose_is_prov { Verbose = verbose }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationTests.cs index ceaf02a75f4..361507786a7 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOperationTests.cs @@ -451,8 +451,10 @@ public void Execute_should_throw_when_binding_is_null( #pragma warning disable CS0618 // Type or member is obsolete var subject = new MapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings); #pragma warning restore CS0618 // Type or member is obsolete + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var exception = Record.Exception(() => ExecuteOperation(subject, (IReadBinding)null, async)); + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, (IReadBinding)null, async)); var argumentNullException = exception.Should().BeOfType().Subject; argumentNullException.ParamName.Should().Be("binding"); @@ -468,10 +470,12 @@ public void Execute_should_throw_when_maxTime_is_exceeded( var subject = new MapReduceOperation(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings); #pragma warning restore CS0618 // Type or member is obsolete subject.MaxTime = TimeSpan.FromSeconds(9001); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); using (var failPoint = FailPoint.ConfigureAlwaysOn(FailPointName.MaxTimeAlwaysTimeout)) { - var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, failPoint.Binding, async)); exception.Should().BeOfType(); } @@ -504,10 +508,11 @@ public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( { ReadConcern = readConcern }; - var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -533,10 +538,11 @@ public void CreateCommand_should_return_the_expected_result_when_using_causal_co { ReadConcern = readConcern }; - var session = OperationTestHelper.CreateSession(isCausallyConsistent: true, operationTime: new BsonTimestamp(100)); var connectionDescription = OperationTestHelper.CreateConnectionDescription(supportsSessions: true); + using var session = OperationTestHelper.CreateSession(isCausallyConsistent: true, operationTime: new BsonTimestamp(100)); + using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedReadConcernDocument = readConcern.ToBsonDocument(); expectedReadConcernDocument["afterClusterTime"] = new BsonTimestamp(100); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOutputToCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOutputToCollectionOperationTests.cs index ca57a2e1f26..1bb318eda3c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOutputToCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/MapReduceOutputToCollectionOperationTests.cs @@ -213,9 +213,10 @@ public void CreateCommand_should_return_expected_result_when_BypassDocumentValid BypassDocumentValidation = bypassDocumentValidation }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -242,9 +243,10 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set WriteConcern = writeConcern }; var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var session = OperationTestHelper.CreateSession(); + using var session = OperationTestHelper.CreateSession(); +using var operationContext = new OperationContext(session); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); + var result = subject.CreateCommand(operationContext, connectionDescription); var expectedResult = new BsonDocument { @@ -590,8 +592,10 @@ public void Execute_should_throw_when_binding_is_null( #pragma warning disable CS0618 // Type or member is obsolete var subject = new MapReduceOutputToCollectionOperation(_collectionNamespace, _outputCollectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); #pragma warning restore CS0618 // Type or member is obsolete + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - var exception = Record.Exception(() => ExecuteOperation(subject, null, async)); + var exception = Record.Exception(() => ExecuteOperation(operationContext, subject, 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 e42b9a5a05a..fed7accd775 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs @@ -139,10 +139,12 @@ protected void EnsureDatabaseExists(string databaseName) private protected TResult ExecuteOperation(IReadOperation operation) { + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadBinding()) using (var bindingHandle = new ReadBindingHandle(binding)) { - return operation.Execute(OperationContext.NoTimeout, bindingHandle); + return operation.Execute(operationContext, bindingHandle); } } @@ -160,42 +162,37 @@ private protected TResult ExecuteOperation(IReadOperation oper private protected async Task ExecuteOperationAsync(IReadOperation operation, IClusterInternal cluster, bool async) { + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadBinding(cluster)) using (var bindingHandle = new ReadBindingHandle(binding)) { return async ? - await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle) : - operation.Execute(OperationContext.NoTimeout, bindingHandle); + await operation.ExecuteAsync(operationContext, bindingHandle) : + operation.Execute(operationContext, bindingHandle); } } - private protected TResult ExecuteOperation(IReadOperation operation, IReadBinding binding, bool async) + private protected TResult ExecuteOperation(OperationContext operationContext, IReadOperation operation, IReadBinding binding, bool async) { if (async) { - return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); + return operation.ExecuteAsync(operationContext, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(OperationContext.NoTimeout, binding); - } - } - - private protected TResult ExecuteOperation(IReadOperation operation, ReadPreference readPreference, bool async) - { - using (var binding = CreateReadBinding(readPreference)) - using (var bindingHandle = new ReadBindingHandle(binding)) - { - return ExecuteOperation(operation, bindingHandle, async); + return operation.Execute(operationContext, binding); } } private protected TResult ExecuteOperationSync(IWriteOperation operation, bool useImplicitSession = false) { - using (var binding = CreateReadWriteBinding(useImplicitSession)) + using (var session = CreateSession(useImplicitSession)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadWriteBinding()) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return operation.Execute(OperationContext.NoTimeout, bindingHandle); + return operation.Execute(operationContext, bindingHandle); } } @@ -211,66 +208,62 @@ private protected TResult ExecuteOperation(IWriteOperation ope } } - private protected TResult ExecuteOperation(IWriteOperation operation, IReadWriteBinding binding, bool async) + private protected TResult ExecuteOperation(OperationContext operationContext, IWriteOperation operation, IReadWriteBinding binding, bool async) { if (async) { - return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); + return operation.ExecuteAsync(operationContext, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(OperationContext.NoTimeout, binding); + return operation.Execute(operationContext, binding); } } private protected async Task ExecuteOperationAsync(IReadOperation operation) { + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadBinding()) using (var bindingHandle = new ReadBindingHandle(binding)) { - return await ExecuteOperationAsync(operation, bindingHandle); + return await operation.ExecuteAsync(operationContext, bindingHandle); } } - private protected async Task ExecuteOperationAsync(IReadOperation operation, IReadBinding binding) - { - return await operation.ExecuteAsync(OperationContext.NoTimeout, binding); - } - private protected async Task ExecuteOperationAsync(IWriteOperation operation, bool useImplicitSession = false) { - using (var binding = CreateReadWriteBinding(useImplicitSession)) + using (var session = CreateSession(useImplicitSession)) + using (var operationContext = new OperationContext(session)) + using (var binding = CreateReadWriteBinding()) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle); + return await operation.ExecuteAsync(operationContext, bindingHandle); } } private protected async Task ExecuteOperationAsync(IWriteOperation operation, IClusterInternal cluster, bool async) { + using (var session = CreateSession()) + using (var operationContext = new OperationContext(session)) using (var binding = CreateReadWriteBinding(cluster: cluster)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { if (async) { - return await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle); + return await operation.ExecuteAsync(operationContext, bindingHandle); } else { - return operation.Execute(OperationContext.NoTimeout, bindingHandle); + return operation.Execute(operationContext, bindingHandle); } } } - private protected TResult ExecuteOperation(IWriteOperation operation, IWriteBinding binding, bool async) + private protected TResult ExecuteOperation(OperationContext operationContext, 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(OperationContext.NoTimeout, binding); - } + operation.ExecuteAsync(operationContext, binding).GetAwaiter().GetResult() : + operation.Execute(operationContext, binding); private protected void CreateIndexes(params CreateIndexRequest[] requests) { @@ -289,14 +282,16 @@ private protected IReadBinding CreateReadBinding(IClusterInternal cluster = null private protected IReadBinding CreateReadBinding(ReadPreference readPreference, IClusterInternal cluster = null) { - return new ReadPreferenceBinding(cluster ?? _cluster, readPreference, _session.Fork()); + return new ReadPreferenceBinding(cluster ?? _cluster, readPreference); } - private protected IReadWriteBinding CreateReadWriteBinding(bool useImplicitSession = false, IClusterInternal cluster = null) + private protected IReadWriteBinding CreateReadWriteBinding(IClusterInternal cluster = null) => + new WritableServerBinding(cluster ?? _cluster); + + private protected ICoreSessionHandle CreateSession(bool useImplicitSession = false, IClusterInternal cluster = null) { var options = new CoreSessionOptions(isImplicit: useImplicitSession); - var session = CoreTestConfiguration.StartSession(cluster ?? _cluster, options); - return new WritableServerBinding(cluster ?? _cluster, session); + return CoreTestConfiguration.StartSession(cluster ?? _cluster, options); } protected void Insert(params BsonDocument[] documents) @@ -553,16 +548,17 @@ private protected void VerifySessionIdSending( using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) { using (var session = CreateSession(cluster, useImplicitSession)) - using (var binding = new WritableServerBinding(cluster, session.Fork())) + using (var binding = new WritableServerBinding(cluster)) { Exception exception; + using var operationContext = new OperationContext(session); if (async) { - exception = Record.Exception(() => executeAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult()); + exception = Record.Exception(() => executeAsync(binding, operationContext).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => execute(binding, OperationContext.NoTimeout)); + exception = Record.Exception(() => execute(binding, operationContext)); } assertResults(eventCapturer, session, exception); @@ -578,7 +574,6 @@ private void AssertSessionIdWasNotSentIfUnacknowledgedWrite(EventCapturer eventC var commandStartedEvent = (CommandStartedEvent)eventCapturer.Next(); var command = commandStartedEvent.Command; command.Contains("lsid").Should().BeFalse(); - session.ReferenceCount().Should().Be(2); } else { @@ -600,8 +595,6 @@ private void AssertSessionIdWasSentWhenSupported(EventCapturer eventCapturer, IC { command["lsid"].Should().Be(session.Id); } - - session.ReferenceCount().Should().Be(2); } private ICoreSessionHandle CreateSession(IClusterInternal cluster, bool useImplicitSession) diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/QueryHelperTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/QueryHelperTests.cs index d713005fb50..3b6a31a2577 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/QueryHelperTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/QueryHelperTests.cs @@ -22,20 +22,6 @@ namespace MongoDB.Driver.Core.Operations { public class QueryHelperTests { - [Theory] - [InlineData(null, null, 0)] - [InlineData(null, 20, 20)] - [InlineData(20, null, 20)] - [InlineData(10, 20, 10)] - [InlineData(20, 10, 10)] - [InlineData(-20, 10, -20)] - public void CalculateFirstBatchSize_should_return_the_correct_result(int? limit, int? batchSize, int expectedResult) - { - var result = QueryHelper.CalculateFirstBatchSize(limit, batchSize); - - result.Should().Be(expectedResult); - } - [Fact] public void CreateReadPreferenceDocument_should_return_null_when_the_serverType_is_not_a_shard_router() { diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs index 48b4bed12bf..f837d53ae88 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs @@ -90,14 +90,14 @@ 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 operationContext = new OperationContext(OperationTestHelper.CreateSession()); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -115,7 +115,6 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap mockChannel.Verify( c => c.Command( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -144,14 +143,14 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\", additional : 1 }"); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession()); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -169,7 +168,6 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi mockChannel.Verify( c => c.Command( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -197,14 +195,14 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\" }"); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession()); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -222,7 +220,6 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen mockChannel.Verify( c => c.Command( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -251,14 +248,14 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_readPr var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\", additional : 1 }"); + using var operationContext = new OperationContext(OperationTestHelper.CreateSession()); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -276,7 +273,6 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_readPr mockChannel.Verify( c => c.Command( It.IsAny(), - binding.Session, readPreference, subject.DatabaseNamespace, subject.Command, @@ -301,8 +297,9 @@ 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 operationContext = new OperationContext(OperationTestHelper.CreateSession()); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannelSource.Verify(c => c.GetChannelAsync(It.IsAny()), Times.Once); @@ -317,9 +314,7 @@ public void Execute_should_call_GetChannel_only_once([Values(false, true)] bool private Mock CreateMockReadBinding(ReadPreference readPreference, IChannelSourceHandle channelSource) { var mockBinding = new Mock(); - 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(), It.IsAny>())).Returns(channelSource); mockBinding.Setup(b => b.GetReadChannelSourceAsync(It.IsAny(), It.IsAny>())).Returns(Task.FromResult(channelSource)); return mockBinding; diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/RenameCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/RenameCollectionOperationTests.cs index 1494f8355c7..7a5ef22847d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/RenameCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/RenameCollectionOperationTests.cs @@ -90,7 +90,8 @@ public void CreateCommand_should_return_expected_result() var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + using var operationContext = new OperationContext(session); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().Be(expectedResult); } @@ -114,7 +115,8 @@ public void CreateCommand_should_return_expected_result_when_dropTarget_is_provi var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription, null); + using var operationContext = new OperationContext(session); + var result = subject.CreateCommand(operationContext, connectionDescription, null); result.Should().Be(expectedResult); } @@ -138,11 +140,11 @@ public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set { WriteConcern = writeConcern }; - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) : OperationContext.NoTimeout; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); - var result = subject.CreateCommand(operationContext, session, connectionDescription, null); + using var operationContext = new OperationContext(session, hasOperationTimeout ? TimeSpan.FromSeconds(42) : null); + var result = subject.CreateCommand(operationContext, connectionDescription, null); var expectedWriteConcern = writeConcern?.ToBsonDocument(); if (hasOperationTimeout) @@ -246,8 +248,10 @@ public void Execute_should_throw_when_binding_is_null( bool async) { var subject = new RenameCollectionOperation(_collectionNamespace, _newCollectionNamespace, _messageEncoderSettings); + using var session = OperationTestHelper.CreateSession(); + using var operationContext = new OperationContext(session); - Action action = () => ExecuteOperation(subject, null, async); + Action action = () => ExecuteOperation(operationContext, subject, null, async); action.ShouldThrow().And.ParamName.Should().Be("binding"); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableReadOperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableReadOperationExecutorTests.cs index 56342417029..4a2fe3032e4 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableReadOperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableReadOperationExecutorTests.cs @@ -14,10 +14,8 @@ */ using System; -using System.IO; using System.Linq; using System.Reflection; -using System.Threading; using FluentAssertions; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; @@ -59,11 +57,10 @@ public void ShouldRetry_should_return_expected_result( int attempt, bool overloadErrorSeen) { - var context = CreateContext(isRetryRequested, isInTransaction); + var context = CreateContext(isRetryRequested); var exception = CoreExceptionHelper.CreateException(nameof(MongoNodeIsRecoveringException)); - var operationContext = hasTimeout - ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) - : new OperationContext(null, CancellationToken.None); + using var session = CreateSession(isInTransaction); + using var operationContext = new OperationContext(session, hasTimeout ? TimeSpan.FromSeconds(42) : null); var random = Mock.Of(); var result = RetryableReadOperationExecutorReflector.ShouldRetry( @@ -85,11 +82,10 @@ public void ShouldRetry_with_non_retryable_exception_should_return_false( int attempt, bool overloadErrorSeen) { - var context = CreateContext(isRetryRequested, isInTransaction); + var context = CreateContext(isRetryRequested); var exception = new InvalidOperationException("Non-retryable exception"); - var operationContext = hasTimeout - ? new OperationContext(TimeSpan.FromSeconds(42), CancellationToken.None) - : new OperationContext(null, CancellationToken.None); + using var session = CreateSession(isInTransaction); + using var operationContext = new OperationContext(session, hasTimeout ? TimeSpan.FromSeconds(42) : null); var random = Mock.Of(); var result = RetryableReadOperationExecutorReflector.ShouldRetry( @@ -107,9 +103,10 @@ public void ShouldRetry_with_system_overloaded_exception_should_apply_backpressu bool expected, int attempt) { - var context = CreateContext(retryRequested: true, isInTransaction: false); + var context = CreateContext(retryRequested: true); var exception = CoreExceptionHelper.CreateMongoCommandExceptionWithLabels(2, "SystemOverloadedError", "RetryableError"); - var operationContext = new OperationContext(null, CancellationToken.None); + using var session = CreateSession(false); + using var operationContext = new OperationContext(session); var randomMock = new Mock(); randomMock.Setup(r => r.NextDouble()).Returns(0.5); @@ -126,9 +123,10 @@ public void ShouldRetry_with_system_overloaded_exception_should_apply_backpressu [Fact] public void ShouldRetry_with_system_overloaded_exception_should_not_retry_when_retryRequested_is_false() { - var context = CreateContext(retryRequested: false, isInTransaction: false); + var context = CreateContext(retryRequested: false); var exception = CoreExceptionHelper.CreateMongoCommandExceptionWithLabels(2, "SystemOverloadedError", "RetryableError"); - var operationContext = new OperationContext(null, CancellationToken.None); + using var session = CreateSession(false); + using var operationContext = new OperationContext(session); var random = Mock.Of(); var result = RetryableReadOperationExecutorReflector.ShouldRetry( @@ -138,14 +136,18 @@ public void ShouldRetry_with_system_overloaded_exception_should_not_retry_when_r } // private methods - private static RetryableReadContext CreateContext(bool retryRequested, bool isInTransaction) + private static RetryableReadContext CreateContext(bool retryRequested) { - var sessionMock = new Mock(); - sessionMock.SetupGet(m => m.IsInTransaction).Returns(isInTransaction); var bindingMock = new Mock(); - bindingMock.SetupGet(m => m.Session).Returns(sessionMock.Object); return new RetryableReadContext(bindingMock.Object, retryRequested, RetryabilityHelper.OperationRetryBackpressureConstants.DefaultMaxRetries, enableOverloadRetargeting: false); } + + private static ICoreSessionHandle CreateSession(bool isInTransaction) + { + var sessionMock = new Mock(); + sessionMock.SetupGet(m => m.IsInTransaction).Returns(isInTransaction); + return sessionMock.Object; + } } internal static class RetryableReadOperationExecutorReflector diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs index c91ffc68019..fe88768a9c1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs @@ -64,8 +64,10 @@ public void DoesContextAllowRetries_should_return_expected_result( bool expectedResult) { var context = CreateContext(retryRequested, areRetryableWritesSupported, hasSessionId, isInTransaction); + using var session = CreateSession(hasSessionId, isInTransaction); + using var operationContext = new OperationContext(session); - var result = RetryableWriteOperationExecutorReflector.DoesContextAllowRetries(context, context.ChannelSource.ServerDescription); + var result = RetryableWriteOperationExecutorReflector.DoesContextAllowRetries(operationContext, context, context.ChannelSource.ServerDescription); result.Should().Be(expectedResult); } @@ -87,9 +89,7 @@ public void IsOperationAcknowledged_should_return_expected_result(bool? isAcknow private IWriteBinding CreateBinding(bool areRetryableWritesSupported, bool hasSessionId, bool isInTransaction) { var mockBinding = new Mock(); - var session = CreateSession(hasSessionId, isInTransaction); var channelSource = CreateChannelSource(areRetryableWritesSupported); - mockBinding.SetupGet(m => m.Session).Returns(session); mockBinding.Setup(m => m.GetWriteChannelSource(It.IsAny(), It.IsAny>())).Returns(channelSource); return mockBinding.Object; } @@ -118,8 +118,9 @@ private RetryableWriteContext CreateContext(bool retryRequested, bool areRetryab { var binding = CreateBinding(areRetryableWritesSupported, hasSessionId, isInTransaction); var context = new RetryableWriteContext(binding, retryRequested, RetryabilityHelper.OperationRetryBackpressureConstants.DefaultMaxRetries, false); - context.SelectServer(OperationContext.NoTimeout, null); - context.AcquireChannel(OperationContext.NoTimeout); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + context.SelectServer(operationContext, null); + context.AcquireChannel(operationContext); return context; } @@ -138,8 +139,8 @@ internal static class RetryableWriteOperationExecutorReflector public static bool AreRetryableWritesSupported(ServerDescription serverDescription) => (bool)Reflector.InvokeStatic(typeof(RetryableWriteOperationExecutor), nameof(AreRetryableWritesSupported), serverDescription); - public static bool DoesContextAllowRetries(RetryableWriteContext context, ServerDescription server) - => (bool)Reflector.InvokeStatic(typeof(RetryableWriteOperationExecutor), nameof(DoesContextAllowRetries), context, server); + public static bool DoesContextAllowRetries(OperationContext operationContext, RetryableWriteContext context, ServerDescription server) + => (bool)Reflector.InvokeStatic(typeof(RetryableWriteOperationExecutor), nameof(DoesContextAllowRetries), operationContext, context, server); public static bool IsOperationAcknowledged(WriteConcern writeConcern) => (bool)Reflector.InvokeStatic(typeof(RetryableWriteOperationExecutor), nameof(IsOperationAcknowledged), writeConcern); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs index 3c1046d270f..93d845e1f17 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs @@ -66,14 +66,15 @@ 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 session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - binding.Session, ReadPreference.Primary, subject.DatabaseNamespace, subject.Command, @@ -91,7 +92,6 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap mockChannel.Verify( c => c.Command( It.IsAny(), - binding.Session, ReadPreference.Primary, subject.DatabaseNamespace, subject.Command, @@ -118,14 +118,15 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; var command = BsonDocument.Parse("{ command : 1 }"); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - It.IsAny(), It.IsAny(), subject.DatabaseNamespace, command, @@ -143,7 +144,6 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi mockChannel.Verify( c => c.Command( It.IsAny(), - It.IsAny(), It.IsAny(), subject.DatabaseNamespace, command, @@ -170,14 +170,15 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\" }"); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); - ExecuteOperation(subject, binding, async); + ExecuteOperation(operationContext, subject, binding, async); if (async) { mockChannel.Verify( c => c.CommandAsync( It.IsAny(), - binding.Session, ReadPreference.Primary, subject.DatabaseNamespace, subject.Command, @@ -195,7 +196,6 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen mockChannel.Verify( c => c.Command( It.IsAny(), - binding.Session, ReadPreference.Primary, subject.DatabaseNamespace, subject.Command, @@ -214,8 +214,6 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen private Mock CreateMockWriteBinding(IChannelSourceHandle channelSource) { 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(), It.IsAny>())).Returns(channelSource); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/WriteConcernHelperTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/WriteConcernHelperTests.cs index 8f85439ccb3..6c3cfddc386 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/WriteConcernHelperTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/WriteConcernHelperTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using FluentAssertions; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; @@ -54,19 +53,19 @@ public void GetEffectiveWriteConcern_should_return_expected_result( string expectedResult) { var session = CreateSession(isInTransaction: isInTransaction); - var operationContext = hasOperationTimeout ? new OperationContext(TimeSpan.FromMilliseconds(42), CancellationToken.None) : OperationContext.NoTimeout; + using var operationContext = new OperationContext(session, hasOperationTimeout ? TimeSpan.FromMilliseconds(42) : null); var writeConcern = writeConcernJson == null ? null : WriteConcern.FromBsonDocument(BsonDocument.Parse(writeConcernJson)); - var result = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, session, writeConcern); + var result = WriteConcernHelper.GetEffectiveWriteConcern(operationContext, writeConcern); result.Should().Be(expectedResult); } // private methods - private ICoreSession CreateSession( + private ICoreSessionHandle CreateSession( bool isInTransaction) { - var mockSession = new Mock(); + var mockSession = new Mock(); mockSession.SetupGet(m => m.IsInTransaction).Returns(isInTransaction); return mockSession.Object; } diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs index 26c7a3b7eac..78b81e7515c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs @@ -181,9 +181,10 @@ public async Task GetChannel_should_clear_connection_pool_when_opening_connectio _eventLogger); server.Initialize(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => server.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => server.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => server.GetChannelAsync(operationContext)) : + Record.Exception(() => server.GetChannel(operationContext)); exception.Should().BeOfType(); mockConnectionPool.Verify(p => p.Clear(It.IsAny()), Times.Once()); @@ -195,9 +196,10 @@ public async Task GetChannel_should_get_a_connection([Values(false, true)] bool { _subject.Initialize(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var channel = async ? - await _subject.GetChannelAsync(OperationContext.NoTimeout) : - _subject.GetChannel(OperationContext.NoTimeout); + await _subject.GetChannelAsync(operationContext) : + _subject.GetChannel(operationContext); channel.Should().NotBeNull(); } @@ -210,9 +212,10 @@ public async Task GetChannel_should_not_increase_operations_count_on_exception( { IClusterableServer server = SetupServer(connectionOpenException, !connectionOpenException); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(operationContext)) : + Record.Exception(() => _subject.GetChannel(operationContext)); exception.Should().NotBeNull(); server.OutstandingOperationsCount.Should().Be(0); @@ -227,11 +230,12 @@ public async Task GetChannel_should_set_operations_count_correctly( IClusterableServer server = SetupServer(false, false); var channels = new List(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); for (int i = 0; i < operationsCount; i++) { var connection = async ? - await server.GetChannelAsync(OperationContext.NoTimeout) : - server.GetChannel(OperationContext.NoTimeout); + await server.GetChannelAsync(operationContext) : + server.GetChannel(operationContext); channels.Add(connection); } @@ -249,9 +253,10 @@ await server.GetChannelAsync(OperationContext.NoTimeout) : public async Task GetChannel_should_throw_when_not_initialized( [Values(false, true)] bool async) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(operationContext)) : + Record.Exception(() => _subject.GetChannel(operationContext)); exception.Should().BeOfType(); } @@ -262,9 +267,10 @@ public async Task GetChannel_should_throw_when_disposed([Values(false, true)] bo { _subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(operationContext)) : + Record.Exception(() => _subject.GetChannel(operationContext)); exception.Should().BeOfType(); } @@ -301,9 +307,10 @@ public async Task GetChannel_should_not_update_topology_and_clear_connection_poo var subject = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, mockConnectionPoolFactory.Object, _serverApi, _eventLogger); subject.Initialize(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(operationContext)) : + Record.Exception(() => subject.GetChannel(operationContext)); exception.Should().Be(openConnectionException); subject.Description.Type.Should().Be(ServerType.LoadBalanced); diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs index 39a1810e780..b6a3b45c9e7 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs @@ -213,9 +213,10 @@ public async Task GetChannel_should_clear_connection_pool_when_opening_connectio server.Initialize(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => server.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => server.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => server.GetChannelAsync(operationContext)) : + Record.Exception(() => server.GetChannel(operationContext)); exception.Should().BeOfType(); mockConnectionPool.Verify(p => p.Clear(It.IsAny()), Times.Once()); @@ -229,9 +230,10 @@ public async Task GetChannel_should_get_a_connection( { _subject.Initialize(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var connection = async ? - await _subject.GetChannelAsync(OperationContext.NoTimeout) : - _subject.GetChannel(OperationContext.NoTimeout); + await _subject.GetChannelAsync(operationContext) : + _subject.GetChannel(operationContext); connection.Should().NotBeNull(); } @@ -244,9 +246,10 @@ public async Task GetChannel_should_not_increase_operations_count_on_exception( { IClusterableServer server = SetupServer(connectionOpenException, !connectionOpenException); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(operationContext)) : + Record.Exception(() => _subject.GetChannel(operationContext)); exception.Should().NotBeNull(); server.OutstandingOperationsCount.Should().Be(0); @@ -261,11 +264,12 @@ public async Task GetChannel_should_set_operations_count_correctly( IClusterableServer server = SetupServer(false, false); var channels = new List(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); for (int i = 0; i < operationsCount; i++) { var connection = async ? - await server.GetChannelAsync(OperationContext.NoTimeout) : - server.GetChannel(OperationContext.NoTimeout); + await server.GetChannelAsync(operationContext) : + server.GetChannel(operationContext); channels.Add(connection); } @@ -283,9 +287,10 @@ await server.GetChannelAsync(OperationContext.NoTimeout) : public async Task GetChannel_should_throw_when_not_initialized( [Values(false, true)] bool async) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(operationContext)) : + Record.Exception(() => _subject.GetChannel(operationContext)); exception.Should().BeOfType(); } @@ -298,9 +303,10 @@ public async Task GetChannel_should_throw_when_disposed( { _subject.Dispose(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(operationContext)) : + Record.Exception(() => _subject.GetChannel(operationContext)); exception.Should().BeOfType(); } @@ -345,9 +351,10 @@ public async Task GetChannel_should_update_topology_and_clear_connection_pool_on subject.Initialize(); connectionPool.SetReady(); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(operationContext)) : + Record.Exception(() => subject.GetChannel(operationContext)); exception.Should().Be(openConnectionException); subject.Description.Type.Should().Be(ServerType.Unknown); @@ -830,9 +837,10 @@ public void Command_should_send_the_greater_of_the_session_and_cluster_cluster_t var eventCapturer = new EventCapturer().Capture(e => e.CommandName == "ping"); using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) + using (var operationContext = new OperationContext(session)) { - var server = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); - using (var channel = server.GetChannel(OperationContext.NoTimeout)) + var server = cluster.SelectServer(operationContext, WritableServerSelector.Instance); + using (var channel = server.GetChannel(operationContext)) { session.AdvanceClusterTime(sessionClusterTime); server.ClusterClock.AdvanceClusterTime(clusterClusterTime); @@ -841,8 +849,7 @@ public void Command_should_send_the_greater_of_the_session_and_cluster_cluster_t try { channel.Command( - OperationContext.NoTimeout, - session, + operationContext, ReadPreference.Primary, DatabaseNamespace.Admin, command, @@ -877,14 +884,14 @@ public void Command_should_update_the_session_and_cluster_cluster_times() var eventCapturer = new EventCapturer().Capture(e => e.CommandName == "ping"); using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) + using (var operationContext = new OperationContext(session)) { - var server = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); - using (var channel = server.GetChannel(OperationContext.NoTimeout)) + var server = cluster.SelectServer(operationContext, WritableServerSelector.Instance); + using (var channel = server.GetChannel(operationContext)) { var command = BsonDocument.Parse("{ ping : 1 }"); channel.Command( - OperationContext.NoTimeout, - session, + operationContext, ReadPreference.Primary, DatabaseNamespace.Admin, command, @@ -920,17 +927,17 @@ public async Task Command_should_use_serverApi([Values(false, true)] bool async) using (var cluster = CoreTestConfiguration.CreateCluster(builder)) using (var session = cluster.StartSession()) + using (var operationContext = new OperationContext(session)) { - var server = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); - using (var channel = server.GetChannel(OperationContext.NoTimeout)) + var server = cluster.SelectServer(operationContext, WritableServerSelector.Instance); + using (var channel = server.GetChannel(operationContext)) { var command = BsonDocument.Parse("{ ping : 1 }"); if (async) { await channel .CommandAsync( - OperationContext.NoTimeout, - session, + operationContext, ReadPreference.Primary, DatabaseNamespace.Admin, command, @@ -945,8 +952,7 @@ await channel else { channel.Command( - OperationContext.NoTimeout, - session, + operationContext, ReadPreference.Primary, DatabaseNamespace.Admin, command, diff --git a/tests/MongoDB.Driver.Tests/Core/WireProtocol/CommandWriteProtocolTests.cs b/tests/MongoDB.Driver.Tests/Core/WireProtocol/CommandWriteProtocolTests.cs index 2e989358f7e..ebacf33e4ac 100644 --- a/tests/MongoDB.Driver.Tests/Core/WireProtocol/CommandWriteProtocolTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/WireProtocol/CommandWriteProtocolTests.cs @@ -78,7 +78,8 @@ public void Execute_should_use_cached_IWireProtocol_if_available([Values(false, var commandResponse = MessageHelper.BuildCommandResponse(CreateRawBsonDocument(new BsonDocument("ok", 1))); var connectionId = SetupConnection(mockConnection); - var result = subject.Execute(OperationContext.NoTimeout, mockConnection.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var result = subject.Execute(operationContext, mockConnection.Object); var cachedWireProtocol = subject._cachedWireProtocol(); cachedWireProtocol.Should().NotBeNull(); @@ -92,7 +93,7 @@ public void Execute_should_use_cached_IWireProtocol_if_available([Values(false, subject._responseHandling(CommandResponseHandling.Ignore); // will trigger the exception if the CommandUsingCommandMessageWireProtocol ctor will be called result = null; - var exception = Record.Exception(() => { result = subject.Execute(OperationContext.NoTimeout, mockConnection.Object); }); + var exception = Record.Exception(() => { result = subject.Execute(operationContext, mockConnection.Object); }); if (withSameConnection) { @@ -119,7 +120,7 @@ ConnectionId SetupConnection(Mock connection, ConnectionId id = nul } connection - .Setup(c => c.ReceiveMessage(OperationContext.NoTimeout, It.IsAny(), It.IsAny(), messageEncoderSettings)) + .Setup(c => c.ReceiveMessage(It.IsAny(), It.IsAny(), It.IsAny(), messageEncoderSettings)) .Returns(commandResponse); connection.SetupGet(c => c.ConnectionId).Returns(id); connection @@ -159,13 +160,14 @@ public async Task Execute_should_use_serverApi_with_getMoreCommand( serverApi, TimeSpan.FromMilliseconds(42)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.ExecuteAsync(OperationContext.NoTimeout, connection); + await subject.ExecuteAsync(operationContext, connection); } else { - subject.Execute(OperationContext.NoTimeout, connection); + subject.Execute(operationContext, connection); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(4)).Should().BeTrue(); @@ -204,13 +206,14 @@ public async Task Execute_should_use_serverApi_in_transaction( serverApi, TimeSpan.FromMilliseconds(42)); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.ExecuteAsync(OperationContext.NoTimeout, connection); + await subject.ExecuteAsync(operationContext, connection); } else { - subject.Execute(OperationContext.NoTimeout, connection); + subject.Execute(operationContext, connection); } SpinWait.SpinUntil(() => connection.GetSentMessages().Count >= 1, TimeSpan.FromSeconds(4)).Should().BeTrue(); @@ -261,7 +264,8 @@ public void Execute_should_wait_for_response_when_CommandResponseHandling_is_Ret .Setup(c => c.ReceiveMessage(It.IsAny(), It.IsAny(), It.IsAny(), messageEncoderSettings)) .Returns(commandResponse); - var result = subject.Execute(OperationContext.NoTimeout, mockConnection.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var result = subject.Execute(operationContext, mockConnection.Object); result.Should().Be("{ok: 1}"); } @@ -286,8 +290,8 @@ public void Execute_should_not_wait_for_response_when_CommandResponseHandling_is var mockConnection = new Mock(); mockConnection.Setup(c => c.Settings).Returns(() => new ConnectionSettings()); - - var result = subject.Execute(OperationContext.NoTimeout, mockConnection.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var result = subject.Execute(operationContext, mockConnection.Object); result.Should().BeNull(); mockConnection.Verify( @@ -322,7 +326,8 @@ public async Task ExecuteAsync_should_wait_for_response_when_CommandResponseHand .Setup(c => c.ReceiveMessageAsync(It.IsAny(), It.IsAny(), It.IsAny(), messageEncoderSettings)) .Returns(Task.FromResult(commandResponse)); - var result = await subject.ExecuteAsync(OperationContext.NoTimeout, mockConnection.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var result = await subject.ExecuteAsync(operationContext, mockConnection.Object); result.Should().Be("{ok: 1}"); } @@ -348,7 +353,8 @@ public async Task ExecuteAsync_should_not_wait_for_response_when_CommandResponse var mockConnection = new Mock(); mockConnection.Setup(c => c.Settings).Returns(() => new ConnectionSettings()); - var result = await subject.ExecuteAsync(OperationContext.NoTimeout, mockConnection.Object); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var result = await subject.ExecuteAsync(operationContext, mockConnection.Object); result.Should().BeNull(); mockConnection.Verify(c => c.ReceiveMessageAsync(It.IsAny(), It.IsAny(), It.IsAny(), messageEncoderSettings), Times.Once); diff --git a/tests/MongoDB.Driver.Tests/MockOperationExecutor.cs b/tests/MongoDB.Driver.Tests/MockOperationExecutor.cs index ee6e0d015f3..98b10917440 100644 --- a/tests/MongoDB.Driver.Tests/MockOperationExecutor.cs +++ b/tests/MongoDB.Driver.Tests/MockOperationExecutor.cs @@ -43,11 +43,6 @@ public IMongoClient Client set { _client = value; } } - public int QueuedCallCount - { - get { return _calls.Count; } - } - public void Dispose() { } @@ -64,7 +59,6 @@ public void EnqueueException(Exception exception) public TResult ExecuteReadOperation( OperationContext operationContext, - IClientSessionHandle session, IReadOperation operation, ReadPreference readPreference, bool allowChannelPinning) @@ -74,9 +68,9 @@ public TResult ExecuteReadOperation( Operation = operation, CancellationToken = operationContext.CancellationToken, ReadPreference = readPreference, - SessionId = session?.WrappedCoreSession.Id, + SessionId = operationContext.Session.Id, Timeout = operationContext.Timeout, - UsedImplicitSession = session == null || session.IsImplicit + UsedImplicitSession = operationContext.Session.IsImplicit }); if (_results.Count > 0) @@ -97,14 +91,13 @@ public TResult ExecuteReadOperation( public Task ExecuteReadOperationAsync( OperationContext operationContext, - IClientSessionHandle session, IReadOperation operation, ReadPreference readPreference, bool allowChannelPinning) { try { - var result = ExecuteReadOperation(operationContext, session, operation, readPreference, allowChannelPinning); + var result = ExecuteReadOperation(operationContext, operation, readPreference, allowChannelPinning); return Task.FromResult(result); } catch (Exception ex) @@ -117,7 +110,6 @@ public Task ExecuteReadOperationAsync( public TResult ExecuteWriteOperation( OperationContext operationContext, - IClientSessionHandle session, IWriteOperation operation, bool allowChannelPinning) { @@ -125,9 +117,9 @@ public TResult ExecuteWriteOperation( { Operation = operation, CancellationToken = operationContext.CancellationToken, - SessionId = session?.WrappedCoreSession.Id, + SessionId = operationContext.Session.Id, Timeout = operationContext.Timeout, - UsedImplicitSession = session == null || session.IsImplicit + UsedImplicitSession = operationContext.Session.IsImplicit }); if (_results.Count > 0) @@ -148,13 +140,12 @@ public TResult ExecuteWriteOperation( public Task ExecuteWriteOperationAsync( OperationContext operationContext, - IClientSessionHandle session, IWriteOperation operation, bool allowChannelPinning) { try { - var result = ExecuteWriteOperation(operationContext, session, operation, allowChannelPinning); + var result = ExecuteWriteOperation(operationContext, operation, allowChannelPinning); return Task.FromResult(result); } catch (Exception ex) diff --git a/tests/MongoDB.Driver.Tests/OperationContextExtensionsTests.cs b/tests/MongoDB.Driver.Tests/OperationContextExtensionsTests.cs index bf7d8345b77..a7c808ea8f2 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextExtensionsTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextExtensionsTests.cs @@ -16,6 +16,7 @@ using System; using System.Threading; using FluentAssertions; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; using Xunit; @@ -41,7 +42,7 @@ public void IsRootContextTimeoutConfigured_should_throw_on_null() public void IsRootContextTimeoutConfigured_should_return_expected_result(bool expectedResult, int? timeoutMs) { TimeSpan? timeout = timeoutMs.HasValue ? TimeSpan.FromMilliseconds(timeoutMs.Value) : null; - var subject = new OperationContext(timeout, CancellationToken.None); + var subject = new OperationContext(NoCoreSession.NewHandle(), timeout, CancellationToken.None); var result = subject.IsRootContextTimeoutConfigured(); @@ -68,7 +69,7 @@ public void RemainingTimeoutOrDefault_should_return_expected_result(int expected var clock = new FrozenClock(DateTime.UtcNow); TimeSpan? timeout = timeoutMs.HasValue ? TimeSpan.FromMilliseconds(timeoutMs.Value) : null; var defaultValue = TimeSpan.FromMilliseconds(defaultValueMs); - var subject = new OperationContext(clock, timeout, CancellationToken.None); + var subject = new OperationContext(NoCoreSession.NewHandle(), clock, timeout, CancellationToken.None); var result = subject.RemainingTimeoutOrDefault(defaultValue); diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index 8348bb2de38..5770515927d 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -18,8 +18,10 @@ using System.Threading; using System.Threading.Tasks; using FluentAssertions; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; using MongoDB.TestHelpers.XunitExtensions; +using Moq; using Xunit; namespace MongoDB.Driver.Tests @@ -29,13 +31,15 @@ public class OperationContextTests [Fact] public void Constructor_should_initialize_properties() { + var session = Mock.Of(); var timeout = TimeSpan.FromSeconds(42); var clock = new FrozenClock(DateTime.UtcNow); using var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; - using var operationContext = new OperationContext(clock, timeout, cancellationToken); + using var operationContext = new OperationContext(session, clock, timeout, cancellationToken); + operationContext.Session.Should().Be(session); operationContext.Timeout.Should().Be(timeout); operationContext.RemainingTimeout.Should().Be(timeout); operationContext.CancellationToken.Should().Be(cancellationToken); @@ -45,33 +49,21 @@ public void Constructor_should_initialize_properties() [Fact] public void Constructor_should_throw_on_negative_timeout() { - var exception = Record.Exception(() => new OperationContext(TimeSpan.FromSeconds(-5), CancellationToken.None)); + var session = Mock.Of(); + + var exception = Record.Exception(() => new OperationContext(session, TimeSpan.FromSeconds(-5), CancellationToken.None)); exception.Should().BeOfType(); } [Fact] - public void Constructor_with_metadata_should_initialize_all_properties() + public void Dispose_should_not_dispose_session() { - var timeout = TimeSpan.FromSeconds(30); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - using var operationContext = new OperationContext( - timeout, - "find", - "testdb", - "testcol", - true, - cancellationToken); + var session = new Mock(); + var operationContext = new OperationContext(session.Object); - operationContext.Timeout.Should().Be(timeout); - operationContext.CancellationToken.Should().Be(cancellationToken); - operationContext.OperationName.Should().Be("find"); - operationContext.DatabaseName.Should().Be("testdb"); - operationContext.CollectionName.Should().Be("testcol"); - operationContext.IsTracingEnabled.Should().BeTrue(); - operationContext.RootContext.Should().Be(operationContext); + operationContext.Dispose(); + session.Verify(s => s.Dispose(), Times.Never); } [Theory] @@ -393,7 +385,8 @@ public void WithTimeout_should_throw_on_negative_timeout() private static OperationContext CreateSubject(TimeSpan? timeout, TimeSpan elapsed = default, CancellationToken cancellationToken = default) { var clock = new FrozenClock(DateTime.UtcNow); - var result = new OperationContext(clock, timeout, cancellationToken); + var session = Mock.Of(); + var result = new OperationContext(session, clock, timeout, cancellationToken); if (elapsed != TimeSpan.Zero) { diff --git a/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs index 99921a17bd1..b18895ba846 100644 --- a/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Driver.Core.Bindings; @@ -43,12 +42,12 @@ public void StartImplicitSession_should_call_cluster_StartSession() public async Task ExecuteReadOperation_throws_on_null_operation([Values(true, false)] bool async) { var subject = CreateSubject(out _); - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); - var session = Mock.Of(); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); var exception = async ? - await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(operationContext, session, null, ReadPreference.Primary, true)) : - Record.Exception(() => subject.ExecuteReadOperation(operationContext, session, null, ReadPreference.Primary, true)); + await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(operationContext, null, ReadPreference.Primary, true)) : + Record.Exception(() => subject.ExecuteReadOperation(operationContext, null, ReadPreference.Primary, true)); exception.Should().BeOfType() .Subject.ParamName.Should().Be("operation"); @@ -59,66 +58,34 @@ await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(oper public async Task ExecuteReadOperation_throws_on_null_readPreference([Values(true, false)] bool async) { var subject = CreateSubject(out _); - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); var operation = Mock.Of>(); - var session = Mock.Of(); var exception = async ? - await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(operationContext, session, operation, null, true)) : - Record.Exception(() => subject.ExecuteReadOperation(operationContext, session, operation, null, true)); + await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(operationContext, operation, null, true)) : + Record.Exception(() => subject.ExecuteReadOperation(operationContext, operation, null, true)); exception.Should().BeOfType() .Subject.ParamName.Should().Be("readPreference"); } - [Theory] - [ParameterAttributeData] - public async Task ExecuteReadOperation_throws_on_null_session([Values(true, false)] bool async) - { - var subject = CreateSubject(out _); - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); - var operation = Mock.Of>(); - - var exception = async ? - await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(operationContext, null, operation, ReadPreference.Primary, true)) : - Record.Exception(() => subject.ExecuteReadOperation(operationContext, null, operation, ReadPreference.Primary, true)); - - exception.Should().BeOfType() - .Subject.ParamName.Should().Be("session"); - } - [Theory] [ParameterAttributeData] public async Task ExecuteWriteOperation_throws_on_null_operation([Values(true, false)] bool async) { var subject = CreateSubject(out _); - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); - var session = Mock.Of(); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); var exception = async ? - await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(operationContext, session, null, true)) : - Record.Exception(() => subject.ExecuteWriteOperation(operationContext, session, null, true)); + await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(operationContext, null, true)) : + Record.Exception(() => subject.ExecuteWriteOperation(operationContext, null, true)); exception.Should().BeOfType() .Subject.ParamName.Should().Be("operation"); } - [Theory] - [ParameterAttributeData] - public async Task ExecuteWriteOperation_throws_on_null_session([Values(true, false)] bool async) - { - var subject = CreateSubject(out _); - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); - var operation = Mock.Of>(); - - var exception = async ? - await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(operationContext, null, operation, true)) : - Record.Exception(() => subject.ExecuteWriteOperation(operationContext, null, operation, true)); - - exception.Should().BeOfType() - .Subject.ParamName.Should().Be("session"); - } - private OperationExecutor CreateSubject(out Mock clusterMock) { clusterMock = new Mock(); diff --git a/tests/MongoDB.Driver.Tests/Specifications/client-backpressure/prose-tests/ClientBackpressureProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/client-backpressure/prose-tests/ClientBackpressureProseTests.cs index e3520869f94..c04362f8135 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/client-backpressure/prose-tests/ClientBackpressureProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/client-backpressure/prose-tests/ClientBackpressureProseTests.cs @@ -18,7 +18,6 @@ using System.Diagnostics; using System.Linq; using System.Net; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -90,7 +89,8 @@ private async Task AssertBackoffBehavior( Action executeSync, Func executeAsync) { - var operationContext = new OperationContext(TimeSpan.FromSeconds(30), CancellationToken.None); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session, timeout: TimeSpan.FromSeconds(30)); // Test with no backoff (jitter = 0) var noBackoffRandom = new Mock(); @@ -129,12 +129,9 @@ private async Task AssertBackoffBehavior( private static RetryableReadContext CreateRetryableReadContext(IRandom random, int maxAdaptiveRetries = 2) { - var sessionMock = new Mock(); - sessionMock.SetupGet(s => s.IsInTransaction).Returns(false); var (channelSourceMock, channelMock) = CreateChannelMocks(); var bindingMock = new Mock(); - bindingMock.SetupGet(b => b.Session).Returns(sessionMock.Object); bindingMock.Setup(b => b.GetReadChannelSource(It.IsAny(), It.IsAny>())) .Returns(channelSourceMock.Object); bindingMock.Setup(b => b.GetReadChannelSourceAsync(It.IsAny(), It.IsAny>())) @@ -148,13 +145,9 @@ private static RetryableReadContext CreateRetryableReadContext(IRandom random, i private static RetryableWriteContext CreateRetryableWriteContext(IRandom random) { - var sessionMock = new Mock(); - sessionMock.SetupGet(s => s.IsInTransaction).Returns(false); - sessionMock.SetupGet(s => s.Id).Returns(new BsonDocument("id", 1)); var (channelSourceMock, channelMock) = CreateChannelMocks(); var bindingMock = new Mock(); - bindingMock.SetupGet(b => b.Session).Returns(sessionMock.Object); bindingMock.Setup(b => b.GetWriteChannelSource(It.IsAny(), It.IsAny>())) .Returns(channelSourceMock.Object); bindingMock.Setup(b => b.GetWriteChannelSourceAsync(It.IsAny(), It.IsAny>())) 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 69be702d7e0..28faf2b578f 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 @@ -3456,10 +3456,11 @@ private void DropCollection(CollectionNamespace collectionNamespace, BsonDocumen { var operation = DropCollectionOperation.CreateEncryptedDropCollectionOperationIfConfigured(collectionNamespace, encryptedFields, CoreTestConfiguration.MessageEncoderSettings, configureDropCollectionConfigurator: null); using (var session = CoreTestConfiguration.StartSession(_cluster)) - using (var binding = new WritableServerBinding(_cluster, session.Fork())) + using (var operationContext = new OperationContext(session)) + using (var binding = new WritableServerBinding(_cluster)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - operation.Execute(OperationContext.NoTimeout, bindingHandle); + operation.Execute(operationContext, 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 5cf836b4d57..1f8f4525be9 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 @@ -26,6 +26,7 @@ using MongoDB.Bson.TestHelpers; using MongoDB.Bson.TestHelpers.JsonDrivenTests; using MongoDB.Driver.Core; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Configuration; @@ -402,9 +403,10 @@ private void ExecuteCheckOut( void CheckOut(BsonDocument op, IConnectionPool cp, ConcurrentDictionary cm) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var conn = async ? - cp.AcquireConnectionAsync(OperationContext.NoTimeout).GetAwaiter().GetResult() : - cp.AcquireConnection(OperationContext.NoTimeout); + cp.AcquireConnectionAsync(operationContext).GetAwaiter().GetResult() : + cp.AcquireConnection(operationContext); if (op.TryGetValue("label", out var label)) { @@ -664,7 +666,8 @@ private void ParseSettings( connectionIdLocalValueProvider: connectionIdProvider)) .Subscribe(eventCapturer)); - var server = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); + var server = cluster.SelectServer(operationContext, WritableServerSelector.Instance); connectionPool = server._connectionPool(); if (test.TryGetValue(Schema.Intergration.failPoint, out var failPointDocument)) diff --git a/tests/MongoDB.Driver.Tests/Specifications/mongodb-handshake/prose-tests/MongoDbHandshakeProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/mongodb-handshake/prose-tests/MongoDbHandshakeProseTests.cs index 8c934da0f26..87f78975ac7 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/mongodb-handshake/prose-tests/MongoDbHandshakeProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/mongodb-handshake/prose-tests/MongoDbHandshakeProseTests.cs @@ -22,6 +22,7 @@ using MongoDB.Bson; using MongoDB.Bson.TestHelpers; using MongoDB.Driver.Core; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -92,13 +93,14 @@ public async Task DriverAcceptsArbitraryAuthMechanism([Values(false, true)] bool socketReadTimeout: Timeout.InfiniteTimeSpan, socketWriteTimeout: Timeout.InfiniteTimeSpan); + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); if (async) { - await subject.OpenAsync(OperationContext.NoTimeout); + await subject.OpenAsync(operationContext); } else { - subject.Open(OperationContext.NoTimeout); + subject.Open(operationContext); } subject._state().Should().Be(3); // 3 - open. 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 7d219685071..f590e051cc1 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 @@ -24,6 +24,7 @@ using MongoDB.Bson; using MongoDB.Bson.TestHelpers; using MongoDB.Driver.Core; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Events; @@ -219,7 +220,9 @@ 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(OperationContext.NoTimeout, WritableServerSelector.Instance); + using var session = NoCoreSession.NewHandle(); + using var operationContext = new OperationContext(session); + var server = client.GetClusterInternal().SelectServer(operationContext, 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 diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs index a61e7d6658a..dca8acd21de 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs @@ -22,6 +22,7 @@ using MongoDB.Bson.Serialization; using MongoDB.Bson.TestHelpers.JsonDrivenTests; using MongoDB.Driver.Core; +using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; using MongoDB.Driver.Core.Configuration; @@ -81,9 +82,10 @@ public void RunTestDefinition(JsonDrivenTestCase testCase) for (int i = 0; i < testData.iterations; i++) { + using var operationContext = new OperationContext(NoCoreSession.NewHandle()); var selectedServer = testData.async - ? cluster.SelectServerAsync(OperationContext.NoTimeout, readPreferenceSelector).GetAwaiter().GetResult() - : cluster.SelectServer(OperationContext.NoTimeout, readPreferenceSelector); + ? cluster.SelectServerAsync(operationContext, readPreferenceSelector).GetAwaiter().GetResult() + : cluster.SelectServer(operationContext, readPreferenceSelector); selectionHistogram[selectedServer.ServerId]++; } diff --git a/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs index c64dac69178..8b10334e65e 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs @@ -1,4 +1,4 @@ -/* Copyright 2021-present MongoDB Inc. +/* 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. @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using FluentAssertions; @@ -28,7 +27,6 @@ using MongoDB.Driver.Core.TestHelpers.Logging; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; using MongoDB.Driver.Encryption; -using MongoDB.Driver.TestHelpers; using MongoDB.TestHelpers.XunitExtensions; using Xunit; using Xunit.Abstractions; @@ -389,7 +387,6 @@ public void Retrieving_SnapshotTime_on_non_snapshot_session_raises_error() var mongoClient = DriverTestConfiguration.Client; using var session = mongoClient.StartSession(sessionOptions); - var exception = Record.Exception(() => session.GetSnapshotTime()); exception.Should().BeOfType(); exception.Message.Should().Contain("non-snapshot session");