-
Notifications
You must be signed in to change notification settings - Fork 504
/
Copy pathClientRetryPolicyTests.cs
657 lines (556 loc) · 31.4 KB
/
ClientRetryPolicyTests.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
namespace Microsoft.Azure.Cosmos.Client.Tests
{
using System;
using Microsoft.Azure.Cosmos.Routing;
using Microsoft.Azure.Documents;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Documents.Collections;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Cosmos.Common;
/// <summary>
/// Tests for <see cref="ClientRetryPolicy"/>
/// </summary>
[TestClass]
public sealed class ClientRetryPolicyTests
{
private static Uri Location1Endpoint = new Uri("https://location1.documents.azure.com");
private static Uri Location2Endpoint = new Uri("https://location2.documents.azure.com");
private ReadOnlyCollection<string> preferredLocations;
private AccountProperties databaseAccount;
private GlobalPartitionEndpointManager partitionKeyRangeLocationCache;
private Mock<IDocumentClientInternal> mockedClient;
/// <summary>
/// Tests behavior of Multimaster Accounts on metadata writes where the default location is not the hub region
/// </summary>
[TestMethod]
public void MultimasterMetadataWriteRetryTest()
{
const bool enableEndpointDiscovery = false;
//Creates GlobalEndpointManager where enableEndpointDiscovery is False and
//Default location is false
using GlobalEndpointManager endpointManager = this.Initialize(
useMultipleWriteLocations: true,
enableEndpointDiscovery: enableEndpointDiscovery,
isPreferredLocationsListEmpty: true,
multimasterMetadataWriteRetryTest: true);
ClientRetryPolicy retryPolicy = new ClientRetryPolicy(endpointManager, this.partitionKeyRangeLocationCache, enableEndpointDiscovery, new RetryOptions());
//Creates a metadata write request
DocumentServiceRequest request = this.CreateRequest(false, true);
Assert.IsTrue(endpointManager.IsMultimasterMetadataWriteRequest(request));
//On first attempt should get incorrect (default/non hub) location
retryPolicy.OnBeforeSendRequest(request);
Assert.AreEqual(request.RequestContext.LocationEndpointToRoute, ClientRetryPolicyTests.Location2Endpoint);
//Creation of 403.3 Error
HttpStatusCode forbidden = HttpStatusCode.Forbidden;
SubStatusCodes writeForbidden = SubStatusCodes.WriteForbidden;
Exception forbiddenWriteFail = new Exception();
Mock<INameValueCollection> nameValueCollection = new Mock<INameValueCollection>();
DocumentClientException documentClientException = new DocumentClientException(
message: "Multimaster Metadata Write Fail",
innerException: forbiddenWriteFail,
statusCode: forbidden,
substatusCode: writeForbidden,
requestUri: request.RequestContext.LocationEndpointToRoute,
responseHeaders: nameValueCollection.Object);
CancellationToken cancellationToken = new CancellationToken();
//Tests behavior of should retry
Task<ShouldRetryResult> shouldRetry = retryPolicy.ShouldRetryAsync(documentClientException, cancellationToken);
Assert.IsTrue(shouldRetry.Result.ShouldRetry);
//Now since the retry context is not null, should route to the hub region
retryPolicy.OnBeforeSendRequest(request);
Assert.AreEqual(request.RequestContext.LocationEndpointToRoute, ClientRetryPolicyTests.Location1Endpoint);
}
/// <summary>
/// Tests to see if different 503 substatus codes are handeled correctly
/// </summary>
/// <param name="testCode">The substatus code being Tested.</param>
[DataRow((int)SubStatusCodes.Unknown)]
[DataRow((int)SubStatusCodes.TransportGenerated503)]
[DataTestMethod]
public void Http503SubStatusHandelingTests(int testCode)
{
const bool enableEndpointDiscovery = true;
//Create GlobalEndpointManager
using GlobalEndpointManager endpointManager = this.Initialize(
useMultipleWriteLocations: false,
enableEndpointDiscovery: enableEndpointDiscovery,
isPreferredLocationsListEmpty: true);
//Create Retry Policy
ClientRetryPolicy retryPolicy = new ClientRetryPolicy(endpointManager, this.partitionKeyRangeLocationCache, enableEndpointDiscovery, new RetryOptions());
CancellationToken cancellationToken = new CancellationToken();
Exception serviceUnavailableException = new Exception();
Mock<INameValueCollection> nameValueCollection = new Mock<INameValueCollection>();
HttpStatusCode serviceUnavailable = HttpStatusCode.ServiceUnavailable;
DocumentClientException documentClientException = new DocumentClientException(
message: "Service Unavailable",
innerException: serviceUnavailableException,
responseHeaders: nameValueCollection.Object,
statusCode: serviceUnavailable,
substatusCode: (SubStatusCodes)testCode,
requestUri: null
);
Task<ShouldRetryResult> retryStatus = retryPolicy.ShouldRetryAsync(documentClientException, cancellationToken);
Assert.IsFalse(retryStatus.Result.ShouldRetry);
}
[TestMethod]
public Task ClientRetryPolicy_Retry_SingleMaster_Read_PreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: true, useMultipleWriteLocations: false, usesPreferredLocations: true, shouldHaveRetried: true);
}
[TestMethod]
public Task ClientRetryPolicy_Retry_MultiMaster_Read_PreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: true, useMultipleWriteLocations: true, usesPreferredLocations: true, shouldHaveRetried: true);
}
[TestMethod]
public Task ClientRetryPolicy_Retry_MultiMaster_Write_PreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: false, useMultipleWriteLocations: true, usesPreferredLocations: true, shouldHaveRetried: true);
}
[TestMethod]
public Task ClientRetryPolicy_NoRetry_SingleMaster_Write_PreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: false, useMultipleWriteLocations: false, usesPreferredLocations: true, shouldHaveRetried: false);
}
[TestMethod]
public Task ClientRetryPolicy_NoRetry_SingleMaster_Read_NoPreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: true, useMultipleWriteLocations: false, usesPreferredLocations: false, shouldHaveRetried: false);
}
[TestMethod]
public Task ClientRetryPolicy_NoRetry_SingleMaster_Write_NoPreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: false, useMultipleWriteLocations: false, usesPreferredLocations: false, shouldHaveRetried: false);
}
[TestMethod]
public Task ClientRetryPolicy_NoRetry_MultiMaster_Read_NoPreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: true, useMultipleWriteLocations: true, usesPreferredLocations: false, false);
}
[TestMethod]
public Task ClientRetryPolicy_NoRetry_MultiMaster_Write_NoPreferredLocations()
{
return this.ValidateConnectTimeoutTriggersClientRetryPolicy(isReadRequest: false, useMultipleWriteLocations: true, usesPreferredLocations: false, false);
}
private async Task ValidateConnectTimeoutTriggersClientRetryPolicy(
bool isReadRequest,
bool useMultipleWriteLocations,
bool usesPreferredLocations,
bool shouldHaveRetried)
{
List<string> newPhysicalUris = new List<string>();
newPhysicalUris.Add("https://default.documents.azure.com");
newPhysicalUris.Add("https://location1.documents.azure.com");
newPhysicalUris.Add("https://location2.documents.azure.com");
newPhysicalUris.Add("https://location3.documents.azure.com");
Dictionary<Uri, Exception> uriToException = new Dictionary<Uri, Exception>();
uriToException.Add(new Uri("https://default.documents.azure.com"), new GoneException(new TransportException(TransportErrorCode.ConnectTimeout, innerException: null, activityId: Guid.NewGuid(), requestUri: new Uri("https://default.documents.azure.com"), sourceDescription: "description", userPayload: true, payloadSent: true), SubStatusCodes.TransportGenerated410));
uriToException.Add(new Uri("https://location1.documents.azure.com"), new GoneException(new TransportException(TransportErrorCode.ConnectTimeout, innerException: null, activityId: Guid.NewGuid(), requestUri: new Uri("https://location1.documents.azure.com"), sourceDescription: "description", userPayload: true, payloadSent: true), SubStatusCodes.TransportGenerated410));
uriToException.Add(new Uri("https://location2.documents.azure.com"), new GoneException(new TransportException(TransportErrorCode.ConnectTimeout, innerException: null, activityId: Guid.NewGuid(), requestUri: new Uri("https://location2.documents.azure.com"), sourceDescription: "description", userPayload: true, payloadSent: true), SubStatusCodes.TransportGenerated410));
uriToException.Add(new Uri("https://location3.documents.azure.com"), new GoneException(new TransportException(TransportErrorCode.ConnectTimeout, innerException: null, activityId: Guid.NewGuid(), requestUri: new Uri("https://location3.documents.azure.com"), sourceDescription: "description", userPayload: true, payloadSent: true), SubStatusCodes.TransportGenerated410));
using MockDocumentClientContext mockDocumentClientContext = this.InitializeMockedDocumentClient(useMultipleWriteLocations, !usesPreferredLocations);
mockDocumentClientContext.GlobalEndpointManager.InitializeAccountPropertiesAndStartBackgroundRefresh(mockDocumentClientContext.DatabaseAccount);
MockAddressResolver mockAddressResolver = new MockAddressResolver(newPhysicalUris, newPhysicalUris);
SessionContainer sessionContainer = new SessionContainer("localhost");
MockTransportClient mockTransportClient = new MockTransportClient(null, uriToException);
MockServiceConfigurationReader mockServiceConfigurationReader = new MockServiceConfigurationReader();
MockAuthorizationTokenProvider mockAuthorizationTokenProvider = new MockAuthorizationTokenProvider();
ReplicatedResourceClient replicatedResourceClient = new ReplicatedResourceClient(
addressResolver: mockAddressResolver,
sessionContainer: sessionContainer,
protocol: Protocol.Tcp,
transportClient: mockTransportClient,
serviceConfigReader: mockServiceConfigurationReader,
authorizationTokenProvider: mockAuthorizationTokenProvider,
enableReadRequestsFallback: false,
useMultipleWriteLocations: useMultipleWriteLocations,
detectClientConnectivityIssues: true,
disableRetryWithRetryPolicy: false,
enableReplicaValidation: false);
// Reducing retry timeout to avoid long-running tests
replicatedResourceClient.GoneAndRetryWithRetryTimeoutInSecondsOverride = 1;
this.partitionKeyRangeLocationCache = GlobalPartitionEndpointManagerNoOp.Instance;
ClientRetryPolicy retryPolicy = new ClientRetryPolicy(mockDocumentClientContext.GlobalEndpointManager, this.partitionKeyRangeLocationCache, enableEndpointDiscovery: true, new RetryOptions());
INameValueCollection headers = new DictionaryNameValueCollection();
headers.Set(HttpConstants.HttpHeaders.ConsistencyLevel, ConsistencyLevel.BoundedStaleness.ToString());
using (DocumentServiceRequest request = DocumentServiceRequest.Create(
isReadRequest ? OperationType.Read : OperationType.Create,
ResourceType.Document,
"dbs/OVJwAA==/colls/OVJwAOcMtA0=/docs/OVJwAOcMtA0BAAAAAAAAAA==/",
AuthorizationTokenType.PrimaryMasterKey,
headers))
{
int retryCount = 0;
try
{
await BackoffRetryUtility<StoreResponse>.ExecuteAsync(
() =>
{
retryPolicy.OnBeforeSendRequest(request);
if (retryCount == 1)
{
Uri expectedEndpoint = null;
if (usesPreferredLocations)
{
expectedEndpoint = new Uri(mockDocumentClientContext.DatabaseAccount.ReadLocationsInternal.First(l => l.Name == mockDocumentClientContext.PreferredLocations[1]).Endpoint);
}
else
{
if (isReadRequest)
{
expectedEndpoint = new Uri(mockDocumentClientContext.DatabaseAccount.ReadLocationsInternal[1].Endpoint);
}
else
{
expectedEndpoint = new Uri(mockDocumentClientContext.DatabaseAccount.WriteLocationsInternal[1].Endpoint);
}
}
Assert.AreEqual(expectedEndpoint, request.RequestContext.LocationEndpointToRoute);
}
else if (retryCount > 1)
{
Assert.Fail("Should retry once");
}
retryCount++;
return replicatedResourceClient.InvokeAsync(request);
},
retryPolicy);
Assert.Fail();
}
catch (ServiceUnavailableException)
{
if (shouldHaveRetried)
{
Assert.AreEqual(2, retryCount, $"Retry count {retryCount}, shouldHaveRetried {shouldHaveRetried} isReadRequest {isReadRequest} useMultipleWriteLocations {useMultipleWriteLocations} usesPreferredLocations {usesPreferredLocations}");
}
else
{
Assert.AreEqual(1, retryCount, $"Retry count {retryCount}, shouldHaveRetried {shouldHaveRetried} isReadRequest {isReadRequest} useMultipleWriteLocations {useMultipleWriteLocations} usesPreferredLocations {usesPreferredLocations}");
}
}
}
}
private static AccountProperties CreateDatabaseAccount(
bool useMultipleWriteLocations,
bool enforceSingleMasterSingleWriteLocation)
{
Collection<AccountRegion> writeLocations = new Collection<AccountRegion>()
{
{ new AccountRegion() { Name = "location1", Endpoint = ClientRetryPolicyTests.Location1Endpoint.ToString() } },
{ new AccountRegion() { Name = "location2", Endpoint = ClientRetryPolicyTests.Location2Endpoint.ToString() } },
};
if (!useMultipleWriteLocations
&& enforceSingleMasterSingleWriteLocation)
{
// Some pre-existing tests depend on the account having multiple write locations even on single master setup
// Newer tests can correctly define a single master account (single write region) without breaking existing tests
writeLocations = new Collection<AccountRegion>()
{
{ new AccountRegion() { Name = "location1", Endpoint = ClientRetryPolicyTests.Location1Endpoint.ToString() } }
};
}
AccountProperties databaseAccount = new AccountProperties()
{
EnableMultipleWriteLocations = useMultipleWriteLocations,
ReadLocationsInternal = new Collection<AccountRegion>()
{
{ new AccountRegion() { Name = "location1", Endpoint = ClientRetryPolicyTests.Location1Endpoint.ToString() } },
{ new AccountRegion() { Name = "location2", Endpoint = ClientRetryPolicyTests.Location2Endpoint.ToString() } },
},
WriteLocationsInternal = writeLocations
};
return databaseAccount;
}
private GlobalEndpointManager Initialize(
bool useMultipleWriteLocations,
bool enableEndpointDiscovery,
bool isPreferredLocationsListEmpty,
bool enforceSingleMasterSingleWriteLocation = false, // Some tests depend on the Initialize to create an account with multiple write locations, even when not multi master
ReadOnlyCollection<string> preferedRegionListOverride = null,
bool enablePartitionLevelFailover = false,
bool multimasterMetadataWriteRetryTest = false)
{
this.databaseAccount = ClientRetryPolicyTests.CreateDatabaseAccount(
useMultipleWriteLocations,
enforceSingleMasterSingleWriteLocation);
if (isPreferredLocationsListEmpty)
{
this.preferredLocations = new List<string>().AsReadOnly();
}
else
{
// Allow for override at the test method level if needed
this.preferredLocations = preferedRegionListOverride != null ? preferedRegionListOverride : new List<string>()
{
"location1",
"location2"
}.AsReadOnly();
}
if (!multimasterMetadataWriteRetryTest)
{
this.mockedClient = new Mock<IDocumentClientInternal>();
mockedClient.Setup(owner => owner.ServiceEndpoint).Returns(ClientRetryPolicyTests.Location1Endpoint);
mockedClient.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>())).ReturnsAsync(this.databaseAccount);
}
else
{
this.mockedClient = new Mock<IDocumentClientInternal>();
mockedClient.Setup(owner => owner.ServiceEndpoint).Returns(ClientRetryPolicyTests.Location2Endpoint);
mockedClient.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>())).ReturnsAsync(this.databaseAccount);
}
ConnectionPolicy connectionPolicy = new ConnectionPolicy()
{
EnableEndpointDiscovery = enableEndpointDiscovery,
UseMultipleWriteLocations = useMultipleWriteLocations,
};
foreach (string preferredLocation in this.preferredLocations)
{
connectionPolicy.PreferredLocations.Add(preferredLocation);
}
GlobalEndpointManager endpointManager = new GlobalEndpointManager(this.mockedClient.Object, connectionPolicy);
endpointManager.InitializeAccountPropertiesAndStartBackgroundRefresh(this.databaseAccount);
if (enablePartitionLevelFailover)
{
this.partitionKeyRangeLocationCache = new GlobalPartitionEndpointManagerCore(endpointManager);
}
else
{
this.partitionKeyRangeLocationCache = GlobalPartitionEndpointManagerNoOp.Instance;
}
return endpointManager;
}
private DocumentServiceRequest CreateRequest(bool isReadRequest, bool isMasterResourceType)
{
if (isReadRequest)
{
return DocumentServiceRequest.Create(OperationType.Read, isMasterResourceType ? ResourceType.Database : ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey);
}
else
{
return DocumentServiceRequest.Create(OperationType.Create, isMasterResourceType ? ResourceType.Database : ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey);
}
}
private MockDocumentClientContext InitializeMockedDocumentClient(
bool useMultipleWriteLocations,
bool isPreferredLocationsListEmpty)
{
AccountProperties databaseAccount = new AccountProperties()
{
EnableMultipleWriteLocations = useMultipleWriteLocations,
ReadLocationsInternal = new Collection<AccountRegion>()
{
{ new AccountRegion() { Name = "location1", Endpoint = new Uri("https://location1.documents.azure.com").ToString() } },
{ new AccountRegion() { Name = "location2", Endpoint = new Uri("https://location2.documents.azure.com").ToString() } },
{ new AccountRegion() { Name = "location3", Endpoint = new Uri("https://location3.documents.azure.com").ToString() } },
},
WriteLocationsInternal = new Collection<AccountRegion>()
{
{ new AccountRegion() { Name = "location1", Endpoint = new Uri("https://location1.documents.azure.com").ToString() } },
{ new AccountRegion() { Name = "location2", Endpoint = new Uri("https://location2.documents.azure.com").ToString() } },
{ new AccountRegion() { Name = "location3", Endpoint = new Uri("https://location3.documents.azure.com").ToString() } },
}
};
MockDocumentClientContext mockDocumentClientContext = new MockDocumentClientContext();
mockDocumentClientContext.DatabaseAccount = databaseAccount;
mockDocumentClientContext.PreferredLocations = isPreferredLocationsListEmpty ? new List<string>().AsReadOnly() : new List<string>()
{
"location1",
"location3"
}.AsReadOnly();
mockDocumentClientContext.LocationCache = new LocationCache(
mockDocumentClientContext.PreferredLocations,
new Uri("https://default.documents.azure.com"),
true,
10,
useMultipleWriteLocations);
mockDocumentClientContext.LocationCache.OnDatabaseAccountRead(mockDocumentClientContext.DatabaseAccount);
Mock<IDocumentClientInternal> mockedClient = new Mock<IDocumentClientInternal>();
mockedClient.Setup(owner => owner.ServiceEndpoint).Returns(new Uri("https://default.documents.azure.com"));
mockedClient.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny<Uri>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockDocumentClientContext.DatabaseAccount);
ConnectionPolicy connectionPolicy = new ConnectionPolicy()
{
UseMultipleWriteLocations = useMultipleWriteLocations,
};
foreach (string preferredLocation in mockDocumentClientContext.PreferredLocations)
{
connectionPolicy.PreferredLocations.Add(preferredLocation);
}
mockDocumentClientContext.DocumentClientInternal = mockedClient.Object;
mockDocumentClientContext.GlobalEndpointManager = new GlobalEndpointManager(mockDocumentClientContext.DocumentClientInternal, connectionPolicy);
return mockDocumentClientContext;
}
private class MockDocumentClientContext : IDisposable
{
public IDocumentClientInternal DocumentClientInternal { get; set; }
public GlobalEndpointManager GlobalEndpointManager { get; set; }
public LocationCache LocationCache { get; set; }
public ReadOnlyCollection<string> PreferredLocations { get; set; }
public AccountProperties DatabaseAccount { get; set; }
public void Dispose()
{
this.GlobalEndpointManager.Dispose();
}
}
private class MockAddressResolver : IAddressResolverExtension
{
private List<AddressInformation> oldAddressInformations;
private List<AddressInformation> newAddressInformations;
public int NumberOfRefreshes { get; set; }
public MockAddressResolver(List<string> oldPhysicalUris, List<string> newPhysicalUris)
{
this.NumberOfRefreshes = 0;
this.oldAddressInformations = new List<AddressInformation>();
for (int i = 0; i < oldPhysicalUris.Count; i++)
{
this.oldAddressInformations.Add(new AddressInformation(
isPrimary: i == 0,
isPublic: true,
physicalUri: oldPhysicalUris[i],
protocol: Protocol.Tcp));
}
this.newAddressInformations = new List<AddressInformation>();
for (int i = 0; i < newPhysicalUris.Count; i++)
{
this.newAddressInformations.Add(new AddressInformation(
isPrimary: i == 0,
isPublic: true,
physicalUri: newPhysicalUris[i],
protocol: Protocol.Tcp));
}
}
public Task<PartitionAddressInformation> ResolveAsync(DocumentServiceRequest request, bool forceRefreshPartitionAddresses, CancellationToken cancellationToken)
{
List<AddressInformation> addressInformations = new List<AddressInformation>();
request.RequestContext.ResolvedPartitionKeyRange = new PartitionKeyRange() { Id = "0" };
if (forceRefreshPartitionAddresses)
{
this.NumberOfRefreshes++;
return Task.FromResult<PartitionAddressInformation>(new PartitionAddressInformation(this.newAddressInformations.ToArray()));
}
return Task.FromResult<PartitionAddressInformation>(new PartitionAddressInformation(this.oldAddressInformations.ToArray()));
}
public Task UpdateAsync(IReadOnlyList<AddressCacheToken> addressCacheTokens, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task OpenConnectionsToAllReplicasAsync(
string databaseName,
string containerLinkUri,
CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task UpdateAsync(Documents.Rntbd.ServerKey serverKey, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public void SetOpenConnectionsHandler(
IOpenConnectionsHandler openConnectionHandler)
{
throw new NotImplementedException();
}
}
private class MockTransportClient : TransportClient
{
private Dictionary<Uri, StoreResponse> uriToStoreResponseMap;
private Dictionary<Uri, Exception> uriToExceptionMap;
public MockTransportClient(
Dictionary<Uri, StoreResponse> uriToStoreResponseMap,
Dictionary<Uri, Exception> uriToExceptionMap)
{
this.uriToStoreResponseMap = uriToStoreResponseMap;
this.uriToExceptionMap = uriToExceptionMap;
}
internal override Task<StoreResponse> InvokeStoreAsync(Uri physicalAddress, ResourceOperation resourceOperation, DocumentServiceRequest request)
{
if (this.uriToStoreResponseMap != null && this.uriToStoreResponseMap.ContainsKey(physicalAddress))
{
return Task.FromResult<StoreResponse>(this.uriToStoreResponseMap[physicalAddress]);
}
if (this.uriToExceptionMap != null && this.uriToExceptionMap.ContainsKey(physicalAddress))
{
throw this.uriToExceptionMap[physicalAddress];
}
throw new InvalidOperationException();
}
}
private class MockServiceConfigurationReader : IServiceConfigurationReader
{
public string DatabaseAccountId
{
get { return "localhost"; }
}
public Uri DatabaseAccountApiEndpoint { get; private set; }
public ReplicationPolicy UserReplicationPolicy
{
get { return new ReplicationPolicy(); }
}
public ReplicationPolicy SystemReplicationPolicy
{
get { return new ReplicationPolicy(); }
}
public ConsistencyLevel DefaultConsistencyLevel
{
get { return ConsistencyLevel.BoundedStaleness; }
}
public ReadPolicy ReadPolicy
{
get { return new ReadPolicy(); }
}
public string PrimaryMasterKey
{
get { return "key"; }
}
public string SecondaryMasterKey
{
get { return "key"; }
}
public string PrimaryReadonlyMasterKey
{
get { return "key"; }
}
public string SecondaryReadonlyMasterKey
{
get { return "key"; }
}
public string ResourceSeedKey
{
get { return "seed"; }
}
public string SubscriptionId
{
get { return Guid.Empty.ToString(); }
}
public Task InitializeAsync()
{
return Task.FromResult(true);
}
}
private class MockAuthorizationTokenProvider : IAuthorizationTokenProvider
{
public ValueTask<(string token, string payload)> GetUserAuthorizationAsync(
string resourceAddress,
string resourceType,
string requestVerb,
INameValueCollection headers,
AuthorizationTokenType tokenType)
{
return new ValueTask<(string token, string payload)>(("authtoken!", null));
}
public Task AddSystemAuthorizationHeaderAsync(DocumentServiceRequest request, string federationId, string verb, string resourceId)
{
request.Headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);
request.Headers[HttpConstants.HttpHeaders.Authorization] = "authtoken!";
return Task.FromResult(0);
}
}
}
}