-
Notifications
You must be signed in to change notification settings - Fork 15
/
MongoPersistence.cs
775 lines (677 loc) · 30.2 KB
/
MongoPersistence.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
using MongoDB.Bson;
using MongoDB.Driver;
using NStore.Core.Logging;
using NStore.Core.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace NStore.Persistence.Mongo
{
public interface IMongoPersistence : IPersistence
{
Task InitAsync(CancellationToken cancellationToken);
}
public class MongoPersistence : MongoPersistence<MongoChunk>
{
public MongoPersistence(MongoPersistenceOptions options) : base(options)
{
}
}
public class MongoPersistence<TChunk> : IMongoPersistence, IEnhancedPersistence
where TChunk : IMongoChunk, new()
{
private IMongoDatabase _partitionsDb;
private IMongoDatabase _countersDb;
private IMongoCollection<TChunk> _chunks;
private IMongoCollection<Counter> _counters;
private readonly IMongoPayloadSerializer _mongoPayloadSerializer;
private readonly MongoPersistenceOptions _options;
private readonly INStoreLogger _logger;
private long _sequence = 0;
/// <summary>
/// Index for partitionId+Index, used for concurrency check.
/// </summary>
private const string PartitionIndexIdx = "partition_index";
/// <summary>
/// Index on partitionId+operationId, for idempotency on operations
/// </summary>
private const string PartitionOperationIdx = "partition_operation";
public bool SupportsFillers => true;
public MongoPersistence(MongoPersistenceOptions options)
{
if (options == null || !options.IsValid())
{
throw new MongoPersistenceException("Invalid options");
}
_options = options;
var partitionsBuild = new MongoUrlBuilder(options.PartitionsConnectionString);
_logger = options.LoggerFactory.CreateLogger(
$"Mongo-{String.Join(",", partitionsBuild.Servers.Select(s => $"{s.Host}:{s.Port}"))}, {options.PartitionsCollectionName}");
_mongoPayloadSerializer = options.MongoPayloadSerializer ?? new TypeSystemMongoPayloadSerializer();
Connect();
}
private void Connect()
{
var partitionsBuild = new MongoUrlBuilder(_options.PartitionsConnectionString);
_options.CustomizePartitionSettings(partitionsBuild);
var settings = MongoClientSettings.FromUrl(partitionsBuild.ToMongoUrl());
//by default we will use LINQv2. There are bugs in older version of mongo < 4.4
//and we feel safer to use the old LINQ provider.
settings.LinqProvider = MongoDB.Driver.Linq.LinqProvider.V2;
//The caller has the option to force the use of other link provider due to customization
//of the partition client settings.
_options.CustomizePartitionClientSettings(settings);
var partitionsClient = new MongoClient(settings);
this._partitionsDb = partitionsClient.GetDatabase(partitionsBuild.DatabaseName);
if (_options.SequenceConnectionString == null)
{
this._countersDb = _partitionsDb;
}
else
{
var countersUrlBuilder = new MongoUrlBuilder(_options.SequenceConnectionString);
_options.CustomizeSequenceSettings(countersUrlBuilder);
var countersSettings = MongoClientSettings.FromUrl(countersUrlBuilder.ToMongoUrl());
_options.CustomizeSequenceClientSettings(countersSettings);
var countersClient = new MongoClient(countersSettings);
this._countersDb = countersClient.GetDatabase(countersUrlBuilder.DatabaseName);
}
}
public async Task Drop(CancellationToken cancellationToken)
{
await this._partitionsDb
.DropCollectionAsync(_options.PartitionsCollectionName, cancellationToken)
.ConfigureAwait(false);
await this._countersDb
.DropCollectionAsync(_options.SequenceCollectionName, cancellationToken)
.ConfigureAwait(false);
}
public async Task ReadForwardAsync(
string partitionId,
long fromLowerIndexInclusive,
ISubscription subscription,
long toUpperIndexInclusive,
int limit,
CancellationToken cancellationToken
)
{
var filter = Builders<TChunk>.Filter.And(
Builders<TChunk>.Filter.Eq(x => x.PartitionId, partitionId),
Builders<TChunk>.Filter.Gte(x => x.Index, fromLowerIndexInclusive),
Builders<TChunk>.Filter.Lte(x => x.Index, toUpperIndexInclusive)
);
var sort = Builders<TChunk>.Sort.Ascending(x => x.Index);
var options = new FindOptions<TChunk>() { Sort = sort };
if (limit != int.MaxValue)
{
options.Limit = limit;
}
await PushToSubscriber(
fromLowerIndexInclusive,
subscription,
options,
filter,
false,
cancellationToken).ConfigureAwait(false);
}
public async Task ReadForwardMultiplePartitionsAsync(
IEnumerable<string> partitionIdsList,
long fromLowerIndexInclusive,
ISubscription subscription,
long toUpperIndexInclusive,
CancellationToken cancellationToken)
{
var filter = Builders<TChunk>.Filter.And(
Builders<TChunk>.Filter.In(x => x.PartitionId, partitionIdsList),
Builders<TChunk>.Filter.Gte(x => x.Index, fromLowerIndexInclusive),
Builders<TChunk>.Filter.Lte(x => x.Index, toUpperIndexInclusive)
);
var sort = Builders<TChunk>.Sort.Ascending(x => x.Index);
var options = new FindOptions<TChunk>() { Sort = sort };
await PushToSubscriber(
fromLowerIndexInclusive,
subscription,
options,
filter,
false,
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Pushes a result of a query to a subscriber handling all the logic.
/// </summary>
/// <param name="start"></param>
/// <param name="subscription"></param>
/// <param name="options"></param>
/// <param name="filter"></param>
/// <param name="broadcastPosition"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task PushToSubscriber(
long start,
ISubscription subscription,
FindOptions<TChunk> options,
FilterDefinition<TChunk> filter,
bool broadcastPosition,
CancellationToken cancellationToken)
{
long positionOrIndex = 0;
await subscription.OnStartAsync(start).ConfigureAwait(false);
try
{
using (var cursor = await _chunks.FindAsync(filter, options, cancellationToken).ConfigureAwait(false))
{
while (await cursor.MoveNextAsync(cancellationToken).ConfigureAwait(false))
{
foreach (var b in cursor.Current)
{
positionOrIndex = broadcastPosition ? b.Position : b.Index;
_mongoPayloadSerializer.ApplyDeserialization(b);
if (!await subscription.OnNextAsync(b).ConfigureAwait(false))
{
await subscription.StoppedAsync(positionOrIndex).ConfigureAwait(false);
return;
}
}
}
}
await subscription.CompletedAsync(positionOrIndex).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
_logger.LogWarning($"PushToSubscriber: {ex.Message}.\n{ex.StackTrace}");
await subscription.StoppedAsync(positionOrIndex).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogError($"Error During PushToSubscriber: {e.Message}.\n{e.StackTrace}");
await subscription.OnErrorAsync(positionOrIndex, e).ConfigureAwait(false);
}
}
public async Task ReadBackwardAsync(
string partitionId,
long fromUpperIndexInclusive,
ISubscription subscription,
long toLowerIndexInclusive,
int limit,
CancellationToken cancellationToken
)
{
var filter = Builders<TChunk>.Filter.And(
Builders<TChunk>.Filter.Eq(x => x.PartitionId, partitionId),
Builders<TChunk>.Filter.Lte(x => x.Index, fromUpperIndexInclusive),
Builders<TChunk>.Filter.Gte(x => x.Index, toLowerIndexInclusive)
);
var sort = Builders<TChunk>.Sort.Descending(x => x.Index);
var options = new FindOptions<TChunk>() { Sort = sort };
if (limit != int.MaxValue)
{
options.Limit = limit;
}
await PushToSubscriber(
fromUpperIndexInclusive,
subscription,
options,
filter,
false,
cancellationToken
).ConfigureAwait(false);
}
public async Task<IChunk> ReadSingleBackwardAsync(
string partitionId,
long fromUpperIndexInclusive,
CancellationToken cancellationToken
)
{
var filter = Builders<TChunk>.Filter.And(
Builders<TChunk>.Filter.Eq(x => x.PartitionId, partitionId),
Builders<TChunk>.Filter.Lte(x => x.Index, fromUpperIndexInclusive)
);
var sort = Builders<TChunk>.Sort.Descending(x => x.Index);
var options = new FindOptions<TChunk>() { Sort = sort, Limit = 1 };
using (var cursor = await _chunks.FindAsync(filter, options, cancellationToken).ConfigureAwait(false))
{
var chunk = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
return _mongoPayloadSerializer.ApplyDeserialization(chunk);
}
}
public async Task ReadAllAsync(long fromPositionInclusive, ISubscription subscription, int limit,
CancellationToken cancellationToken)
{
var filter = Builders<TChunk>.Filter.Gte(x => x.Position, fromPositionInclusive);
var options = new FindOptions<TChunk>()
{
Sort = Builders<TChunk>.Sort.Ascending(x => x.Position)
};
if (limit != int.MaxValue)
{
options.Limit = limit;
}
await PushToSubscriber(fromPositionInclusive, subscription, options, filter, true, cancellationToken)
.ConfigureAwait(false);
}
public async Task<long> ReadLastPositionAsync(CancellationToken cancellationToken)
{
var filter = Builders<TChunk>.Filter.Empty;
var projection = Builders<TChunk>.Projection.Include(x => x.Position);
var options = new FindOptions<TChunk, BsonDocument>()
{
Sort = Builders<TChunk>.Sort.Descending(x => x.Position),
Limit = 1,
Projection = projection
};
using (var cursor = await _chunks
.FindAsync(filter, options, cancellationToken)
.ConfigureAwait(false)
)
{
var lastPosition = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
if (lastPosition != null)
{
return lastPosition[0].AsInt64;
}
return 0;
}
}
public async Task<IChunk> ReplaceOneAsync
(
long position,
string partitionId,
long index,
object payload,
string operationId,
CancellationToken cancellationToken)
{
var filterByPosition = Builders<TChunk>.Filter.Eq(x => x.Position, position);
var chunk = new TChunk();
chunk.Init(
position,
partitionId,
index,
_mongoPayloadSerializer.Serialize(payload),
operationId ?? Guid.NewGuid().ToString()
);
try
{
var result = await _chunks.ReplaceOneAsync(
filterByPosition,
chunk,
(ReplaceOptions)null,
cancellationToken).ConfigureAwait(false);
if (!result.IsAcknowledged)
{
throw new MongoPersistenceException("Replace not Ackowledged");
}
return chunk;
}
catch (MongoWriteException ex)
{
//Need to understand what kind of exception we had, some of them could lead to a retry
if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
//Index violation, we do have a chunk that broke an unique index, we need to know if this is
//at partitionId level (concurrency) or at position level (UseLocalSequence == false and multiple process/appdomain are appending to the stream).
if (ex.Message.Contains(PartitionIndexIdx))
{
_logger.LogInformation($"DuplicateStreamIndexException: {ex.Message}.\n{ex.ToString()}");
throw new DuplicateStreamIndexException(chunk.PartitionId, chunk.Index);
}
if (ex.Message.Contains(PartitionOperationIdx))
{
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
return null;
}
}
throw;
}
}
public async Task<IChunk> ReadOneAsync(long position, CancellationToken cancellationToken)
{
var filterByPosition = Builders<TChunk>.Filter.Eq(x => x.Position, position);
var cursor = await _chunks.FindAsync(filterByPosition, cancellationToken: cancellationToken);
var chunk = await cursor.FirstOrDefaultAsync(cancellationToken: cancellationToken);
return chunk;
}
public async Task DeleteAsync(
string partitionId,
long fromLowerIndexInclusive,
long toUpperIndexInclusive,
CancellationToken cancellationToken
)
{
var filterById = Builders<TChunk>.Filter.Eq(x => x.PartitionId, partitionId);
if (fromLowerIndexInclusive > 0)
{
filterById = Builders<TChunk>.Filter.And(
filterById,
Builders<TChunk>.Filter.Gte(x => x.Index, fromLowerIndexInclusive)
);
}
if (toUpperIndexInclusive < long.MaxValue)
{
filterById = Builders<TChunk>.Filter.And(
filterById,
Builders<TChunk>.Filter.Lte(x => x.Index, toUpperIndexInclusive)
);
}
await _chunks.DeleteManyAsync(filterById, cancellationToken).ConfigureAwait(false);
}
public async Task<IChunk> ReadByOperationIdAsync(string partitionId, string operationId,
CancellationToken cancellationToken)
{
var filter = Builders<TChunk>.Filter.And(
Builders<TChunk>.Filter.Eq(x => x.PartitionId, partitionId),
Builders<TChunk>.Filter.Eq(x => x.OperationId, operationId)
);
var cursor = await _chunks.FindAsync(filter, cancellationToken: cancellationToken)
.ConfigureAwait(false);
var chunk = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
return _mongoPayloadSerializer.ApplyDeserialization(chunk);
}
public async Task ReadAllByOperationIdAsync(string operationId, ISubscription subscription,
CancellationToken cancellationToken)
{
var filter = Builders<TChunk>.Filter.Eq(x => x.OperationId, operationId);
var options = new FindOptions<TChunk>()
{
Sort = Builders<TChunk>.Sort.Ascending(x => x.Position)
};
await PushToSubscriber(0, subscription, options, filter, true, cancellationToken)
.ConfigureAwait(false);
}
private async Task PersistAsEmptyAsync(
TChunk chunk,
CancellationToken cancellationToken = default(CancellationToken)
)
{
TChunk empty;
//@@REVIEW partial index on mongo?
if (chunk.PartitionId == "::empty")
{
// reuse chunk
empty = chunk;
empty.RewriteIndex(empty.Position);
empty.RewriteOperationId("_" + empty.Position);
}
else
{
empty = new TChunk();
empty.Init(
chunk.Position,
"::empty",
chunk.Position,
_mongoPayloadSerializer.Serialize(null),
"_" + chunk.Position
);
}
await InternalPersistAsync(empty, cancellationToken).ConfigureAwait(false);
}
private async Task<IChunk> InternalPersistAsync(
TChunk chunk,
CancellationToken cancellationToken = default
)
{
int retry = 0;
while (true)
{
try
{
await _chunks.InsertOneAsync(chunk, cancellationToken: cancellationToken)
.ConfigureAwait(false);
return chunk;
}
catch (MongoWriteException ex)
{
//Circuit breaker, if for same reason we cannot write the chunk, we need to stop the process not retrying infiinte times.
if (retry++ > 100)
{
_logger.LogError($"Error During InternalPersistAsync. Reached number of max {retry} retry count: {ex.Message}.\n{ex}");
throw;
}
//Need to understand what kind of exception we had, some of them could lead to a retry
if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
//Index violation, we do have a chunk that broke an unique index, we need to know if this is
//at partitionId level (concurrency) or at position level (UseLocalSequence == false and multiple process/appdomain are appending to the stream).
if (ex.Message.Contains(PartitionIndexIdx))
{
await PersistAsEmptyAsync(chunk, cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
$"DuplicateStreamIndexException: {ex.Message}.\n{ex.ToString()}");
throw new DuplicateStreamIndexException(chunk.PartitionId, chunk.Index);
}
if (ex.Message.Contains(PartitionOperationIdx))
{
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
//since we should ignore the chunk (already exist a chunk with that operation Id, we fill with a blank).
await PersistAsEmptyAsync(chunk, cancellationToken).ConfigureAwait(false);
return null;
}
if (ex.Message.Contains("_id_"))
{
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
//some other process steals the Position, we need to warn the user, because too many of this error could suggest to enable UseLocalSequence
_logger.LogWarning(
$@"Error writing chunk #{chunk.Position} - Some other process already wrote position {chunk.Position}.
Operation will be retried.
If you see too many of this kind of errors, consider enabling UseLocalSequence.
{ex.Message} - {ex.GetType().FullName} ");
await ReloadSequence(cancellationToken).ConfigureAwait(false);
chunk.RewritePosition(await GetNextId(1, cancellationToken).ConfigureAwait(false));
continue;
}
}
_logger.LogError($"Error During InternalPersistAsync: {ex.Message}.\n{ex}");
throw;
}
}
}
public async Task InitAsync(CancellationToken cancellationToken)
{
if (_partitionsDb == null)
{
Connect();
}
if (_options.DropOnInit)
{
Drop(cancellationToken).Wait(cancellationToken);
}
_chunks = _partitionsDb.GetCollection<TChunk>(_options.PartitionsCollectionName);
_counters = _countersDb.GetCollection<Counter>(_options.SequenceCollectionName);
await CreateIndexAsync(cancellationToken).ConfigureAwait(false);
if (_options.UseLocalSequence)
{
await ReloadSequence(cancellationToken).ConfigureAwait(false);
}
else
{
await EnsureFirstSequenceRecord().ConfigureAwait(false);
}
}
private async Task CreateIndexAsync(CancellationToken cancellationToken)
{
//Indexes are created only if connection string is not associated to a standard readonly user.
if (!_options.ReadonlyUser)
{
var partitionIndex = new CreateIndexModel<TChunk>(Builders<TChunk>.IndexKeys
.Ascending(x => x.PartitionId)
.Ascending(x => x.Index),
new CreateIndexOptions()
{
Unique = true,
Name = PartitionIndexIdx
});
var partitionOperation = new CreateIndexModel<TChunk>(
Builders<TChunk>.IndexKeys
.Ascending(x => x.PartitionId)
.Ascending(x => x.OperationId),
new CreateIndexOptions()
{
Unique = true,
Name = PartitionOperationIdx
});
await _chunks.Indexes.CreateOneAsync(
partitionIndex,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
await _chunks.Indexes.CreateOneAsync(
partitionOperation,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
private async Task ReloadSequence(CancellationToken cancellationToken = default)
{
var filter = Builders<TChunk>.Filter.Empty;
var lastRecord = await _chunks
.Find(filter)
.SortByDescending(x => x.Position)
.Project(Builders<TChunk>.Projection.Include("_id"))
.Limit(1)
.ToCursorAsync()
.ConfigureAwait(false);
var record = await lastRecord.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
this._sequence = record == null ? 0 : record["_id"].AsInt64;
}
private async Task EnsureFirstSequenceRecord()
{
//initialize if needed
var existing = _counters.AsQueryable().SingleOrDefault(c => c.Id == _options.SequenceId);
if (existing == null)
{
try
{
await _counters.InsertOneAsync(new Counter()
{
Id = _options.SequenceId,
LastValue = 0L
}).ConfigureAwait(false);
}
catch (MongoWriteException ex)
{
if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
//ignore the error, in the meanwhile between loading existing value and inserting someone else already inserted the record, everything is normal.
}
else
{
throw;
}
}
}
}
private async Task<long> GetNextId(int size, CancellationToken cancellationToken = default)
{
if (_options.UseLocalSequence)
{
return Interlocked.Add(ref _sequence, size);
}
// server side sequence
var filter = Builders<Counter>.Filter.Eq(x => x.Id, _options.SequenceId);
var update = Builders<Counter>.Update.Inc(x => x.LastValue, size);
var options = new FindOneAndUpdateOptions<Counter>()
{
IsUpsert = true,
ReturnDocument = ReturnDocument.After
};
var updateResult = await _counters.FindOneAndUpdateAsync(
filter,
update,
options,
cancellationToken
)
.ConfigureAwait(false);
return updateResult.LastValue;
}
public async Task<IChunk> AppendAsync(
string partitionId,
long index,
object payload,
string operationId,
CancellationToken cancellationToken)
{
if (index < 0)
{
throw new InvalidStreamIndexException(partitionId, index);
}
long id = await GetNextId(1, cancellationToken).ConfigureAwait(false);
var chunk = new TChunk();
chunk.Init(
id,
partitionId,
index,
_mongoPayloadSerializer.Serialize(payload),
operationId ?? Guid.NewGuid().ToString()
);
return await InternalPersistAsync(chunk, cancellationToken).ConfigureAwait(false);
}
public async Task AppendBatchAsync(WriteJob[] queue, CancellationToken cancellationToken)
{
var insertCount = queue.Length;
var lastId = await GetNextId(insertCount, cancellationToken)
.ConfigureAwait(false);
var firstId = lastId - insertCount + 1;
var chunks = new TChunk[insertCount];
for (var currentIdx = 0; currentIdx < insertCount; currentIdx++)
{
var current = queue[currentIdx];
long id = firstId + currentIdx;
var chunk = new TChunk();
chunk.Init(
id,
current.PartitionId,
current.Index,
_mongoPayloadSerializer.Serialize(current.Payload),
current.OperationId ?? Guid.NewGuid().ToString()
);
chunks[currentIdx] = chunk;
}
var options = new InsertManyOptions()
{
IsOrdered = false,
};
try
{
await _chunks
.InsertManyAsync(chunks, options, cancellationToken)
.ConfigureAwait(false);
}
catch (MongoBulkWriteException<TChunk> e)
{
foreach (var err in e.WriteErrors)
{
if (err.Category == ServerErrorCategory.DuplicateKey)
{
if (err.Message.Contains(PartitionIndexIdx))
{
queue[err.Index].Failed(WriteJob.WriteResult.DuplicatedIndex);
continue;
}
if (err.Message.Contains(PartitionOperationIdx))
{
queue[err.Index].Failed(WriteJob.WriteResult.DuplicatedOperation);
}
}
}
}
for (var index = 0; index < queue.Length; index++)
{
var writeJob = queue[index];
if (writeJob.Result == WriteJob.WriteResult.None)
{
writeJob.Succeeded(chunks[index]);
}
}
}
}
}