diff --git a/src/MongoDB.Driver/AggregateOptions.cs b/src/MongoDB.Driver/AggregateOptions.cs
index cafe47e785b..65267d669a8 100644
--- a/src/MongoDB.Driver/AggregateOptions.cs
+++ b/src/MongoDB.Driver/AggregateOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2015-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.
@@ -34,6 +34,7 @@ public class AggregateOptions
private BsonDocument _let;
private TimeSpan? _maxAwaitTime;
private TimeSpan? _maxTime;
+ private TimeSpan? _timeout;
private ExpressionTranslationOptions _translationOptions;
private bool? _useCursor;
@@ -121,12 +122,22 @@ public TimeSpan? MaxAwaitTime
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
+
///
/// Gets or sets the translation options.
///
diff --git a/src/MongoDB.Driver/BulkWriteOptions.cs b/src/MongoDB.Driver/BulkWriteOptions.cs
index 12b75cbb018..d3c62f52b1b 100644
--- a/src/MongoDB.Driver/BulkWriteOptions.cs
+++ b/src/MongoDB.Driver/BulkWriteOptions.cs
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -27,6 +29,7 @@ public sealed class BulkWriteOptions
private BsonValue _comment;
private bool _isOrdered;
private BsonDocument _let;
+ private TimeSpan? _timeout;
// constructors
///
@@ -73,5 +76,14 @@ public BsonDocument Let
get { return _let; }
set { _let = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ChangeStreamOptions.cs b/src/MongoDB.Driver/ChangeStreamOptions.cs
index c4da3830611..c9dc41994e0 100644
--- a/src/MongoDB.Driver/ChangeStreamOptions.cs
+++ b/src/MongoDB.Driver/ChangeStreamOptions.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.
@@ -35,6 +35,7 @@ public class ChangeStreamOptions
private bool? _showExpandedEvents;
private BsonDocument _startAfter;
private BsonTimestamp _startAtOperationTime;
+ private TimeSpan? _timeout;
// public properties
///
@@ -166,5 +167,14 @@ public BsonTimestamp StartAtOperationTime
get { return _startAtOperationTime; }
set { _startAtOperationTime = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ClientBulkWriteOptions.cs b/src/MongoDB.Driver/ClientBulkWriteOptions.cs
index 9ba9c366c6b..aa81ce2935b 100644
--- a/src/MongoDB.Driver/ClientBulkWriteOptions.cs
+++ b/src/MongoDB.Driver/ClientBulkWriteOptions.cs
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -22,6 +24,8 @@ namespace MongoDB.Driver
///
public sealed class ClientBulkWriteOptions
{
+ private TimeSpan? _timeout;
+
///
/// Initializes a new instance of the class.
///
@@ -75,6 +79,15 @@ public ClientBulkWriteOptions(
///
public BsonDocument Let { get; set; }
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
+
///
/// Whether detailed results for each successful operation should be included in the returned results.
///
diff --git a/src/MongoDB.Driver/OperationOptionsBase.cs b/src/MongoDB.Driver/ClientSessionExtensions.cs
similarity index 51%
rename from src/MongoDB.Driver/OperationOptionsBase.cs
rename to src/MongoDB.Driver/ClientSessionExtensions.cs
index 5f564ca1b27..163308fc715 100644
--- a/src/MongoDB.Driver/OperationOptionsBase.cs
+++ b/src/MongoDB.Driver/ClientSessionExtensions.cs
@@ -13,15 +13,22 @@
* limitations under the License.
*/
-using System;
-using System.Threading;
+namespace MongoDB.Driver;
-namespace MongoDB.Driver
+internal static class ClientSessionExtensions
{
- internal abstract record OperationOptionsBase(TimeSpan Timeout)
+ public static ReadPreference GetEffectiveReadPreference(this IClientSession session, ReadPreference defaultReadPreference)
{
- public OperationContext ToOperationContext(CancellationToken cancellationToken)
- => new (Timeout, cancellationToken);
+ if (session.IsInTransaction)
+ {
+ var transactionReadPreference = session.WrappedCoreSession.CurrentTransaction.TransactionOptions.ReadPreference;
+ if (transactionReadPreference != null)
+ {
+ return transactionReadPreference;
+ }
+ }
+
+ return defaultReadPreference ?? ReadPreference.Primary;
}
}
diff --git a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs
index 073492ea4da..d91eee1610e 100644
--- a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs
+++ b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs
@@ -146,7 +146,7 @@ public bool IsInTransaction
EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction));
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
try
{
if (_currentTransaction.IsEmpty)
@@ -197,7 +197,7 @@ public bool IsInTransaction
EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction));
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
try
{
if (_currentTransaction.IsEmpty)
@@ -297,7 +297,7 @@ public long AdvanceTransactionNumber()
EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction));
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
try
{
_isCommitTransactionInProgress = true;
@@ -334,7 +334,7 @@ public long AdvanceTransactionNumber()
EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction));
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
try
{
_isCommitTransactionInProgress = true;
diff --git a/src/MongoDB.Driver/Core/Configuration/ConnectionString.cs b/src/MongoDB.Driver/Core/Configuration/ConnectionString.cs
index 79349c035cc..e92479d1cc3 100644
--- a/src/MongoDB.Driver/Core/Configuration/ConnectionString.cs
+++ b/src/MongoDB.Driver/Core/Configuration/ConnectionString.cs
@@ -98,6 +98,7 @@ public sealed class ConnectionString
private TimeSpan? _socketTimeout;
private int? _srvMaxHosts;
private string _srvServiceName;
+ private TimeSpan? _timeout;
private bool? _tls;
private bool? _tlsDisableCertificateRevocationCheck;
private bool? _tlsInsecure;
@@ -399,7 +400,6 @@ public bool? RetryReads
get { return _retryReads; }
}
-
///
/// Gets a value indicating whether or not to retry writes.
///
@@ -468,6 +468,11 @@ public bool? Ssl
[Obsolete("Use TlsInsecure instead.")]
public bool? SslVerifyCertificate => !_tlsInsecure;
+ ///
+ /// Gets the per-operation timeout.
+ ///
+ public TimeSpan? Timeout => _timeout;
+
///
/// Gets whether to use TLS.
///
@@ -1089,6 +1094,10 @@ private void ParseOption(string name, string value)
var sslVerifyCertificateValue = ParseBoolean(name, value);
_tlsInsecure = EnsureTlsInsecureIsValid(!sslVerifyCertificateValue);
break;
+ case "timeout":
+ case "timeoutms":
+ _timeout = value == "0" ? System.Threading.Timeout.InfiniteTimeSpan : ParseTimeSpan(name, value);
+ break;
case "tlsdisablecertificaterevocationcheck":
var tlsDisableCertificateRevocationCheckValue = ParseBoolean(name, value);
_tlsDisableCertificateRevocationCheck =
diff --git a/src/MongoDB.Driver/Core/Misc/Ensure.cs b/src/MongoDB.Driver/Core/Misc/Ensure.cs
index 7fbab39b9b7..8cd1163f7f1 100644
--- a/src/MongoDB.Driver/Core/Misc/Ensure.cs
+++ b/src/MongoDB.Driver/Core/Misc/Ensure.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.
@@ -444,11 +444,12 @@ public static string IsNullOrNotEmpty(string value, string paramName)
/// The value of the parameter.
public static TimeSpan? IsNullOrValidTimeout(TimeSpan? value, string paramName)
{
- if (value != null)
+ if (value == null)
{
- IsValidTimeout(value.Value, paramName);
+ return null;
}
- return value;
+
+ return IsValidTimeout(value.Value, paramName);
}
///
@@ -459,12 +460,12 @@ public static string IsNullOrNotEmpty(string value, string paramName)
/// The value of the parameter.
public static TimeSpan IsValidTimeout(TimeSpan value, string paramName)
{
- if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
+ if (value > TimeSpan.Zero || value == Timeout.InfiniteTimeSpan)
{
- var message = string.Format("Invalid timeout: {0}.", value);
- throw new ArgumentException(message, paramName);
+ return value;
}
- return value;
+
+ throw new ArgumentOutOfRangeException($"Invalid timeout: {value}.", paramName);
}
///
diff --git a/src/MongoDB.Driver/Core/Misc/Feature.cs b/src/MongoDB.Driver/Core/Misc/Feature.cs
index fecba2788f6..47bf7bb65f9 100644
--- a/src/MongoDB.Driver/Core/Misc/Feature.cs
+++ b/src/MongoDB.Driver/Core/Misc/Feature.cs
@@ -570,7 +570,7 @@ public void ThrowIfNotSupported(IMongoClient client, CancellationToken cancellat
{
var cluster = client.GetClusterInternal();
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ 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))
@@ -589,7 +589,7 @@ public async Task ThrowIfNotSupportedAsync(IMongoClient client, CancellationToke
{
var cluster = client.GetClusterInternal();
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ 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))
diff --git a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs
index 86eae237593..8f1947cc546 100644
--- a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs
@@ -288,7 +288,7 @@ public IAsyncCursor Execute(OperationContext operationContext, Retryabl
using (EventContext.BeginOperation())
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var result = operation.Execute(operationContext, context);
context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime);
@@ -317,7 +317,7 @@ public async Task> ExecuteAsync(OperationContext operation
using (EventContext.BeginOperation())
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false);
context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime);
@@ -326,7 +326,7 @@ public async Task> ExecuteAsync(OperationContext operation
}
}
- internal BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
+ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription)
{
var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);
var command = new BsonDocument
@@ -334,7 +334,7 @@ internal BsonDocument CreateCommand(ConnectionDescription connectionDescription,
{ "aggregate", _collectionNamespace == null ? (BsonValue)1 : _collectionNamespace.CollectionName },
{ "pipeline", new BsonArray(_pipeline) },
{ "allowDiskUse", () => _allowDiskUse.Value, _allowDiskUse.HasValue },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "collation", () => _collation.ToBsonDocument(), _collation != null },
{ "hint", _hint, _hint != null },
{ "let", _let, _let != null },
@@ -354,10 +354,10 @@ internal BsonDocument CreateCommand(ConnectionDescription connectionDescription,
private IDisposable BeginOperation() => EventContext.BeginOperation(null, "aggregate");
- private ReadCommandOperation CreateOperation(RetryableReadContext context)
+ private ReadCommandOperation CreateOperation(OperationContext operationContext, RetryableReadContext context)
{
var databaseNamespace = _collectionNamespace == null ? _databaseNamespace : _collectionNamespace.DatabaseNamespace;
- var command = CreateCommand(context.Channel.ConnectionDescription, context.Binding.Session);
+ var command = CreateCommand(operationContext, context.Binding.Session, context.Channel.ConnectionDescription);
var serializer = new AggregateResultDeserializer(_resultSerializer);
return new ReadCommandOperation(databaseNamespace, command, serializer, MessageEncoderSettings)
{
diff --git a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs
index 79c684d9752..f8ed350f732 100644
--- a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.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.
@@ -157,7 +157,7 @@ public BsonDocument Execute(OperationContext operationContext, IWriteBinding bin
using (var channel = channelSource.GetChannel(operationContext))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference);
return operation.Execute(operationContext, channelBinding);
}
}
@@ -172,12 +172,12 @@ public async Task ExecuteAsync(OperationContext operationContext,
using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference);
return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false);
}
}
- public BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ public BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
var readConcern = _readConcern != null
? ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern)
@@ -189,7 +189,7 @@ public BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescript
{ "pipeline", new BsonArray(_pipeline) },
{ "allowDiskUse", () => _allowDiskUse.Value, _allowDiskUse.HasValue },
{ "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "collation", () => _collation.ToBsonDocument(), _collation != null },
{ "readConcern", readConcern, readConcern != null },
{ "writeConcern", writeConcern, writeConcern != null },
@@ -202,9 +202,9 @@ public BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescript
private IDisposable BeginOperation() => EventContext.BeginOperation("aggregate");
- private WriteCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription, ReadPreference effectiveReadPreference)
+ private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, ReadPreference effectiveReadPreference)
{
- var command = CreateCommand(session, connectionDescription);
+ var command = CreateCommand(operationContext, session, connectionDescription);
var operation = new WriteCommandOperation(_databaseNamespace, command, BsonDocumentSerializer.Instance, MessageEncoderSettings);
if (effectiveReadPreference != null)
{
diff --git a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs
index dd5c7e0ba9f..6791ae3a44a 100644
--- a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs
+++ b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs
@@ -220,7 +220,7 @@ private CursorBatch ExecuteGetMoreCommand(IChannelHandle channel, Can
try
{
// TODO: CSOT: Implement operation context support for Cursors
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
result = channel.Command(
operationContext,
_channelSource.Session,
@@ -250,7 +250,7 @@ private async Task> ExecuteGetMoreCommandAsync(IChannelHa
try
{
// TODO: CSOT: Implement operation context support for Cursors
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
result = await channel.CommandAsync(
operationContext,
_channelSource.Session,
@@ -276,7 +276,7 @@ private async Task> ExecuteGetMoreCommandAsync(IChannelHa
private void ExecuteKillCursorsCommand(IChannelHandle channel, CancellationToken cancellationToken)
{
// TODO: CSOT: Implement operation context support for Cursors
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
var command = CreateKillCursorsCommand();
var result = channel.Command(
operationContext,
@@ -298,7 +298,7 @@ private void ExecuteKillCursorsCommand(IChannelHandle channel, CancellationToken
private async Task ExecuteKillCursorsCommandAsync(IChannelHandle channel, CancellationToken cancellationToken)
{
// TODO: CSOT: Implement operation context support for Cursors
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
var command = CreateKillCursorsCommand();
var result = await channel.CommandAsync(
operationContext,
@@ -418,7 +418,7 @@ private void DisposeChannelSourceIfNoLongerNeeded()
private CursorBatch GetNextBatch(CancellationToken cancellationToken)
{
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
using (EventContext.BeginOperation(_operationId))
using (var channel = _channelSource.GetChannel(operationContext))
{
@@ -429,7 +429,7 @@ private CursorBatch GetNextBatch(CancellationToken cancellationToken)
private async Task> GetNextBatchAsync(CancellationToken cancellationToken)
{
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
using (EventContext.BeginOperation(_operationId))
using (var channel = await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false))
{
@@ -445,7 +445,7 @@ private bool IsMongoCursorNotFoundException(MongoCommandException exception)
private void KillCursors(CancellationToken cancellationToken)
{
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
using (EventContext.BeginOperation(_operationId))
using (EventContext.BeginKillCursors(_collectionNamespace))
using (var channel = _channelSource.GetChannel(operationContext.WithTimeout(TimeSpan.FromSeconds(10))))
@@ -460,7 +460,7 @@ private void KillCursors(CancellationToken cancellationToken)
private async Task KillCursorsAsync(CancellationToken cancellationToken)
{
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ 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))
diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs
index afd01623847..f43cb30a168 100644
--- a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs
+++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs
@@ -262,7 +262,7 @@ private IAsyncCursor Resume(CancellationToken cancellationToken
{
ReconfigureOperationResumeValues();
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
return _changeStreamOperation.Resume(operationContext, _binding);
}
@@ -270,7 +270,7 @@ private async Task> ResumeAsync(CancellationToken
{
ReconfigureOperationResumeValues();
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
return await _changeStreamOperation.ResumeAsync(operationContext, _binding).ConfigureAwait(false);
}
diff --git a/src/MongoDB.Driver/Core/Operations/CountOperation.cs b/src/MongoDB.Driver/Core/Operations/CountOperation.cs
index cd83e1d374d..1f19a2063ac 100644
--- a/src/MongoDB.Driver/Core/Operations/CountOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/CountOperation.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.
@@ -109,7 +109,7 @@ public long? Skip
set { _skip = value; }
}
- public BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
+ public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription)
{
var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);
return new BsonDocument
@@ -119,7 +119,7 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I
{ "limit", () => _limit.Value, _limit.HasValue },
{ "skip", () => _skip.Value, _skip.HasValue },
{ "hint", _hint, _hint != null },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "collation", () => _collation.ToBsonDocument(), _collation != null },
{ "comment", _comment, _comment != null },
{ "readConcern", readConcern, readConcern != null }
@@ -139,7 +139,7 @@ public long Execute(OperationContext operationContext, IReadBinding binding)
public long Execute(OperationContext operationContext, RetryableReadContext context)
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var document = operation.Execute(operationContext, context);
return document["n"].ToInt64();
}
@@ -157,16 +157,16 @@ public async Task ExecuteAsync(OperationContext operationContext, IReadBin
public async Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context)
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var document = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false);
return document["n"].ToInt64();
}
private IDisposable BeginOperation() => EventContext.BeginOperation("count");
- private ReadCommandOperation CreateOperation(RetryableReadContext context)
+ private ReadCommandOperation CreateOperation(OperationContext operationContext, RetryableReadContext context)
{
- var command = CreateCommand(context.Channel.ConnectionDescription, context.Binding.Session);
+ var command = CreateCommand(operationContext, context.Binding.Session, context.Channel.ConnectionDescription);
return new ReadCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings)
{
RetryRequested = _retryRequested // might be overridden by retryable read context
diff --git a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs
index f4e071950ad..ea57950eea7 100644
--- a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.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.
@@ -93,7 +93,7 @@ public BsonDocument Execute(OperationContext operationContext, IWriteBinding bin
using (var channel = channelSource.GetChannel(operationContext))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription);
return operation.Execute(operationContext, channelBinding);
}
}
@@ -105,12 +105,12 @@ public async Task ExecuteAsync(OperationContext operationContext,
using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription);
return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false);
}
}
- internal BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ internal BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
var maxWireVersion = connectionDescription.MaxWireVersion;
var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(session, _writeConcern);
@@ -123,7 +123,7 @@ internal BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescri
{
{ "createIndexes", _collectionNamespace.CollectionName },
{ "indexes", new BsonArray(_requests.Select(request => request.CreateIndexDocument())) },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "writeConcern", writeConcern, writeConcern != null },
{ "comment", _comment, _comment != null },
{ "commitQuorum", () => _commitQuorum.ToBsonValue(), _commitQuorum != null }
@@ -132,10 +132,10 @@ internal BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescri
private IDisposable BeginOperation() => EventContext.BeginOperation(null, "createIndexes");
- private WriteCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
var databaseNamespace = _collectionNamespace.DatabaseNamespace;
- var command = CreateCommand(session, connectionDescription);
+ var command = CreateCommand(operationContext, session, connectionDescription);
var resultSerializer = BsonDocumentSerializer.Instance;
return new WriteCommandOperation(databaseNamespace, command, resultSerializer, _messageEncoderSettings);
}
diff --git a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs
index 0e25eb3d097..a64cee8a13c 100644
--- a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/DistinctOperation.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.
@@ -111,7 +111,7 @@ public IAsyncCursor Execute(OperationContext operationContext, IReadBind
using (BeginOperation())
using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested))
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var result = operation.Execute(operationContext, context);
binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime);
@@ -127,7 +127,7 @@ public async Task> ExecuteAsync(OperationContext operationC
using (BeginOperation())
using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false))
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false);
binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime);
@@ -136,7 +136,7 @@ public async Task> ExecuteAsync(OperationContext operationC
}
}
- public BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
+ public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription)
{
var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);
return new BsonDocument
@@ -144,7 +144,7 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I
{ "distinct", _collectionNamespace.CollectionName },
{ "key", _fieldName },
{ "query", _filter, _filter != null },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "collation", () => _collation.ToBsonDocument(), _collation != null },
{ "comment", _comment, _comment != null },
{ "readConcern", readConcern, readConcern != null }
@@ -153,9 +153,9 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I
private IDisposable BeginOperation() => EventContext.BeginOperation("distinct");
- private ReadCommandOperation CreateOperation(RetryableReadContext context)
+ private ReadCommandOperation CreateOperation(OperationContext operationContext, RetryableReadContext context)
{
- var command = CreateCommand(context.Channel.ConnectionDescription, context.Binding.Session);
+ var command = CreateCommand(operationContext, context.Binding.Session, context.Channel.ConnectionDescription);
var serializer = new DistinctResultDeserializer(_valueSerializer);
return new ReadCommandOperation(_collectionNamespace.DatabaseNamespace, command, serializer, _messageEncoderSettings)
diff --git a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs
index ef68ad071c5..72e8b1bc53b 100644
--- a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.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.
@@ -84,14 +84,14 @@ public TimeSpan? MaxTime
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
- public BsonDocument CreateCommand(ICoreSessionHandle session)
+ public BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session)
{
var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(session, _writeConcern);
return new BsonDocument
{
{ "dropIndexes", _collectionNamespace.CollectionName },
{ "index", _indexName },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "writeConcern", writeConcern, writeConcern != null },
{ "comment", _comment, _comment != null }
};
@@ -106,7 +106,7 @@ public BsonDocument Execute(OperationContext operationContext, IWriteBinding bin
using (var channel = channelSource.GetChannel(operationContext))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session);
+ var operation = CreateOperation(operationContext, channelBinding.Session);
BsonDocument result;
try
{
@@ -133,7 +133,7 @@ public async Task ExecuteAsync(OperationContext operationContext,
using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session);
+ var operation = CreateOperation(operationContext, channelBinding.Session);
BsonDocument result;
try
{
@@ -153,9 +153,9 @@ public async Task ExecuteAsync(OperationContext operationContext,
private IDisposable BeginOperation() => EventContext.BeginOperation("dropIndexes");
- private WriteCommandOperation CreateOperation(ICoreSessionHandle session)
+ private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session)
{
- var command = CreateCommand(session);
+ var command = CreateCommand(operationContext, session);
return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings);
}
diff --git a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs
index d32198f81af..1b346fe013f 100644
--- a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs
+++ b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.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.
@@ -124,7 +124,7 @@ public TResult ExecuteAttempt(OperationContext operationContext, RetryableWriteC
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber);
using (var rawBsonDocument = operation.Execute(operationContext, channelBinding))
{
return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument);
@@ -140,7 +140,7 @@ public async Task ExecuteAttemptAsync(OperationContext operationContext
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription, transactionNumber);
using (var rawBsonDocument = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false))
{
return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument);
@@ -148,15 +148,15 @@ public async Task ExecuteAttemptAsync(OperationContext operationContext
}
}
- public abstract BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber);
+ public abstract BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber);
protected abstract IElementNameValidator GetCommandValidator();
private IDisposable BeginOperation() => EventContext.BeginOperation("findAndModify");
- private WriteCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
+ private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
{
- var command = CreateCommand(session, connectionDescription, transactionNumber);
+ var command = CreateCommand(operationContext, session, connectionDescription, transactionNumber);
return new WriteCommandOperation(_collectionNamespace.DatabaseNamespace, command, RawBsonDocumentSerializer.Instance, _messageEncoderSettings)
{
CommandValidator = GetCommandValidator()
diff --git a/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs
index a06756a1a6f..dcc41a6876b 100644
--- a/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/FindOneAndDeleteOperation.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.
@@ -74,7 +74,7 @@ public BsonDocument Sort
set { _sort = value; }
}
- public override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
+ public override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
{
var wireVersion = connectionDescription.MaxWireVersion;
FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion);
@@ -95,7 +95,7 @@ public override BsonDocument CreateCommand(ICoreSessionHandle session, Connectio
{ "remove", true },
{ "sort", _sort, _sort != null },
{ "fields", _projection, _projection != null },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "writeConcern", writeConcern, writeConcern != null },
{ "collation", () => Collation.ToBsonDocument(), Collation != null },
{ "comment", Comment, Comment != null },
diff --git a/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs
index f7aaa59e809..a69e2a651c1 100644
--- a/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/FindOneAndReplaceOperation.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.
@@ -103,7 +103,7 @@ public BsonDocument Sort
set { _sort = value; }
}
- public override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
+ public override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
{
var wireVersion = connectionDescription.MaxWireVersion;
FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion);
@@ -126,7 +126,7 @@ public override BsonDocument CreateCommand(ICoreSessionHandle session, Connectio
{ "sort", _sort, _sort != null },
{ "fields", _projection, _projection != null },
{ "upsert", true, _isUpsert },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "writeConcern", writeConcern, writeConcern != null },
{ "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue },
{ "collation", () => Collation.ToBsonDocument(), Collation != null },
diff --git a/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs
index 42f1e1702d2..bd0aca46a50 100644
--- a/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/FindOneAndUpdateOperation.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.
@@ -112,7 +112,7 @@ public BsonValue Update
get { return _update; }
}
- public override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
+ public override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber)
{
var wireVersion = connectionDescription.MaxWireVersion;
FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion);
@@ -135,7 +135,7 @@ public override BsonDocument CreateCommand(ICoreSessionHandle session, Connectio
{ "sort", _sort, _sort != null },
{ "fields", _projection, _projection != null },
{ "upsert", true, _isUpsert },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "writeConcern", writeConcern, writeConcern != null },
{ "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue },
{ "collation", () => Collation.ToBsonDocument(), Collation != null },
diff --git a/src/MongoDB.Driver/Core/Operations/FindOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOperation.cs
index 364d71bccfa..ec42b994f37 100644
--- a/src/MongoDB.Driver/Core/Operations/FindOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/FindOperation.cs
@@ -1,4 +1,4 @@
-/* Copyright 2015-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.
@@ -237,7 +237,7 @@ public BsonDocument Sort
set { _sort = value; }
}
- public BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
+ public BsonDocument CreateCommand(OperationContext operationContext, ICoreSession session, ConnectionDescription connectionDescription)
{
var wireVersion = connectionDescription.MaxWireVersion;
FindProjectionChecker.ThrowIfAggregationExpressionIsUsedWhenNotSupported(_projection, wireVersion);
@@ -254,7 +254,6 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I
var effectiveComment = _comment;
var effectiveHint = _hint;
var effectiveMax = _max;
- var effectiveMaxTime = _maxTime;
var effectiveMin = _min;
var effectiveReturnKey = _returnKey;
var effectiveShowRecordId = _showRecordId;
@@ -273,7 +272,7 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I
{ "batchSize", () => batchSize.Value, batchSize.HasValue && batchSize > 0 },
{ "singleBatch", () => _limit < 0 || _singleBatch.Value, _limit < 0 || _singleBatch.HasValue },
{ "comment", effectiveComment, effectiveComment != null },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(effectiveMaxTime.Value), effectiveMaxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "max", effectiveMax, effectiveMax != null },
{ "min", effectiveMin, effectiveMin != null },
{ "returnKey", () => effectiveReturnKey.Value, effectiveReturnKey.HasValue },
@@ -307,7 +306,7 @@ public IAsyncCursor Execute(OperationContext operationContext, Retrya
using (EventContext.BeginFind(_batchSize, _limit))
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var commandResult = operation.Execute(operationContext, context);
return CreateCursor(context.ChannelSource, context.Channel, commandResult);
}
@@ -330,7 +329,7 @@ public async Task> ExecuteAsync(OperationContext operati
using (EventContext.BeginFind(_batchSize, _limit))
{
- var operation = CreateOperation(context);
+ var operation = CreateOperation(operationContext, context);
var commandResult = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false);
return CreateCursor(context.ChannelSource, context.Channel, commandResult);
}
@@ -375,9 +374,9 @@ private CursorBatch CreateFirstCursorBatch(BsonDocument cursorDocumen
private IDisposable BeginOperation() => EventContext.BeginOperation(null, "find");
- private ReadCommandOperation CreateOperation(RetryableReadContext context)
+ private ReadCommandOperation CreateOperation(OperationContext operationContext, RetryableReadContext context)
{
- var command = CreateCommand(context.Channel.ConnectionDescription, context.Binding.Session);
+ var command = CreateCommand(operationContext, context.Binding.Session, context.Channel.ConnectionDescription);
var operation = new ReadCommandOperation(
_collectionNamespace.DatabaseNamespace,
command,
diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs
index a68b2227278..21f2a99d684 100644
--- a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.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.
@@ -95,7 +95,7 @@ public IAsyncCursor Execute(OperationContext operationContext, IReadBin
using (var channel = channelSource.GetChannel(operationContext))
using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription);
var result = operation.Execute(operationContext, channelBinding);
return new SingleBatchAsyncCursor(result);
}
@@ -110,16 +110,16 @@ public async Task> ExecuteAsync(OperationContext operation
using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false))
using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription);
var result = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false);
return new SingleBatchAsyncCursor(result);
}
}
///
- protected internal override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ protected internal override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
- var command = base.CreateCommand(session, connectionDescription);
+ var command = base.CreateCommand(operationContext, session, connectionDescription);
var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);
if (readConcern != null)
@@ -130,9 +130,9 @@ protected internal override BsonDocument CreateCommand(ICoreSessionHandle sessio
return command;
}
- private ReadCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ private ReadCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
- var command = CreateCommand(session, connectionDescription);
+ var command = CreateCommand(operationContext, session, connectionDescription);
var resultArraySerializer = new ArraySerializer(_resultSerializer);
var resultSerializer = new ElementDeserializer("results", resultArraySerializer);
return new ReadCommandOperation(CollectionNamespace.DatabaseNamespace, command, resultSerializer, MessageEncoderSettings)
diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs
index 5840e28ac78..f1f455352bc 100644
--- a/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.cs
+++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperationBase.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.
@@ -221,15 +221,7 @@ public bool? Verbose
}
// methods
- ///
- /// Creates the command.
- ///
- /// The session.
- /// The connection description.
- ///
- /// The command.
- ///
- protected internal virtual BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ protected internal virtual BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
return new BsonDocument
{
@@ -244,7 +236,7 @@ protected internal virtual BsonDocument CreateCommand(ICoreSessionHandle session
{ "scope", _scope, _scope != null },
{ "jsMode", () => _javaScriptMode.Value, _javaScriptMode.HasValue },
{ "verbose", () => _verbose.Value, _verbose.HasValue },
- { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
+ { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue && !operationContext.IsRootContextTimeoutConfigured() },
{ "collation", () => _collation.ToBsonDocument(), _collation != null }
};
}
diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs
index 99e32b1adcd..2fe04c0ace8 100644
--- a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs
+++ b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.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.
@@ -139,9 +139,9 @@ public WriteConcern WriteConcern
// methods
///
- protected internal override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ protected internal override BsonDocument CreateCommand(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
- var command = base.CreateCommand(session, connectionDescription);
+ var command = base.CreateCommand(operationContext, session, connectionDescription);
if (_bypassDocumentValidation.HasValue)
{
@@ -177,7 +177,7 @@ public BsonDocument Execute(OperationContext operationContext, IWriteBinding bin
using (var channel = channelSource.GetChannel(operationContext))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription);
return operation.Execute(operationContext, channelBinding);
}
}
@@ -191,14 +191,14 @@ public async Task ExecuteAsync(OperationContext operationContext,
using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false))
using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork()))
{
- var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription);
+ var operation = CreateOperation(operationContext, channelBinding.Session, channel.ConnectionDescription);
return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false);
}
}
- private WriteCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription)
+ private WriteCommandOperation CreateOperation(OperationContext operationContext, ICoreSessionHandle session, ConnectionDescription connectionDescription)
{
- var command = CreateCommand(session, connectionDescription);
+ var command = CreateCommand(operationContext, session, connectionDescription);
return new WriteCommandOperation(CollectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, MessageEncoderSettings);
}
}
diff --git a/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs b/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs
index ee352025f0c..0521743d5ae 100644
--- a/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs
+++ b/src/MongoDB.Driver/Core/Servers/RoundTripTimeMonitor.cs
@@ -125,7 +125,7 @@ private void MonitorServer()
_logger?.LogDebug(_serverId, "Monitoring started");
var helloOk = false;
- using var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, _cancellationToken);
+ using var operationContext = new OperationContext(null, _cancellationToken);
while (!operationContext.IsCancelledOrTimedOut())
{
try
diff --git a/src/MongoDB.Driver/Core/WireProtocol/CommandUsingCommandMessageWireProtocol.cs b/src/MongoDB.Driver/Core/WireProtocol/CommandUsingCommandMessageWireProtocol.cs
index 25481d385a6..7f572c96297 100644
--- a/src/MongoDB.Driver/Core/WireProtocol/CommandUsingCommandMessageWireProtocol.cs
+++ b/src/MongoDB.Driver/Core/WireProtocol/CommandUsingCommandMessageWireProtocol.cs
@@ -376,13 +376,14 @@ private Type0CommandMessageSection CreateType0Section(OperationCon
if (operationContext.IsRootContextTimeoutConfigured() && _roundTripTime > TimeSpan.Zero)
{
- var serverTimeout = operationContext.RemainingTimeout - _roundTripTime;
- if (serverTimeout < TimeSpan.Zero)
+ var serverTimeout = operationContext.RemainingTimeout;
+ if (serverTimeout != Timeout.InfiniteTimeSpan)
{
- throw new TimeoutException();
- }
+ serverTimeout -= _roundTripTime;
- AddIfNotAlreadyAdded("maxTimeMS", (long)serverTimeout.TotalMilliseconds);
+ var serverTimeoutMs = MaxTimeHelper.ToMaxTimeMS(serverTimeout);
+ AddIfNotAlreadyAdded("maxTimeMS", serverTimeoutMs);
+ }
}
var elementAppendingSerializer = new ElementAppendingSerializer(BsonDocumentSerializer.Instance, extraElements);
diff --git a/src/MongoDB.Driver/CountOptions.cs b/src/MongoDB.Driver/CountOptions.cs
index 2a85963cda7..5507b26e50c 100644
--- a/src/MongoDB.Driver/CountOptions.cs
+++ b/src/MongoDB.Driver/CountOptions.cs
@@ -31,6 +31,7 @@ public sealed class CountOptions
private long? _limit;
private TimeSpan? _maxTime;
private long? _skip;
+ private TimeSpan? _timeout;
// properties
///
@@ -72,6 +73,7 @@ public long? Limit
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
@@ -86,5 +88,14 @@ public long? Skip
get { return _skip; }
set { _skip = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/CreateCollectionOptions.cs b/src/MongoDB.Driver/CreateCollectionOptions.cs
index e5e62381158..86e7396c848 100644
--- a/src/MongoDB.Driver/CreateCollectionOptions.cs
+++ b/src/MongoDB.Driver/CreateCollectionOptions.cs
@@ -16,6 +16,7 @@
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -35,6 +36,7 @@ public class CreateCollectionOptions
private long? _maxSize;
private bool? _noPadding;
private BsonDocument _storageEngine;
+ private TimeSpan? _timeout;
private TimeSeriesOptions _timeSeriesOptions;
private bool? _usePowerOf2Sizes;
private IBsonSerializerRegistry _serializerRegistry;
@@ -145,6 +147,15 @@ public BsonDocument StorageEngine
set { _storageEngine = value; }
}
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
+
///
/// Gets or sets the to use when creating a time series collection.
///
diff --git a/src/MongoDB.Driver/CreateManyIndexesOptions.cs b/src/MongoDB.Driver/CreateManyIndexesOptions.cs
index 7122d65847b..ab372a81fd7 100644
--- a/src/MongoDB.Driver/CreateManyIndexesOptions.cs
+++ b/src/MongoDB.Driver/CreateManyIndexesOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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.
@@ -28,6 +28,7 @@ public class CreateManyIndexesOptions
private BsonValue _comment;
private CreateIndexCommitQuorum _commitQuorum;
private TimeSpan? _maxTime;
+ private TimeSpan? _timeout;
// public properties
///
@@ -54,10 +55,20 @@ public CreateIndexCommitQuorum CommitQuorum
/// Gets or sets the maximum time.
///
/// The maximum time.
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/CreateOneIndexOptions.cs b/src/MongoDB.Driver/CreateOneIndexOptions.cs
index 06ab3bf76d7..553a4e81d12 100644
--- a/src/MongoDB.Driver/CreateOneIndexOptions.cs
+++ b/src/MongoDB.Driver/CreateOneIndexOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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,6 +26,7 @@ public class CreateOneIndexOptions
// private fields
private CreateIndexCommitQuorum _commitQuorum;
private TimeSpan? _maxTime;
+ private TimeSpan? _timeout;
// public properties
///
@@ -42,10 +43,20 @@ public CreateIndexCommitQuorum CommitQuorum
/// Gets or sets the maximum time.
///
/// The maximum time.
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/CreateViewOptions.cs b/src/MongoDB.Driver/CreateViewOptions.cs
index 1226e714841..82873304f72 100644
--- a/src/MongoDB.Driver/CreateViewOptions.cs
+++ b/src/MongoDB.Driver/CreateViewOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2016-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,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson.Serialization;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -27,6 +29,7 @@ public class CreateViewOptions
private Collation _collation;
private IBsonSerializer _documentSerializer;
private IBsonSerializerRegistry _serializerRegistry;
+ private TimeSpan? _timeout;
// properties
///
@@ -64,5 +67,14 @@ public IBsonSerializerRegistry SerializerRegistry
get { return _serializerRegistry; }
set { _serializerRegistry = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/DeleteOptions.cs b/src/MongoDB.Driver/DeleteOptions.cs
index e8e31e98758..385bea2d8fc 100644
--- a/src/MongoDB.Driver/DeleteOptions.cs
+++ b/src/MongoDB.Driver/DeleteOptions.cs
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -27,6 +29,7 @@ public sealed class DeleteOptions
private BsonValue _comment;
private BsonValue _hint;
private BsonDocument _let;
+ private TimeSpan? _timeout;
// properties
///
@@ -64,5 +67,14 @@ public BsonDocument Let
get { return _let; }
set { _let = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/DistinctOptions.cs b/src/MongoDB.Driver/DistinctOptions.cs
index 5aee87e814e..12cffefc521 100644
--- a/src/MongoDB.Driver/DistinctOptions.cs
+++ b/src/MongoDB.Driver/DistinctOptions.cs
@@ -28,6 +28,7 @@ public sealed class DistinctOptions
private Collation _collation;
private BsonValue _comment;
private TimeSpan? _maxTime;
+ private TimeSpan? _timeout;
// properties
///
@@ -51,10 +52,20 @@ public BsonValue Comment
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/DropCollectionOptions.cs b/src/MongoDB.Driver/DropCollectionOptions.cs
index 8c3e13bb483..3e72ce31f6f 100644
--- a/src/MongoDB.Driver/DropCollectionOptions.cs
+++ b/src/MongoDB.Driver/DropCollectionOptions.cs
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -23,6 +25,7 @@ namespace MongoDB.Driver
public class DropCollectionOptions
{
private BsonDocument _encryptedFields;
+ private TimeSpan? _timeout;
///
/// Gets or sets encrypted fields.
@@ -32,5 +35,14 @@ public BsonDocument EncryptedFields
get { return _encryptedFields; }
set { _encryptedFields = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/DropIndexOptions.cs b/src/MongoDB.Driver/DropIndexOptions.cs
index d345fc0cb48..e4e4060e607 100644
--- a/src/MongoDB.Driver/DropIndexOptions.cs
+++ b/src/MongoDB.Driver/DropIndexOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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,6 +26,7 @@ public class DropIndexOptions
{
private BsonValue _comment;
private TimeSpan? _maxTime;
+ private TimeSpan? _timeout;
///
/// Gets or sets the comment.
@@ -43,10 +44,20 @@ public BsonValue Comment
/// Gets or sets the maximum time.
///
/// The maximum time.
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/EstimatedDocumentCountOptions.cs b/src/MongoDB.Driver/EstimatedDocumentCountOptions.cs
index 2789601d1da..2dc5740075e 100644
--- a/src/MongoDB.Driver/EstimatedDocumentCountOptions.cs
+++ b/src/MongoDB.Driver/EstimatedDocumentCountOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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,6 +27,7 @@ public sealed class EstimatedDocumentCountOptions
// private fields
private BsonValue _comment;
private TimeSpan? _maxTime;
+ private TimeSpan? _timeout;
// public properties
///
@@ -41,10 +42,20 @@ public BsonValue Comment
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/FindFluent.cs b/src/MongoDB.Driver/FindFluent.cs
index cc25e841b29..f8ab83f322a 100644
--- a/src/MongoDB.Driver/FindFluent.cs
+++ b/src/MongoDB.Driver/FindFluent.cs
@@ -133,7 +133,9 @@ public override IFindFluent Project(P
Limit = _options.Limit,
Max = _options.Max,
MaxAwaitTime = _options.MaxAwaitTime,
+#pragma warning disable CS0618 // Type or member is obsolete
MaxTime = _options.MaxTime,
+#pragma warning restore CS0618 // Type or member is obsolete
Min = _options.Min,
NoCursorTimeout = _options.NoCursorTimeout,
#pragma warning disable 618
@@ -144,6 +146,7 @@ public override IFindFluent Project(P
ShowRecordId = _options.ShowRecordId,
Skip = _options.Skip,
Sort = _options.Sort,
+ Timeout = _options.Timeout,
TranslationOptions = _options.TranslationOptions
};
return new FindFluent(_session, _collection, _filter, newOptions);
@@ -227,10 +230,12 @@ public override string ToString(ExpressionTranslationOptions translationOptions)
sb.Append(".limit(" + _options.Limit.Value.ToString() + ")");
}
+#pragma warning disable CS0618 // Type or member is obsolete
if (_options.MaxTime != null)
{
sb.Append(".maxTime(" + _options.MaxTime.Value.TotalMilliseconds + ")");
}
+#pragma warning restore CS0618 // Type or member is obsolete
if (_options.Hint != null)
{
@@ -273,8 +278,11 @@ private CountOptions CreateCountOptions()
Collation = _options.Collation,
Hint = _options.Hint,
Limit = _options.Limit,
+#pragma warning disable CS0618 // Type or member is obsolete
MaxTime = _options.MaxTime,
- Skip = _options.Skip
+#pragma warning restore CS0618 // Type or member is obsolete
+ Skip = _options.Skip,
+ Timeout = _options.Timeout
};
}
diff --git a/src/MongoDB.Driver/FindOneAndDeleteOptions.cs b/src/MongoDB.Driver/FindOneAndDeleteOptions.cs
index 7cb6f5317fa..3a50bb2c27a 100644
--- a/src/MongoDB.Driver/FindOneAndDeleteOptions.cs
+++ b/src/MongoDB.Driver/FindOneAndDeleteOptions.cs
@@ -34,6 +34,7 @@ public class FindOneAndDeleteOptions
private TimeSpan? _maxTime;
private ProjectionDefinition _projection;
private SortDefinition _sort;
+ private TimeSpan? _timeout;
// properties
///
@@ -75,6 +76,7 @@ public BsonDocument Let
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
@@ -98,6 +100,15 @@ public SortDefinition Sort
get { return _sort; }
set { _sort = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
///
diff --git a/src/MongoDB.Driver/FindOneAndReplaceOptions.cs b/src/MongoDB.Driver/FindOneAndReplaceOptions.cs
index bca48a2e621..c6353cc3105 100644
--- a/src/MongoDB.Driver/FindOneAndReplaceOptions.cs
+++ b/src/MongoDB.Driver/FindOneAndReplaceOptions.cs
@@ -37,6 +37,7 @@ public class FindOneAndReplaceOptions
private ProjectionDefinition _projection;
private ReturnDocument _returnDocument;
private SortDefinition _sort;
+ private TimeSpan? _timeout;
// constructors
///
@@ -105,6 +106,7 @@ public bool IsUpsert
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
@@ -137,6 +139,15 @@ public SortDefinition Sort
get { return _sort; }
set { _sort = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
///
diff --git a/src/MongoDB.Driver/FindOneAndUpdateOptions.cs b/src/MongoDB.Driver/FindOneAndUpdateOptions.cs
index 683156671da..ba976fcf635 100644
--- a/src/MongoDB.Driver/FindOneAndUpdateOptions.cs
+++ b/src/MongoDB.Driver/FindOneAndUpdateOptions.cs
@@ -39,6 +39,7 @@ public class FindOneAndUpdateOptions
private ProjectionDefinition _projection;
private ReturnDocument _returnDocument;
private SortDefinition _sort;
+ private TimeSpan? _timeout;
// constructors
///
@@ -119,6 +120,7 @@ public BsonDocument Let
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
@@ -151,6 +153,15 @@ public SortDefinition Sort
get { return _sort; }
set { _sort = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
///
diff --git a/src/MongoDB.Driver/FindOptions.cs b/src/MongoDB.Driver/FindOptions.cs
index 3ceb5cdfdaa..29569dcdb23 100644
--- a/src/MongoDB.Driver/FindOptions.cs
+++ b/src/MongoDB.Driver/FindOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2015-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.
@@ -41,6 +41,7 @@ public abstract class FindOptionsBase
private bool? _oplogReplay;
private bool? _returnKey;
private bool? _showRecordId;
+ private TimeSpan? _timeout;
private ExpressionTranslationOptions _translationOptions;
// constructors
@@ -146,6 +147,7 @@ public TimeSpan? MaxAwaitTime
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
@@ -198,6 +200,15 @@ public bool? ShowRecordId
set { _showRecordId = value; }
}
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
+
///
/// Gets or sets the translation options.
///
diff --git a/src/MongoDB.Driver/GridFS/GridFSBucket.cs b/src/MongoDB.Driver/GridFS/GridFSBucket.cs
index 7bd029044b8..7e65af290a3 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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
options = options ?? new GridFSUploadOptions();
using (var sourceStream = new MemoryStream(source))
diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs
index 23f5e48f877..d3c400afd76 100644
--- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs
+++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs
@@ -197,7 +197,7 @@ private void GetFirstBatch(CancellationToken cancellationToken)
{
var operation = CreateFirstBatchOperation();
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
_cursor = operation.Execute(operationContext, Binding);
GetNextBatch(cancellationToken);
}
@@ -206,7 +206,7 @@ private async Task GetFirstBatchAsync(CancellationToken cancellationToken)
{
var operation = CreateFirstBatchOperation();
// TODO: CSOT implement proper way to obtain the operationContext
- var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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 f77fc81f56f..9b21d21e476 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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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 843412df7ef..921bbac4232 100644
--- a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs
+++ b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs
@@ -173,7 +173,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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(null, cancellationToken);
using (var cursor = operation.Execute(operationContext, Binding))
{
var documents = cursor.ToList();
@@ -186,7 +186,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(Timeout.InfiniteTimeSpan, cancellationToken);
+ var operationContext = new OperationContext(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/IInheritableMongoClientSettings.cs b/src/MongoDB.Driver/IInheritableMongoClientSettings.cs
index 04eb99990f3..2e54fda9d4c 100644
--- a/src/MongoDB.Driver/IInheritableMongoClientSettings.cs
+++ b/src/MongoDB.Driver/IInheritableMongoClientSettings.cs
@@ -15,7 +15,6 @@
using System;
using System.Text;
-using MongoDB.Bson;
namespace MongoDB.Driver
{
@@ -24,6 +23,7 @@ internal interface IInheritableMongoClientSettings
ReadConcern ReadConcern { get; }
UTF8Encoding ReadEncoding { get; }
ReadPreference ReadPreference { get; }
+ TimeSpan? Timeout { get; }
WriteConcern WriteConcern { get; }
UTF8Encoding WriteEncoding { get; }
}
diff --git a/src/MongoDB.Driver/IMongoClientExtensions.cs b/src/MongoDB.Driver/IMongoClientExtensions.cs
index d2dd23c498c..edf59ca8b4e 100644
--- a/src/MongoDB.Driver/IMongoClientExtensions.cs
+++ b/src/MongoDB.Driver/IMongoClientExtensions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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.
@@ -18,7 +18,6 @@
using MongoDB.Bson;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Misc;
-using MongoDB.Driver.Core.Operations;
namespace MongoDB.Driver
{
diff --git a/src/MongoDB.Driver/IMongoCollectionExtensions.cs b/src/MongoDB.Driver/IMongoCollectionExtensions.cs
index fe5277a10d3..aa519ea5570 100644
--- a/src/MongoDB.Driver/IMongoCollectionExtensions.cs
+++ b/src/MongoDB.Driver/IMongoCollectionExtensions.cs
@@ -1192,7 +1192,9 @@ private static IFindFluent FindHelper(IClientSe
Let = options.Let,
Max = options.Max,
MaxAwaitTime = options.MaxAwaitTime,
+#pragma warning disable CS0618 // Type or member is obsolete
MaxTime = options.MaxTime,
+#pragma warning restore CS0618 // Type or member is obsolete
Min = options.Min,
NoCursorTimeout = options.NoCursorTimeout,
#pragma warning disable 618
@@ -1200,6 +1202,7 @@ private static IFindFluent FindHelper(IClientSe
#pragma warning restore 618
ReturnKey = options.ReturnKey,
ShowRecordId = options.ShowRecordId,
+ Timeout = options.Timeout,
TranslationOptions = options.TranslationOptions
};
}
diff --git a/src/MongoDB.Driver/IMongoDatabaseExtensions.cs b/src/MongoDB.Driver/IMongoDatabaseExtensions.cs
index 81c1bb67174..931736b6c9d 100644
--- a/src/MongoDB.Driver/IMongoDatabaseExtensions.cs
+++ b/src/MongoDB.Driver/IMongoDatabaseExtensions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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.
diff --git a/src/MongoDB.Driver/IOperationExecutor.cs b/src/MongoDB.Driver/IOperationExecutor.cs
index b935561469f..b64c2380776 100644
--- a/src/MongoDB.Driver/IOperationExecutor.cs
+++ b/src/MongoDB.Driver/IOperationExecutor.cs
@@ -25,29 +25,31 @@ internal interface IOperationExecutor : IDisposable
TResult ExecuteReadOperation(
IClientSessionHandle session,
IReadOperation operation,
- ReadOperationOptions options,
+ ReadPreference readPreference,
bool allowChannelPinning,
+ TimeSpan? timeout,
CancellationToken cancellationToken);
Task ExecuteReadOperationAsync(
IClientSessionHandle session,
IReadOperation operation,
- ReadOperationOptions options,
+ ReadPreference readPreference,
bool allowChannelPinning,
+ TimeSpan? timeout,
CancellationToken cancellationToken);
TResult ExecuteWriteOperation(
IClientSessionHandle session,
IWriteOperation operation,
- WriteOperationOptions options,
bool allowChannelPinning,
+ TimeSpan? timeout,
CancellationToken cancellationToken);
Task ExecuteWriteOperationAsync(
IClientSessionHandle session,
IWriteOperation operation,
- WriteOperationOptions options,
bool allowChannelPinning,
+ TimeSpan? timeout,
CancellationToken cancellationToken);
IClientSessionHandle StartImplicitSession();
diff --git a/src/MongoDB.Driver/InsertManyOptions.cs b/src/MongoDB.Driver/InsertManyOptions.cs
index 088fda4723a..07d0d8df773 100644
--- a/src/MongoDB.Driver/InsertManyOptions.cs
+++ b/src/MongoDB.Driver/InsertManyOptions.cs
@@ -11,9 +11,12 @@
* 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;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -26,6 +29,7 @@ public sealed class InsertManyOptions
private bool? _bypassDocumentValidation;
private BsonValue _comment;
private bool _isOrdered;
+ private TimeSpan? _timeout;
// constructors
///
@@ -63,5 +67,14 @@ public bool IsOrdered
get { return _isOrdered; }
set { _isOrdered = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/InsertOneOptions.cs b/src/MongoDB.Driver/InsertOneOptions.cs
index 3f2ddf773ba..ffebe926df7 100644
--- a/src/MongoDB.Driver/InsertOneOptions.cs
+++ b/src/MongoDB.Driver/InsertOneOptions.cs
@@ -11,9 +11,12 @@
* 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;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -22,10 +25,10 @@ namespace MongoDB.Driver
///
public sealed class InsertOneOptions
{
- private BsonValue _comment;
-
// private fields
private bool? _bypassDocumentValidation;
+ private BsonValue _comment;
+ private TimeSpan? _timeout;
// public properties
///
@@ -45,5 +48,14 @@ public BsonValue Comment
get { return _comment; }
set { _comment = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ListCollectionNamesOptions.cs b/src/MongoDB.Driver/ListCollectionNamesOptions.cs
index ae1b89308c7..61385a179b4 100644
--- a/src/MongoDB.Driver/ListCollectionNamesOptions.cs
+++ b/src/MongoDB.Driver/ListCollectionNamesOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2018-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,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -26,6 +28,7 @@ public sealed class ListCollectionNamesOptions
private bool? authorizedCollections;
private BsonValue _comment;
private FilterDefinition _filter;
+ private TimeSpan? _timeout;
// properties
///
@@ -54,5 +57,14 @@ public FilterDefinition Filter
get { return _filter; }
set { _filter = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ListCollectionsOptions.cs b/src/MongoDB.Driver/ListCollectionsOptions.cs
index 218fcd03655..3bff8742ea9 100644
--- a/src/MongoDB.Driver/ListCollectionsOptions.cs
+++ b/src/MongoDB.Driver/ListCollectionsOptions.cs
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -26,6 +28,7 @@ public sealed class ListCollectionsOptions
private int? _batchSize;
private BsonValue _comment;
private FilterDefinition _filter;
+ private TimeSpan? _timeout;
// properties
///
@@ -54,5 +57,14 @@ public FilterDefinition Filter
get { return _filter; }
set { _filter = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ListDatabaseNamesOptions.cs b/src/MongoDB.Driver/ListDatabaseNamesOptions.cs
index 6e3d696dcf0..44e5bedb57f 100644
--- a/src/MongoDB.Driver/ListDatabaseNamesOptions.cs
+++ b/src/MongoDB.Driver/ListDatabaseNamesOptions.cs
@@ -1,4 +1,4 @@
-/* Copyright 2020-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,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -26,6 +28,7 @@ public sealed class ListDatabaseNamesOptions
private bool? _authorizedDatabases;
private BsonValue _comment;
private FilterDefinition _filter;
+ private TimeSpan? _timeout;
// properties
///
@@ -54,5 +57,14 @@ public FilterDefinition Filter
get { return _filter; }
set { _filter = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ListDatabasesOptions.cs b/src/MongoDB.Driver/ListDatabasesOptions.cs
index 9fc9bb550ba..9194e2da82e 100644
--- a/src/MongoDB.Driver/ListDatabasesOptions.cs
+++ b/src/MongoDB.Driver/ListDatabasesOptions.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.
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -27,6 +29,7 @@ public sealed class ListDatabasesOptions
private BsonValue _comment;
private FilterDefinition _filter;
private bool? _nameOnly;
+ private TimeSpan? _timeout;
// properties
///
@@ -64,5 +67,14 @@ public bool? NameOnly
get { return _nameOnly; }
set { _nameOnly = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/ListIndexesOptions.cs b/src/MongoDB.Driver/ListIndexesOptions.cs
index 4df3bcc77bf..d5307be8bcc 100644
--- a/src/MongoDB.Driver/ListIndexesOptions.cs
+++ b/src/MongoDB.Driver/ListIndexesOptions.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.
@@ -13,7 +13,9 @@
* limitations under the License.
*/
+using System;
using MongoDB.Bson;
+using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
@@ -24,6 +26,7 @@ public sealed class ListIndexesOptions
{
private int? _batchSize;
private BsonValue _comment;
+ private TimeSpan? _timeout;
///
/// Gets or sets the batch size.
@@ -42,5 +45,14 @@ public BsonValue Comment
get { return _comment; }
set { _comment = value; }
}
+
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
}
}
diff --git a/src/MongoDB.Driver/MapReduceOptions.cs b/src/MongoDB.Driver/MapReduceOptions.cs
index 53075a94f60..b898f58b55d 100644
--- a/src/MongoDB.Driver/MapReduceOptions.cs
+++ b/src/MongoDB.Driver/MapReduceOptions.cs
@@ -40,6 +40,7 @@ public sealed class MapReduceOptions
private IBsonSerializer _resultSerializer;
private BsonDocument _scope;
private SortDefinition _sort;
+ private TimeSpan? _timeout;
private bool? _verbose;
// properties
@@ -101,6 +102,7 @@ public long? Limit
///
/// Gets or sets the maximum time.
///
+ [Obsolete("MaxTime is obsolete and will be removed in a future version. Use Timeout instead.")]
public TimeSpan? MaxTime
{
get { return _maxTime; }
@@ -143,6 +145,15 @@ public SortDefinition Sort
set { _sort = value; }
}
+ ///
+ /// Gets or sets the operation timeout.
+ ///
+ public TimeSpan? Timeout
+ {
+ get => _timeout;
+ set => _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
+
///
/// Gets or sets whether to include timing information.
///
diff --git a/src/MongoDB.Driver/MongoClient.cs b/src/MongoDB.Driver/MongoClient.cs
index 0df21ba32cc..4fde2d760bd 100644
--- a/src/MongoDB.Driver/MongoClient.cs
+++ b/src/MongoDB.Driver/MongoClient.cs
@@ -45,8 +45,6 @@ public sealed class MongoClient : IMongoClient
private readonly IOperationExecutor _operationExecutor;
private readonly MongoClientSettings _settings;
private readonly ILogger _logger;
- private readonly ReadOperationOptions _readOperationOptions;
- private readonly WriteOperationOptions _writeOperationOptions;
// constructors
///
@@ -92,9 +90,6 @@ internal MongoClient(MongoClientSettings settings, Func();
_cluster = _settings.ClusterSource.Get(_settings.ToClusterKey());
_operationExecutor = _operationExecutorFactory(this);
- // TODO: CSOT populate the timeout from settings
- _readOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan, DefaultReadPreference: _settings.ReadPreference);
- _writeOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan);
if (settings.AutoEncryptionOptions != null)
{
@@ -149,7 +144,7 @@ public ClientBulkWriteResult BulkWrite(IClientSessionHandle session, IReadOnlyLi
Ensure.IsNotNull(session, nameof(session));
ThrowIfDisposed();
var operation = CreateClientBulkWriteOperation(models, options);
- return ExecuteWriteOperation(session, operation, cancellationToken);
+ return ExecuteWriteOperation(session, operation, options?.Timeout, cancellationToken);
}
///
@@ -166,7 +161,7 @@ public Task BulkWriteAsync(IClientSessionHandle session,
Ensure.IsNotNull(session, nameof(session));
ThrowIfDisposed();
var operation = CreateClientBulkWriteOperation(models, options);
- return ExecuteWriteOperationAsync(session, operation, cancellationToken);
+ return ExecuteWriteOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
///
@@ -213,7 +208,8 @@ public void DropDatabase(IClientSessionHandle session, string name, Cancellation
Ensure.IsNotNull(session, nameof(session));
ThrowIfDisposed();
var operation = CreateDropDatabaseOperation(name);
- ExecuteWriteOperation(session, operation, cancellationToken);
+ // TODO: CSOT: find a way to add timeout parameter to the interface method
+ ExecuteWriteOperation(session, operation, null, cancellationToken);
}
///
@@ -230,7 +226,8 @@ public Task DropDatabaseAsync(IClientSessionHandle session, string name, Cancell
Ensure.IsNotNull(session, nameof(session));
ThrowIfDisposed();
var opertion = CreateDropDatabaseOperation(name);
- return ExecuteWriteOperationAsync(session, opertion, cancellationToken);
+ // TODO: CSOT: find a way to add timeout parameter to the interface method
+ return ExecuteWriteOperationAsync(session, opertion, null, cancellationToken);
}
///
@@ -344,7 +341,7 @@ public IAsyncCursor ListDatabases(
ThrowIfDisposed();
Ensure.IsNotNull(session, nameof(session));
var operation = CreateListDatabasesOperation(options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
///
@@ -380,7 +377,7 @@ public Task> ListDatabasesAsync(
Ensure.IsNotNull(session, nameof(session));
ThrowIfDisposed();
var operation = CreateListDatabasesOperation(options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
///
@@ -421,7 +418,7 @@ public IChangeStreamCursor Watch(
Ensure.IsNotNull(pipeline, nameof(pipeline));
ThrowIfDisposed();
var operation = CreateChangeStreamOperation(pipeline, options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
///
@@ -446,7 +443,7 @@ public Task> WatchAsync(
Ensure.IsNotNull(pipeline, nameof(pipeline));
ThrowIfDisposed();
var operation = CreateChangeStreamOperation(pipeline, options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
///
@@ -549,6 +546,7 @@ private ListDatabasesOptions CreateListDatabasesOptionsFromListDatabaseNamesOpti
listDatabasesOptions.AuthorizedDatabases = options.AuthorizedDatabases;
listDatabasesOptions.Filter = options.Filter;
listDatabasesOptions.Comment = options.Comment;
+ listDatabasesOptions.Timeout = options.Timeout;
}
return listDatabasesOptions;
@@ -565,17 +563,24 @@ private ChangeStreamOperation CreateChangeStreamOperation(
_settings.RetryReads,
_settings.TranslationOptions);
- private TResult ExecuteReadOperation(IClientSessionHandle session, IReadOperation operation, CancellationToken cancellationToken)
- => _operationExecutor.ExecuteReadOperation(session, operation, _readOperationOptions, false, cancellationToken);
+ private TResult ExecuteReadOperation(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken)
+ {
+ var readPreference = session.GetEffectiveReadPreference(_settings.ReadPreference);
+ return _operationExecutor.ExecuteReadOperation(session, operation, readPreference, false, timeout ?? _settings.Timeout, cancellationToken);
+ }
+
+ private Task ExecuteReadOperationAsync(IClientSessionHandle session, IReadOperation operation, TimeSpan? timeout, CancellationToken cancellationToken)
+ {
+ var readPreference = session.GetEffectiveReadPreference(_settings.ReadPreference);
+ return _operationExecutor.ExecuteReadOperationAsync(session, operation, readPreference, false, timeout ?? _settings.Timeout, cancellationToken);
+ }
- private Task ExecuteReadOperationAsync(IClientSessionHandle session, IReadOperation operation, CancellationToken cancellationToken)
- => _operationExecutor.ExecuteReadOperationAsync(session, operation, _readOperationOptions, false, cancellationToken);
+ private TResult ExecuteWriteOperation(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, CancellationToken cancellationToken)
+ => _operationExecutor.ExecuteWriteOperation(session, operation, false, timeout ?? _settings.Timeout, cancellationToken);
- private TResult ExecuteWriteOperation(IClientSessionHandle session, IWriteOperation operation, CancellationToken cancellationToken)
- => _operationExecutor.ExecuteWriteOperation(session, operation, _writeOperationOptions, false, cancellationToken);
+ private Task ExecuteWriteOperationAsync(IClientSessionHandle session, IWriteOperation operation, TimeSpan? timeout, CancellationToken cancellationToken)
+ => _operationExecutor.ExecuteWriteOperationAsync(session, operation, false, timeout ?? _settings.Timeout, cancellationToken);
- private Task ExecuteWriteOperationAsync(IClientSessionHandle session, IWriteOperation operation, CancellationToken cancellationToken)
- => _operationExecutor.ExecuteWriteOperationAsync(session, operation, _writeOperationOptions, false, cancellationToken);
private MessageEncoderSettings GetMessageEncoderSettings()
{
diff --git a/src/MongoDB.Driver/MongoClientSettings.cs b/src/MongoDB.Driver/MongoClientSettings.cs
index d7da362ca92..fd76f48f141 100644
--- a/src/MongoDB.Driver/MongoClientSettings.cs
+++ b/src/MongoDB.Driver/MongoClientSettings.cs
@@ -22,7 +22,6 @@
using MongoDB.Driver.Core.Configuration;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.Servers;
-using MongoDB.Driver.Encryption;
using MongoDB.Shared;
namespace MongoDB.Driver
@@ -74,6 +73,7 @@ public class MongoClientSettings : IEquatable, IInheritable
private int _srvMaxHosts;
private string _srvServiceName;
private SslSettings _sslSettings;
+ private TimeSpan? _timeout;
private ExpressionTranslationOptions _translationOptions;
private bool _useTls;
private int _waitQueueSize;
@@ -125,6 +125,7 @@ public MongoClientSettings()
_srvMaxHosts = 0;
_srvServiceName = MongoInternalDefaults.MongoClientSettings.SrvServiceName;
_sslSettings = null;
+ _timeout = System.Threading.Timeout.InfiniteTimeSpan;
_translationOptions = null;
_useTls = false;
#pragma warning disable 618
@@ -666,6 +667,19 @@ public SslSettings SslSettings
}
}
+ ///
+ /// Gets or sets the per-operation timeout
+ ///
+ public TimeSpan? Timeout
+ {
+ get { return _timeout; }
+ set
+ {
+ ThrowIfFrozen();
+ _timeout = Ensure.IsNullOrValidTimeout(value, nameof(Timeout));
+ }
+ }
+
///
/// Gets or sets the translation options.
///
@@ -881,6 +895,7 @@ public static MongoClientSettings FromUrl(MongoUrl url)
{
clientSettings.SslSettings = new SslSettings { CheckCertificateRevocation = false };
}
+ clientSettings.Timeout = url.Timeout;
clientSettings.UseTls = url.UseTls;
#pragma warning disable 618
clientSettings.WaitQueueSize = url.ComputedWaitQueueSize;
@@ -935,6 +950,7 @@ public MongoClientSettings Clone()
clone._srvMaxHosts = _srvMaxHosts;
clone._srvServiceName = _srvServiceName;
clone._sslSettings = (_sslSettings == null) ? null : _sslSettings.Clone();
+ clone._timeout = _timeout;
clone._translationOptions = _translationOptions;
clone._useTls = _useTls;
clone._waitQueueSize = _waitQueueSize;
@@ -1004,6 +1020,7 @@ public override bool Equals(object obj)
_srvMaxHosts == rhs._srvMaxHosts &&
_srvServiceName == rhs._srvServiceName &&
_sslSettings == rhs._sslSettings &&
+ _timeout == rhs._timeout &&
object.Equals(_translationOptions, rhs._translationOptions) &&
_useTls == rhs._useTls &&
_waitQueueSize == rhs._waitQueueSize &&
@@ -1091,6 +1108,7 @@ public override int GetHashCode()
.Hash(_srvMaxHosts)
.Hash(_srvServiceName)
.Hash(_sslSettings)
+ .Hash(_timeout)
.Hash(_translationOptions)
.Hash(_useTls)
.Hash(_waitQueueSize)
@@ -1172,6 +1190,10 @@ public override string ToString()
{
sb.AppendFormat("SslSettings={0};", _sslSettings);
}
+ if(_timeout != System.Threading.Timeout.InfiniteTimeSpan)
+ {
+ sb.AppendFormat("Timeout={0};", _timeout);
+ }
sb.AppendFormat("Tls={0};", _useTls);
sb.AppendFormat("TlsInsecure={0};", _allowInsecureTls);
if (_translationOptions != null)
diff --git a/src/MongoDB.Driver/MongoCollectionBase.cs b/src/MongoDB.Driver/MongoCollectionBase.cs
index 8a38110a899..b7c937de1c0 100644
--- a/src/MongoDB.Driver/MongoCollectionBase.cs
+++ b/src/MongoDB.Driver/MongoCollectionBase.cs
@@ -164,7 +164,8 @@ private DeleteResult DeleteMany(FilterDefinition filter, DeleteOption
var bulkWriteOptions = new BulkWriteOptions
{
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = bulkWriteFunc(new[] { model }, bulkWriteOptions);
return DeleteResult.FromCore(result);
@@ -205,7 +206,8 @@ private async Task DeleteManyAsync(FilterDefinition fil
var bulkWriteOptions = new BulkWriteOptions
{
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = await bulkWriteFuncAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false);
return DeleteResult.FromCore(result);
@@ -246,7 +248,8 @@ private DeleteResult DeleteOne(FilterDefinition filter, DeleteOptions
var bulkWriteOptions = new BulkWriteOptions
{
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = bulkWrite(new[] { model }, bulkWriteOptions);
return DeleteResult.FromCore(result);
@@ -287,7 +290,8 @@ private async Task DeleteOneAsync(FilterDefinition filt
var bulkWriteOptions = new BulkWriteOptions
{
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = await bulkWriteAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false);
return DeleteResult.FromCore(result);
@@ -435,7 +439,8 @@ private void InsertOne(TDocument document, InsertOneOptions options, Action documents, InsertManyOptions opti
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- IsOrdered = options.IsOrdered
+ IsOrdered = options.IsOrdered,
+ Timeout = options.Timeout
};
bulkWrite(models, bulkWriteOptions);
}
@@ -524,7 +531,8 @@ private Task InsertManyAsync(IEnumerable documents, InsertManyOptions
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- IsOrdered = options.IsOrdered
+ IsOrdered = options.IsOrdered,
+ Timeout = options.Timeout
};
return bulkWriteAsync(models, bulkWriteOptions);
}
@@ -598,7 +606,8 @@ private ReplaceOneResult ReplaceOne(FilterDefinition filter, TDocumen
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = bulkWrite(new[] { model }, bulkWriteOptions);
return ReplaceOneResult.FromCore(result);
@@ -656,7 +665,8 @@ private async Task ReplaceOneAsync(FilterDefinition
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = await bulkWriteAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false);
return ReplaceOneResult.FromCore(result);
@@ -697,7 +707,8 @@ private UpdateResult UpdateMany(FilterDefinition filter, UpdateDefini
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = bulkWrite(new[] { model }, bulkWriteOptions);
return UpdateResult.FromCore(result);
@@ -738,7 +749,8 @@ private async Task UpdateManyAsync(FilterDefinition fil
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = await bulkWriteAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false);
return UpdateResult.FromCore(result);
@@ -784,7 +796,8 @@ private UpdateResult UpdateOne(FilterDefinition filter, UpdateDefinit
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = bulkWrite(new[] { model }, bulkWriteOptions);
return UpdateResult.FromCore(result);
@@ -830,7 +843,8 @@ private async Task UpdateOneAsync(FilterDefinition filt
{
BypassDocumentValidation = options.BypassDocumentValidation,
Comment = options.Comment,
- Let = options.Let
+ Let = options.Let,
+ Timeout = options.Timeout
};
var result = await bulkWriteAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false);
return UpdateResult.FromCore(result);
diff --git a/src/MongoDB.Driver/MongoCollectionImpl.cs b/src/MongoDB.Driver/MongoCollectionImpl.cs
index 8ad05198a18..310d2ca29c3 100644
--- a/src/MongoDB.Driver/MongoCollectionImpl.cs
+++ b/src/MongoDB.Driver/MongoCollectionImpl.cs
@@ -39,8 +39,6 @@ internal sealed class MongoCollectionImpl : MongoCollectionBase _documentSerializer;
private readonly MongoCollectionSettings _settings;
- private readonly ReadOperationOptions _readOperationOptions;
- private readonly WriteOperationOptions _writeOperationOptions;
// constructors
public MongoCollectionImpl(IMongoDatabase database, CollectionNamespace collectionNamespace, MongoCollectionSettings settings, IClusterInternal cluster, IOperationExecutor operationExecutor)
@@ -58,9 +56,6 @@ private MongoCollectionImpl(IMongoDatabase database, CollectionNamespace collect
_documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer));
_messageEncoderSettings = GetMessageEncoderSettings();
- // TODO: CSOT populate the timeout from settings
- _readOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan, DefaultReadPreference: _settings.ReadPreference);
- _writeOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan);
}
// properties
@@ -114,13 +109,13 @@ public override IAsyncCursor Aggregate(IClientSessionHandle se
if (isAggregateToCollection)
{
var aggregateOperation = CreateAggregateToCollectionOperation(renderedPipeline, options);
- ExecuteWriteOperation(session, aggregateOperation, cancellationToken);
+ ExecuteWriteOperation(session, aggregateOperation, options.Timeout, cancellationToken);
return CreateAggregateToCollectionResultCursor(session, renderedPipeline, options);
}
else
{
var aggregateOperation = CreateAggregateOperation(renderedPipeline, options);
- return ExecuteReadOperation(session, aggregateOperation, cancellationToken);
+ return ExecuteReadOperation(session, aggregateOperation, options.Timeout, cancellationToken);
}
}
@@ -141,13 +136,13 @@ public override async Task> AggregateAsync(IClien
if (isAggregateToCollection)
{
var aggregateOperation = CreateAggregateToCollectionOperation(renderedPipeline, options);
- await ExecuteWriteOperationAsync(session, aggregateOperation, cancellationToken).ConfigureAwait(false);
+ await ExecuteWriteOperationAsync(session, aggregateOperation, options.Timeout, cancellationToken).ConfigureAwait(false);
return CreateAggregateToCollectionResultCursor(session, renderedPipeline, options);
}
else
{
var aggregateOperation = CreateAggregateOperation(renderedPipeline, options);
- return await ExecuteReadOperationAsync(session, aggregateOperation, cancellationToken).ConfigureAwait(false);
+ return await ExecuteReadOperationAsync(session, aggregateOperation, options.Timeout, cancellationToken).ConfigureAwait(false);
}
}
@@ -171,7 +166,7 @@ public override void AggregateToCollection(IClientSessionHandle session
}
var aggregateOperation = CreateAggregateToCollectionOperation(renderedPipeline, options);
- ExecuteWriteOperation(session, aggregateOperation, cancellationToken);
+ ExecuteWriteOperation(session, aggregateOperation, options.Timeout, cancellationToken);
}
public override async Task AggregateToCollectionAsync(PipelineDefinition pipeline, AggregateOptions options, CancellationToken cancellationToken = default)
@@ -194,7 +189,7 @@ public override Task AggregateToCollectionAsync(IClientSessionHandle se
}
var aggregateOperation = CreateAggregateToCollectionOperation(renderedPipeline, options);
- return ExecuteWriteOperationAsync(session, aggregateOperation, cancellationToken);
+ return ExecuteWriteOperationAsync(session, aggregateOperation, options.Timeout, cancellationToken);
}
public override BulkWriteResult BulkWrite(IEnumerable> requests, BulkWriteOptions options, CancellationToken cancellationToken = default)
@@ -216,7 +211,7 @@ public override BulkWriteResult BulkWrite(IClientSessionHandle sessio
var operation = CreateBulkWriteOperation(session, requestsArray, options);
try
{
- var result = ExecuteWriteOperation(session, operation, cancellationToken);
+ var result = ExecuteWriteOperation(session, operation, options?.Timeout, cancellationToken);
return BulkWriteResult.FromCore(result, requestsArray);
}
catch (MongoBulkWriteOperationException ex)
@@ -244,7 +239,7 @@ public override async Task> BulkWriteAsync(IClientSes
var operation = CreateBulkWriteOperation(session, requestsArray, options);
try
{
- var result = await ExecuteWriteOperationAsync(session, operation, cancellationToken).ConfigureAwait(false);
+ var result = await ExecuteWriteOperationAsync(session, operation, options?.Timeout, cancellationToken).ConfigureAwait(false);
return BulkWriteResult.FromCore(result, requestsArray);
}
catch (MongoBulkWriteOperationException ex)
@@ -267,7 +262,7 @@ public override long Count(IClientSessionHandle session, FilterDefinition CountAsync(IClientSessionHandle session, FilterDefini
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateCountOperation(filter, options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
public override long CountDocuments(FilterDefinition filter, CountOptions options, CancellationToken cancellationToken = default)
@@ -299,7 +294,7 @@ public override long CountDocuments(IClientSessionHandle session, FilterDefiniti
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateCountDocumentsOperation(filter, options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
public override async Task CountDocumentsAsync(FilterDefinition filter, CountOptions options, CancellationToken cancellationToken = default)
@@ -314,7 +309,7 @@ public override Task CountDocumentsAsync(IClientSessionHandle session, Fil
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateCountDocumentsOperation(filter, options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
public override IAsyncCursor Distinct(FieldDefinition field, FilterDefinition filter, DistinctOptions options, CancellationToken cancellationToken = default)
@@ -330,7 +325,7 @@ public override IAsyncCursor Distinct(IClientSessionHandle sessi
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateDistinctOperation(field, filter, options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
public override async Task> DistinctAsync(FieldDefinition field, FilterDefinition filter, DistinctOptions options, CancellationToken cancellationToken = default)
@@ -346,7 +341,7 @@ public override Task> DistinctAsync(IClientSessionH
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateDistinctOperation(field, filter, options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
public override IAsyncCursor DistinctMany(FieldDefinition> field, FilterDefinition filter, DistinctOptions options, CancellationToken cancellationToken = default)
@@ -362,7 +357,7 @@ public override IAsyncCursor DistinctMany(IClientSessionHandle ses
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateDistinctManyOperation(field, filter, options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
public override async Task> DistinctManyAsync(FieldDefinition> field, FilterDefinition filter, DistinctOptions options, CancellationToken cancellationToken = default)
@@ -378,21 +373,21 @@ public override Task> DistinctManyAsync(IClientSessio
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateDistinctManyOperation(field, filter, options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
public override long EstimatedDocumentCount(EstimatedDocumentCountOptions options, CancellationToken cancellationToken = default)
{
using var session = _operationExecutor.StartImplicitSession();
var operation = CreateEstimatedDocumentCountOperation(options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
public override async Task EstimatedDocumentCountAsync(EstimatedDocumentCountOptions options, CancellationToken cancellationToken = default)
{
using var session = _operationExecutor.StartImplicitSession();
var operation = CreateEstimatedDocumentCountOperation(options);
- return await ExecuteReadOperationAsync(session, operation, cancellationToken).ConfigureAwait(false);
+ return await ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken).ConfigureAwait(false);
}
public override IAsyncCursor FindSync(FilterDefinition filter, FindOptions options, CancellationToken cancellationToken = default)
@@ -407,7 +402,7 @@ public override IAsyncCursor FindSync(IClientSessionHa
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateFindOperation(filter, options);
- return ExecuteReadOperation(session, operation, cancellationToken);
+ return ExecuteReadOperation(session, operation, options?.Timeout, cancellationToken);
}
public override async Task> FindAsync(FilterDefinition filter, FindOptions options, CancellationToken cancellationToken = default)
@@ -422,7 +417,7 @@ public override Task> FindAsync(IClientSe
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateFindOperation(filter, options);
- return ExecuteReadOperationAsync(session, operation, cancellationToken);
+ return ExecuteReadOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
public override TProjection FindOneAndDelete(FilterDefinition filter, FindOneAndDeleteOptions options, CancellationToken cancellationToken = default)
@@ -437,7 +432,7 @@ public override TProjection FindOneAndDelete(IClientSessionHandle s
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateFindOneAndDeleteOperation(filter, options);
- return ExecuteWriteOperation(session, operation, cancellationToken);
+ return ExecuteWriteOperation(session, operation, options?.Timeout, cancellationToken);
}
public override async Task FindOneAndDeleteAsync(FilterDefinition filter, FindOneAndDeleteOptions options, CancellationToken cancellationToken = default)
@@ -452,7 +447,7 @@ public override Task FindOneAndDeleteAsync(IClientSess
Ensure.IsNotNull(filter, nameof(filter));
var operation = CreateFindOneAndDeleteOperation(filter, options);
- return ExecuteWriteOperationAsync(session, operation, cancellationToken);
+ return ExecuteWriteOperationAsync(session, operation, options?.Timeout, cancellationToken);
}
public override TProjection FindOneAndReplace