Esempio n. 1
0
            public Task <TResult> CommandAsync <TResult>(
                ICoreSession session,
                ReadPreference readPreference,
                DatabaseNamespace databaseNamespace,
                BsonDocument command,
                IElementNameValidator commandValidator,
                BsonDocument additionalOptions,
                Func <CommandResponseHandling> responseHandling,
                bool slaveOk,
                IBsonSerializer <TResult> resultSerializer,
                MessageEncoderSettings messageEncoderSettings,
                CancellationToken cancellationToken)
            {
                readPreference = GetEffectiveReadPreference(slaveOk, readPreference);
                var result = CommandAsync(
                    session,
                    readPreference,
                    databaseNamespace,
                    command,
                    null, // commandPayloads
                    commandValidator,
                    additionalOptions,
                    null, // postWriteAction
                    CommandResponseHandling.Return,
                    resultSerializer,
                    messageEncoderSettings,
                    cancellationToken);

                if (responseHandling != null && responseHandling() != CommandResponseHandling.Return)
                {
                    throw new NotSupportedException("This overload requires responseHandling to be 'Return'.");
                }

                return(result);
            }
Esempio n. 2
0
 private void MarkSessionDirtyIfNeeded(ICoreSession session, Exception ex)
 {
     if (ex is MongoConnectionException)
     {
         session.MarkDirty();
     }
 }
        // constructors
        public CommandUsingCommandMessageWireProtocol(
            ICoreSession session,
            ReadPreference readPreference,
            DatabaseNamespace databaseNamespace,
            BsonDocument command,
            IEnumerable <Type1CommandMessageSection> commandPayloads,
            IElementNameValidator commandValidator,
            BsonDocument additionalOptions,
            CommandResponseHandling responseHandling,
            IBsonSerializer <TCommandResult> resultSerializer,
            MessageEncoderSettings messageEncoderSettings,
            Action <IMessageEncoderPostProcessor> postWriteAction)
        {
            if (responseHandling != CommandResponseHandling.Return && responseHandling != CommandResponseHandling.NoResponseExpected)
            {
                throw new ArgumentException("CommandResponseHandling must be Return or NoneExpected.", nameof(responseHandling));
            }

            _session                = Ensure.IsNotNull(session, nameof(session));
            _readPreference         = readPreference;
            _databaseNamespace      = Ensure.IsNotNull(databaseNamespace, nameof(databaseNamespace));
            _command                = Ensure.IsNotNull(command, nameof(command));
            _commandPayloads        = commandPayloads?.ToList(); // can be null
            _commandValidator       = Ensure.IsNotNull(commandValidator, nameof(commandValidator));
            _additionalOptions      = additionalOptions;         // can be null
            _responseHandling       = responseHandling;
            _resultSerializer       = Ensure.IsNotNull(resultSerializer, nameof(resultSerializer));
            _messageEncoderSettings = messageEncoderSettings;
            _postWriteAction        = postWriteAction; // can be null
        }
 public static void AutoStartTransactionIfApplicable(this ICoreSession session)
 {
     if (!session.IsInTransaction && session.Options != null && session.Options.AutoStartTransaction)
     {
         session.StartTransaction();
     }
 }
Esempio n. 5
0
            public Task <TResult> CommandAsync <TResult>(
                ICoreSession session,
                ReadPreference readPreference,
                DatabaseNamespace databaseNamespace,
                BsonDocument command,
                IEnumerable <Type1CommandMessageSection> commandPayloads,
                IElementNameValidator commandValidator,
                BsonDocument additionalOptions,
                Action <IMessageEncoderPostProcessor> postWriteAction,
                CommandResponseHandling responseHandling,
                IBsonSerializer <TResult> resultSerializer,
                MessageEncoderSettings messageEncoderSettings,
                CancellationToken cancellationToken)
            {
                var protocol = new CommandWireProtocol <TResult>(
                    CreateClusterClockAdvancingCoreSession(session),
                    readPreference,
                    databaseNamespace,
                    command,
                    commandPayloads,
                    commandValidator,
                    additionalOptions,
                    postWriteAction,
                    responseHandling,
                    resultSerializer,
                    messageEncoderSettings);

                return(ExecuteProtocolAsync(protocol, cancellationToken));
            }
 internal static void UnpinServerIfNeededOnCommandException(ICoreSession session, Exception exception)
 {
     if (session.IsInTransaction && ShouldUnpinServerOnCommandException(exception))
     {
         session.CurrentTransaction.PinnedServer = null;
     }
 }
Esempio n. 7
0
        public static IDictionary <string, string> ToHeaders(this ICoreSession session)
        {
            if (session is null)
            {
                return(null);
            }
            var dictionary = new Dictionary <string, string>
            {
                { SessionConsts.CityId, session?.City?.Id },

                { SessionConsts.CompanyId, session?.Company?.Id?.AsStringOrDefault() },
                { SessionConsts.CompanyName, session?.Company?.Name },

                { SessionConsts.StoreId, session?.Store?.Id?.AsStringOrDefault() },
                { SessionConsts.StoreName, session?.Store?.Name },

                { SessionConsts.BrokerId, session?.Broker?.Id },
                { SessionConsts.BrokerName, session?.Broker?.Name },

                { SessionConsts.OrganizationId, session?.Organization?.Id },
                { SessionConsts.OrganizationName, session?.Organization?.Name },
                { SessionConsts.CurrentUserId, session?.User?.Id },
                { SessionConsts.CurrentUserName, session?.User?.Name }
            };

            return(dictionary);
        }
Esempio n. 8
0
            public Task <TResult> CommandAsync <TResult>(
                ICoreSession session,
                ReadPreference readPreference,
                DatabaseNamespace databaseNamespace,
                BsonDocument command,
                IElementNameValidator commandValidator,
                BsonDocument additionalOptions,
                Func <CommandResponseHandling> responseHandling,
                IBsonSerializer <TResult> resultSerializer,
                MessageEncoderSettings messageEncoderSettings,
                CancellationToken cancellationToken)
            {
                var protocol = new CommandWireProtocol <TResult>(
                    CreateClusterClockAdvancingCoreSession(session),
                    readPreference,
                    databaseNamespace,
                    command,
                    commandValidator,
                    additionalOptions,
                    responseHandling,
                    resultSerializer,
                    messageEncoderSettings);

                return(ExecuteProtocolAsync(protocol, cancellationToken));
            }
Esempio n. 9
0
 public Task <TResult> CommandAsync <TResult>(
     ICoreSession session,
     ReadPreference readPreference,
     DatabaseNamespace databaseNamespace,
     BsonDocument command,
     IElementNameValidator commandValidator,
     BsonDocument additionalOptions,
     Func <CommandResponseHandling> responseHandling,
     bool slaveOk,
     IBsonSerializer <TResult> resultSerializer,
     MessageEncoderSettings messageEncoderSettings,
     CancellationToken cancellationToken)
 {
     readPreference = GetEffectiveReadPreference(slaveOk, readPreference);
     return(CommandAsync(
                session,
                readPreference,
                databaseNamespace,
                command,
                commandValidator,
                additionalOptions,
                responseHandling,
                resultSerializer,
                messageEncoderSettings,
                cancellationToken));
 }
Esempio n. 10
0
 public TestMessage2Handler(ICoreSession session,
                            ICoreSessionProvider coreSessionProvider,
                            ITestServiceForTestMessage2 testServiceForTestMessage2)
 {
     _session                    = session;
     _coreSessionProvider        = coreSessionProvider;
     _testServiceForTestMessage2 = testServiceForTestMessage2;
 }
Esempio n. 11
0
        public static BsonDocument GetWriteConcernForWriteCommand(ICoreSession session, WriteConcern writeConcern)
        {
            if (!session.IsInTransaction && writeConcern != null && !writeConcern.IsServerDefault)
            {
                return(writeConcern.ToBsonDocument());
            }

            return(null);
        }
Esempio n. 12
0
        public static BsonDocument GetWriteConcernForCommand(ICoreSession session, WriteConcern writeConcern, SemanticVersion serverVersion, Feature requiredFeature)
        {
            if (!session.IsInTransaction && writeConcern != null && !writeConcern.IsServerDefault && requiredFeature.IsSupported(serverVersion))
            {
                return(writeConcern.ToBsonDocument());
            }

            return(null);
        }
Esempio n. 13
0
        public static BsonDocument GetReadConcernForSnapshotSesssion(ICoreSession session, ConnectionDescription connectionDescription)
        {
            if (AreSessionsSupported(connectionDescription) && session.IsSnapshot)
            {
                Feature.SnapshotReads.ThrowIfNotSupported(connectionDescription.MaxWireVersion);

                var readConcernDocument = ReadConcern.Snapshot.ToBsonDocument();
                if (session.SnapshotTime != null)
                {
                    readConcernDocument.Add("atClusterTime", session.SnapshotTime);
                }

                return(readConcernDocument);
            }

            return(null);
        }
Esempio n. 14
0
        // private static methods
        private static BsonDocument ToBsonDocument(ICoreSession session, ConnectionDescription connectionDescription, ReadConcern readConcern)
        {
            // causal consistency
            var shouldSendAfterClusterTime = AreSessionsSupported(connectionDescription) && session.IsCausallyConsistent && session.OperationTime != null;
            var shouldSendReadConcern      = !readConcern.IsServerDefault || shouldSendAfterClusterTime;

            if (shouldSendReadConcern)
            {
                var readConcernDocument = readConcern.ToBsonDocument();
                if (shouldSendAfterClusterTime)
                {
                    readConcernDocument.Add("afterClusterTime", session.OperationTime);
                }
                return(readConcernDocument);
            }

            return(null);
        }
Esempio n. 15
0
 // constructors
 public CommandUsingQueryMessageWireProtocol(
     ICoreSession session,
     ReadPreference readPreference,
     DatabaseNamespace databaseNamespace,
     BsonDocument command,
     IElementNameValidator commandValidator,
     BsonDocument additionalOptions,
     Func <CommandResponseHandling> responseHandling,
     IBsonSerializer <TCommandResult> resultSerializer,
     MessageEncoderSettings messageEncoderSettings)
 {
     _session                = Ensure.IsNotNull(session, nameof(session));
     _readPreference         = readPreference;
     _databaseNamespace      = Ensure.IsNotNull(databaseNamespace, nameof(databaseNamespace));
     _command                = Ensure.IsNotNull(command, nameof(command));
     _commandValidator       = Ensure.IsNotNull(commandValidator, nameof(commandValidator));
     _additionalOptions      = additionalOptions; // can be null
     _responseHandling       = responseHandling;
     _resultSerializer       = Ensure.IsNotNull(resultSerializer, nameof(resultSerializer));
     _messageEncoderSettings = messageEncoderSettings;
 }
        private int _previousRequestId;   // RequestId from the previous response

        // constructors
        public CommandUsingCommandMessageWireProtocol(
            ICoreSession session,
            ReadPreference readPreference,
            DatabaseNamespace databaseNamespace,
            BsonDocument command,
            IEnumerable <Type1CommandMessageSection> commandPayloads,
            IElementNameValidator commandValidator,
            BsonDocument additionalOptions,
            CommandResponseHandling responseHandling,
            IBsonSerializer <TCommandResult> resultSerializer,
            MessageEncoderSettings messageEncoderSettings,
            Action <IMessageEncoderPostProcessor> postWriteAction,
            ServerApi serverApi)
        {
            if (responseHandling != CommandResponseHandling.Return &&
                responseHandling != CommandResponseHandling.NoResponseExpected &&
                responseHandling != CommandResponseHandling.ExhaustAllowed)
            {
                throw new ArgumentException("CommandResponseHandling must be Return, NoneExpected or ExhaustAllowed.", nameof(responseHandling));
            }

            _session                = Ensure.IsNotNull(session, nameof(session));
            _readPreference         = readPreference;
            _databaseNamespace      = Ensure.IsNotNull(databaseNamespace, nameof(databaseNamespace));
            _command                = Ensure.IsNotNull(command, nameof(command));
            _commandPayloads        = commandPayloads?.ToList(); // can be null
            _commandValidator       = Ensure.IsNotNull(commandValidator, nameof(commandValidator));
            _additionalOptions      = additionalOptions;         // can be null
            _responseHandling       = responseHandling;
            _resultSerializer       = Ensure.IsNotNull(resultSerializer, nameof(resultSerializer));
            _messageEncoderSettings = messageEncoderSettings;
            _postWriteAction        = postWriteAction; // can be null
            _serverApi              = serverApi;       // can be null

            if (messageEncoderSettings != null)
            {
                _documentFieldDecryptor = messageEncoderSettings.GetOrDefault <IBinaryDocumentFieldDecryptor>(MessageEncoderSettingsName.BinaryDocumentFieldDecryptor, null);
                _documentFieldEncryptor = messageEncoderSettings.GetOrDefault <IBinaryCommandFieldEncryptor>(MessageEncoderSettingsName.BinaryDocumentFieldEncryptor, null);
            }
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="WrappingCoreSession" /> class.
 /// </summary>
 /// <param name="wrapped">The wrapped.</param>
 /// <param name="ownsWrapped">if set to <c>true</c> [owns wrapped].</param>
 public WrappingCoreSession(ICoreSession wrapped, bool ownsWrapped)
 {
     _wrapped     = Ensure.IsNotNull(wrapped, nameof(wrapped));
     _ownsWrapped = ownsWrapped;
 }
Esempio n. 18
0
        internal BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);

            return(new BsonDocument
            {
                { "geoSearch", _collectionNamespace.CollectionName },
                { "near", _near, _near != null },
                { "limit", () => _limit.Value, _limit.HasValue },
                { "maxDistance", () => _maxDistance.Value, _maxDistance.HasValue },
                { "search", _search, _search != null },
                { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
                { "readConcern", readConcern, readConcern != null }
            });
        }
Esempio n. 19
0
 private ICoreSession CreateClusterClockAdvancingCoreSession(ICoreSession session)
 {
     return(new ClusterClockAdvancingCoreSession(session, _server.ClusterClock));
 }
Esempio n. 20
0
 public static string GetCurrentUserName(this ICoreSession session) => session?.User?.Name;
Esempio n. 21
0
 public static string GetCurrentUserId(this ICoreSession session) => session?.User?.Id;
Esempio n. 22
0
        // methods
        internal BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            Feature.ReadConcern.ThrowIfNotSupported(connectionDescription.ServerVersion, _readConcern);
            Feature.Collation.ThrowIfNotSupported(connectionDescription.ServerVersion, _collation);

            var command = new BsonDocument
            {
                { "count", _collectionNamespace.CollectionName },
                { "query", _filter, _filter != null },
                { "limit", () => _limit.Value, _limit.HasValue },
                { "skip", () => _skip.Value, _skip.HasValue },
                { "hint", _hint, _hint != null },
                { "maxTimeMS", () => _maxTime.Value.TotalMilliseconds, _maxTime.HasValue },
                { "collation", () => _collation.ToBsonDocument(), _collation != null }
            };

            ReadConcernHelper.AppendReadConcern(command, _readConcern, connectionDescription, session);

            return(command);
        }
Esempio n. 23
0
        // methods
        internal BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);

            return(new BsonDocument
            {
                { "parallelCollectionScan", _collectionNamespace.CollectionName },
                { "numCursors", _numberOfCursors },
                { "readConcern", readConcern, readConcern != null }
            });
        }
        // methods
        internal BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            Feature.ReadConcern.ThrowIfNotSupported(connectionDescription.ServerVersion, _readConcern);
            Feature.Collation.ThrowIfNotSupported(connectionDescription.ServerVersion, _collation);

            var firstBatchSize = _firstBatchSize ?? (_batchSize > 0 ? _batchSize : null);
            var isShardRouter  = connectionDescription.IsMasterResult.ServerType == ServerType.ShardRouter;

            var command = new BsonDocument
            {
                { "find", _collectionNamespace.CollectionName },
                { "filter", _filter, _filter != null },
                { "sort", _sort, _sort != null },
                { "projection", _projection, _projection != null },
                { "hint", _hint, _hint != null },
                { "skip", () => _skip.Value, _skip.HasValue },
                { "limit", () => Math.Abs(_limit.Value), _limit.HasValue&& _limit != 0 },
                { "batchSize", () => firstBatchSize.Value, firstBatchSize.HasValue },
                { "singleBatch", () => _limit < 0 || _singleBatch.Value, _limit < 0 || _singleBatch.HasValue },
                { "comment", _comment, _comment != null },
                { "maxScan", () => _maxScan.Value, _maxScan.HasValue },
                { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
                { "max", _max, _max != null },
                { "min", _min, _min != null },
                { "returnKey", () => _returnKey.Value, _returnKey.HasValue },
                { "showRecordId", () => _showRecordId.Value, _showRecordId.HasValue },
                { "snapshot", () => _snapshot.Value, _snapshot.HasValue },
                { "tailable", true, _cursorType == CursorType.Tailable || _cursorType == CursorType.TailableAwait },
                { "oplogReplay", () => _oplogReplay.Value, _oplogReplay.HasValue },
                { "noCursorTimeout", () => _noCursorTimeout.Value, _noCursorTimeout.HasValue },
                { "awaitData", true, _cursorType == CursorType.TailableAwait },
                { "allowPartialResults", () => _allowPartialResults.Value, _allowPartialResults.HasValue&& isShardRouter },
                { "collation", () => _collation.ToBsonDocument(), _collation != null }
            };

            ReadConcernHelper.AppendReadConcern(command, _readConcern, connectionDescription, session);

            return(command);
        }
Esempio n. 25
0
 public UnitTestCoreSessionProvider(UnitTestCurrentUser currentUser)
 {
     _currentUser = currentUser;
     Session      = new UnitTestCoreSession(null, null, _currentUser);
 }
Esempio n. 26
0
        internal BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            Feature.ReadConcern.ThrowIfNotSupported(connectionDescription.ServerVersion, _readConcern);
            Feature.Collation.ThrowIfNotSupported(connectionDescription.ServerVersion, _collation);

            var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern);

            return(new BsonDocument
            {
                { "geoNear", _collectionNamespace.CollectionName },
                { "near", _near },
                { "limit", () => _limit.Value, _limit.HasValue },
                { "maxDistance", () => _maxDistance.Value, _maxDistance.HasValue },
                { "query", _filter, _filter != null },
                { "spherical", () => _spherical.Value, _spherical.HasValue },
                { "distanceMultiplier", () => _distanceMultiplier.Value, _distanceMultiplier.HasValue },
                { "includeLocs", () => _includeLocs.Value, _includeLocs.HasValue },
                { "uniqueDocs", () => _uniqueDocs.Value, _uniqueDocs.HasValue },
                { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
                { "collation", () => _collation.ToBsonDocument(), _collation != null },
                { "readConcern", readConcern, readConcern != null }
            });
        }
Esempio n. 27
0
        /// <inheritdoc/>
        protected internal override BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            Feature.ReadConcern.ThrowIfNotSupported(connectionDescription.ServerVersion, _readConcern);

            var command = base.CreateCommand(connectionDescription, session);

            ReadConcernHelper.AppendReadConcern(command, _readConcern, connectionDescription, session);

            return(command);
        }
Esempio n. 28
0
 private TResult ExecuteProtocol <TResult>(IWireProtocol <TResult> protocol, ICoreSession session, CancellationToken cancellationToken)
 {
     try
     {
         return(protocol.Execute(_connection, cancellationToken));
     }
     catch (Exception ex)
     {
         MarkSessionDirtyIfNeeded(session, ex);
         _server.HandleChannelException(_connection, ex);
         throw;
     }
 }
Esempio n. 29
0
        // methods
        /// <inheritdoc/>
        protected internal override BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session)
        {
            var command = base.CreateCommand(connectionDescription, session);

            if (_bypassDocumentValidation.HasValue && Feature.BypassDocumentValidation.IsSupported(connectionDescription.ServerVersion))
            {
                command["bypassDocumentValidation"] = _bypassDocumentValidation.Value;
            }
            if (Feature.CommandsThatWriteAcceptWriteConcern.ShouldSendWriteConcern(connectionDescription.ServerVersion, _writeConcern))
            {
                command["writeConcern"] = _writeConcern.ToBsonDocument();
            }
            return(command);
        }
Esempio n. 30
0
 private async Task <TResult> ExecuteProtocolAsync <TResult>(IWireProtocol <TResult> protocol, ICoreSession session, CancellationToken cancellationToken)
 {
     try
     {
         return(await protocol.ExecuteAsync(_connection, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception ex)
     {
         MarkSessionDirtyIfNeeded(session, ex);
         _server.HandleChannelException(_connection, ex);
         throw;
     }
 }