protected override Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken)
        {
            var deleteRequest = (DeleteRequest)request;
            var isMulti = deleteRequest.Limit == 0;

            return channel.DeleteAsync(
               CollectionNamespace,
               deleteRequest.Filter,
               isMulti,
               MessageEncoderSettings,
               WriteConcern,
               cancellationToken);
        }
        protected override Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken)
        {
            var updateRequest = (UpdateRequest)request;

            return channel.UpdateAsync(
                CollectionNamespace,
                MessageEncoderSettings,
                WriteConcern,
                updateRequest.Filter,
                updateRequest.Update,
                ElementNameValidatorFactory.ForUpdateType(updateRequest.UpdateType),
                updateRequest.IsMulti,
                updateRequest.IsUpsert,
                cancellationToken);
        }
        //  methods
        protected override Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken)
        {
            var insertRequest = (InsertRequest)request;
            var documentSource = new BatchableSource<BsonDocument>(new[] { insertRequest.Document });

            return channel.InsertAsync(
                CollectionNamespace,
                WriteConcern,
                BsonDocumentSerializer.Instance,
                MessageEncoderSettings,
                documentSource,
                MaxBatchCount,
                MaxBatchLength,
                !IsOrdered, // continueOnError
                null, // shouldSendGetLastError
                cancellationToken);
        }
        protected override Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken)
        {
            var deleteRequest = (DeleteRequest)request;
            var isMulti = deleteRequest.Limit == 0;
            if (deleteRequest.Collation != null)
            {
                throw new NotSupportedException("OP_DELETE does not support collations.");
            }

            return channel.DeleteAsync(
               CollectionNamespace,
               deleteRequest.Filter,
               isMulti,
               MessageEncoderSettings,
               WriteConcern,
               cancellationToken);
        }
예제 #5
0
        private void ExecuteKillCursorsCommand(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var command = CreateKillCursorsCommand();
            var result  = channel.Command(
                _channelSource.Session,
                null, // readPreference
                _collectionNamespace.DatabaseNamespace,
                command,
                null, // commandPayloads
                NoOpElementNameValidator.Instance,
                null, // additionalOptions
                null, // postWriteAction
                CommandResponseHandling.Return,
                BsonDocumentSerializer.Instance,
                _messageEncoderSettings,
                cancellationToken);

            ThrowIfKillCursorsCommandFailed(result, channel.ConnectionDescription.ConnectionId);
        }
예제 #6
0
        private async Task <CursorBatch <TDocument> > ExecuteGetMoreCommandAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var command = CreateGetMoreCommand();
            var result  = await channel.CommandAsync <BsonDocument>(
                _channelSource.Session,
                null, // readPreference
                _collectionNamespace.DatabaseNamespace,
                command,
                null, // commandPayloads
                NoOpElementNameValidator.Instance,
                null, // additionalOptions
                null, // postWriteAction
                CommandResponseHandling.Return,
                __getMoreCommandResultSerializer,
                _messageEncoderSettings,
                cancellationToken).ConfigureAwait(false);

            return(CreateCursorBatch(result));
        }
        private async Task <BulkWriteBatchResult> ExecuteBatchAsync(IChannelHandle channel, BatchableSource <WriteRequest> requestSource, int originalIndex, CancellationToken cancellationToken)
        {
            var maxBatchCount       = Math.Min(_maxBatchCount ?? int.MaxValue, channel.ConnectionDescription.MaxBatchCount);
            var maxBatchLength      = Math.Min(_maxBatchLength ?? int.MaxValue, channel.ConnectionDescription.MaxDocumentSize);
            var maxDocumentSize     = channel.ConnectionDescription.MaxDocumentSize;
            var maxWireDocumentSize = channel.ConnectionDescription.MaxWireDocumentSize;

            var batchSerializer    = CreateBatchSerializer(maxBatchCount, maxBatchLength, maxDocumentSize, maxWireDocumentSize);
            var writeCommand       = CreateWriteCommand(batchSerializer, requestSource);
            var writeCommandResult = await ExecuteProtocolAsync(channel, writeCommand, cancellationToken).ConfigureAwait(false);

            var indexMap = new IndexMap.RangeBased(0, originalIndex, requestSource.Batch.Count);

            return(BulkWriteBatchResult.Create(
                       _isOrdered,
                       requestSource.Batch,
                       writeCommandResult,
                       indexMap));
        }
예제 #8
0
        // methods
        public async Task <WriteConcernResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var requests = new[] { _request };

            var operation = new BulkUpdateOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                IsOrdered    = true,
                WriteConcern = _writeConcern
            };

            BulkWriteOperationResult         bulkWriteResult;
            MongoBulkWriteOperationException bulkWriteException = null;

            try
            {
                bulkWriteResult = await operation.ExecuteAsync(channel, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                bulkWriteResult    = ex.Result;
                bulkWriteException = ex;
            }

            var converter = new BulkWriteOperationResultConverter();

            if (bulkWriteException != null)
            {
                throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, bulkWriteException);
            }
            else
            {
                if (_writeConcern.IsAcknowledged)
                {
                    return(converter.ToWriteConcernResult(bulkWriteResult));
                }
                else
                {
                    return(null);
                }
            }
        }
        protected override Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken)
        {
            var updateRequest = (UpdateRequest)request;
            if (updateRequest.Collation != null)
            {
                throw new NotSupportedException("BulkUpdateOperationEmulator does not support collations.");
            }

            return channel.UpdateAsync(
                CollectionNamespace,
                MessageEncoderSettings,
                WriteConcern,
                updateRequest.Filter,
                updateRequest.Update,
                ElementNameValidatorFactory.ForUpdateType(updateRequest.UpdateType),
                updateRequest.IsMulti,
                updateRequest.IsUpsert,
                cancellationToken);
        }
        // public methods
        public WriteConcernResult Execute(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var operation = CreateOperation();
            BulkWriteOperationResult result;
            MongoBulkWriteOperationException exception = null;
            try
            {
                result = operation.Execute(channel, cancellationToken);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result = ex.Result;
                exception = ex;
            }

            return CreateResultOrThrow(channel, result, exception);
        }
예제 #11
0
        protected override Task <WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken)
        {
            var updateRequest = (UpdateRequest)request;

            if (updateRequest.Collation != null)
            {
                throw new NotSupportedException("BulkUpdateOperationEmulator does not support collations.");
            }

            return(channel.UpdateAsync(
                       CollectionNamespace,
                       MessageEncoderSettings,
                       WriteConcern,
                       updateRequest.Filter,
                       updateRequest.Update,
                       ElementNameValidatorFactory.ForUpdateType(updateRequest.UpdateType),
                       updateRequest.IsMulti,
                       updateRequest.IsUpsert,
                       cancellationToken));
        }
예제 #12
0
        private WriteConcernResult CreateResultOrThrow(IChannelHandle channel, BulkWriteOperationResult result, MongoBulkWriteOperationException exception)
        {
            var converter = new BulkWriteOperationResultConverter();

            if (exception != null)
            {
                throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, exception);
            }
            else
            {
                if (_writeConcern.IsAcknowledged)
                {
                    return(converter.ToWriteConcernResult(result));
                }
                else
                {
                    return(null);
                }
            }
        }
예제 #13
0
        // methods
        private Task <CursorBatch <TDocument> > ExecuteProtocolAsync(IChannelHandle channel, BsonDocument wrappedQuery, bool slaveOk, CancellationToken cancellationToken)
        {
            var firstBatchSize = QueryHelper.CalculateFirstBatchSize(_limit, _batchSize);

            return(channel.QueryAsync <TDocument>(
                       _collectionNamespace,
                       wrappedQuery,
                       _projection,
                       NoOpElementNameValidator.Instance,
                       _skip ?? 0,
                       firstBatchSize,
                       slaveOk,
                       _allowPartialResults,
                       _noCursorTimeout,
                       _cursorType != CursorType.NonTailable,   // tailable
                       _cursorType == CursorType.TailableAwait, //await data
                       _resultSerializer,
                       _messageEncoderSettings,
                       cancellationToken));
        }
        public async Task <WriteConcernResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var operation = CreateOperation();
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                result = await operation.ExecuteAsync(channel, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(CreateResultOrThrow(channel, result, exception));
        }
        // public methods
        public WriteConcernResult Execute(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var operation = CreateOperation();
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                result = operation.Execute(channel, cancellationToken);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(CreateResultOrThrow(channel, result, exception));
        }
        // methods
        public async Task<WriteConcernResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, "channel");

            var requests = new[] { _request };

            var operation = new BulkUpdateOperation(_collectionNamespace, requests, _messageEncoderSettings)
            {
                IsOrdered = true,
                WriteConcern = _writeConcern
            };

            BulkWriteOperationResult bulkWriteResult;
            MongoBulkWriteOperationException bulkWriteException = null;
            try
            {
                bulkWriteResult = await operation.ExecuteAsync(channel, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                bulkWriteResult = ex.Result;
                bulkWriteException = ex;
            }

            var converter = new BulkWriteOperationResultConverter();
            if (bulkWriteException != null)
            {
                throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, bulkWriteException);
            }
            else
            {
                if (_writeConcern.IsAcknowledged)
                {
                    return converter.ToWriteConcernResult(bulkWriteResult);
                }
                else
                {
                    return null;
                }
            }
        }
예제 #17
0
        // methods
        private Task <CursorBatch <TDocument> > ExecuteGetMoreProtocolAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var numberToReturn = _batchSize;

            if (_limit != 0)
            {
                numberToReturn = Math.Abs(_limit) - _count;
                if (_batchSize != 0 && numberToReturn > _batchSize)
                {
                    numberToReturn = _batchSize;
                }
            }
            return(channel.GetMoreAsync <TDocument>(
                       _collectionNamespace,
                       _query,
                       _cursorId,
                       numberToReturn,
                       _serializer,
                       _messageEncoderSettings,
                       cancellationToken));
        }
예제 #18
0
        // private methods
        private void Initialize(CancellationToken cancellationToken)
        {
            _channelSource = _binding.GetWriteChannelSource(cancellationToken);
            var serverDescription = _channelSource.ServerDescription;

            try
            {
                _channel = _channelSource.GetChannel(cancellationToken);
            }
            catch (MongoConnectionPoolPausedException)
            {
                if (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription))
                {
                    ReplaceChannelSource(_binding.GetWriteChannelSource(cancellationToken));
                    ReplaceChannel(_channelSource.GetChannel(cancellationToken));
                }
                else
                {
                    throw;
                }
            }
        }
예제 #19
0
        private Task <WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            if (_request.Collation != null)
            {
                throw new NotSupportedException("OP_UPDATE does not support collations.");
            }
            if (_request.ArrayFilters != null)
            {
                throw new NotSupportedException("OP_UPDATE does not support arrayFilters.");
            }

            return(channel.UpdateAsync(
                       _collectionNamespace,
                       _messageEncoderSettings,
                       _writeConcern,
                       _request.Filter,
                       _request.Update,
                       ElementNameValidatorFactory.ForUpdateType(_request.UpdateType),
                       _request.IsMulti,
                       _request.IsUpsert,
                       cancellationToken));
        }
        private IReadOnlyList <BsonDocument> GetFirstBatchUsingQueryMessage(IChannelHandle channel, BsonDocument query, int batchSize, CancellationToken cancellationToken, out long cursorId)
        {
            var result = channel.Query(
                _collectionNamespace,
                query,
                null,  // fields
                NoOpElementNameValidator.Instance,
                0,     // skip
                batchSize,
                false, // slaveOk
                false, // partialOk
                false, // noCursorTimeout
                false, // oplogReplay
                false, // tailableCursor
                false, // awaitData
                BsonDocumentSerializer.Instance,
                _messageEncoderSettings,
                cancellationToken);

            cursorId = result.CursorId;
            return(result.Documents);
        }
예제 #21
0
        private async Task <IEnumerable <WriteConcernResult> > InsertBatchesAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var helper = new BatchHelper(_documentSource, _writeConcern, _continueOnError);

            foreach (var batch in helper.GetBatches())
            {
                try
                {
                    batch.Result = await ExecuteProtocolAsync(channel, batch, cancellationToken).ConfigureAwait(false);
                }
                catch (MongoWriteConcernException ex)
                {
                    batch.Result = helper.HandleException(ex);
                    if (!_continueOnError)
                    {
                        return(null);
                    }
                }
            }

            return(helper.CreateFinalResultOrThrow());
        }
예제 #22
0
        // methods
        protected override WriteConcernResult ExecuteProtocol(IChannelHandle channel, UpdateRequest request, CancellationToken cancellationToken)
        {
            if (request.Collation != null)
            {
                throw new NotSupportedException("BulkUpdateOperationEmulator does not support collations.");
            }
            if (request.ArrayFilters != null)
            {
                throw new NotSupportedException("BulkUpdateOperationEmulator does not support arrayFilters.");
            }

            return(channel.Update(
                       CollectionNamespace,
                       MessageEncoderSettings,
                       WriteConcern,
                       request.Filter,
                       request.Update,
                       ElementNameValidatorFactory.ForUpdateType(request.UpdateType),
                       request.IsMulti,
                       request.IsUpsert,
                       cancellationToken));
        }
예제 #23
0
        private async Task InitializeAsync(CancellationToken cancellationToken)
        {
            _channelSource = await _binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false);

            var serverDescription = _channelSource.ServerDescription;

            try
            {
                _channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false);
            }
            catch (MongoConnectionPoolPausedException)
            {
                if (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription))
                {
                    ReplaceChannelSource(await _binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false));
                    ReplaceChannel(await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false));
                }
                else
                {
                    throw;
                }
            }
        }
예제 #24
0
        // methods
        private CursorBatch <TDocument> ExecuteProtocol(IChannelHandle channel, BsonDocument wrappedQuery, bool slaveOk, CancellationToken cancellationToken)
        {
            var firstBatchSize = QueryHelper.CalculateFirstBatchSize(_limit, _firstBatchSize ?? _batchSize);

#pragma warning disable 618
            return(channel.Query <TDocument>(
                       _collectionNamespace,
                       wrappedQuery,
                       _projection,
                       NoOpElementNameValidator.Instance,
                       _skip ?? 0,
                       firstBatchSize,
                       slaveOk,
                       _allowPartialResults ?? false,
                       _noCursorTimeout ?? false,
                       _oplogReplay ?? false,
                       _cursorType != CursorType.NonTailable,   // tailable
                       _cursorType == CursorType.TailableAwait, //await data
                       _resultSerializer,
                       _messageEncoderSettings,
                       cancellationToken));

#pragma warning restore 618
        }
예제 #25
0
        private async Task <BulkWriteOperationResult> ExecuteBatchesAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var batchResults      = new List <BulkWriteBatchResult>();
            var remainingRequests = Enumerable.Empty <WriteRequest>();
            var hasWriteErrors    = false;

            var decoratedRequests = DecorateRequests(_requests);

            using (var enumerator = decoratedRequests.GetEnumerator())
            {
                var originalIndex = 0;

                var requestSource = new BatchableSource <WriteRequest>(enumerator);
                while (requestSource.HasMore)
                {
                    if (hasWriteErrors && _isOrdered)
                    {
                        // note: we have to materialize the list of remaining items before the enumerator gets Disposed
                        remainingRequests = remainingRequests.Concat(requestSource.GetRemainingItems()).ToList();
                        break;
                    }

                    var batchResult = await ExecuteBatchAsync(channel, requestSource, originalIndex, cancellationToken).ConfigureAwait(false);

                    batchResults.Add(batchResult);
                    hasWriteErrors |= batchResult.HasWriteErrors;
                    originalIndex  += batchResult.BatchCount;

                    requestSource.ClearBatch();
                }
            }

            var combiner = new BulkWriteBatchResultCombiner(batchResults, _writeConcern.IsAcknowledged);

            return(combiner.CreateResultOrThrowIfHasErrors(channel.ConnectionDescription.ConnectionId, remainingRequests.ToList()));
        }
        private async Task <BulkWriteBatchResult> ExecuteBatchAsync(IChannelHandle channel, ICoreSessionHandle session, Run run, bool isLast, CancellationToken cancellationToken)
        {
            BulkWriteOperationResult         result;
            MongoBulkWriteOperationException exception = null;

            try
            {
                switch (run.RequestType)
                {
                case WriteRequestType.Delete:
                    result = await ExecuteDeletesAsync(channel, session, run.Requests.Cast <DeleteRequest>(), isLast, cancellationToken).ConfigureAwait(false);

                    break;

                case WriteRequestType.Insert:
                    result = await ExecuteInsertsAsync(channel, session, run.Requests.Cast <InsertRequest>(), isLast, cancellationToken).ConfigureAwait(false);

                    break;

                case WriteRequestType.Update:
                    result = await ExecuteUpdatesAsync(channel, session, run.Requests.Cast <UpdateRequest>(), isLast, cancellationToken).ConfigureAwait(false);

                    break;

                default:
                    throw new MongoInternalException("Unrecognized RequestType.");
                }
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result    = ex.Result;
                exception = ex;
            }

            return(BulkWriteBatchResult.Create(result, exception, run.IndexMap));
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelReadBinding"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="readPreference">The read preference.</param>
 public ChannelReadBinding(IServer server, IChannelHandle channel, ReadPreference readPreference)
 {
     _server = Ensure.IsNotNull(server, nameof(server));
     _channel = Ensure.IsNotNull(channel, nameof(channel));
     _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference));
 }
 // constructors
 public ChannelChannelSource(IServer server, IChannelHandle channel)
 {
     _server = Ensure.IsNotNull(server, nameof(server));
     _channel = Ensure.IsNotNull(channel, nameof(channel));
 }
 // constructors
 public ChannelChannelSource(IServer server, IChannelHandle channel)
 {
     _server  = Ensure.IsNotNull(server, "server");
     _channel = Ensure.IsNotNull(channel, "channel");
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelReadWriteBinding"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="channel">The channel.</param>
 public ChannelReadWriteBinding(IServer server, IChannelHandle channel)
 {
     _server = Ensure.IsNotNull(server, nameof(server));
     _channel = Ensure.IsNotNull(channel, nameof(channel));
 }
        private async Task InitializeAsync(CancellationToken cancellationToken)
        {
            _channelSource = await _binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false);

            _channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false);
        }
 private WriteConcernResult CreateResultOrThrow(IChannelHandle channel, BulkWriteOperationResult result, MongoBulkWriteOperationException exception)
 {
     var converter = new BulkWriteOperationResultConverter();
     if (exception != null)
     {
         throw converter.ToWriteConcernException(channel.ConnectionDescription.ConnectionId, exception);
     }
     else
     {
         if (_writeConcern.IsAcknowledged)
         {
             return converter.ToWriteConcernResult(result);
         }
         else
         {
             return null;
         }
     }
 }
 public BatchHelper(BulkMixedWriteOperation operation, IChannelHandle channel)
 {
     _operation = operation;
     _channel   = channel;
 }
 /// <summary>
 /// Replaces the channel.
 /// </summary>
 /// <param name="channel">The channel.</param>
 public void ReplaceChannel(IChannelHandle channel)
 {
     Ensure.IsNotNull(channel, nameof(channel));
     _channel?.Dispose();
     _channel = channel;
 }
 // constructors
 public ChannelChannelSource(IServer server, IChannelHandle channel)
 {
     _server = Ensure.IsNotNull(server, "server");
     _channel = Ensure.IsNotNull(channel, "channel");
 }
        private BulkWriteOperationResult ExecuteInserts(IChannelHandle channel, ICoreSessionHandle session, IEnumerable <InsertRequest> requests, bool isLast, CancellationToken cancellationToken)
        {
            var operation = CreateInsertOperation(requests, isLast);

            return(operation.Execute(channel, session, cancellationToken));
        }
        private async Task <IEnumerable <WriteConcernResult> > InsertMultipleBatchesAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var       results        = _writeConcern.IsAcknowledged ? new List <WriteConcernResult>() : null;
            Exception finalException = null;

            WriteConcern batchWriteConcern      = _writeConcern;
            Func <bool>  shouldSendGetLastError = null;

            if (!_writeConcern.IsAcknowledged && !_continueOnError)
            {
                batchWriteConcern      = WriteConcern.Acknowledged;
                shouldSendGetLastError = () => _documentSource.HasMore;
            }

            while (_documentSource.HasMore)
            {
                WriteConcernResult result;
                try
                {
                    result = await ExecuteProtocolAsync(channel, batchWriteConcern, shouldSendGetLastError, cancellationToken).ConfigureAwait(false);
                }
                catch (MongoWriteConcernException ex)
                {
                    result = ex.WriteConcernResult;
                    if (_continueOnError)
                    {
                        finalException = ex;
                    }
                    else if (_writeConcern.IsAcknowledged)
                    {
                        results.Add(result);
                        ex.Data["results"] = results;
                        throw;
                    }
                    else
                    {
                        return(null);
                    }
                }

                if (results != null)
                {
                    results.Add(result);
                }

                _documentSource.ClearBatch();
            }

            if (_writeConcern.IsAcknowledged && finalException != null)
            {
                finalException.Data["results"] = results;
                throw finalException;
            }

            return(results);
        }
        // methods
        protected virtual async Task<BulkWriteBatchResult> EmulateSingleRequestAsync(IChannelHandle channel, WriteRequest request, int originalIndex, CancellationToken cancellationToken)
        {
            WriteConcernResult writeConcernResult = null;
            MongoWriteConcernException writeConcernException = null;
            try
            {
                writeConcernResult = await ExecuteProtocolAsync(channel, request, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoWriteConcernException ex)
            {
                writeConcernResult = ex.WriteConcernResult;
                writeConcernException = ex;
            }

            var indexMap = new IndexMap.RangeBased(0, originalIndex, 1);
            return BulkWriteBatchResult.Create(
                request,
                writeConcernResult,
                writeConcernException,
                indexMap);
        }
        public async Task<BulkWriteOperationResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            var batchResults = new List<BulkWriteBatchResult>();
            var remainingRequests = new List<WriteRequest>();
            var hasWriteErrors = false;

            var originalIndex = 0;
            foreach (WriteRequest request in _requests)
            {
                if (hasWriteErrors && _isOrdered)
                {
                    remainingRequests.Add(request);
                    continue;
                }

                var batchResult = await EmulateSingleRequestAsync(channel, request, originalIndex, cancellationToken).ConfigureAwait(false);
                batchResults.Add(batchResult);

                hasWriteErrors |= batchResult.HasWriteErrors;
                originalIndex++;
            }

            var combiner = new BulkWriteBatchResultCombiner(batchResults, _writeConcern.IsAcknowledged);
            return combiner.CreateResultOrThrowIfHasErrors(channel.ConnectionDescription.ConnectionId, remainingRequests);
        }
        public async Task<WriteConcernResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(channel, nameof(channel));

            var operation = CreateOperation();
            BulkWriteOperationResult result;
            MongoBulkWriteOperationException exception = null;
            try
            {
                result = await operation.ExecuteAsync(channel, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoBulkWriteOperationException ex)
            {
                result = ex.Result;
                exception = ex;
            }

            return CreateResultOrThrow(channel, result, exception);
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelReadBinding"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="channel">The channel.</param>
 /// <param name="readPreference">The read preference.</param>
 public ChannelReadBinding(IServer server, IChannelHandle channel, ReadPreference readPreference)
 {
     _server = Ensure.IsNotNull(server, "server");
     _channel = Ensure.IsNotNull(channel, "channel");
     _readPreference = Ensure.IsNotNull(readPreference, "readPreference");
 }
 private Task <WriteConcernResult> InsertSingleBatchAsync(IChannelHandle channel, CancellationToken cancellationToken)
 {
     return(ExecuteProtocolAsync(channel, _writeConcern, null, cancellationToken));
 }
 protected abstract Task<WriteConcernResult> ExecuteProtocolAsync(IChannelHandle channel, WriteRequest request, CancellationToken cancellationToken);
        // private methods
        private BulkWriteBatchResult EmulateSingleRequest(IChannelHandle channel, WriteRequest request, int originalIndex, CancellationToken cancellationToken)
        {
            WriteConcernResult writeConcernResult = null;
            MongoWriteConcernException writeConcernException = null;
            try
            {
                writeConcernResult = ExecuteProtocol(channel, request, cancellationToken);
            }
            catch (MongoWriteConcernException ex)
            {
                writeConcernResult = ex.WriteConcernResult;
                writeConcernException = ex;
            }

            return CreateSingleRequestResult(request, originalIndex, writeConcernResult, writeConcernException);
        }
        private async Task<BulkWriteBatchResult> EmulateSingleRequestAsync(IChannelHandle channel, WriteRequest request, int originalIndex, CancellationToken cancellationToken)
        {
            WriteConcernResult writeConcernResult = null;
            MongoWriteConcernException writeConcernException = null;
            try
            {
                writeConcernResult = await ExecuteProtocolAsync(channel, request, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoWriteConcernException ex)
            {
                writeConcernResult = ex.WriteConcernResult;
                writeConcernException = ex;
            }

            return CreateSingleRequestResult(request, originalIndex, writeConcernResult, writeConcernException);
        }
        private Task <BulkWriteOperationResult> ExecuteUpdatesAsync(IChannelHandle channel, ICoreSessionHandle session, IEnumerable <UpdateRequest> requests, bool isLast, CancellationToken cancellationToken)
        {
            var operation = CreateUpdateOperation(requests, isLast);

            return(operation.ExecuteAsync(channel, session, cancellationToken));
        }
 public BatchHelper(BulkUnmixedWriteOperationEmulatorBase operation, IChannelHandle channel)
 {
     _operation = operation;
     _channel = channel;
 }
 private IReadOnlyList <BsonDocument> GetFirstBatch(IChannelHandle channel, BsonDocument query, int batchSize, CancellationToken cancellationToken, out long cursorId)
 {
     return(GetFirstBatchUsingFindCommand(channel, query, batchSize, cancellationToken, out cursorId));
 }
 // public methods
 public BulkWriteOperationResult Execute(IChannelHandle channel, CancellationToken cancellationToken)
 {
     var helper = new BatchHelper(this, channel);
     foreach (var batch in helper.GetBatches())
     {
         batch.Result = EmulateSingleRequest(channel, batch.Request, batch.OriginalIndex, cancellationToken);
     }
     return helper.GetFinalResultOrThrow();
 }
 // private methods
 private void Initialize(CancellationToken cancellationToken)
 {
     _channelSource = _binding.GetWriteChannelSource(cancellationToken);
     _channel       = _channelSource.GetChannel(cancellationToken);
 }
 public async Task<BulkWriteOperationResult> ExecuteAsync(IChannelHandle channel, CancellationToken cancellationToken)
 {
     var helper = new BatchHelper(this, channel);
     foreach (var batch in helper.GetBatches())
     {
         batch.Result = await EmulateSingleRequestAsync(channel, batch.Request, batch.OriginalIndex, cancellationToken).ConfigureAwait(false);
     }
     return helper.GetFinalResultOrThrow();
 }
예제 #52
0
        /// <inheritdoc />
        protected override IEnumerable <Type1CommandMessageSection> CreateCommandPayloads(IChannelHandle channel, int attempt)
        {
            BatchableSource <DeleteRequest> deletes;

            if (attempt == 1)
            {
                deletes = _deletes;
            }
            else
            {
                deletes = new BatchableSource <DeleteRequest>(_deletes.Items, _deletes.Offset, _deletes.ProcessedCount, canBeSplit: false);
            }
            var maxBatchCount   = Math.Min(MaxBatchCount ?? int.MaxValue, channel.ConnectionDescription.MaxBatchCount);
            var maxDocumentSize = channel.ConnectionDescription.MaxWireDocumentSize;
            var payload         = new Type1CommandMessageSection <DeleteRequest>("deletes", deletes, DeleteRequestSerializer.Instance, NoOpElementNameValidator.Instance, maxBatchCount, maxDocumentSize);

            return(new Type1CommandMessageSection[] { payload });
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelReadWriteBinding"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="channel">The channel.</param>
 public ChannelReadWriteBinding(IServer server, IChannelHandle channel)
 {
     _server = Ensure.IsNotNull(server, "server");
     _channel = Ensure.IsNotNull(channel, "channel");
 }