-
Notifications
You must be signed in to change notification settings - Fork 2
/
AttemptContext.cs
1611 lines (1444 loc) · 79 KB
/
AttemptContext.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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Couchbase.Core;
using Couchbase.Core.Diagnostics.Tracing;
using Couchbase.Core.Exceptions;
using Couchbase.Core.Exceptions.KeyValue;
using Couchbase.Core.IO.Operations;
using Couchbase.Core.IO.Transcoders;
using Couchbase.Core.Logging;
using Couchbase.KeyValue;
using Couchbase.Transactions.ActiveTransactionRecords;
using Couchbase.Transactions.Cleanup;
using Couchbase.Transactions.Components;
using Couchbase.Transactions.Config;
using Couchbase.Transactions.DataAccess;
using Couchbase.Transactions.DataModel;
using Couchbase.Transactions.Error;
using Couchbase.Transactions.Error.Attempts;
using Couchbase.Transactions.Error.External;
using Couchbase.Transactions.Error.Internal;
using Couchbase.Transactions.Forwards;
using Couchbase.Transactions.Internal;
using Couchbase.Transactions.Internal.Test;
using Couchbase.Transactions.LogUtil;
using Couchbase.Transactions.Support;
using DnsClient.Internal;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static Couchbase.Transactions.Error.ErrorBuilder;
using Exception = System.Exception;
using ILoggerFactory = Microsoft.Extensions.Logging.ILoggerFactory;
namespace Couchbase.Transactions
{
public class AttemptContext
{
private static readonly TimeSpan WriteWriteConflictTimeLimit = TimeSpan.FromSeconds(1);
private readonly TransactionContext _overallContext;
private readonly TransactionConfig _config;
private readonly ITestHooks _testHooks;
internal IRedactor Redactor { get; }
private AttemptStates _state = AttemptStates.NOTHING_WRITTEN;
private readonly ErrorTriage _triage;
private readonly List<StagedMutation> _stagedMutations = new List<StagedMutation>();
private readonly object _initAtrLock = new object();
private IAtrRepository? _atr = null;
private IDocumentRepository _docs;
private readonly DurabilityLevel _effectiveDurabilityLevel;
private readonly List<MutationToken> _finalMutations = new List<MutationToken>();
private readonly ConcurrentDictionary<long, TransactionOperationFailedException> _previousErrors = new ConcurrentDictionary<long, TransactionOperationFailedException>();
private bool _expirationOvertimeMode = false;
private readonly ILoggerFactory _loggerFactory;
private readonly IRequestTracer _requestTracer;
public string AttemptId { get; }
public string TransactionId => _overallContext.TransactionId;
internal bool UnstagingComplete { get; private set; } = false;
internal AttemptContext(TransactionContext overallContext,
TransactionConfig config,
string attemptId,
ITestHooks? testHooks,
IRedactor redactor,
Microsoft.Extensions.Logging.ILoggerFactory loggerFactory,
IDocumentRepository? documentRepository = null,
IAtrRepository? atrRepository = null,
IRequestTracer? requestTracer = null)
{
_requestTracer = requestTracer ?? new NoopRequestTracer();
AttemptId = attemptId ?? throw new ArgumentNullException(nameof(attemptId));
_overallContext = overallContext ?? throw new ArgumentNullException(nameof(overallContext));
_config = config ?? throw new ArgumentNullException(nameof(config));
_testHooks = testHooks ?? DefaultTestHooks.Instance;
Redactor = redactor ?? throw new ArgumentNullException(nameof(redactor));
_effectiveDurabilityLevel = _overallContext.PerConfig?.DurabilityLevel ?? config.DurabilityLevel;
_loggerFactory = loggerFactory;
Logger = loggerFactory.CreateLogger<AttemptContext>();
_triage = new ErrorTriage(this, loggerFactory);
_docs = documentRepository ?? new DocumentRepository(_overallContext, _config.KeyValueTimeout, _effectiveDurabilityLevel, AttemptId);
if (atrRepository != null)
{
_atr = atrRepository;
}
}
public ILogger<AttemptContext> Logger { get; }
/// <summary>
/// Gets a document.
/// </summary>
/// <param name="collection">The collection to look up the document in.</param>
/// <param name="id">The ID of the document.</param>
/// <returns>A <see cref="TransactionGetResult"/> containing the document.</returns>
/// <exception cref="DocumentNotFoundException">If the document does not exist.</exception>
public async Task<TransactionGetResult> GetAsync(ICouchbaseCollection collection, string id)
{
var getResult = await GetOptionalAsync(collection, id).CAF();
if (getResult == null)
{
throw new DocumentNotFoundException();
}
return getResult;
}
/// <summary>
/// Gets a document or null.
/// </summary>
/// <param name="collection">The collection to look up the document in.</param>
/// <param name="id">The ID of the document.</param>
/// <param name="parentSpan">The optional parent tracing span.</param>
/// <returns>A <see cref="TransactionGetResult"/> containing the document, or null if not found.</returns>
public async Task<TransactionGetResult?> GetOptionalAsync(ICouchbaseCollection collection, string id, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
DoneCheck();
CheckErrors();
CheckExpiryAndThrow(id, hookPoint: ITestHooks.HOOK_GET);
/*
* Check stagedMutations.
If the doc already exists in there as a REPLACE or INSERT return its post-transaction content in a TransactionGetResult.
Protocol 2.0 amendment: and TransactionGetResult::links().isDeleted() reflecting whether it is a tombstone or not.
Else if the doc already exists in there as a remove, return empty.
*/
var staged = FindStaged(collection, id);
if (staged != null)
{
switch (staged.Type)
{
case StagedMutationType.Insert:
case StagedMutationType.Replace:
// LOGGER.info(attemptId, "found own-write of mutated doc %s", RedactableArgument.redactUser(id));
return TransactionGetResult.FromOther(staged.Doc, new JObjectContentWrapper(staged.Content), TransactionJsonDocumentStatus.OwnWrite);
case StagedMutationType.Remove:
// LOGGER.info(attemptId, "found own-write of removed doc %s", RedactableArgument.redactUser(id));
return null;
default:
throw new InvalidOperationException($"Document '{Redactor.UserData(id)}' was staged with type {staged.Type}");
}
}
try
{
try
{
await _testHooks.BeforeDocGet(this, id).CAF();
var result = await GetWithMavAsync(collection, id, parentSpan: traceSpan.Item);
await _testHooks.AfterGetComplete(this, id).CAF();
await ForwardCompatibility.Check(this, ForwardCompatibility.Gets, result?.TransactionXattrs?.ForwardCompatibility);
return result;
}
catch (Exception ex)
{
var tr = _triage.TriageGetErrors(ex);
switch (tr.ec)
{
case ErrorClass.FailDocNotFound:
return TransactionGetResult.Empty;
default:
throw _triage.AssertNotNull(tr, ex);
}
}
}
catch (TransactionOperationFailedException toSave)
{
SaveErrorWrapper(toSave);
throw;
}
}
private async Task<TransactionGetResult?> GetWithMavAsync(ICouchbaseCollection collection, string id, string? resolveMissingAtrEntry = null, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
try
{
// we need to resolve the state of that transaction. Here is where we do the “Monotonic Atomic View” (MAV) logic
try
{
// Do a Sub-Document lookup, getting all transactional metadata, the “$document” virtual xattr,
// and the document’s body. Timeout is set as in Timeouts.
var docLookupResult = await _docs.LookupDocumentAsync(collection, id, fullDocument: true).CAF();
Logger.LogDebug("{method} for {redactedId}, attemptId={attemptId}, postCas={postCas}", nameof(GetWithMavAsync), Redactor.UserData(id), AttemptId, docLookupResult.Cas);
if (docLookupResult == null)
{
return TransactionGetResult.Empty;
}
var txn = docLookupResult?.TransactionXattrs;
if (txn?.Id?.AttemptId == null
|| txn?.Id?.Transactionid == null
|| txn?.AtrRef?.BucketName == null
|| txn?.AtrRef?.CollectionName == null)
{
// Not in a transaction, or insufficient transaction metadata
return docLookupResult!.IsDeleted
? TransactionGetResult.Empty
: docLookupResult.GetPreTransactionResult(TransactionJsonDocumentStatus.Normal);
}
if (resolveMissingAtrEntry == txn.Id?.AttemptId)
{
// This is our second attempt getting the document, and it’s in the same state as before
return docLookupResult!.IsDeleted
? TransactionGetResult.Empty
: docLookupResult.GetPostTransactionResult(TransactionJsonDocumentStatus.InTxnOther);
}
resolveMissingAtrEntry = txn.Id?.AttemptId;
// TODO: double-check if atr attemptid == this attempt id, and return post-transaction version
// (should have been covered by staged mutation check)
var getCollectionTask = _atr?.GetAtrCollection(txn.AtrRef)
?? AtrRepository.GetAtrCollection(txn.AtrRef, collection);
var docAtrCollection = await getCollectionTask.CAF()
?? throw new ActiveTransactionRecordNotFoundException();
var findEntryTask = _atr?.FindEntryForTransaction(docAtrCollection, txn.AtrRef.Id!, txn.Id!.AttemptId)
?? AtrRepository.FindEntryForTransaction(docAtrCollection, txn.AtrRef.Id!, txn.Id!.AttemptId, _config.KeyValueTimeout);
var atrEntry = await findEntryTask.CAF()
?? throw new ActiveTransactionRecordEntryNotFoundException();
if (txn.Id!.AttemptId == AttemptId)
{
if (txn.Operation?.Type == "remove")
{
return TransactionGetResult.Empty;
}
else
{
return docLookupResult!.GetPostTransactionResult(TransactionJsonDocumentStatus.OwnWrite);
}
}
await ForwardCompatibility.Check(this, ForwardCompatibility.GetsReadingAtr, atrEntry.ForwardCompatibility);
if (atrEntry.State == AttemptStates.COMMITTED || atrEntry.State == AttemptStates.COMPLETED)
{
if (txn.Operation?.Type == "remove")
{
return TransactionGetResult.Empty;
}
return docLookupResult!.GetPostTransactionResult(TransactionJsonDocumentStatus.InTxnCommitted);
}
if (docLookupResult!.IsDeleted || txn.Operation?.Type == "insert")
{
return TransactionGetResult.Empty;
}
return docLookupResult.GetPreTransactionResult(TransactionJsonDocumentStatus.InTxnOther);
}
catch (ActiveTransactionRecordEntryNotFoundException)
{
throw;
}
catch (Exception atrLookupException)
{
var atrLookupTriage = _triage.TriageAtrLookupInMavErrors(atrLookupException);
throw _triage.AssertNotNull(atrLookupTriage, atrLookupException);
}
}
catch (ActiveTransactionRecordEntryNotFoundException ex)
{
Logger.LogWarning("ATR entry not found: {ex}", ex);
if (resolveMissingAtrEntry == null)
{
throw;
}
return await GetWithMavAsync(collection, id, resolveMissingAtrEntry).CAF();
}
}
private void CheckErrors()
{
/*
* Before performing any operation, including commit, check if the errors member is non-empty.
* If so, raise an Error(ec=FAIL_OTHER, cause=PreviousOperationFailed).
*/
if (!_previousErrors.IsEmpty)
{
throw ErrorBuilder.CreateError(this, ErrorClass.FailOther)
.Cause(new PreviousOperationFailedException(_previousErrors.Values))
.Build();
}
}
private StagedMutation FindStaged(ICouchbaseCollection collection, string id)
{
return _stagedMutations.Find(sm => sm.Doc.Id == id
&& sm.Doc.Collection.Name == collection.Name
&& sm.Doc.Collection.Scope.Name == collection.Scope.Name
&& sm.Doc.Collection.Scope.Bucket.Name == collection.Scope.Bucket.Name);
}
private StagedMutation FindStaged(TransactionGetResult doc) => FindStaged(doc.Collection, doc.Id);
/// <summary>
/// Replace the content of a document previously fetched in this transaction with new content.
/// </summary>
/// <param name="doc">The <see cref="TransactionGetResult"/> of a document previously looked up in this transaction.</param>
/// <param name="content">The updated content.</param>
/// <param name="parentSpan">The optional parent tracing span.</param>
/// <returns>A <see cref="TransactionGetResult"/> reflecting the updated content.</returns>
public async Task<TransactionGetResult> ReplaceAsync(TransactionGetResult doc, object content, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
DoneCheck();
CheckErrors();
CheckExpiryAndThrow(doc.Id, ITestHooks.HOOK_REPLACE);
await CheckWriteWriteConflict(doc, ForwardCompatibility.WriteWriteConflictReplacing, traceSpan.Item).CAF();
await InitAtrIfNeeded(doc.Collection, doc.Id, traceSpan.Item);
await SetAtrPendingIfFirstMutation(doc.Collection, traceSpan.Item);
return await CreateStagedReplace(doc, content, accessDeleted: doc.IsDeleted, parentSpan: traceSpan.Item);
}
private async Task SetAtrPendingIfFirstMutation(ICouchbaseCollection collection, IRequestSpan? parentSpan)
{
if (_stagedMutations.Count == 0)
{
await SetAtrPending(parentSpan);
}
}
private async Task<TransactionGetResult> CreateStagedReplace(TransactionGetResult doc, object content, bool accessDeleted, IRequestSpan? parentSpan)
{
using var traceSpan = TraceSpan(parent: parentSpan);
_ = _atr ?? throw new ArgumentNullException(nameof(_atr), "ATR should have already been initialized");
try
{
try
{
await _testHooks.BeforeStagedReplace(this, doc.Id);
var contentWrapper = new JObjectContentWrapper(content);
bool isTombstone = doc.Cas == 0;
(var updatedCas, var mutationToken) = await _docs.MutateStagedReplace(doc, content, _atr, accessDeleted).CAF();
Logger.LogDebug("{method} for {redactedId}, attemptId={attemptId}, preCase={preCas}, postCas={postCas}, accessDeleted={accessDeleted}", nameof(CreateStagedReplace), Redactor.UserData(doc.Id), AttemptId, doc.Cas, updatedCas, accessDeleted);
await _testHooks.AfterStagedReplaceComplete(this, doc.Id).CAF();
doc.Cas = updatedCas;
var stagedOld = FindStaged(doc);
if (stagedOld != null)
{
_stagedMutations.Remove(stagedOld);
}
if (stagedOld?.Type == StagedMutationType.Insert)
{
// If doc is already in stagedMutations as an INSERT or INSERT_SHADOW, then remove that, and add this op as a new INSERT or INSERT_SHADOW(depending on what was replaced).
_stagedMutations.Add(new StagedMutation(doc, content, StagedMutationType.Insert, mutationToken));
}
else
{
// If doc is already in stagedMutations as a REPLACE, then overwrite it.
_stagedMutations.Add(new StagedMutation(doc, content, StagedMutationType.Replace, mutationToken));
}
return TransactionGetResult.FromInsert(
doc.Collection,
doc.Id,
contentWrapper,
_overallContext.TransactionId,
AttemptId,
_atr.AtrId,
_atr.BucketName,
_atr.ScopeName,
_atr.CollectionName,
updatedCas,
isTombstone);
}
catch (Exception ex)
{
var triaged = _triage.TriageCreateStagedRemoveOrReplaceError(ex);
if (triaged.ec == ErrorClass.FailExpiry)
{
_expirationOvertimeMode = true;
}
throw _triage.AssertNotNull(triaged, ex);
}
}
catch (TransactionOperationFailedException toSave)
{
SaveErrorWrapper(toSave);
throw;
}
}
/// <summary>
/// Insert a document.
/// </summary>
/// <param name="collection">The collection to insert the document into.</param>
/// <param name="id">The ID of the new document.</param>
/// <param name="content">The content of the new document.</param>
/// <param name="parentSpan">The optional parent tracing span.</param>
/// <returns>A <see cref="TransactionGetResult"/> representing the inserted document.</returns>
public async Task<TransactionGetResult> InsertAsync(ICouchbaseCollection collection, string id, object content, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
using var logScope = Logger.BeginMethodScope();
DoneCheck();
CheckErrors();
// If this document already exists in StagedMutation, raise Error(FAIL_OTHER, cause=IllegalStateException [or platform-specific equivalent]).
if (_stagedMutations.Any(sm => sm.Doc.FullyQualifiedId == TransactionGetResult.GetFullyQualifiedId(collection, id)))
{
throw CreateError(this, ErrorClass.FailOther)
.Cause(new InvalidOperationException("Document is already staged for a mutation."))
.Build();
}
CheckExpiryAndThrow(id, hookPoint: ITestHooks.HOOK_INSERT);
await InitAtrIfNeeded(collection, id, traceSpan.Item);
await SetAtrPendingIfFirstMutation(collection, traceSpan.Item);
return await CreateStagedInsert(collection, id, content, parentSpan: traceSpan.Item).CAF();
}
private async Task<TransactionGetResult> CreateStagedInsert(ICouchbaseCollection collection, string id, object content, ulong? cas = null, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
try
{
bool isTombstone = cas == null;
var result = await RepeatUntilSuccessOrThrow<TransactionGetResult?>(async () =>
{
try
{
// Check expiration again, since insert might be retried.
ErrorIfExpiredAndNotInExpiryOvertimeMode(ITestHooks.HOOK_CREATE_STAGED_INSERT, id);
await _testHooks.BeforeStagedInsert(this, id).CAF();
var contentWrapper = new JObjectContentWrapper(content);
(var updatedCas, var mutationToken) = await _docs.MutateStagedInsert(collection, id, content, _atr!, cas);
Logger.LogDebug("{method} for {redactedId}, attemptId={attemptId}, preCas={preCas}, postCas={postCas}", nameof(CreateStagedInsert), Redactor.UserData(id), AttemptId, cas, updatedCas);
_ = _atr ?? throw new ArgumentNullException(nameof(_atr), "ATR should have already been initialized");
var getResult = TransactionGetResult.FromInsert(
collection,
id,
contentWrapper,
_overallContext.TransactionId,
AttemptId,
_atr.AtrId,
_atr.BucketName,
_atr.ScopeName,
_atr.CollectionName,
updatedCas,
isTombstone);
await _testHooks.AfterStagedInsertComplete(this, id).CAF();
var stagedMutation = new StagedMutation(getResult, content, StagedMutationType.Insert,
mutationToken);
_stagedMutations.Add(stagedMutation);
return (RepeatAction.NoRepeat, getResult);
}
catch (Exception ex)
{
var triaged = _triage.TriageCreateStagedInsertErrors(ex, _expirationOvertimeMode);
switch (triaged.ec)
{
case ErrorClass.FailExpiry:
_expirationOvertimeMode = true;
throw _triage.AssertNotNull(triaged, ex);
case ErrorClass.FailAmbiguous:
return (RepeatAction.RepeatWithDelay, null);
case ErrorClass.FailCasMismatch:
case ErrorClass.FailDocAlreadyExists:
var repeatAction = await RepeatUntilSuccessOrThrow<RepeatAction>(async () =>
{
// handle FAIL_DOC_ALREADY_EXISTS
try
{
Logger.LogDebug("{method}.HandleDocExists for {redactedId}, attemptId={attemptId}, preCas={preCas}", nameof(CreateStagedInsert), Redactor.UserData(id), AttemptId, 0);
await _testHooks.BeforeGetDocInExistsDuringStagedInsert(this, id).CAF();
var docWithMeta = await _docs.LookupDocumentAsync(collection, id, fullDocument: false).CAF();
await ForwardCompatibility.Check(this, ForwardCompatibility.WriteWriteConflictInsertingGet, docWithMeta?.TransactionXattrs?.ForwardCompatibility);
var docInATransaction =
docWithMeta?.TransactionXattrs?.Id?.Transactionid != null;
isTombstone = docWithMeta?.IsDeleted == true;
if (isTombstone && !docInATransaction)
{
// If the doc is a tombstone and not in any transaction
// -> It’s ok to go ahead and overwrite.
// Perform this algorithm (createStagedInsert) from the top with cas=the cas from the get.
cas = docWithMeta!.Cas;
// (innerRepeat, createStagedInsertRepeat)
return (RepeatAction.NoRepeat, RepeatAction.RepeatNoDelay);
}
// Else if the doc is not in a transaction
// -> Raise Error(FAIL_DOC_ALREADY_EXISTS, cause=DocumentExistsException).
// There is logic further up the stack that handles this by fast-failing the transaction.
if (!docInATransaction)
{
throw CreateError(this, ErrorClass.FailDocAlreadyExists)
.Cause(new DocumentExistsException())
.Build();
}
else
{
// Else call the CheckWriteWriteConflict logic, which conveniently does everything we need to handle the above cases.
var getResult = docWithMeta!.GetPostTransactionResult(TransactionJsonDocumentStatus.InTxnOther);
await CheckWriteWriteConflict(getResult, ForwardCompatibility.WriteWriteConflictInserting, traceSpan.Item).CAF();
// If this logic succeeds, we are ok to overwrite the doc.
// Perform this algorithm (createStagedInsert) from the top, with cas=the cas from the get.
cas = docWithMeta.Cas;
return (RepeatAction.NoRepeat, RepeatAction.RepeatNoDelay);
}
}
catch (Exception exDocExists)
{
var triagedDocExists = _triage.TriageDocExistsOnStagedInsertErrors(exDocExists);
throw _triage.AssertNotNull(triagedDocExists, exDocExists);
}
}).CAF();
return (repeatAction, null);
}
throw _triage.AssertNotNull(triaged, ex);
}
}).CAF();
return result ?? throw new InvalidOperationException("Final result should not be null");
}
catch (TransactionOperationFailedException toSave)
{
SaveErrorWrapper(toSave);
throw;
}
}
private IEnumerable<StagedMutation> StagedInserts =>
_stagedMutations.Where(sm => sm.Type == StagedMutationType.Insert);
private IEnumerable<StagedMutation> StagedReplaces => _stagedMutations.Where(sm => sm.Type == StagedMutationType.Replace);
private IEnumerable<StagedMutation> StagedRemoves => _stagedMutations.Where(sm => sm.Type == StagedMutationType.Remove);
private async Task SetAtrPending(IRequestSpan? parentSpan)
{
using var traceSpan = TraceSpan(parent: parentSpan);
var atrId = _atr!.AtrId;
try
{
await RepeatUntilSuccessOrThrow(async () =>
{
try
{
ErrorIfExpiredAndNotInExpiryOvertimeMode(ITestHooks.HOOK_ATR_PENDING);
await _testHooks.BeforeAtrPending(this);
var t1 = _overallContext.StartTime;
var t2 = DateTimeOffset.UtcNow;
var tElapsed = t2 - t1;
var tc = _config.ExpirationTime;
var tRemaining = tc - tElapsed;
var exp = (ulong)Math.Max(Math.Min(tRemaining.TotalMilliseconds, tc.TotalMilliseconds), 0);
await _atr.MutateAtrPending(exp);
Logger?.LogDebug($"{nameof(SetAtrPending)} for {Redactor.UserData(_atr.FullPath)} (attempt={AttemptId})");
await _testHooks.AfterAtrPending(this);
_state = AttemptStates.PENDING;
return RepeatAction.NoRepeat;
}
catch (Exception ex)
{
var triaged = _triage.TriageSetAtrPendingErrors(ex, _expirationOvertimeMode);
Logger.LogWarning("Failed with {ec} in {method}: {reason}", triaged.ec, nameof(SetAtrPending), ex.Message);
switch (triaged.ec)
{
case ErrorClass.FailExpiry:
_expirationOvertimeMode = true;
break;
case ErrorClass.FailAmbiguous:
return RepeatAction.RepeatWithDelay;
case ErrorClass.FailPathAlreadyExists:
// proceed as though op was successful.
return RepeatAction.NoRepeat;
}
throw _triage.AssertNotNull(triaged, ex);
}
}).CAF();
}
catch (TransactionOperationFailedException toSave)
{
SaveErrorWrapper(toSave);
throw;
}
}
/// <summary>
/// Remove a document previously looked up in this transaction.
/// </summary>
/// <param name="doc">The <see cref="TransactionGetResult"/> of a document previously looked up in this transaction.</param>
/// <param name="parentSpan">The optional parent tracing span.</param>
/// <returns>A task representing the asynchronous work.</returns>
public async Task RemoveAsync(TransactionGetResult doc, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
DoneCheck();
CheckErrors();
CheckExpiryAndThrow(doc.Id, ITestHooks.HOOK_REMOVE);
if (StagedInserts.Any(sm => sm.Doc.FullyQualifiedId == doc.FullyQualifiedId))
{
throw CreateError(this, ErrorClass.FailOther)
.Cause(new InvalidOperationException("Document is already staged for insert."))
.Build();
}
await CheckWriteWriteConflict(doc, ForwardCompatibility.WriteWriteConflictRemoving, traceSpan.Item).CAF();
await InitAtrIfNeeded(doc.Collection, doc.Id, traceSpan.Item);
await SetAtrPendingIfFirstMutation(doc.Collection, traceSpan.Item).CAF();
await CreateStagedRemove(doc, traceSpan.Item).CAF();
}
private async Task CreateStagedRemove(TransactionGetResult doc, IRequestSpan? parentSpan)
{
using var traceSpan = TraceSpan(parent: parentSpan);
try
{
try
{
await _testHooks.BeforeStagedRemove(this, doc.Id).CAF();
(var updatedCas, var mutationToken) = await _docs.MutateStagedRemove(doc, _atr!).CAF();
Logger?.LogDebug($"{nameof(CreateStagedRemove)} for {Redactor.UserData(doc.Id)}, attemptId={AttemptId}, preCas={doc.Cas}, postCas={updatedCas}");
await _testHooks.AfterStagedRemoveComplete(this, doc.Id).CAF();
doc.Cas = updatedCas;
if (_stagedMutations.Exists(sm => sm.Doc.Id == doc.Id && sm.Type == StagedMutationType.Insert))
{
// TXNJ-35: handle insert-delete with same doc
// CommitAsync+rollback: Want to delete the staged empty doc
// However this is hard in practice. If we remove from stagedInsert and add to
// stagedRemove then commit will work fine, but rollback will not remove the doc.
// So, fast fail this scenario.
throw new InvalidOperationException(
$"doc {Redactor.UserData(doc.Id)} is being removed after being inserted in the same txn.");
}
var stagedRemove = new StagedMutation(doc, TransactionFields.StagedDataRemoveKeyword,
StagedMutationType.Remove, mutationToken);
_stagedMutations.Add(stagedRemove);
}
catch (Exception ex)
{
var triaged = _triage.TriageCreateStagedRemoveOrReplaceError(ex);
if (triaged.ec == ErrorClass.FailExpiry)
{
_expirationOvertimeMode = true;
}
throw _triage.AssertNotNull(triaged, ex);
}
}
catch (TransactionOperationFailedException toSave)
{
SaveErrorWrapper(toSave);
throw;
}
}
internal async Task AutoCommit(IRequestSpan? parentSpan)
{
switch (_state)
{
case AttemptStates.NOTHING_WRITTEN:
case AttemptStates.PENDING:
await CommitAsync(parentSpan).CAF();
break;
}
}
public async Task CommitAsync(IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
if (!_previousErrors.IsEmpty)
{
_triage.ThrowIfCommitWithPreviousErrors(_previousErrors.Values);
}
// https://hackmd.io/Eaf20XhtRhi8aGEn_xIH8A#CommitAsync
CheckExpiryAndThrow(null, ITestHooks.HOOK_BEFORE_COMMIT);
DoneCheck();
if (_stagedMutations.Count == 0)
{
// If no mutation has been performed. Return success.
// This will leave state as NOTHING_WRITTEN,
return;
}
await SetAtrCommit(traceSpan.Item).CAF();
await UnstageDocs(traceSpan.Item).CAF();
await SetAtrComplete(traceSpan.Item).CAF();
}
private async Task SetAtrComplete(IRequestSpan? parentSpan)
{
using var traceSpan = TraceSpan(parent: parentSpan);
// https://hackmd.io/Eaf20XhtRhi8aGEn_xIH8A#SetATRComplete
if (HasExpiredClientSide(null, ITestHooks.HOOK_ATR_COMPLETE) && !_expirationOvertimeMode)
{
// If transaction has expired and not in ExpiryOvertimeMode: though technically expired, the transaction should be regarded
// as successful, as this is just a cleanup step.
// Return success.
return;
}
try
{
await _testHooks.BeforeAtrComplete(this).CAF();
await _atr!.MutateAtrComplete().CAF();
Logger?.LogDebug($"{nameof(SetAtrComplete)} for {Redactor.UserData(_atr.FullPath)} (attempt={AttemptId})");
await _testHooks.AfterAtrComplete(this).CAF();
_state = AttemptStates.COMPLETED;
UnstagingComplete = true;
}
catch (Exception ex)
{
var triaged = _triage.TriageSetAtrCompleteErrors(ex);
if (triaged.toThrow != null)
{
throw triaged.toThrow;
}
else
{
// Else -> Setting the ATR to COMPLETED is purely a cleanup step, there’s no need to retry it until expiry.
// Simply return success (leaving state at COMMITTED).
return;
}
}
}
private async Task UnstageDocs(IRequestSpan? parentSpan)
{
using var traceSpan = TraceSpan(parent: parentSpan);
foreach (var sm in _stagedMutations)
{
(var cas, var content) = await FetchIfNeededBeforeUnstage(sm).CAF();
switch (sm.Type)
{
case StagedMutationType.Remove:
await UnstageRemove(sm).CAF();
break;
case StagedMutationType.Insert:
await UnstageInsertOrReplace(sm, cas, content, insertMode: true, ambiguityResolutionMode: false).CAF();
break;
case StagedMutationType.Replace:
await UnstageInsertOrReplace(sm, cas, content, insertMode: false, ambiguityResolutionMode: false).CAF();
break;
default:
throw new InvalidOperationException($"Cannot un-stage transaction mutation of type {sm.Type}");
}
}
}
private async Task UnstageRemove(StagedMutation sm, bool ambiguityResolutionMode = false, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
// TODO: Updated spec.
// https://hackmd.io/Eaf20XhtRhi8aGEn_xIH8A#Unstaging-Removes
int retryCount = -1;
await RepeatUntilSuccessOrThrow(async () =>
{
retryCount++;
try
{
await _testHooks.BeforeDocRemoved(this, sm.Doc.Id).CAF();
if (!_expirationOvertimeMode && HasExpiredClientSide(sm.Doc.Id, ITestHooks.HOOK_REMOVE_DOC))
{
_expirationOvertimeMode = true;
}
await _docs.UnstageRemove(sm.Doc.Collection, sm.Doc.Id).CAF();
Logger.LogDebug("Unstaged RemoveAsync successfully for {redactedId)} (retryCount={retryCount}", Redactor.UserData(sm.Doc.FullyQualifiedId), retryCount);
await _testHooks.AfterDocRemovedPreRetry(this, sm.Doc.Id).CAF();
return RepeatAction.NoRepeat;
}
catch (Exception ex)
{
var triaged = _triage.TriageUnstageRemoveErrors(ex, _expirationOvertimeMode);
if (_expirationOvertimeMode)
{
throw ErrorBuilder.CreateError(this, ErrorClass.FailExpiry, new AttemptExpiredException(this))
.DoNotRollbackAttempt()
.RaiseException(TransactionOperationFailedException.FinalError.TransactionFailedPostCommit)
.Build();
}
switch (triaged.ec)
{
case ErrorClass.FailAmbiguous:
ambiguityResolutionMode = true;
return RepeatAction.RepeatWithDelay;
}
throw _triage.AssertNotNull(triaged, ex);
}
}).CAF();
_finalMutations.Add(sm.MutationToken);
await _testHooks.AfterDocRemovedPostRetry(this, sm.Doc.Id).CAF();
}
private Task<(ulong cas, object content)> FetchIfNeededBeforeUnstage(StagedMutation sm)
{
// https://hackmd.io/Eaf20XhtRhi8aGEn_xIH8A#FetchIfNeededBeforeUnstage
// TODO: consider implementing ExtMemoryOptUnstaging mode
// For now, assuming ExtTimeOptUnstaging mode...
return Task.FromResult((sm.Doc.Cas, sm.Content));
}
private async Task UnstageInsertOrReplace(StagedMutation sm, ulong cas, object content, bool insertMode = false, bool ambiguityResolutionMode = false, IRequestSpan? parentSpan = null)
{
using var traceSpan = TraceSpan(parent: parentSpan);
// https://hackmd.io/Eaf20XhtRhi8aGEn_xIH8A#Unstaging-Inserts-and-Replaces-Protocol-20-version
await RepeatUntilSuccessOrThrow(async () =>
{
try
{
if (!_expirationOvertimeMode && HasExpiredClientSide(sm.Doc.Id, ITestHooks.HOOK_COMMIT_DOC))
{
_expirationOvertimeMode = true;
}
await _testHooks.BeforeDocCommitted(this, sm.Doc.Id).CAF();
(ulong updatedCas, MutationToken mutationToken) = await _docs.UnstageInsertOrReplace(sm.Doc.Collection, sm.Doc.Id, cas, content, insertMode).CAF();
Logger.LogInformation(
"Unstaged mutation successfully on {redactedId}, attempt={attemptId}, insertMode={insertMode}, ambiguityResolutionMode={ambiguityResolutionMode}, preCas={cas}, postCas={updatedCas}",
Redactor.UserData(sm.Doc.FullyQualifiedId),
AttemptId,
insertMode,
ambiguityResolutionMode,
cas,
updatedCas);
if (mutationToken != null)
{
_finalMutations.Add(mutationToken);
}
await _testHooks.AfterDocCommittedBeforeSavingCas(this, sm.Doc.Id).CAF();
sm.Doc.Cas = updatedCas;
await _testHooks.AfterDocCommitted(this, sm.Doc.Id).CAF();
return RepeatAction.NoRepeat;
}
catch (Exception ex)
{
var triaged = _triage.TriageUnstageInsertOrReplaceErrors(ex, _expirationOvertimeMode);
if (_expirationOvertimeMode)
{
throw ErrorBuilder.CreateError(this, ErrorClass.FailExpiry, new AttemptExpiredException(this))
.DoNotRollbackAttempt()
.RaiseException(TransactionOperationFailedException.FinalError.TransactionFailedPostCommit)
.Build();
}
switch (triaged.ec)
{
case ErrorClass.FailAmbiguous:
ambiguityResolutionMode = true;
return RepeatAction.RepeatWithDelay;
case ErrorClass.FailCasMismatch:
if (ambiguityResolutionMode)
{
throw _triage.AssertNotNull(triaged, ex);
}
else
{
cas = 0;
return RepeatAction.RepeatWithDelay;
}
case ErrorClass.FailDocNotFound:
// TODO: publish IllegalDocumentState event to the application.
Logger?.LogError("IllegalDocumentState: " + triaged.ec);
insertMode = true;
return RepeatAction.RepeatWithDelay;
case ErrorClass.FailDocAlreadyExists:
if (ambiguityResolutionMode)
{
throw _triage.AssertNotNull(triaged, ex);
}
else
{
// TODO: publish an IllegalDocumentState event to the application.
Logger?.LogError("IllegalDocumentState: " + triaged.ec);
insertMode = false;
cas = 0;
return RepeatAction.RepeatWithDelay;
}
}
throw _triage.AssertNotNull(triaged, ex);
}
}).CAF();
}
private async Task SetAtrCommit(IRequestSpan? parentSpan)
{
_ = _atr ?? throw new InvalidOperationException($"{nameof(SetAtrCommit)} without initializing ATR.");
using var traceSpan = TraceSpan(parent: parentSpan);
await RepeatUntilSuccessOrThrow(async () =>
{
try
{
ErrorIfExpiredAndNotInExpiryOvertimeMode(ITestHooks.HOOK_ATR_COMMIT);
await _testHooks.BeforeAtrCommit(this).CAF();
await _atr.MutateAtrCommit(_stagedMutations).CAF();
Logger.LogDebug("{method} for {atr} (attempt={attemptId})", nameof(SetAtrCommit), Redactor.UserData(_atr.FullPath), AttemptId);
await _testHooks.AfterAtrCommit(this).CAF();
_state = AttemptStates.COMMITTED;
return RepeatAction.NoRepeat;
}
catch (Exception ex)
{
var triaged = _triage.TriageSetAtrCommitErrors(ex);
if (triaged.ec == ErrorClass.FailExpiry)
{
_expirationOvertimeMode = true;
}
else if (triaged.ec == ErrorClass.FailAmbiguous)
{
return await RepeatUntilSuccessOrThrow<RepeatAction>(async () =>
{
var topRetry = await ResolveSetAtrCommitAmbiguity(traceSpan.Item).CAF();
return (RepeatAction.NoRepeat, topRetry);
});
}
throw _triage.AssertNotNull(triaged, ex);
}
}).CAF();
}
private async Task<RepeatAction> ResolveSetAtrCommitAmbiguity(IRequestSpan? parentSpan)
{
using var traceSpan = TraceSpan(parent: parentSpan);
var setAtrCommitRetryAction = await RepeatUntilSuccessOrThrow<RepeatAction>(async () =>
{
try
{
ErrorIfExpiredAndNotInExpiryOvertimeMode(ITestHooks.HOOK_ATR_COMMIT_AMBIGUITY_RESOLUTION);
await _testHooks.BeforeAtrCommitAmbiguityResolution(this).CAF();
var refreshedStatus = await _atr!.LookupAtrState().CAF();
if (!Enum.TryParse<AttemptStates>(refreshedStatus, out var parsedRefreshStatus))
{
throw CreateError(this, ErrorClass.FailOther)
.Cause(new InvalidOperationException(
$"ATR state '{refreshedStatus}' could not be parsed"))
.DoNotRollbackAttempt()
.Build();
}
Logger.LogDebug("Atr State = {atrState}", parsedRefreshStatus);
switch (parsedRefreshStatus)
{
case AttemptStates.COMMITTED:
// The ambiguous operation actually succeeded. Return success.
return (retry: RepeatAction.NoRepeat, finalVal: RepeatAction.NoRepeat);
case AttemptStates.PENDING:
// The ambiguous operation did not succeed. Restart from the top of SetATRCommit.
return (retry: RepeatAction.NoRepeat, RepeatAction.RepeatWithDelay);
case AttemptStates.ABORTED:
case AttemptStates.ROLLED_BACK: