Exemplo n.º 1
0
        private IReadOnlyList <IAsyncCursor <TDocument> > CreateCursors(IChannelSourceHandle channelSource, BsonDocument command, BsonDocument result)
        {
            var cursors = new List <AsyncCursor <TDocument> >();

            foreach (var cursorDocument in result["cursors"].AsBsonArray.Select(v => v["cursor"].AsBsonDocument))
            {
                var cursorId   = cursorDocument["id"].ToInt64();
                var firstBatch = cursorDocument["firstBatch"].AsBsonArray.Select(v =>
                {
                    var bsonDocument = (BsonDocument)v;
                    using (var reader = new BsonDocumentReader(bsonDocument))
                    {
                        var context  = BsonDeserializationContext.CreateRoot(reader);
                        var document = _serializer.Deserialize(context);
                        return(document);
                    }
                })
                                 .ToList();

                var cursor = new AsyncCursor <TDocument>(
                    channelSource.Fork(),
                    _collectionNamespace,
                    command,
                    firstBatch,
                    cursorId,
                    _batchSize ?? 0,
                    0, // limit
                    _serializer,
                    _messageEncoderSettings);

                cursors.Add(cursor);
            }

            return(cursors);
        }
        public void Session_reference_count_should_be_decremented_as_soon_as_possible(int collectionSize, int batchSize)
        {
            RequireServer.Check();
            DropCollection();
            var documents = Enumerable.Range(1, collectionSize).Select(n => new BsonDocument("_id", n));

            Insert(documents);

            _session.ReferenceCount().Should().Be(1);
            var cancellationToken = CancellationToken.None;

            using (var binding = new ReadPreferenceBinding(CoreTestConfiguration.Cluster, ReadPreference.Primary, _session.Fork()))
                using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(cancellationToken))
                    using (var channel = channelSource.GetChannel(cancellationToken))
                    {
                        var  query = new BsonDocument();
                        long cursorId;
                        var  firstBatch = GetFirstBatch(channel, query, batchSize, cancellationToken, out cursorId);

                        using (var cursor = new AsyncCursor <BsonDocument>(channelSource, _collectionNamespace, firstBatch, cursorId, batchSize, null, BsonDocumentSerializer.Instance, new MessageEncoderSettings()))
                        {
                            AssertExpectedSessionReferenceCount(_session, cursor);
                            while (cursor.MoveNext(cancellationToken))
                            {
                                AssertExpectedSessionReferenceCount(_session, cursor);
                            }
                            AssertExpectedSessionReferenceCount(_session, cursor);
                        }
                    }
            _session.ReferenceCount().Should().Be(1);
        }
Exemplo n.º 3
0
        private async Task <IAsyncCursor <BsonDocument> > ExecuteUsingCommandAsync(IChannelSourceHandle channelSource, ReadPreference readPreference, CancellationToken cancellationToken)
        {
            var databaseNamespace = _collectionNamespace.DatabaseNamespace;
            var command           = new BsonDocument("listIndexes", _collectionNamespace.CollectionName);
            var operation         = new ReadCommandOperation <BsonDocument>(databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings);

            try
            {
                var response = await operation.ExecuteAsync(channelSource, readPreference, cancellationToken).ConfigureAwait(false);

                var cursorDocument = response["cursor"].AsBsonDocument;
                var cursor         = new AsyncCursor <BsonDocument>(
                    channelSource.Fork(),
                    CollectionNamespace.FromFullName(cursorDocument["ns"].AsString),
                    command,
                    cursorDocument["firstBatch"].AsBsonArray.OfType <BsonDocument>().ToList(),
                    cursorDocument["id"].ToInt64(),
                    0,
                    0,
                    BsonDocumentSerializer.Instance,
                    _messageEncoderSettings);

                return(cursor);
            }
            catch (MongoCommandException ex)
            {
                if (ex.Code == 26)
                {
                    return(new SingleBatchAsyncCursor <BsonDocument>(new List <BsonDocument>()));
                }
                throw;
            }
        }
 // private methods
 private void Close(AsyncCursor <BsonDocument> asyncCursor, bool async, CancellationToken cancellationToken)
 {
     if (async)
     {
         asyncCursor.CloseAsync(cancellationToken).GetAwaiter().GetResult();
     }
     else
     {
         asyncCursor.Close(cancellationToken);
     }
 }
Exemplo n.º 5
0
        private IAsyncCursor <BsonDocument> CreateCursor(IChannelSourceHandle channelSource, BsonDocument result, BsonDocument command)
        {
            var cursorDocument = result["cursor"].AsBsonDocument;
            var cursor         = new AsyncCursor <BsonDocument>(
                channelSource.Fork(),
                CollectionNamespace.FromFullName(cursorDocument["ns"].AsString),
                command,
                cursorDocument["firstBatch"].AsBsonArray.OfType <BsonDocument>().ToList(),
                cursorDocument["id"].ToInt64(),
                0,
                0,
                BsonDocumentSerializer.Instance,
                _messageEncoderSettings);

            return(cursor);
        }
Exemplo n.º 6
0
        /// <inheritdoc/>
        public async Task <IReadOnlyList <IAsyncCursor <TDocument> > > ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(binding, nameof(binding));

            using (EventContext.BeginOperation())
                using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false))
                {
                    var command   = CreateCommand();
                    var operation = new ReadCommandOperation <BsonDocument>(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings);
                    var result    = await operation.ExecuteAsync(channelSource, binding.ReadPreference, cancellationToken).ConfigureAwait(false);

                    var cursors = new List <AsyncCursor <TDocument> >();

                    foreach (var cursorDocument in result["cursors"].AsBsonArray.Select(v => v["cursor"].AsBsonDocument))
                    {
                        var cursorId   = cursorDocument["id"].ToInt64();
                        var firstBatch = cursorDocument["firstBatch"].AsBsonArray.Select(v =>
                        {
                            var bsonDocument = (BsonDocument)v;
                            using (var reader = new BsonDocumentReader(bsonDocument))
                            {
                                var context  = BsonDeserializationContext.CreateRoot(reader);
                                var document = _serializer.Deserialize(context);
                                return(document);
                            }
                        })
                                         .ToList();

                        var cursor = new AsyncCursor <TDocument>(
                            channelSource.Fork(),
                            _collectionNamespace,
                            command,
                            firstBatch,
                            cursorId,
                            _batchSize ?? 0,
                            0, // limit
                            _serializer,
                            _messageEncoderSettings);

                        cursors.Add(cursor);
                    }

                    return(cursors);
                }
        }
        // private methods
        private AsyncCursorEnumerator <BsonDocument> CreateSubject(int count)
        {
            var firstBatch = Enumerable.Range(0, count)
                             .Select(i => new BsonDocument("_id", i))
                             .ToArray();

            var cursor = new AsyncCursor <BsonDocument>(
                channelSource: new Mock <IChannelSource>().Object,
                collectionNamespace: new CollectionNamespace("foo", "bar"),
                firstBatch: firstBatch,
                cursorId: 0,
                batchSize: null,
                limit: null,
                serializer: BsonDocumentSerializer.Instance,
                messageEncoderSettings: new MessageEncoderSettings());

            return(new AsyncCursorEnumerator <BsonDocument>(cursor, CancellationToken.None));
        }
Exemplo n.º 8
0
        public void Constructor_should_call_Dispose_on_connectionSource_if_cursorId_is_zero(int cursorId, bool shouldCallDispose)
        {
            var connectionSource = Substitute.For <IConnectionSource>();
            var subject          = new AsyncCursor <BsonDocument>(
                connectionSource,
                new CollectionNamespace("databaseName", "collectionName"),
                new BsonDocument(),  // query
                new BsonDocument[0], // firstBatch
                cursorId,
                0,                   // batchSize
                0,                   // limit
                BsonDocumentSerializer.Instance,
                null,                // messageEncoderSettings
                Timeout.InfiniteTimeSpan,
                CancellationToken.None);

            connectionSource.Received(shouldCallDispose ? 1 : 0).Dispose();
        }
        public void constructor_should_initialize_instance()
        {
            var channelSource       = new Mock <IChannelSource>().Object;
            var databaseNamespace   = new DatabaseNamespace("test");
            var collectionNamespace = new CollectionNamespace(databaseNamespace, "test");
            var query                  = new BsonDocument("x", 1);
            var firstBatch             = new BsonDocument[] { new BsonDocument("y", 2) };
            var cursorId               = 1L;
            var batchSize              = 2;
            var limit                  = 3;
            var serializer             = BsonDocumentSerializer.Instance;
            var messageEncoderSettings = new MessageEncoderSettings();
            var maxTime                = TimeSpan.FromSeconds(1);

            var result = new AsyncCursor <BsonDocument>(
                channelSource,
                collectionNamespace,
                query,
                firstBatch,
                cursorId,
                batchSize,
                limit,
                serializer,
                messageEncoderSettings,
                maxTime);

            var reflector = new Reflector(result);

            reflector.BatchSize.Should().Be(batchSize);
            reflector.ChannelSource.Should().Be(channelSource);
            reflector.CollectionNamespace.Should().Be(collectionNamespace);
            reflector.Count.Should().Be(firstBatch.Length);
            reflector.CurrentBatch.Should().BeNull();
            reflector.CursorId.Should().Be(cursorId);
            reflector.Disposed.Should().BeFalse();
            reflector.FirstBatch.Should().Equal(firstBatch);
            reflector.Limit.Should().Be(limit);
            reflector.MaxTime.Should().Be(maxTime);
            reflector.MessageEncoderSettings.Should().BeEquivalentTo(messageEncoderSettings);
            reflector.Query.Should().Be(query);
            reflector.Serializer.Should().Be(serializer);
        }
Exemplo n.º 10
0
        private IReadOnlyList <IAsyncCursor <TDocument> > CreateCursors(IChannelSourceHandle channelSource, BsonDocument command, BsonDocument result)
        {
            var cursors = new List <AsyncCursor <TDocument> >();

            using (var getMoreChannelSource = new ChannelSourceHandle(new ServerChannelSource(channelSource.Server, channelSource.Session.Fork())))
            {
                foreach (var cursorDocument in result["cursors"].AsBsonArray.Select(v => v["cursor"].AsBsonDocument))
                {
                    var cursorId   = cursorDocument["id"].ToInt64();
                    var firstBatch = cursorDocument["firstBatch"].AsBsonArray.Select(v =>
                    {
                        var bsonDocument = (BsonDocument)v;
                        using (var reader = new BsonDocumentReader(bsonDocument))
                        {
                            var context  = BsonDeserializationContext.CreateRoot(reader);
                            var document = _serializer.Deserialize(context);
                            return(document);
                        }
                    })
                                     .ToList();

                    // it's not affected by loadbalancing logic since it was deprecated in server version 4.1.
                    var cursor = new AsyncCursor <TDocument>(
                        getMoreChannelSource.Fork(),
                        _collectionNamespace,
                        command,
                        firstBatch,
                        cursorId,
                        _batchSize ?? 0,
                        0, // limit
                        _serializer,
                        _messageEncoderSettings);

                    cursors.Add(cursor);
                }
            }

            return(cursors);
        }
        public void constructor_should_initialize_instance()
        {
            var channelSource       = new Mock <IChannelSource>().Object;
            var databaseNamespace   = new DatabaseNamespace("test");
            var collectionNamespace = new CollectionNamespace(databaseNamespace, "test");
            var firstBatch          = new BsonDocument[] { new BsonDocument("y", 2) };
            var cursorId            = 1L;
            var batchSize           = 2;
            var limit                  = 3;
            var serializer             = BsonDocumentSerializer.Instance;
            var messageEncoderSettings = new MessageEncoderSettings();
            var maxTime                = TimeSpan.FromSeconds(1);

            var result = new AsyncCursor <BsonDocument>(
                channelSource,
                collectionNamespace,
                comment: null,
                firstBatch,
                cursorId,
                batchSize,
                limit,
                serializer,
                messageEncoderSettings,
                maxTime);

            result._batchSize().Should().Be(batchSize);
            result._channelSource().Should().Be(channelSource);
            result._collectionNamespace().Should().Be(collectionNamespace);
            result._count().Should().Be(firstBatch.Length);
            result._currentBatch().Should().BeNull();
            result._cursorId().Should().Be(cursorId);
            result._disposed().Should().BeFalse();
            result._firstBatch().Should().Equal(firstBatch);
            result._limit().Should().Be(limit);
            result._maxTime().Should().Be(maxTime);
            result._messageEncoderSettings().Should().BeEquivalentTo(messageEncoderSettings);
            result._serializer().Should().Be(serializer);
        }
Exemplo n.º 12
0
        private async Task <IAsyncCursor <BsonDocument> > ExecuteUsingCommandAsync(IChannelSourceHandle channelSource, ReadPreference readPreference, CancellationToken cancellationToken)
        {
            var command = new BsonDocument
            {
                { "listCollections", 1 },
                { "filter", _filter, _filter != null }
            };
            var operation = new ReadCommandOperation <BsonDocument>(_databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings);
            var response  = await operation.ExecuteAsync(channelSource, readPreference, cancellationToken).ConfigureAwait(false);

            var cursorDocument = response["cursor"].AsBsonDocument;
            var cursor         = new AsyncCursor <BsonDocument>(
                channelSource.Fork(),
                CollectionNamespace.FromFullName(cursorDocument["ns"].AsString),
                command,
                cursorDocument["firstBatch"].AsBsonArray.OfType <BsonDocument>().ToList(),
                cursorDocument["id"].ToInt64(),
                0,
                0,
                BsonDocumentSerializer.Instance,
                _messageEncoderSettings);

            return(cursor);
        }
 public static MessageEncoderSettings _messageEncoderSettings(this AsyncCursor <BsonDocument> obj) => (MessageEncoderSettings)Reflector.GetFieldValue(obj, nameof(_messageEncoderSettings));
 public static TimeSpan?_maxTime(this AsyncCursor <BsonDocument> obj) => (TimeSpan?)Reflector.GetFieldValue(obj, nameof(_maxTime));
 public static int _limit(this AsyncCursor <BsonDocument> obj) => (int)Reflector.GetFieldValue(obj, nameof(_limit));
 public static IReadOnlyList <BsonDocument> _firstBatch(this AsyncCursor <BsonDocument> obj) => (IReadOnlyList <BsonDocument>)Reflector.GetFieldValue(obj, nameof(_firstBatch));
 public static bool _disposed(this AsyncCursor <BsonDocument> obj) => (bool)Reflector.GetFieldValue(obj, nameof(_disposed));
 public static long _cursorId(this AsyncCursor <BsonDocument> obj) => (long)Reflector.GetFieldValue(obj, nameof(_cursorId));
Exemplo n.º 19
0
 public static BsonDocument _query(this AsyncCursor <BsonDocument> obj) => (BsonDocument)Reflector.GetFieldValue(obj, nameof(_query));
 public static IChannelSource _channelSource(this AsyncCursor <BsonDocument> obj) => (IChannelSource)Reflector.GetFieldValue(obj, nameof(_channelSource));
 // private fields
 public static int?_batchSize(this AsyncCursor <BsonDocument> obj) => (int?)Reflector.GetFieldValue(obj, nameof(_batchSize));
 // private methods
 public static BsonDocument CreateGetMoreCommand(this AsyncCursor <BsonDocument> obj, ConnectionDescription connectionDescription) => (BsonDocument)Reflector.Invoke(obj, nameof(CreateGetMoreCommand), connectionDescription);
Exemplo n.º 23
0
 // constructors
 public Reflector(AsyncCursor <BsonDocument> instance)
 {
     _instance = instance;
 }
 public static IBsonSerializer <BsonDocument> _serializer(this AsyncCursor <BsonDocument> obj) => (IBsonSerializer <BsonDocument>)Reflector.GetFieldValue(obj, nameof(_serializer));
 public static BsonDocument CreateKillCursorsCommand(this AsyncCursor <BsonDocument> obj) => (BsonDocument)Reflector.Invoke(obj, nameof(CreateKillCursorsCommand));
 public static CollectionNamespace _collectionNamespace(this AsyncCursor <BsonDocument> obj) => (CollectionNamespace)Reflector.GetFieldValue(obj, nameof(_collectionNamespace));