-
Notifications
You must be signed in to change notification settings - Fork 504
/
Copy pathGatewayAddressCacheTests.cs
1665 lines (1461 loc) · 86.5 KB
/
GatewayAddressCacheTests.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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Common;
using Microsoft.Azure.Cosmos.Routing;
using Microsoft.Azure.Cosmos.Tests;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Rntbd;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
/// <summary>
/// Tests for <see cref="GatewayAddressCache"/>.
/// </summary>
[TestClass]
public class GatewayAddressCacheTests
{
private const string DatabaseAccountApiEndpoint = "https://endpoint.azure.com";
private readonly Mock<ICosmosAuthorizationTokenProvider> mockTokenProvider;
private readonly Mock<IServiceConfigurationReader> mockServiceConfigReader;
private readonly Mock<PartitionKeyRangeCache> partitionKeyRangeCache;
private readonly int targetReplicaSetSize = 4;
private readonly PartitionKeyRangeIdentity testPartitionKeyRangeIdentity;
private readonly ServiceIdentity serviceIdentity;
private readonly Uri serviceName;
public GatewayAddressCacheTests()
{
this.mockTokenProvider = new Mock<ICosmosAuthorizationTokenProvider>();
this.mockTokenProvider.Setup(foo => foo.GetUserAuthorizationTokenAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Documents.Collections.INameValueCollection>(), It.IsAny<AuthorizationTokenType>(), It.IsAny<ITrace>()))
.Returns(new ValueTask<string>("token!"));
this.mockServiceConfigReader = new Mock<IServiceConfigurationReader>();
this.mockServiceConfigReader.Setup(foo => foo.SystemReplicationPolicy).Returns(new ReplicationPolicy() { MaxReplicaSetSize = this.targetReplicaSetSize });
this.mockServiceConfigReader.Setup(foo => foo.UserReplicationPolicy).Returns(new ReplicationPolicy() { MaxReplicaSetSize = this.targetReplicaSetSize });
this.testPartitionKeyRangeIdentity = new PartitionKeyRangeIdentity("YxM9ANCZIwABAAAAAAAAAA==", "YxM9ANCZIwABAAAAAAAAAA==");
this.serviceName = new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint);
this.serviceIdentity = new ServiceIdentity("federation1", this.serviceName, false);
List<PartitionKeyRange> partitionKeyRanges = new ()
{
new PartitionKeyRange()
{
MinInclusive = Documents.Routing.PartitionKeyInternal.MinimumInclusiveEffectivePartitionKey,
MaxExclusive = Documents.Routing.PartitionKeyInternal.MaximumExclusiveEffectivePartitionKey,
Id = "0"
}
};
this.partitionKeyRangeCache = new Mock<PartitionKeyRangeCache>(null, null, null);
this.partitionKeyRangeCache
.Setup(m => m.TryGetOverlappingRangesAsync(
It.IsAny<string>(),
It.IsAny<Documents.Routing.Range<string>>(),
It.IsAny<ITrace>(),
It.IsAny<bool>()))
.Returns(Task.FromResult((IReadOnlyList<PartitionKeyRange>)partitionKeyRanges));
}
[TestMethod]
public void TestGatewayAddressCacheAutoRefreshOnSuboptimalPartition()
{
FakeMessageHandler messageHandler = new FakeMessageHandler();
HttpClient httpClient = new HttpClient(messageHandler);
httpClient.Timeout = TimeSpan.FromSeconds(120);
GatewayAddressCache cache = new GatewayAddressCache(
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: null,
suboptimalPartitionForceRefreshIntervalInSeconds: 2);
int initialAddressesCount = cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
false,
CancellationToken.None).Result.AllAddresses.Count();
Assert.IsTrue(initialAddressesCount < this.targetReplicaSetSize);
Task.Delay(3000).Wait();
int finalAddressCount = cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
false,
CancellationToken.None).Result.AllAddresses.Count();
Assert.IsTrue(finalAddressCount == this.targetReplicaSetSize);
}
[TestMethod]
public async Task TestGatewayAddressCacheUpdateOnConnectionResetAsync()
{
FakeMessageHandler messageHandler = new FakeMessageHandler();
HttpClient httpClient = new HttpClient(messageHandler)
{
Timeout = TimeSpan.FromSeconds(120)
};
GatewayAddressCache cache = new GatewayAddressCache(
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: null,
suboptimalPartitionForceRefreshIntervalInSeconds: 2,
enableTcpConnectionEndpointRediscovery: true);
PartitionAddressInformation addresses = await cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
false,
CancellationToken.None);
Assert.IsNotNull(addresses.AllAddresses.Select(address => address.PhysicalUri == "https://blabla.com"));
// Mark transport addresses to Unhealthy depcting a connection reset event.
ServerKey faultyServerKey = new (new Uri("https://blabla2.com"));
await cache.MarkAddressesToUnhealthyAsync(faultyServerKey);
// check if the addresss is updated
addresses = await cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
false,
CancellationToken.None);
// Validate that the above transport uri with host blabla2.com has been marked Unhealthy.
IReadOnlyList<TransportAddressUri> transportAddressUris = addresses
.Get(Protocol.Tcp)?
.ReplicaTransportAddressUris;
TransportAddressUri transportAddressUri = transportAddressUris
.Single(x => x.ReplicaServerKey.Equals(faultyServerKey));
Assert.IsTrue(condition: transportAddressUri.GetCurrentHealthState().GetHealthStatus().Equals(TransportAddressHealthState.HealthStatus.Unhealthy));
}
[TestMethod]
public async Task TestGatewayAddressCacheAvoidCacheRefresWhenAlreadyUpdatedAsync()
{
Mock<IHttpHandler> mockHttpHandler = new Mock<IHttpHandler>(MockBehavior.Strict);
string oldAddress = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/4s";
string newAddress = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/5s";
mockHttpHandler.SetupSequence(x => x.SendAsync(
It.IsAny<HttpRequestMessage>(),
It.IsAny<CancellationToken>()))
.Returns(MockCosmosUtil.CreateHttpResponseOfAddresses(new List<string>()
{
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/1p",
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/2s",
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/3s",
oldAddress,
}))
.Returns(MockCosmosUtil.CreateHttpResponseOfAddresses(new List<string>()
{
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/1p",
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/2s",
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/3s",
newAddress,
}));
HttpClient httpClient = new HttpClient(new HttpHandlerHelper(mockHttpHandler.Object));
GatewayAddressCache cache = new GatewayAddressCache(
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: null,
suboptimalPartitionForceRefreshIntervalInSeconds: 2,
enableTcpConnectionEndpointRediscovery: true);
DocumentServiceRequest request1 = DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid);
DocumentServiceRequest request2 = DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid);
PartitionAddressInformation request1Addresses = await cache.TryGetAddressesAsync(
request: request1,
partitionKeyRangeIdentity: this.testPartitionKeyRangeIdentity,
serviceIdentity: this.serviceIdentity,
forceRefreshPartitionAddresses: false,
cancellationToken: CancellationToken.None);
PartitionAddressInformation request2Addresses = await cache.TryGetAddressesAsync(
request: request2,
partitionKeyRangeIdentity: this.testPartitionKeyRangeIdentity,
serviceIdentity: this.serviceIdentity,
forceRefreshPartitionAddresses: false,
cancellationToken: CancellationToken.None);
Assert.AreEqual(request1Addresses, request2Addresses);
Assert.AreEqual(4, request1Addresses.AllAddresses.Count());
Assert.AreEqual(1, request1Addresses.AllAddresses.Count(x => x.PhysicalUri == oldAddress));
Assert.AreEqual(0, request1Addresses.AllAddresses.Count(x => x.PhysicalUri == newAddress));
// check if the addresss is updated
request1Addresses = await cache.TryGetAddressesAsync(
request: request1,
partitionKeyRangeIdentity: this.testPartitionKeyRangeIdentity,
serviceIdentity: this.serviceIdentity,
forceRefreshPartitionAddresses: true,
cancellationToken: CancellationToken.None);
// Even though force refresh is true it will just use the new cache
// value rather than doing a gateway call to do another refresh since the value
// already changed from the last cache access
request2Addresses = await cache.TryGetAddressesAsync(
request: request2,
partitionKeyRangeIdentity: this.testPartitionKeyRangeIdentity,
serviceIdentity: this.serviceIdentity,
forceRefreshPartitionAddresses: true,
cancellationToken: CancellationToken.None);
Assert.AreEqual(request1Addresses, request2Addresses);
Assert.AreEqual(4, request1Addresses.AllAddresses.Count());
Assert.AreEqual(0, request1Addresses.AllAddresses.Count(x => x.PhysicalUri == oldAddress));
Assert.AreEqual(1, request1Addresses.AllAddresses.Count(x => x.PhysicalUri == newAddress));
mockHttpHandler.VerifyAll();
}
[TestMethod]
[Timeout(2000)]
public void GlobalAddressResolverUpdateAsyncSynchronizationTest()
{
SynchronizationContext prevContext = SynchronizationContext.Current;
try
{
TestSynchronizationContext syncContext = new TestSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(syncContext);
syncContext.Post(_ =>
{
UserAgentContainer container = new UserAgentContainer(clientId: 0);
FakeMessageHandler messageHandler = new FakeMessageHandler();
AccountProperties databaseAccount = new AccountProperties();
Mock<IDocumentClientInternal> mockDocumentClient = new Mock<IDocumentClientInternal>();
mockDocumentClient.Setup(owner => owner.ServiceEndpoint).Returns(new Uri("https://blabla.com/"));
mockDocumentClient.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>())).ReturnsAsync(databaseAccount);
GlobalEndpointManager globalEndpointManager = new GlobalEndpointManager(mockDocumentClient.Object, new ConnectionPolicy());
GlobalPartitionEndpointManager partitionKeyRangeLocationCache = new GlobalPartitionEndpointManagerCore(globalEndpointManager);
ConnectionPolicy connectionPolicy = new ConnectionPolicy
{
RequestTimeout = TimeSpan.FromSeconds(10)
};
GlobalAddressResolver globalAddressResolver = new GlobalAddressResolver(
endpointManager: globalEndpointManager,
partitionKeyRangeLocationCache: partitionKeyRangeLocationCache,
protocol: Documents.Client.Protocol.Tcp,
tokenProvider: this.mockTokenProvider.Object,
collectionCache: null,
routingMapProvider: null,
serviceConfigReader: this.mockServiceConfigReader.Object,
connectionPolicy: connectionPolicy,
httpClient: MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)));
ConnectionStateListener connectionStateListener = new ConnectionStateListener(globalAddressResolver);
connectionStateListener.OnConnectionEvent(ConnectionEvent.ReadEof, DateTime.Now, new Documents.Rntbd.ServerKey(new Uri("https://endpoint.azure.com:4040/")));
}, state: null);
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevContext);
}
}
[TestMethod]
[Owner("aysarkar")]
public async Task GatewayAddressCacheInNetworkRequestTestAsync()
{
FakeMessageHandler messageHandler = new FakeMessageHandler();
HttpClient httpClient = new(messageHandler);
httpClient.Timeout = TimeSpan.FromSeconds(120);
GatewayAddressCache cache = new GatewayAddressCache(
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: null,
suboptimalPartitionForceRefreshIntervalInSeconds: 2,
enableTcpConnectionEndpointRediscovery: true);
// No header should be present.
PartitionAddressInformation legacyRequest = await cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
false,
CancellationToken.None);
Assert.IsFalse(legacyRequest.IsLocalRegion);
// Header indicates the request is from the same azure region.
messageHandler.Headers[HttpConstants.HttpHeaders.LocalRegionRequest] = "true";
PartitionAddressInformation inNetworkAddresses = await cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
true,
CancellationToken.None);
Assert.IsTrue(inNetworkAddresses.IsLocalRegion);
// Header indicates the request is not from the same azure region.
messageHandler.Headers[HttpConstants.HttpHeaders.LocalRegionRequest] = "false";
PartitionAddressInformation outOfNetworkAddresses = await cache.TryGetAddressesAsync(
DocumentServiceRequest.Create(OperationType.Invalid, ResourceType.Address, AuthorizationTokenType.Invalid),
this.testPartitionKeyRangeIdentity,
this.serviceIdentity,
true,
CancellationToken.None);
Assert.IsFalse(outOfNetworkAddresses.IsLocalRegion);
}
/// <summary>
/// Test to validate that when <see cref="GatewayAddressCache.OpenConnectionsAsync()"/> is called with a
/// valid open connection handler, the handler method is indeed invoked.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task OpenConnectionsAsync_WithValidOpenConnectionHandler_ShouldInvokeHandlerMethod()
{
// Arrange.
FakeMessageHandler messageHandler = new ();
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>());
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
HttpClient httpClient = new(messageHandler)
{
Timeout = TimeSpan.FromSeconds(120)
};
GatewayAddressCache cache = new (
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: fakeOpenConnectionHandler,
suboptimalPartitionForceRefreshIntervalInSeconds: 2);
// Act.
await cache.OpenConnectionsAsync(
databaseName: "test-database",
collection: containerProperties,
partitionKeyRangeIdentities: new List<PartitionKeyRangeIdentity>()
{
this.testPartitionKeyRangeIdentity
},
shouldOpenRntbdChannels: true,
cancellationToken: CancellationToken.None);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 0,
expectedTotalHandlerInvocationCount: 1,
expectedTotalReceivedAddressesCount: 3,
expectedTotalSuccessAddressesToOpenCount: 3);
}
/// <summary>
/// Test to validate that when <see cref="GatewayAddressCache.OpenConnectionsAsync()"/> is invoked with a
/// open connection handler that throws an exception, the handler method is indeed invoked
/// and the exception is handled in such a way that the cosmos client initialization does not fail.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task OpenConnectionsAsync_WhenConnectionHandlerThrowsException_ShouldNotFailInitialization()
{
// Arrange.
FakeMessageHandler messageHandler = new ();
FakeOpenConnectionHandler fakeOpenConnectionHandler = new(failingIndexes: new HashSet<int>() { 0, 1, 2});
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
HttpClient httpClient = new(messageHandler);
GatewayAddressCache cache = new (
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: fakeOpenConnectionHandler,
suboptimalPartitionForceRefreshIntervalInSeconds: 2);
// Act.
await cache.OpenConnectionsAsync(
databaseName: "test-database",
collection: containerProperties,
partitionKeyRangeIdentities: new List<PartitionKeyRangeIdentity>()
{
this.testPartitionKeyRangeIdentity
},
shouldOpenRntbdChannels: true,
cancellationToken: CancellationToken.None);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 3,
expectedTotalHandlerInvocationCount: 1,
expectedTotalReceivedAddressesCount: 3,
expectedTotalSuccessAddressesToOpenCount: 0);
}
/// <summary>
/// Test to validate that when <see cref="GatewayAddressCache.OpenConnectionsAsync()"/> is invoked with a null
/// open connection handler, the handler method is never invoked, thus no attempt to open connections
/// to the backend replica happens.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task OpenConnectionsAsync_WithNullOpenConnectionHandler_ShouldNotInvokeHandlerMethod()
{
// Arrange.
FakeMessageHandler messageHandler = new ();
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>());
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
HttpClient httpClient = new(messageHandler)
{
Timeout = TimeSpan.FromSeconds(120)
};
GatewayAddressCache cache = new(
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: null,
suboptimalPartitionForceRefreshIntervalInSeconds: 2);
// Act.
await cache.OpenConnectionsAsync(
databaseName: "test-database",
collection: containerProperties,
partitionKeyRangeIdentities: new List<PartitionKeyRangeIdentity>()
{
this.testPartitionKeyRangeIdentity
},
shouldOpenRntbdChannels: true,
cancellationToken: CancellationToken.None);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 0,
expectedTotalHandlerInvocationCount: 0,
expectedTotalReceivedAddressesCount: 0,
expectedTotalSuccessAddressesToOpenCount: 0);
}
/// <summary>
/// Test to validate that when <see cref="GatewayAddressCache.OpenConnectionsAsync()"/> is called with a valid open connection handler
/// and a cancellation token that will expire with a pre-configured time, the handler method is indeed invoked and the open connection
/// operation gets cancelled successfully, if the cancellation token expires. The open connection operation succeeds if the operation
/// is finished before the cancellation token expiry time.
/// </summary>
[TestMethod]
[Owner("dkunda")]
[DataRow(1, 2, 1, 0, 3, 0, true, DisplayName = "Validate that when the cancellation token expiry time (i.e. 1 sec) is smaller than the open connection opperation duration (i.e. 2 sec)," +
"the open connection operation gets cancelled and the cancellation token is indeed respected and eventually cancelled.")]
[DataRow(3, 1, 1, 0, 3, 3, false, DisplayName = "Validate that when the cancellation token expiry time (i.e. 3 sec) is larger than the open connection opperation duration (i.e. 1 sec)," +
"the open connection operation completes successfully and the cancellation token is not cancelled.")]
public async Task OpenConnectionsAsync_WithValidOpenConnectionHandlerAndCancellationTokenExpires_ShouldInvokeHandlerMethodAndCancelToken(
int cancellationTokenTimeoutInSeconds,
int openConnectionDelayInSeconds,
int expectedTotalHandlerInvocationCount,
int expectedTotalFailedAddressesToOpenCount,
int expectedTotalReceivedAddressesCount,
int expectedTotalSuccessAddressesToOpenCount,
bool shouldCancelToken)
{
// Arrange.
FakeMessageHandler messageHandler = new ();
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (
failingIndexes: new HashSet<int>(),
openConnectionDelayInSeconds: openConnectionDelayInSeconds);
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
HttpClient httpClient = new(messageHandler)
{
Timeout = TimeSpan.FromSeconds(120)
};
CancellationTokenSource cts = new (TimeSpan.FromSeconds(cancellationTokenTimeoutInSeconds));
CancellationToken token = cts.Token;
GatewayAddressCache cache = new (
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),
openConnectionsHandler: fakeOpenConnectionHandler,
suboptimalPartitionForceRefreshIntervalInSeconds: 2);
// Act.
await cache.OpenConnectionsAsync(
databaseName: "test-database",
collection: containerProperties,
partitionKeyRangeIdentities: new List<PartitionKeyRangeIdentity>()
{
this.testPartitionKeyRangeIdentity
},
shouldOpenRntbdChannels: true,
cancellationToken: token);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: expectedTotalFailedAddressesToOpenCount,
expectedTotalHandlerInvocationCount: expectedTotalHandlerInvocationCount,
expectedTotalReceivedAddressesCount: expectedTotalReceivedAddressesCount,
expectedTotalSuccessAddressesToOpenCount: expectedTotalSuccessAddressesToOpenCount);
Assert.AreEqual(shouldCancelToken, token.IsCancellationRequested);
}
/// <summary>
/// Test to validate that when <see cref="GlobalAddressResolver.OpenConnectionsToAllReplicasAsync()"/> is called with a
/// valid open connection handler, the handler method is indeed invoked and an attempt is made to open
/// the connections to the backend replicas.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task GlobalAddressResolver_OpenConnectionsToAllReplicasAsync_WithValidHandler_ShouldOpenConnectionsToBackend()
{
// Arrange.
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>());
UserAgentContainer container = new (clientId: 0);
FakeMessageHandler messageHandler = new ();
AccountProperties databaseAccount = new ();
Mock<IDocumentClientInternal> mockDocumentClient = new ();
mockDocumentClient
.Setup(owner => owner.ServiceEndpoint)
.Returns(new Uri("https://blabla.com/"));
mockDocumentClient
.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseAccount);
GlobalEndpointManager globalEndpointManager = new (
mockDocumentClient.Object,
new ConnectionPolicy());
GlobalPartitionEndpointManager partitionKeyRangeLocationCache = new GlobalPartitionEndpointManagerCore(globalEndpointManager);
ConnectionPolicy connectionPolicy = new ()
{
RequestTimeout = TimeSpan.FromSeconds(120)
};
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
Mock<CollectionCache> mockCollectionCahce = new (MockBehavior.Strict);
mockCollectionCahce
.Setup(x => x.ResolveByNameAsync(
It.IsAny<string>(),
It.IsAny<string>(),
false,
It.IsAny<ITrace>(),
It.IsAny<IClientSideRequestStatistics>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(containerProperties));
GlobalAddressResolver globalAddressResolver = new (
endpointManager: globalEndpointManager,
partitionKeyRangeLocationCache: partitionKeyRangeLocationCache,
protocol: Documents.Client.Protocol.Tcp,
tokenProvider: this.mockTokenProvider.Object,
collectionCache: mockCollectionCahce.Object,
routingMapProvider: this.partitionKeyRangeCache.Object,
serviceConfigReader: this.mockServiceConfigReader.Object,
connectionPolicy: connectionPolicy,
httpClient: MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)));
globalAddressResolver.SetOpenConnectionsHandler(
openConnectionsHandler: fakeOpenConnectionHandler);
// Act.
await globalAddressResolver.OpenConnectionsToAllReplicasAsync(
databaseName: "test-db",
containerLinkUri: "https://test.uri.cosmos.com",
CancellationToken.None);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 0,
expectedTotalHandlerInvocationCount: 1,
expectedTotalReceivedAddressesCount: 3,
expectedTotalSuccessAddressesToOpenCount: 3);
}
/// <summary>
/// Test to validate that when <see cref="GlobalAddressResolver.OpenConnectionsToAllReplicasAsync()"/> is called with a
/// open connection handler that throws an exception, the handler method is indeed invoked and the exception is handled
/// in such a way that the cosmos client initialization does not fail.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task GlobalAddressResolver_OpenConnectionsToAllReplicasAsync_WhenHandlerDelegateThrowsException_ShouldNotFailInitialization()
{
// Arrange.
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>() { 0, 2});
UserAgentContainer container = new(clientId: 0);
FakeMessageHandler messageHandler = new();
AccountProperties databaseAccount = new();
Mock<IDocumentClientInternal> mockDocumentClient = new();
mockDocumentClient
.Setup(owner => owner.ServiceEndpoint)
.Returns(new Uri("https://blabla.com/"));
mockDocumentClient
.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseAccount);
GlobalEndpointManager globalEndpointManager = new(
mockDocumentClient.Object,
new ConnectionPolicy());
GlobalPartitionEndpointManager partitionKeyRangeLocationCache = new GlobalPartitionEndpointManagerCore(globalEndpointManager);
ConnectionPolicy connectionPolicy = new()
{
RequestTimeout = TimeSpan.FromSeconds(120)
};
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
Mock<CollectionCache> mockCollectionCahce = new(MockBehavior.Strict);
mockCollectionCahce
.Setup(x => x.ResolveByNameAsync(
It.IsAny<string>(),
It.IsAny<string>(),
false,
It.IsAny<ITrace>(),
It.IsAny<IClientSideRequestStatistics>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(containerProperties));
GlobalAddressResolver globalAddressResolver = new(
endpointManager: globalEndpointManager,
partitionKeyRangeLocationCache: partitionKeyRangeLocationCache,
protocol: Documents.Client.Protocol.Tcp,
tokenProvider: this.mockTokenProvider.Object,
collectionCache: mockCollectionCahce.Object,
routingMapProvider: this.partitionKeyRangeCache.Object,
serviceConfigReader: this.mockServiceConfigReader.Object,
connectionPolicy: connectionPolicy,
httpClient: MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)));
globalAddressResolver.SetOpenConnectionsHandler(
openConnectionsHandler: fakeOpenConnectionHandler);
// Act.
await globalAddressResolver.OpenConnectionsToAllReplicasAsync(
databaseName: "test-db",
containerLinkUri: "https://test.uri.cosmos.com",
CancellationToken.None);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 2,
expectedTotalHandlerInvocationCount: 1,
expectedTotalReceivedAddressesCount: 3,
expectedTotalSuccessAddressesToOpenCount: 1);
}
/// <summary>
/// Test to validate that when <see cref="GlobalAddressResolver.OpenConnectionsToAllReplicasAsync()"/> is invoked and
/// and an internal operation throws an exception which is other than a transport exception, then the exception is indeed
/// bubbled up and thrown during the cosmos client initialization.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task GlobalAddressResolver_OpenConnectionsToAllReplicasAsync_WhenInternalExceptionThrownApartFromTransportError_ShouldThrowException()
{
// Arrange.
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>());
UserAgentContainer container = new(clientId: 0);
FakeMessageHandler messageHandler = new();
AccountProperties databaseAccount = new();
Mock<IDocumentClientInternal> mockDocumentClient = new();
mockDocumentClient
.Setup(owner => owner.ServiceEndpoint)
.Returns(new Uri("https://blabla.com/"));
mockDocumentClient
.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseAccount);
GlobalEndpointManager globalEndpointManager = new (
mockDocumentClient.Object,
new ConnectionPolicy());
GlobalPartitionEndpointManager partitionKeyRangeLocationCache = new GlobalPartitionEndpointManagerCore(globalEndpointManager);
ConnectionPolicy connectionPolicy = new ()
{
RequestTimeout = TimeSpan.FromSeconds(120)
};
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
Mock<CollectionCache> mockCollectionCahce = new (MockBehavior.Strict);
mockCollectionCahce
.Setup(x => x.ResolveByNameAsync(
It.IsAny<string>(),
It.IsAny<string>(),
false,
It.IsAny<ITrace>(),
It.IsAny<IClientSideRequestStatistics>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(containerProperties));
string exceptionMessage = "Failed to lookup partition key ranges.";
Mock<PartitionKeyRangeCache> partitionKeyRangeCache = new (null, null, null);
partitionKeyRangeCache
.Setup(m => m.TryGetOverlappingRangesAsync(
It.IsAny<string>(),
It.IsAny<Documents.Routing.Range<string>>(),
It.IsAny<ITrace>(),
It.IsAny<bool>()))
.ThrowsAsync(
new Exception(exceptionMessage));
GlobalAddressResolver globalAddressResolver = new(
endpointManager: globalEndpointManager,
partitionKeyRangeLocationCache: partitionKeyRangeLocationCache,
protocol: Documents.Client.Protocol.Tcp,
tokenProvider: this.mockTokenProvider.Object,
collectionCache: mockCollectionCahce.Object,
routingMapProvider: partitionKeyRangeCache.Object,
serviceConfigReader: this.mockServiceConfigReader.Object,
connectionPolicy: connectionPolicy,
httpClient: MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)));
globalAddressResolver.SetOpenConnectionsHandler(
openConnectionsHandler: fakeOpenConnectionHandler);
// Act.
Exception ex = await Assert.ThrowsExceptionAsync<Exception>(() => globalAddressResolver.OpenConnectionsToAllReplicasAsync(
databaseName: "test-db",
containerLinkUri: "https://test.uri.cosmos.com",
CancellationToken.None));
// Assert.
Assert.IsNotNull(ex);
Assert.AreEqual(exceptionMessage, ex.Message);
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 0,
expectedTotalHandlerInvocationCount: 0,
expectedTotalReceivedAddressesCount: 0,
expectedTotalSuccessAddressesToOpenCount: 0);
}
/// <summary>
/// Test to validate that when <see cref="GlobalAddressResolver.OpenConnectionsToAllReplicasAsync()"/> is invoked and
/// no valid collection could be resolved for the given database name and container link uri, thus a null value is
/// returned, then a <see cref="CosmosException"/> is thrown during the cosmos client initialization.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task GlobalAddressResolver_OpenConnectionsToAllReplicasAsync_WhenNullCollectionReturned_ShouldThrowException()
{
// Arrange.
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>());
UserAgentContainer container = new (clientId: 0);
FakeMessageHandler messageHandler = new ();
AccountProperties databaseAccount = new ();
Mock<IDocumentClientInternal> mockDocumentClient = new ();
mockDocumentClient
.Setup(owner => owner.ServiceEndpoint)
.Returns(new Uri("https://blabla.com/"));
mockDocumentClient
.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(databaseAccount);
GlobalEndpointManager globalEndpointManager = new (
mockDocumentClient.Object,
new ConnectionPolicy());
GlobalPartitionEndpointManager partitionKeyRangeLocationCache = new GlobalPartitionEndpointManagerCore(globalEndpointManager);
ConnectionPolicy connectionPolicy = new ()
{
RequestTimeout = TimeSpan.FromSeconds(120)
};
Mock<CollectionCache> mockCollectionCahce = new (MockBehavior.Strict);
mockCollectionCahce
.Setup(x => x.ResolveByNameAsync(
It.IsAny<string>(),
It.IsAny<string>(),
false,
It.IsAny<ITrace>(),
It.IsAny<IClientSideRequestStatistics>(),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<ContainerProperties>(null));
GlobalAddressResolver globalAddressResolver = new (
endpointManager: globalEndpointManager,
partitionKeyRangeLocationCache: partitionKeyRangeLocationCache,
protocol: Documents.Client.Protocol.Tcp,
tokenProvider: this.mockTokenProvider.Object,
collectionCache: mockCollectionCahce.Object,
routingMapProvider: this.partitionKeyRangeCache.Object,
serviceConfigReader: this.mockServiceConfigReader.Object,
connectionPolicy: connectionPolicy,
httpClient: MockCosmosUtil.CreateCosmosHttpClient(() => new HttpClient(messageHandler)));
globalAddressResolver.SetOpenConnectionsHandler(
openConnectionsHandler: fakeOpenConnectionHandler);
// Act.
CosmosException ce = await Assert.ThrowsExceptionAsync<CosmosException>(() => globalAddressResolver.OpenConnectionsToAllReplicasAsync(
databaseName: "test-db",
containerLinkUri: "https://test.uri.cosmos.com",
CancellationToken.None));
// Assert.
Assert.IsNotNull(ce);
Assert.IsTrue(ce.Message.Contains("Could not resolve the collection"));
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 0,
expectedTotalHandlerInvocationCount: 0,
expectedTotalReceivedAddressesCount: 0,
expectedTotalSuccessAddressesToOpenCount: 0);
}
/// <summary>
/// Test to validate that when <see cref="GatewayAddressCache.OpenConnectionsAsync()"/> is called with a
/// valid open connection handler and some of the address resolving fails with exception, then the
/// GatewayAddressCache should ignore the failed addresses and the handler method is indeed invoked
/// for all resolved addresses.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task OpenConnectionsAsync_WhenSomeAddressResolvingFailsWithException_ShouldIgnoreExceptionsAndInvokeHandlerMethodForOtherAddresses()
{
// Arrange.
FakeMessageHandler messageHandler = new ();
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (failingIndexes: new HashSet<int>());
ContainerProperties containerProperties = ContainerProperties.CreateWithResourceId("ccZ1ANCszwk=");
containerProperties.Id = "TestId";
containerProperties.PartitionKeyPath = "/pk";
List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities = Enumerable.Repeat(this.testPartitionKeyRangeIdentity, 70).ToList();
List<Address> addresses = new ()
{
new Address() { IsPrimary = true, PhysicalUri = "https://blabla.com", Protocol = RuntimeConstants.Protocols.RNTBD, PartitionKeyRangeId = "YxM9ANCZIwABAAAAAAAAAA==" },
new Address() { IsPrimary = false, PhysicalUri = "https://blabla3.com", Protocol = RuntimeConstants.Protocols.RNTBD, PartitionKeyRangeId = "YxM9ANCZIwABAAAAAAAAAA==" },
new Address() { IsPrimary = false, PhysicalUri = "https://blabla2.com", Protocol = RuntimeConstants.Protocols.RNTBD, PartitionKeyRangeId = "YxM9ANCZIwABAAAAAAAAAA==" },
new Address() { IsPrimary = false, PhysicalUri = "https://blabla4.com", Protocol = RuntimeConstants.Protocols.RNTBD, PartitionKeyRangeId = "YxM9ANCZIwABAAAAAAAAAA==" },
new Address() { IsPrimary = false, PhysicalUri = "https://blabla5.com", Protocol = RuntimeConstants.Protocols.RNTBD, PartitionKeyRangeId = "YxM9ANCZIwABAAAAAAAAAA==" }
};
FeedResource<Address> addressFeedResource = new ()
{
Id = "YxM9ANCZIwABAAAAAAAAAA==",
SelfLink = "dbs/YxM9AA==/colls/YxM9ANCZIwA=/docs/YxM9ANCZIwABAAAAAAAAAA==/",
Timestamp = DateTime.Now,
InnerCollection = new Collection<Address>(addresses),
};
StringBuilder feedResourceString = new ();
addressFeedResource.SaveTo(feedResourceString);
StringContent content = new (feedResourceString.ToString());
HttpResponseMessage responseMessage = new ()
{
StatusCode = HttpStatusCode.OK,
Content = content,
};
Mock<CosmosHttpClient> mockHttpClient = new ();
mockHttpClient.SetupSequence(x => x.GetAsync(
It.IsAny<Uri>(),
It.IsAny<Documents.Collections.INameValueCollection>(),
It.IsAny<ResourceType>(),
It.IsAny<HttpTimeoutPolicy>(),
It.IsAny<IClientSideRequestStatistics>(),
It.IsAny<CancellationToken>()))
.ThrowsAsync(new Exception("Some random error occurred."))
.ReturnsAsync(responseMessage);
GatewayAddressCache cache = new(
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
mockHttpClient.Object,
openConnectionsHandler: fakeOpenConnectionHandler,
suboptimalPartitionForceRefreshIntervalInSeconds: 2);
// Act.
await cache.OpenConnectionsAsync(
databaseName: "test-database",
collection: containerProperties,
partitionKeyRangeIdentities: partitionKeyRangeIdentities,
shouldOpenRntbdChannels: true,
cancellationToken: CancellationToken.None);
// Assert.
GatewayAddressCacheTests.AssertOpenConnectionHandlerAttributes(
fakeOpenConnectionHandler: fakeOpenConnectionHandler,
expectedTotalFailedAddressesToOpenCount: 0,
expectedTotalHandlerInvocationCount: 1,
expectedTotalReceivedAddressesCount: addresses.Count,
expectedTotalSuccessAddressesToOpenCount: addresses.Count);
}
/// <summary>
/// Test to validate that when replica validation is enabled and force address refresh happens to fetch the latest address from gateway,
/// if in case the gateway returns the same address which was previously unhealthy, the gateway address cache resets the returned status
/// to unhealthy and validates that replica using the open connection handler and finally marks it to connected.
/// </summary>
[TestMethod]
[Owner("dkunda")]
public async Task TryGetAddressesAsync_WhenReplicaVlidationEnabled_ShouldValidateUnhealthyReplicasHealth()
{
// Arrange.
ManualResetEvent manualResetEvent = new(initialState: false);
Mock<IHttpHandler> mockHttpHandler = new (MockBehavior.Strict);
string oldAddress = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/4s";
string newAddress = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/5s";
string addressTobeMarkedUnhealthy = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/2s";
mockHttpHandler.SetupSequence(x => x.SendAsync(
It.IsAny<HttpRequestMessage>(),
It.IsAny<CancellationToken>()))
.Returns(MockCosmosUtil.CreateHttpResponseOfAddresses(new List<string>()
{
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/1p",
addressTobeMarkedUnhealthy,
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/3s",
oldAddress,
}))
.Returns(MockCosmosUtil.CreateHttpResponseOfAddresses(new List<string>()
{
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/1p",
addressTobeMarkedUnhealthy,
"rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/3s",
newAddress,
}));
FakeOpenConnectionHandler fakeOpenConnectionHandler = new (
failingIndexes: new HashSet<int>(),
manualResetEvent: manualResetEvent);
HttpClient httpClient = new (new HttpHandlerHelper(mockHttpHandler.Object));
GatewayAddressCache cache = new (
new Uri(GatewayAddressCacheTests.DatabaseAccountApiEndpoint),
Documents.Client.Protocol.Tcp,
this.mockTokenProvider.Object,
this.mockServiceConfigReader.Object,
MockCosmosUtil.CreateCosmosHttpClient(() => httpClient),