-
Notifications
You must be signed in to change notification settings - Fork 533
Expand file tree
/
Copy pathCosmosItemIntegrationTests.cs
More file actions
2336 lines (2002 loc) · 117 KB
/
CosmosItemIntegrationTests.cs
File metadata and controls
2336 lines (2002 loc) · 117 KB
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
namespace Microsoft.Azure.Cosmos.SDK.EmulatorTests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Diagnostics;
using Microsoft.Azure.Cosmos.FaultInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using static Microsoft.Azure.Cosmos.Routing.GlobalPartitionEndpointManagerCore;
using static Microsoft.Azure.Cosmos.SDK.EmulatorTests.MultiRegionSetupHelpers;
[TestClass]
public class CosmosItemIntegrationTests
{
private string connectionString;
private CosmosClient client;
private Database database;
private Container container;
private Container changeFeedContainer;
private static string region1;
private static string region2;
private static string region3;
private IDictionary<string, Uri> readRegionsMapping;
private IList<Uri> thinClientreadRegionalEndpoints;
private CosmosSystemTextJsonSerializer cosmosSystemTextJsonSerializer;
[TestInitialize]
public async Task TestInitAsync()
{
this.connectionString = ConfigurationManager.GetEnvironmentVariable<string>("COSMOSDB_MULTI_REGION", null);
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
this.cosmosSystemTextJsonSerializer = new MultiRegionSetupHelpers.CosmosSystemTextJsonSerializer(jsonSerializerOptions);
if (string.IsNullOrEmpty(this.connectionString))
{
Assert.Fail("Set environment variable COSMOSDB_MULTI_REGION to run the tests");
}
this.client = new CosmosClient(
this.connectionString,
new CosmosClientOptions()
{
Serializer = this.cosmosSystemTextJsonSerializer,
});
(this.database, this.container, this.changeFeedContainer) = await MultiRegionSetupHelpers.GetOrCreateMultiRegionDatabaseAndContainers(this.client);
this.readRegionsMapping = this.client.DocumentClient.GlobalEndpointManager.GetAvailableReadEndpointsByLocation();
Assert.IsTrue(this.readRegionsMapping.Count() >= 3);
region1 = this.readRegionsMapping.Keys.ElementAt(0);
region2 = this.readRegionsMapping.Keys.ElementAt(1);
region3 = this.readRegionsMapping.Keys.ElementAt(2);
}
[TestCleanup]
public void TestCleanup()
{
try
{
this.container.DeleteItemAsync<CosmosIntegrationTestObject>("deleteMe", new PartitionKey("MMWrite"));
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
// Ignore
}
finally
{
//Do not delete the resources (except MM Write test object), georeplication is slow and we want to reuse the resources
this.client?.Dispose();
}
}
[TestMethod]
[TestCategory("MultiRegion")]
[Timeout(70000)]
public async Task ReadMany2UnreachablePartitionsTest()
{
List<FeedRange> feedRanges = (List<FeedRange>)await this.container.GetFeedRangesAsync();
Assert.IsTrue(feedRanges.Count > 0);
FaultInjectionCondition condition = new FaultInjectionConditionBuilder()
.WithConnectionType(FaultInjectionConnectionType.Direct)
.WithOperationType(FaultInjectionOperationType.QueryItem)
.WithEndpoint(new FaultInjectionEndpointBuilder(
MultiRegionSetupHelpers.dbName,
MultiRegionSetupHelpers.containerName,
feedRanges[0])
.WithReplicaCount(2)
.WithIncludePrimary(false)
.Build())
.Build();
FaultInjectionServerErrorResult result = new FaultInjectionServerErrorResultBuilder(FaultInjectionServerErrorType.Gone)
.WithTimes(int.MaxValue - 1)
.Build();
FaultInjectionRule rule = new FaultInjectionRuleBuilder("connectionDelay", condition, result)
.WithDuration(TimeSpan.FromDays(1))
.Build();
FaultInjector injector = new FaultInjector(new List<FaultInjectionRule> { rule });
rule.Disable();
CosmosClientOptions clientOptions = new CosmosClientOptions()
{
ConnectionMode = ConnectionMode.Direct,
ConsistencyLevel = ConsistencyLevel.Strong,
Serializer = this.cosmosSystemTextJsonSerializer,
FaultInjector = injector,
};
CosmosClient fiClient = new CosmosClient(
connectionString: this.connectionString,
clientOptions: clientOptions);
Database fidb = fiClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container fic = fidb.GetContainer(MultiRegionSetupHelpers.containerName);
IReadOnlyList<(string, PartitionKey)> items = new List<(string, PartitionKey)>()
{
("testId", new PartitionKey("pk")),
("testId2", new PartitionKey("pk2")),
("testId3", new PartitionKey("pk3")),
("testId4", new PartitionKey("pk4")),
};
try
{
rule.Enable();
FeedResponse<CosmosIntegrationTestObject> feedResponse = await fic.ReadManyItemsAsync<CosmosIntegrationTestObject>(items);
}
catch (Exception ex)
{
Assert.Fail(ex.ToString());
}
finally
{
rule.Disable();
fiClient.Dispose();
}
}
[TestMethod]
[Timeout(70000)]
[TestCategory("MultiRegion")]
public async Task DateTimeArrayRoundtrip_BinaryEncoding_CompareExtraDates_IntegrationTest()
{
string binaryEncodingEnabled = "binaryEncodingEnabled" + Guid.NewGuid().ToString("N");
string binaryEncodingDisabled = "binaryEncodingDisabled" + Guid.NewGuid().ToString("N");
string pk = "pk";
string testId = Guid.NewGuid().ToString();
string[] dateStrings =
{
"12/25/2023","2023-12-25","12-25-2023","25.12.2023","25/12/2023",
"Dec 25, 2023","Dec 25 2023","2023-12-25T10:00:00","2023-12-25T10:00:00.123",
"12/25/2023 10:00 AM","12/25/2023 10:00:00 AM","12/25/2023 10:00:00.123 AM","9999-12-31T23:59:59",
"2023-12-25T10:00:00.1","2023-12-25T10:00:00.12",
"2023-12-25T10:00:00.1234","2023-12-25T10:00:00.1234567"
};
string[] formats =
{
"MM/dd/yyyy","yyyy-MM-dd","MM-dd-yyyy","dd.MM.yyyy","dd/MM/yyyy",
"MMM dd, yyyy","MMM dd yyyy","yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.f","yyyy-MM-ddTHH:mm:ss.ff","yyyy-MM-ddTHH:mm:ss.ffff",
"yyyy-MM-ddTHH:mm:ss.fffffff","MM/dd/yyyy hh:mm tt","MM/dd/yyyy hh:mm:ss tt",
"MM/dd/yyyy hh:mm:ss.fff tt"
};
DateTime[] parsedDates = dateStrings
.Select(s => DateTime.ParseExact(s, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None))
.ToArray();
TestCosmosItem testItem = new TestCosmosItem(
id: testId,
pk: pk,
title: "title",
body: "Binary encoding test document.",
createdUtc: DateTime.UtcNow,
modifiedUtc: DateTime.Parse("2025-03-26T20:22:20Z", null, System.Globalization.DateTimeStyles.AdjustToUniversal),
extraDates: parsedDates);
Database db = this.database;
ContainerResponse containerBEEnabledResponse = await db.CreateContainerAsync(binaryEncodingEnabled, "/pk");
ContainerResponse containerBEDisabledResponse = await db.CreateContainerAsync(binaryEncodingDisabled, "/pk");
try
{
// BinaryEncodingEnabled = True
Environment.SetEnvironmentVariable(ConfigurationManager.BinaryEncodingEnabled, "True");
string rawJsonBEEnabled;
string rawJsonBEDisabled;
using (CosmosClient clientBinaryEncodingEnabled = new CosmosClient(this.connectionString))
{
Container containerBinaryEncodingEnabled = clientBinaryEncodingEnabled.GetDatabase(db.Id).GetContainer(binaryEncodingEnabled);
await containerBinaryEncodingEnabled.CreateItemAsync(testItem, new Microsoft.Azure.Cosmos.PartitionKey(pk));
using ResponseMessage response = await containerBinaryEncodingEnabled.ReadItemStreamAsync(testId, new Microsoft.Azure.Cosmos.PartitionKey(pk));
using StreamReader reader = new StreamReader(response.Content, Encoding.UTF8);
rawJsonBEEnabled = await reader.ReadToEndAsync();
}
// BinaryEncodingEnabled = False
Environment.SetEnvironmentVariable(ConfigurationManager.BinaryEncodingEnabled, "False");
using (CosmosClient clientBinaryEncodingDisabled = new CosmosClient(this.connectionString))
{
Container containerBinaryEncodingDisabled = clientBinaryEncodingDisabled.GetDatabase(db.Id).GetContainer(binaryEncodingDisabled);
await containerBinaryEncodingDisabled.CreateItemAsync(testItem, new Microsoft.Azure.Cosmos.PartitionKey(pk));
using ResponseMessage response = await containerBinaryEncodingDisabled.ReadItemStreamAsync(testId, new Microsoft.Azure.Cosmos.PartitionKey(pk));
using StreamReader reader = new StreamReader(response.Content, Encoding.UTF8);
rawJsonBEDisabled = await reader.ReadToEndAsync();
}
using JsonDocument docTrue = JsonDocument.Parse(rawJsonBEEnabled);
using JsonDocument docFalse = JsonDocument.Parse(rawJsonBEDisabled);
string extraDatesTrue = docTrue.RootElement.GetProperty("ExtraDates").GetRawText();
string extraDatesFalse = docFalse.RootElement.GetProperty("ExtraDates").GetRawText();
Assert.AreEqual(extraDatesTrue, extraDatesFalse, $"ExtraDates JSON mismatch:\nTrue: {extraDatesTrue}\nFalse: {extraDatesFalse}");
}
finally
{
await containerBEEnabledResponse.Container.DeleteContainerAsync();
await containerBEDisabledResponse.Container.DeleteContainerAsync();
}
}
[TestMethod]
[TestCategory("MultiRegion")]
[DataRow(FaultInjectionServerErrorType.ServiceUnavailable)]
[DataRow(FaultInjectionServerErrorType.InternalServerError)]
[DataRow(FaultInjectionServerErrorType.DatabaseAccountNotFound)]
[DataRow(FaultInjectionServerErrorType.LeaseNotFound)]
public async Task MetadataEndpointUnavailableCrossRegionalRetryTest(FaultInjectionServerErrorType serverErrorType)
{
FaultInjectionRule collReadBad = new FaultInjectionRuleBuilder(
id: "collread",
condition: new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.MetadataContainer)
.WithRegion(region1)
.Build(),
result: new FaultInjectionServerErrorResultBuilder(serverErrorType)
.Build())
.Build();
FaultInjectionRule pkRangeBad = new FaultInjectionRuleBuilder(
id: "pkrange",
condition: new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.MetadataPartitionKeyRange)
.WithRegion(region1)
.Build(),
result: new FaultInjectionServerErrorResultBuilder(serverErrorType)
.Build())
.Build();
collReadBad.Disable();
pkRangeBad.Disable();
FaultInjector faultInjector = new FaultInjector(new List<FaultInjectionRule> { pkRangeBad, collReadBad });
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
ConsistencyLevel = ConsistencyLevel.Session,
ConnectionMode = ConnectionMode.Direct,
Serializer = this.cosmosSystemTextJsonSerializer,
FaultInjector = faultInjector,
ApplicationPreferredRegions = new List<string> { region1, region2, region3 }
};
using (CosmosClient fiClient = new CosmosClient(
connectionString: this.connectionString,
clientOptions: cosmosClientOptions))
{
Database fidb = fiClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container fic = fidb.GetContainer(MultiRegionSetupHelpers.containerName);
pkRangeBad.Enable();
collReadBad.Enable();
try
{
FeedIterator<CosmosIntegrationTestObject> frTest = fic.GetItemQueryIterator<CosmosIntegrationTestObject>("SELECT * FROM c");
while (frTest.HasMoreResults)
{
FeedResponse<CosmosIntegrationTestObject> feedres = await frTest.ReadNextAsync();
Assert.AreEqual(HttpStatusCode.OK, feedres.StatusCode);
}
}
catch (CosmosException ex)
{
Assert.Fail(ex.Message);
}
finally
{
//Cross regional retry needs to ocur (could trigger for other metadata call to try on secondary region so rule would not trigger)
Assert.IsTrue(pkRangeBad.GetHitCount() + collReadBad.GetHitCount() >= 1);
pkRangeBad.Disable();
collReadBad.Disable();
fiClient.Dispose();
}
}
}
[TestMethod]
[TestCategory("MultiRegion")]
public async Task AddressRefreshTimeoutTest()
{
FaultInjectionRule gatewayRule = new FaultInjectionRuleBuilder(
id: "gatewayRule",
condition: new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.MetadataRefreshAddresses)
.WithRegion(region1)
.Build(),
result: new FaultInjectionServerErrorResultBuilder(FaultInjectionServerErrorType.SendDelay)
.WithDelay(TimeSpan.FromSeconds(65))
.Build())
.Build();
gatewayRule.Disable();
FaultInjector faultInjector = new FaultInjector(new List<FaultInjectionRule> { gatewayRule });
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
ConsistencyLevel = ConsistencyLevel.Session,
ConnectionMode = ConnectionMode.Direct,
Serializer = this.cosmosSystemTextJsonSerializer,
FaultInjector = faultInjector,
RequestTimeout = TimeSpan.FromSeconds(1),
};
using (CosmosClient fiClient = new CosmosClient(
connectionString: this.connectionString,
clientOptions: cosmosClientOptions))
{
Database fidb = fiClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container fic = fidb.GetContainer(MultiRegionSetupHelpers.containerName);
gatewayRule.Enable();
try
{
ItemResponse<CosmosIntegrationTestObject> o = await fic.ReadItemAsync<CosmosIntegrationTestObject>(
"testId",
new PartitionKey("pk"));
Assert.IsTrue(o.StatusCode == HttpStatusCode.OK);
}
catch (Exception ex)
{
Assert.Fail(ex.ToString());
}
finally
{
gatewayRule.Disable();
Assert.IsTrue(gatewayRule.GetHitCount() >= 3);
fiClient.Dispose();
}
}
}
[Owner("dkunda")]
[TestCategory("MultiRegion")]
[DataRow(true, DisplayName = "Test scenario when binary encoding is enabled at client level.")]
[DataRow(false, DisplayName = "Test scenario when binary encoding is disabled at client level.")]
public async Task ExecuteTransactionalBatch_WhenBinaryEncodingEnabled_ShouldCompleteSuccessfully(
bool isBinaryEncodingEnabled)
{
Environment.SetEnvironmentVariable(ConfigurationManager.BinaryEncodingEnabled, isBinaryEncodingEnabled.ToString());
Random random = new();
CosmosIntegrationTestObject testItem = new()
{
Id = $"smTestId{random.Next()}",
Pk = $"smpk{random.Next()}",
};
try
{
CosmosClientOptions cosmosClientOptions = new()
{
ConsistencyLevel = ConsistencyLevel.Session,
RequestTimeout = TimeSpan.FromSeconds(10),
Serializer = new CosmosJsonDotNetSerializer(
cosmosSerializerOptions: new CosmosSerializationOptions()
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
},
binaryEncodingEnabled: isBinaryEncodingEnabled)
};
using CosmosClient cosmosClient = new(
connectionString: this.connectionString,
clientOptions: cosmosClientOptions);
Database database = cosmosClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container container = database.GetContainer(MultiRegionSetupHelpers.containerName);
// Create a transactional batch
TransactionalBatch transactionalBatch = container.CreateTransactionalBatch(new PartitionKey(testItem.Pk));
transactionalBatch.CreateItem(
testItem,
new TransactionalBatchItemRequestOptions
{
EnableContentResponseOnWrite = true,
});
transactionalBatch.ReadItem(
testItem.Id,
new TransactionalBatchItemRequestOptions
{
EnableContentResponseOnWrite = true,
});
// Execute the transactional batch
TransactionalBatchResponse transactionResponse = await transactionalBatch.ExecuteAsync(
new TransactionalBatchRequestOptions
{
});
Assert.AreEqual(HttpStatusCode.OK, transactionResponse.StatusCode);
Assert.AreEqual(2, transactionResponse.Count);
TransactionalBatchOperationResult<CosmosIntegrationTestObject> createOperationResult = transactionResponse.GetOperationResultAtIndex<CosmosIntegrationTestObject>(0);
Assert.IsNotNull(createOperationResult);
Assert.IsNotNull(createOperationResult.Resource);
Assert.AreEqual(testItem.Id, createOperationResult.Resource.Id);
Assert.AreEqual(testItem.Pk, createOperationResult.Resource.Pk);
TransactionalBatchOperationResult<CosmosIntegrationTestObject> readOperationResult = transactionResponse.GetOperationResultAtIndex<CosmosIntegrationTestObject>(1);
Assert.IsNotNull(readOperationResult);
Assert.IsNotNull(readOperationResult.Resource);
Assert.AreEqual(testItem.Id, readOperationResult.Resource.Id);
Assert.AreEqual(testItem.Pk, readOperationResult.Resource.Pk);
}
finally
{
Environment.SetEnvironmentVariable(ConfigurationManager.BinaryEncodingEnabled, null);
await this.container.DeleteItemAsync<CosmosIntegrationTestObject>(
testItem.Id,
new PartitionKey(testItem.Pk));
}
}
[TestMethod]
[TestCategory("MultiRegion")]
[DataRow(ConnectionMode.Direct, "15", "10", DisplayName = "Direct Mode - Scenario when the total iteration count is 15 and circuit breaker consecutive failure threshold is set to 10.")]
[DataRow(ConnectionMode.Direct, "25", "20", DisplayName = "Direct Mode - Scenario when the total iteration count is 25 and circuit breaker consecutive failure threshold is set to 20.")]
[DataRow(ConnectionMode.Direct, "35", "30", DisplayName = "Direct Mode - Scenario when the total iteration count is 35 and circuit breaker consecutive failure threshold is set to 30.")]
[DataRow(ConnectionMode.Gateway, "15", "10", DisplayName = "Gateway Mode - Scenario when the total iteration count is 15 and circuit breaker consecutive failure threshold is set to 10.")]
[DataRow(ConnectionMode.Gateway, "25", "20", DisplayName = "Gateway Mode - Scenario when the total iteration count is 25 and circuit breaker consecutive failure threshold is set to 20.")]
[DataRow(ConnectionMode.Gateway, "35", "30", DisplayName = "Gateway Mode - Scenario when the total iteration count is 35 and circuit breaker consecutive failure threshold is set to 30.")]
[Owner("dkunda")]
[Timeout(70000)]
public async Task ReadItemAsync_WithCircuitBreakerEnabledAndSingleMasterAccountAndServiceUnavailableReceived_ShouldApplyPartitionLevelOverride(
ConnectionMode connectionMode,
string iterationCount,
string circuitBreakerConsecutiveFailureCount)
{
// Arrange.
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, "True");
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerConsecutiveFailureCountForReads, circuitBreakerConsecutiveFailureCount);
// Enabling fault injection rule to simulate a 503 service unavailable scenario.
string serviceUnavailableRuleId = "503-rule-" + Guid.NewGuid().ToString();
FaultInjectionRule serviceUnavailableRule = new FaultInjectionRuleBuilder(
id: serviceUnavailableRuleId,
condition:
new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.ReadItem)
.WithRegion(region1)
.Build(),
result:
FaultInjectionResultBuilder.GetResultBuilder(FaultInjectionServerErrorType.ServiceUnavailable)
.WithDelay(TimeSpan.FromMilliseconds(10))
.Build())
.Build();
List<FaultInjectionRule> rules = new List<FaultInjectionRule> { serviceUnavailableRule };
FaultInjector faultInjector = new FaultInjector(rules);
List<string> preferredRegions = new List<string> { region1, region2, region3 };
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
ConnectionMode = connectionMode,
ConsistencyLevel = ConsistencyLevel.Session,
FaultInjector = faultInjector,
RequestTimeout = TimeSpan.FromSeconds(5),
ApplicationPreferredRegions = preferredRegions,
};
List<CosmosIntegrationTestObject> itemsList = new ()
{
new() { Id = "smTestId1", Pk = "smpk1" },
};
try
{
using CosmosClient cosmosClient = new(connectionString: this.connectionString, clientOptions: cosmosClientOptions);
Database database = cosmosClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container container = database.GetContainer(MultiRegionSetupHelpers.containerName);
// Act and Assert.
await this.TryCreateItems(itemsList);
//Must Ensure the data is replicated to all regions
await Task.Delay(3000);
int consecutiveFailureCount = int.Parse(circuitBreakerConsecutiveFailureCount);
int totalIterations = int.Parse(iterationCount);
for (int attemptCount = 1; attemptCount <= totalIterations; attemptCount++)
{
try
{
ItemResponse<CosmosIntegrationTestObject> readResponse = await container.ReadItemAsync<CosmosIntegrationTestObject>(
id: itemsList[0].Id,
partitionKey: new PartitionKey(itemsList[0].Pk));
IReadOnlyList<(string regionName, Uri uri)> contactedRegionMapping = readResponse.Diagnostics.GetContactedRegions();
HashSet<string> contactedRegions = new(contactedRegionMapping.Select(r => r.regionName));
Assert.AreEqual(
expected: HttpStatusCode.OK,
actual: readResponse.StatusCode);
Assert.IsNotNull(contactedRegions);
PartitionKeyRangeFailoverInfo failoverInfo = TestCommon.GetFailoverInfoForFirstPartitionUsingReflection(
globalPartitionEndpointManager: cosmosClient.ClientContext.DocumentClient.PartitionKeyRangeLocation,
isReadOnlyOrMultiMaster: true);
if (attemptCount > consecutiveFailureCount + 1)
{
if (connectionMode == ConnectionMode.Direct)
{
Assert.IsTrue(contactedRegions.Count == 1, "Asserting that when the consecutive failure count reaches the threshold, the partition was failed over to the next region, and the subsequent read request/s were successful on the next region.");
Assert.IsTrue(contactedRegions.Contains(region2));
}
Assert.AreEqual(this.readRegionsMapping[region2], failoverInfo.Current);
}
else
{
if (connectionMode == ConnectionMode.Direct)
{
Assert.IsTrue(contactedRegions.Count == 2, "Asserting that when the read request succeeds before the consecutive failure count reaches the threshold, the partition didn't over to the next region, and the request was retried on the next region.");
Assert.IsTrue(contactedRegions.Contains(region1) && contactedRegions.Contains(region2));
}
if (attemptCount > consecutiveFailureCount)
{
Assert.AreEqual(this.readRegionsMapping[region2], failoverInfo.Current);
}
else
{
Assert.AreEqual(this.readRegionsMapping[region1], failoverInfo.Current);
}
}
}
catch (CosmosException)
{
Assert.Fail("Read Item operation should succeed.");
}
catch (Exception ex)
{
Assert.Fail($"Unhandled Exception was thrown during ReadItemAsync call. Message: {ex.Message}");
}
}
}
finally
{
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, null);
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerConsecutiveFailureCountForReads, null);
await this.TryDeleteItems(itemsList);
}
}
[TestMethod]
[TestCategory("MultiRegion")]
[DataRow(ConnectionMode.Direct, DisplayName ="Direct Mode")]
[DataRow(ConnectionMode.Gateway, DisplayName = "Gateway Mode")]
[Owner("nalutripician")]
[Timeout(70000)]
public async Task ReadItemAsync_WithCircuitBreakerEnabledAndTimeoutCounterOverwritten(
ConnectionMode connectionMode)
{
// Arrange.
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, "True");
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerTimeoutCounterResetWindowInMinutes, "0.0833"); // setting to 5 seconds
// Enabling fault injection rule to simulate a 503 service unavailable scenario.
string serviceUnavailableRuleId = "503-rule-" + Guid.NewGuid().ToString();
FaultInjectionRule serviceUnavailableRule = new FaultInjectionRuleBuilder(
id: serviceUnavailableRuleId,
condition:
new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.ReadItem)
.WithRegion(region1)
.Build(),
result:
FaultInjectionResultBuilder.GetResultBuilder(FaultInjectionServerErrorType.ServiceUnavailable)
.WithDelay(TimeSpan.FromMilliseconds(10))
.Build())
.Build();
List<FaultInjectionRule> rules = new List<FaultInjectionRule> { serviceUnavailableRule };
FaultInjector faultInjector = new FaultInjector(rules);
List<string> preferredRegions = new List<string> { region1, region2, region3 };
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
ConnectionMode = connectionMode,
ConsistencyLevel = ConsistencyLevel.Session,
FaultInjector = faultInjector,
RequestTimeout = TimeSpan.FromSeconds(5),
ApplicationPreferredRegions = preferredRegions,
};
List<CosmosIntegrationTestObject> itemsList = new()
{
new() { Id = "smTestId1", Pk = "smpk1" },
};
try
{
using CosmosClient cosmosClient = new(connectionString: this.connectionString, clientOptions: cosmosClientOptions);
Database database = cosmosClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container container = database.GetContainer(MultiRegionSetupHelpers.containerName);
// Act and Assert.
await this.TryCreateItems(itemsList);
//Must Ensure the data is replicated to all regions
await Task.Delay(3000);
int readErrorCount = 0;
PartitionKeyRangeFailoverInfo failoverInfo;
for (int i = 1; i <= 3; i++)
{
try
{
ItemResponse<CosmosIntegrationTestObject> readResponse = await container.ReadItemAsync<CosmosIntegrationTestObject>(
id: itemsList[0].Id,
partitionKey: new PartitionKey(itemsList[0].Pk));
IReadOnlyList<(string regionName, Uri uri)> contactedRegionMapping = readResponse.Diagnostics.GetContactedRegions();
HashSet<string> contactedRegions = new(contactedRegionMapping.Select(r => r.regionName));
Assert.AreEqual(
expected: HttpStatusCode.OK,
actual: readResponse.StatusCode);
Assert.IsNotNull(contactedRegions);
failoverInfo = TestCommon.GetFailoverInfoForFirstPartitionUsingReflection(
globalPartitionEndpointManager: cosmosClient.ClientContext.DocumentClient.PartitionKeyRangeLocation,
isReadOnlyOrMultiMaster: true);
failoverInfo.SnapshotConsecutiveRequestFailureCount(out readErrorCount, out _);
Assert.IsTrue(readErrorCount > 0);
}
catch (CosmosException)
{
Assert.Fail("Read Item operation should succeed.");
}
catch (Exception ex)
{
Assert.Fail($"Unhandled Exception was thrown during ReadItemAsync call. Message: {ex.Message}");
}
}
await Task.Delay(6000); // Wait for the timeout counter to reset
try
{
ItemResponse<CosmosIntegrationTestObject> readResponse = await container.ReadItemAsync<CosmosIntegrationTestObject>(
id: itemsList[0].Id,
partitionKey: new PartitionKey(itemsList[0].Pk));
}
catch (CosmosException)
{
Assert.Fail("Read Item operation should succeed after the timeout counter is overwritten.");
}
failoverInfo = TestCommon.GetFailoverInfoForFirstPartitionUsingReflection(
globalPartitionEndpointManager: cosmosClient.ClientContext.DocumentClient.PartitionKeyRangeLocation,
isReadOnlyOrMultiMaster: true);
failoverInfo.SnapshotConsecutiveRequestFailureCount(out int currentReadErrorCount, out _);
Assert.AreEqual(1, currentReadErrorCount, "The read error count should be reset after the timeout counter is overwritten. Then after one more failure it should be incremented by 1.");
Assert.IsTrue(readErrorCount > currentReadErrorCount, "The read error count should be greater than the current before the timeout counter is overwritten.");
}
finally
{
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, null);
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerConsecutiveFailureCountForReads, null);
await this.TryDeleteItems(itemsList);
}
}
[TestMethod]
[TestCategory("MultiRegion")]
[Owner("dkunda")]
[Timeout(70000)]
public async Task ReadItemAsync_WithCircuitBreakerEnabledAndSingleMasterAccountAndServiceUnavailableReceivedFromTwoRegions_ShouldApplyPartitionLevelOverrideToThridRegion()
{
// Arrange.
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, "True");
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerConsecutiveFailureCountForReads, "10");
// Enabling fault injection rule to simulate a 503 service unavailable scenario.
string serviceUnavailableRuleId1 = "503-rule-" + Guid.NewGuid().ToString();
FaultInjectionRule serviceUnavailableRule1 = new FaultInjectionRuleBuilder(
id: serviceUnavailableRuleId1,
condition:
new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.ReadItem)
.WithRegion(region1)
.Build(),
result:
FaultInjectionResultBuilder.GetResultBuilder(FaultInjectionServerErrorType.ServiceUnavailable)
.WithDelay(TimeSpan.FromMilliseconds(10))
.Build())
.Build();
string serviceUnavailableRuleId2 = "503-rule-" + Guid.NewGuid().ToString();
FaultInjectionRule serviceUnavailableRule2 = new FaultInjectionRuleBuilder(
id: serviceUnavailableRuleId2,
condition:
new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.ReadItem)
.WithRegion(region2)
.Build(),
result:
FaultInjectionResultBuilder.GetResultBuilder(FaultInjectionServerErrorType.ServiceUnavailable)
.WithDelay(TimeSpan.FromMilliseconds(10))
.Build())
.Build();
serviceUnavailableRule1.Disable();
serviceUnavailableRule2.Disable();
List<FaultInjectionRule> rules = new List<FaultInjectionRule> { serviceUnavailableRule1, serviceUnavailableRule2 };
FaultInjector faultInjector = new FaultInjector(rules);
List<string> preferredRegions = new List<string> { region1, region2, region3 };
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
ConsistencyLevel = ConsistencyLevel.Session,
FaultInjector = faultInjector,
RequestTimeout = TimeSpan.FromSeconds(5),
ApplicationPreferredRegions = preferredRegions,
};
List<CosmosIntegrationTestObject> itemsList = new()
{
new() { Id = "smTestId1", Pk = "smpk1" },
};
try
{
using CosmosClient cosmosClient = new (connectionString: this.connectionString, clientOptions: cosmosClientOptions);
Database database = cosmosClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container container = database.GetContainer(MultiRegionSetupHelpers.containerName);
// Act and Assert.
await this.TryCreateItems(itemsList);
//Must Ensure the data is replicated to all regions
await Task.Delay(3000);
bool isRegion1Available = true;
bool isRegion2Available = true;
int thresholdCounter = 0;
int totalIterations = 40;
int ppcbDefaultThreshold = 10;
int firstRegionServiceUnavailableAttempt = 3;
int secondRegionServiceUnavailableAttempt = 28;
for (int attemptCount = 1; attemptCount <= totalIterations; attemptCount++)
{
try
{
ItemResponse<CosmosIntegrationTestObject> readResponse = await container.ReadItemAsync<CosmosIntegrationTestObject>(
id: itemsList[0].Id,
partitionKey: new PartitionKey(itemsList[0].Pk));
IReadOnlyList<(string regionName, Uri uri)> contactedRegionMapping = readResponse.Diagnostics.GetContactedRegions();
HashSet<string> contactedRegions = new(contactedRegionMapping.Select(r => r.regionName));
Assert.AreEqual(
expected: HttpStatusCode.OK,
actual: readResponse.StatusCode);
Assert.IsNotNull(contactedRegions);
if (isRegion1Available && isRegion2Available)
{
Assert.IsTrue(contactedRegions.Count == 1, "Assert that, when no failure happened, the read request is being served from region 1.");
Assert.IsTrue(contactedRegions.Contains(region1));
// Simulating service unavailable on region 1.
if (attemptCount == firstRegionServiceUnavailableAttempt)
{
isRegion1Available = false;
serviceUnavailableRule1.Enable();
}
}
else if (isRegion2Available)
{
if (thresholdCounter <= ppcbDefaultThreshold)
{
Assert.IsTrue(contactedRegions.Count == 2, "Asserting that when the read request succeeds before the consecutive failure count reaches the threshold, the partition didn't fail over to the next region, and the request was retried.");
Assert.IsTrue(contactedRegions.Contains(region1) && contactedRegions.Contains(region2));
thresholdCounter++;
}
else
{
Assert.IsTrue(contactedRegions.Count == 1, "Asserting that when the consecutive failure count reaches the threshold, the partition was failed over to the next region, and the subsequent read request/s were successful on the next region.");
Assert.IsTrue(contactedRegions.Contains(region2));
}
// Simulating service unavailable on region 2.
if (attemptCount == secondRegionServiceUnavailableAttempt)
{
isRegion2Available = false;
serviceUnavailableRule2.Enable();
}
}
else
{
if (thresholdCounter <= ppcbDefaultThreshold + 1)
{
Assert.IsTrue(contactedRegions.Count == 2, "Asserting that when the read request fails on the second region, the partition did over to the next region, and the request was retried on the next region.");
Assert.IsTrue(contactedRegions.Contains(region2) && contactedRegions.Contains(region3));
thresholdCounter++;
}
else
{
Assert.IsTrue(contactedRegions.Count == 1, "Asserting that when the consecutive failure count reaches the threshold, the partition was failed over to the third region, and the subsequent read request/s were successful on the third region.");
Assert.IsTrue(contactedRegions.Contains(region3));
}
}
}
catch (CosmosException)
{
Assert.Fail("Read Item operation should succeed.");
}
catch (Exception ex)
{
Assert.Fail($"Unhandled Exception was thrown during ReadItemAsync call. Message: {ex.Message}");
}
}
}
finally
{
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, null);
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerConsecutiveFailureCountForReads, null);
await this.TryDeleteItems(itemsList);
}
}
[TestMethod]
[TestCategory("MultiRegion")]
[Owner("dkunda")]
[Timeout(70000)]
public async Task ReadItemAsync_WithNoPreferredRegionsAndCircuitBreakerEnabledAndSingleMasterAccountAndServiceUnavailableReceived_ShouldApplyPartitionLevelOverride()
{
// Arrange.
Environment.SetEnvironmentVariable(ConfigurationManager.PartitionLevelCircuitBreakerEnabled, "True");
Environment.SetEnvironmentVariable(ConfigurationManager.CircuitBreakerConsecutiveFailureCountForReads, "10");
// Enabling fault injection rule to simulate a 503 service unavailable scenario.
string serviceUnavailableRuleId = "503-rule-" + Guid.NewGuid().ToString();
FaultInjectionRule serviceUnavailableRule = new FaultInjectionRuleBuilder(
id: serviceUnavailableRuleId,
condition:
new FaultInjectionConditionBuilder()
.WithOperationType(FaultInjectionOperationType.ReadItem)
.WithRegion(region1)
.Build(),
result:
FaultInjectionResultBuilder.GetResultBuilder(FaultInjectionServerErrorType.ServiceUnavailable)
.WithDelay(TimeSpan.FromMilliseconds(10))
.Build())
.Build();
List<FaultInjectionRule> rules = new List<FaultInjectionRule> { serviceUnavailableRule };
FaultInjector faultInjector = new FaultInjector(rules);
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
ConnectionMode = ConnectionMode.Direct,
ConsistencyLevel = ConsistencyLevel.Session,
FaultInjector = faultInjector,
RequestTimeout = TimeSpan.FromSeconds(5),
};
List<CosmosIntegrationTestObject> itemsList = new()
{
new() { Id = "smTestId1", Pk = "smpk1" },
};
try
{
using CosmosClient cosmosClient = new(connectionString: this.connectionString, clientOptions: cosmosClientOptions);
Database database = cosmosClient.GetDatabase(MultiRegionSetupHelpers.dbName);
Container container = database.GetContainer(MultiRegionSetupHelpers.containerName);
// Act and Assert.
await this.TryCreateItems(itemsList);
//Must Ensure the data is replicated to all regions
await Task.Delay(3000);
int consecutiveFailureCount = 10;
int totalIterations = 15;
for (int attemptCount = 1; attemptCount <= totalIterations; attemptCount++)
{
try
{
ItemResponse<CosmosIntegrationTestObject> readResponse = await container.ReadItemAsync<CosmosIntegrationTestObject>(
id: itemsList[0].Id,
partitionKey: new PartitionKey(itemsList[0].Pk));
IReadOnlyList<(string regionName, Uri uri)> contactedRegionMapping = readResponse.Diagnostics.GetContactedRegions();
HashSet<string> contactedRegions = new(contactedRegionMapping.Select(r => r.regionName));
Assert.AreEqual(
expected: HttpStatusCode.OK,
actual: readResponse.StatusCode);
Assert.IsNotNull(contactedRegions);
PartitionKeyRangeFailoverInfo failoverInfo = TestCommon.GetFailoverInfoForFirstPartitionUsingReflection(
globalPartitionEndpointManager: cosmosClient.ClientContext.DocumentClient.PartitionKeyRangeLocation,
isReadOnlyOrMultiMaster: true);
if (attemptCount > consecutiveFailureCount + 1)
{
Assert.IsTrue(contactedRegions.Count == 1, "Asserting that when the consecutive failure count reaches the threshold, the partition was failed over to the next region, and the subsequent read request/s were successful on the next region.");
Assert.IsTrue(contactedRegions.Contains(region2));
Assert.AreEqual(this.readRegionsMapping[region2], failoverInfo.Current);
}
else
{
Assert.IsTrue(contactedRegions.Count == 2, "Asserting that when the read request succeeds before the consecutive failure count reaches the threshold, the partition didn't over to the next region, and the request was retried on the next region.");
Assert.IsTrue(contactedRegions.Contains(region1) && contactedRegions.Contains(region2));
if (attemptCount > consecutiveFailureCount)
{
Assert.AreEqual(this.readRegionsMapping[region2], failoverInfo.Current);
}
else
{
Assert.AreEqual(this.readRegionsMapping[region1], failoverInfo.Current);
}
}
}
catch (CosmosException)
{
Assert.Fail("Read Item operation should succeed.");
}
catch (Exception ex)
{
Assert.Fail($"Unhandled Exception was thrown during ReadItemAsync call. Message: {ex.Message}");
}