-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
AsyncCursor.cs
715 lines (656 loc) · 26 KB
/
AsyncCursor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/* Copyright 2013-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver.Core.Bindings;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Events;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.WireProtocol;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;
namespace MongoDB.Driver.Core.Operations
{
/// <summary>
/// Represents an async cursor.
/// </summary>
/// <typeparam name="TDocument">The type of the documents.</typeparam>
public class AsyncCursor<TDocument> : IAsyncCursor<TDocument>, ICursorBatchInfo
{
#region static
// private static fields
private static IBsonSerializer<BsonDocument> __getMoreCommandResultSerializer = new PartiallyRawBsonDocumentSerializer(
"cursor", new PartiallyRawBsonDocumentSerializer(
"nextBatch", new RawBsonArraySerializer()));
#endregion
// fields
private readonly int? _batchSize;
private readonly CollectionNamespace _collectionNamespace;
private IChannelSource _channelSource;
private bool _closed;
private readonly BsonValue _comment;
private int _count;
private IReadOnlyList<TDocument> _currentBatch;
private long _cursorId;
private bool _disposed;
private IReadOnlyList<TDocument> _firstBatch;
private readonly int? _limit;
private readonly TimeSpan? _maxTime;
private readonly MessageEncoderSettings _messageEncoderSettings;
private readonly long? _operationId;
private BsonDocument _postBatchResumeToken;
private readonly IBsonSerializer<TDocument> _serializer;
private readonly bool _wasFirstBatchEmpty;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="AsyncCursor{TDocument}"/> class.
/// </summary>
/// <param name="channelSource">The channel source.</param>
/// <param name="collectionNamespace">The collection namespace.</param>
/// <param name="comment">The comment.</param>
/// <param name="firstBatch">The first batch.</param>
/// <param name="cursorId">The cursor identifier.</param>
/// <param name="batchSize">The size of a batch.</param>
/// <param name="limit">The limit.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="messageEncoderSettings">The message encoder settings.</param>
/// <param name="maxTime">The maxTime for each batch.</param>
public AsyncCursor(
IChannelSource channelSource,
CollectionNamespace collectionNamespace,
BsonValue comment,
IReadOnlyList<TDocument> firstBatch,
long cursorId,
int? batchSize,
int? limit,
IBsonSerializer<TDocument> serializer,
MessageEncoderSettings messageEncoderSettings,
TimeSpan? maxTime = null)
: this(
channelSource,
collectionNamespace,
comment,
firstBatch,
cursorId,
null, // postBatchResumeToken
batchSize,
limit,
serializer,
messageEncoderSettings,
maxTime)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncCursor{TDocument}"/> class.
/// </summary>
/// <param name="channelSource">The channel source.</param>
/// <param name="collectionNamespace">The collection namespace.</param>
/// <param name="query">The query.</param>
/// <param name="firstBatch">The first batch.</param>
/// <param name="cursorId">The cursor identifier.</param>
/// <param name="batchSize">The size of a batch.</param>
/// <param name="limit">The limit.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="messageEncoderSettings">The message encoder settings.</param>
/// <param name="maxTime">The maxTime for each batch.</param>
[Obsolete("Use overload without query.")]
public AsyncCursor(
IChannelSource channelSource,
CollectionNamespace collectionNamespace,
BsonDocument query,
IReadOnlyList<TDocument> firstBatch,
long cursorId,
int? batchSize,
int? limit,
IBsonSerializer<TDocument> serializer,
MessageEncoderSettings messageEncoderSettings,
TimeSpan? maxTime = null)
: this(
channelSource,
collectionNamespace,
query,
firstBatch,
cursorId,
null, // postBatchResumeToken
batchSize,
limit,
serializer,
messageEncoderSettings,
maxTime)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncCursor{TDocument}"/> class.
/// </summary>
/// <param name="channelSource">The channel source.</param>
/// <param name="collectionNamespace">The collection namespace.</param>
/// <param name="query">The query.</param>
/// <param name="firstBatch">The first batch.</param>
/// <param name="cursorId">The cursor identifier.</param>
/// <param name="postBatchResumeToken">The post batch resume token.</param>
/// <param name="batchSize">The size of a batch.</param>
/// <param name="limit">The limit.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="messageEncoderSettings">The message encoder settings.</param>
/// <param name="maxTime">The maxTime for each batch.</param>
[Obsolete("Use overload without query.")]
public AsyncCursor(
IChannelSource channelSource,
CollectionNamespace collectionNamespace,
BsonDocument query, // no longer used, so ingore it
IReadOnlyList<TDocument> firstBatch,
long cursorId,
BsonDocument postBatchResumeToken,
int? batchSize,
int? limit,
IBsonSerializer<TDocument> serializer,
MessageEncoderSettings messageEncoderSettings,
TimeSpan? maxTime)
: this(
channelSource,
collectionNamespace,
comment: null,
firstBatch,
cursorId,
postBatchResumeToken,
batchSize,
limit,
serializer,
messageEncoderSettings,
maxTime)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncCursor{TDocument}"/> class.
/// </summary>
/// <param name="channelSource">The channel source.</param>
/// <param name="collectionNamespace">The collection namespace.</param>
/// <param name="comment">The comment.</param>
/// <param name="firstBatch">The first batch.</param>
/// <param name="cursorId">The cursor identifier.</param>
/// <param name="postBatchResumeToken">The post batch resume token.</param>
/// <param name="batchSize">The size of a batch.</param>
/// <param name="limit">The limit.</param>
/// <param name="serializer">The serializer.</param>
/// <param name="messageEncoderSettings">The message encoder settings.</param>
/// <param name="maxTime">The maxTime for each batch.</param>
public AsyncCursor(
IChannelSource channelSource,
CollectionNamespace collectionNamespace,
BsonValue comment,
IReadOnlyList<TDocument> firstBatch,
long cursorId,
BsonDocument postBatchResumeToken,
int? batchSize,
int? limit,
IBsonSerializer<TDocument> serializer,
MessageEncoderSettings messageEncoderSettings,
TimeSpan? maxTime)
{
_operationId = EventContext.OperationId;
_channelSource = channelSource;
_comment = comment;
_collectionNamespace = Ensure.IsNotNull(collectionNamespace, nameof(collectionNamespace));
_firstBatch = Ensure.IsNotNull(firstBatch, nameof(firstBatch));
_cursorId = cursorId;
_postBatchResumeToken = postBatchResumeToken;
_batchSize = Ensure.IsNullOrGreaterThanOrEqualToZero(batchSize, nameof(batchSize));
_limit = Ensure.IsNullOrGreaterThanOrEqualToZero(limit, nameof(limit));
_serializer = Ensure.IsNotNull(serializer, nameof(serializer));
_messageEncoderSettings = messageEncoderSettings;
_maxTime = maxTime;
if (_limit > 0 && _firstBatch.Count > _limit)
{
_firstBatch = _firstBatch.Take(_limit.Value).ToList();
}
_count = _firstBatch.Count;
_wasFirstBatchEmpty = firstBatch.Count == 0;
DisposeChannelSourceIfNoLongerNeeded();
}
// properties
/// <inheritdoc/>
public IEnumerable<TDocument> Current
{
get
{
ThrowIfDisposed();
return _currentBatch;
}
}
/// <summary>
/// Gets a value indicating whether the first batch was empty or not.
/// </summary>
/// <value>
/// <c>true</c> if the first batch was empty; otherwise, <c>false</c>.
/// </value>
public bool WasFirstBatchEmpty => _wasFirstBatchEmpty;
/// <summary>
/// Gets the post batch resume token.
/// </summary>
/// <value>
/// The post batch resume token.
/// </value>
public BsonDocument PostBatchResumeToken
{
get { return _postBatchResumeToken; }
}
// private methods
private int CalculateGetMoreNumberToReturn()
{
var numberToReturn = _batchSize ?? 0;
if (_limit > 0)
{
var remaining = _limit.Value - _count;
if (numberToReturn == 0 || numberToReturn > remaining)
{
numberToReturn = remaining;
}
}
return numberToReturn;
}
/// <summary>
/// Closes the cursor.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
public void Close(CancellationToken cancellationToken = default(CancellationToken))
{
try
{
CloseIfNotAlreadyClosed(cancellationToken);
}
finally
{
Dispose();
}
}
/// <summary>
/// Closes the cursor.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task.</returns>
public async Task CloseAsync(CancellationToken cancellationToken = default(CancellationToken))
{
try
{
await CloseIfNotAlreadyClosedAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
Dispose();
}
}
private CursorBatch<TDocument> CreateCursorBatch(BsonDocument result)
{
var cursorDocument = result["cursor"].AsBsonDocument;
var cursorId = cursorDocument["id"].ToInt64();
var batch = (RawBsonArray)cursorDocument["nextBatch"];
var postBatchResumeToken = (BsonDocument)cursorDocument.GetValue("postBatchResumeToken", null);
using (batch)
{
var documents = CursorBatchDeserializationHelper.DeserializeBatch(batch, _serializer, _messageEncoderSettings);
return new CursorBatch<TDocument>(cursorId, postBatchResumeToken, documents);
}
}
private BsonDocument CreateGetMoreCommand(ConnectionDescription connectionDescription)
{
var command = new BsonDocument
{
{ "getMore", _cursorId },
{ "collection", _collectionNamespace.CollectionName },
{ "batchSize", () => CalculateGetMoreNumberToReturn(), _batchSize > 0 || _limit > 0 },
{ "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue },
{ "comment", _comment, _comment != null && Feature.GetMoreComment.IsSupported(connectionDescription.MaxWireVersion) },
};
return command;
}
private BsonDocument CreateKillCursorsCommand()
{
var command = new BsonDocument
{
{ "killCursors", _collectionNamespace.CollectionName },
{ "cursors", new BsonArray { _cursorId } }
};
return command;
}
private CursorBatch<TDocument> ExecuteGetMoreCommand(IChannelHandle channel, CancellationToken cancellationToken)
{
var command = CreateGetMoreCommand(channel.ConnectionDescription);
BsonDocument result;
try
{
result = channel.Command<BsonDocument>(
_channelSource.Session,
null, // readPreference
_collectionNamespace.DatabaseNamespace,
command,
null, // commandPayloads
NoOpElementNameValidator.Instance,
null, // additionalOptions
null, // postWriteAction
CommandResponseHandling.Return,
__getMoreCommandResultSerializer,
_messageEncoderSettings,
cancellationToken);
}
catch (MongoCommandException ex) when (IsMongoCursorNotFoundException(ex))
{
throw new MongoCursorNotFoundException(channel.ConnectionDescription.ConnectionId, _cursorId, command);
}
return CreateCursorBatch(result);
}
private async Task<CursorBatch<TDocument>> ExecuteGetMoreCommandAsync(IChannelHandle channel, CancellationToken cancellationToken)
{
var command = CreateGetMoreCommand(channel.ConnectionDescription);
BsonDocument result;
try
{
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);
}
catch (MongoCommandException ex) when (IsMongoCursorNotFoundException(ex))
{
throw new MongoCursorNotFoundException(channel.ConnectionDescription.ConnectionId, _cursorId, command);
}
return CreateCursorBatch(result);
}
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);
}
private async Task ExecuteKillCursorsCommandAsync(IChannelHandle channel, CancellationToken cancellationToken)
{
var command = CreateKillCursorsCommand();
var result = await channel.CommandAsync(
_channelSource.Session,
null, // readPreference
_collectionNamespace.DatabaseNamespace,
command,
null, // commandPayloads
NoOpElementNameValidator.Instance,
null, // additionalOptions
null, // postWriteAction
CommandResponseHandling.Return,
BsonDocumentSerializer.Instance,
_messageEncoderSettings,
cancellationToken)
.ConfigureAwait(false);
ThrowIfKillCursorsCommandFailed(result, channel.ConnectionDescription.ConnectionId);
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_disposed)
{
CloseIfNotAlreadyClosedFromDispose();
if (_channelSource != null)
{
_channelSource.Dispose();
}
_disposed = true;
}
}
}
private void CloseIfNotAlreadyClosed(CancellationToken cancellationToken)
{
if (!_closed)
{
try
{
if (_cursorId != 0)
{
try
{
KillCursors(cancellationToken);
}
catch
{
// ignore exceptions
}
}
}
finally
{
_closed = true;
}
}
}
private async Task CloseIfNotAlreadyClosedAsync(CancellationToken cancellationToken)
{
if (!_closed)
{
try
{
if (_cursorId != 0)
{
try
{
await KillCursorsAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
// ignore exceptions
}
}
}
finally
{
_closed = true;
}
}
}
private void CloseIfNotAlreadyClosedFromDispose()
{
try
{
using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
CloseIfNotAlreadyClosed(source.Token);
}
}
catch
{
// ignore any exceptions from CloseIfNotAlreadyClosed when called from Dispose
}
}
private void DisposeChannelSourceIfNoLongerNeeded()
{
if (_channelSource != null && _cursorId == 0)
{
_channelSource.Dispose();
_channelSource = null;
}
}
private CursorBatch<TDocument> GetNextBatch(CancellationToken cancellationToken)
{
using (EventContext.BeginOperation(_operationId))
using (var channel = _channelSource.GetChannel(cancellationToken))
{
return ExecuteGetMoreCommand(channel, cancellationToken);
}
}
private async Task<CursorBatch<TDocument>> GetNextBatchAsync(CancellationToken cancellationToken)
{
using (EventContext.BeginOperation(_operationId))
using (var channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false))
{
return await ExecuteGetMoreCommandAsync(channel, cancellationToken).ConfigureAwait(false);
}
}
private bool IsMongoCursorNotFoundException(MongoCommandException exception)
{
return exception.Code == (int)ServerErrorCode.CursorNotFound;
}
private void KillCursors(CancellationToken cancellationToken)
{
using (EventContext.BeginOperation(_operationId))
using (EventContext.BeginKillCursors(_collectionNamespace))
using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
using (var channel = _channelSource.GetChannel(cancellationTokenSource.Token))
{
if (!channel.Connection.IsExpired)
{
ExecuteKillCursorsCommand(channel, cancellationToken);
}
}
}
private async Task KillCursorsAsync(CancellationToken cancellationToken)
{
using (EventContext.BeginOperation(_operationId))
using (EventContext.BeginKillCursors(_collectionNamespace))
using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
using (var channel = await _channelSource.GetChannelAsync(cancellationTokenSource.Token).ConfigureAwait(false))
{
if (!channel.Connection.IsExpired)
{
await ExecuteKillCursorsCommandAsync(channel, cancellationToken).ConfigureAwait(false);
}
}
}
/// <inheritdoc/>
public bool MoveNext(CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
bool hasMore;
if (TryMoveNext(out hasMore))
{
return hasMore;
}
var batch = GetNextBatch(cancellationToken);
SaveBatch(batch);
return true;
}
/// <inheritdoc/>
public async Task<bool> MoveNextAsync(CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
bool hasMore;
if (TryMoveNext(out hasMore))
{
return hasMore;
}
var batch = await GetNextBatchAsync(cancellationToken).ConfigureAwait(false);
SaveBatch(batch);
return true;
}
private void SaveBatch(CursorBatch<TDocument> batch)
{
var documents = batch.Documents;
_count += documents.Count;
if (_limit > 0 && _count > _limit.Value)
{
var remove = _count - _limit.Value;
var take = documents.Count - remove;
documents = documents.Take(take).ToList();
_count = _limit.Value;
}
_currentBatch = documents;
_cursorId = batch.CursorId;
_postBatchResumeToken = batch.PostBatchResumeToken;
DisposeChannelSourceIfNoLongerNeeded();
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
private void ThrowIfKillCursorsCommandFailed(BsonDocument commandResult, ConnectionId connectionId)
{
if (!commandResult.GetValue("ok", false).ToBoolean())
{
throw new MongoCommandException(connectionId, "Kill cursors command returned an error.", commandResult);
}
else
{
var notFoundCursors = commandResult["cursorsNotFound"].AsBsonArray;
if (notFoundCursors.Count > 0)
{
throw new MongoCursorNotFoundException(connectionId, _cursorId, commandResult);
}
var killedCursors = commandResult["cursorsKilled"].AsBsonArray.Select(c => c.ToInt64());
if (!killedCursors.Contains(_cursorId))
{
throw new MongoCommandException(connectionId, "Kill cursors command failed.", commandResult);
}
}
}
private bool TryMoveNext(out bool hasMore)
{
hasMore = false;
if (_firstBatch != null)
{
_currentBatch = _firstBatch;
_firstBatch = null;
hasMore = true;
return true;
}
if (_currentBatch == null)
{
return true;
}
if (_cursorId == 0 || (_limit > 0 && _count == _limit.Value))
{
_currentBatch = null;
return true;
}
return false;
}
}
}