Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ClientRetryPolicy: Fixes behavior to Meta-data write operations in multimaster accounts #3466

Merged
merged 14 commits into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions Microsoft.Azure.Cosmos/src/ClientRetryPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ public void OnBeforeSendRequest(DocumentServiceRequest request)
{
// set location-based routing directive based on request retry context
request.RequestContext.RouteToLocation(this.retryContext.RetryLocationIndex, this.retryContext.RetryRequestOnPreferredLocations);

if (this.retryContext.RouteToHub)
{
request.RequestContext.RouteToLocation(this.globalEndpointManager.GetHubUri());
}
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved
}

// Resolve the endpoint for the request and pin the resolution to the resolved endpoint
Expand Down Expand Up @@ -185,6 +190,20 @@ private async Task<ShouldRetryResult> ShouldRetryInternalAsync(
this.documentServiceRequest?.RequestContext?.LocationEndpointToRoute?.ToString() ?? string.Empty,
this.documentServiceRequest?.ResourceAddress ?? string.Empty);

if (this.globalEndpointManager.IsMetadataWriteRequestMultimaster(this.documentServiceRequest))
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved
{
ShouldRetryResult retryResult = await this.ShouldRetryOnEndpointFailureAsync(
isReadRequest: false,
markBothReadAndWriteAsUnavailable: false,
forceRefresh: true,
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved
retryOnPreferredLocations: false,
overwriteEndpointDiscovery: true);

this.retryContext.RouteToHub = true;
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved

return retryResult;
}

return await this.ShouldRetryOnEndpointFailureAsync(
isReadRequest: false,
markBothReadAndWriteAsUnavailable: false,
Expand Down Expand Up @@ -243,9 +262,10 @@ private async Task<ShouldRetryResult> ShouldRetryOnEndpointFailureAsync(
bool isReadRequest,
bool markBothReadAndWriteAsUnavailable,
bool forceRefresh,
bool retryOnPreferredLocations)
bool retryOnPreferredLocations,
bool overwriteEndpointDiscovery = false)
{
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount)
if (this.failoverRetryCount > MaxRetryCount || (!this.enableEndpointDiscovery && !overwriteEndpointDiscovery))
{
DefaultTrace.TraceInformation("ClientRetryPolicy: ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {0}, Endpoint = {1}",
this.failoverRetryCount,
Expand All @@ -255,7 +275,7 @@ private async Task<ShouldRetryResult> ShouldRetryOnEndpointFailureAsync(

this.failoverRetryCount++;

if (this.locationEndpoint != null)
if (this.locationEndpoint != null && !overwriteEndpointDiscovery)
{
if (isReadRequest || markBothReadAndWriteAsUnavailable)
{
Expand Down Expand Up @@ -400,6 +420,8 @@ private sealed class RetryContext
{
public int RetryLocationIndex { get; set; }
public bool RetryRequestOnPreferredLocations { get; set; }

public bool RouteToHub { get; set; }
}
}
}
11 changes: 10 additions & 1 deletion Microsoft.Azure.Cosmos/src/Routing/GlobalEndpointManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ public GlobalEndpointManager(IDocumentClientInternal owner, ConnectionPolicy con

public int PreferredLocationCount => this.connectionPolicy.PreferredLocations != null ? this.connectionPolicy.PreferredLocations.Count : 0;

public bool IsMetadataWriteRequestMultimaster(DocumentServiceRequest request)
{
return this.locationCache.IsMetadataWriteRequestOnMultimasterAccount(request);
}

public Uri GetHubUri()
{
return this.locationCache.GetHubUri();
}

/// <summary>
/// This will get the account information.
/// It will try the global endpoint first.
Expand Down Expand Up @@ -541,7 +551,6 @@ private async Task RefreshDatabaseAccountInternalAsync(bool forceRefresh)
}
}
}

internal async Task<AccountProperties> GetDatabaseAccountAsync(bool forceRefresh = false)
{
#nullable disable // Needed because AsyncCache does not have nullable enabled
Expand Down
15 changes: 15 additions & 0 deletions Microsoft.Azure.Cosmos/src/Routing/LocationCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Microsoft.Azure.Cosmos.Routing
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using Microsoft.Azure.Cosmos.Core.Trace;
Expand Down Expand Up @@ -206,6 +207,20 @@ public void OnLocationPreferenceChanged(ReadOnlyCollection<string> preferredLoca
preferenceList: preferredLocations);
}

public bool IsMetadataWriteRequestOnMultimasterAccount(DocumentServiceRequest request)
{
return !request.IsReadOnlyRequest && this.locationInfo.AvailableWriteLocations.Count > 1
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved
&& !this.CanUseMultipleWriteLocations(request);
}

public Uri GetHubUri()
{
DatabaseAccountLocationsInfo currentLocationInfo = this.locationInfo;
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved
string writeLocation = currentLocationInfo.AvailableWriteLocations[0];
Uri locationEndpointToRoute = currentLocationInfo.AvailableWriteEndpointByLocation[writeLocation];
NaluTripician marked this conversation as resolved.
Show resolved Hide resolved
return locationEndpointToRoute;
}

/// <summary>
/// Resolves request to service endpoint.
/// 1. If this is a write request
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
namespace Microsoft.Azure.Cosmos.Client.Tests
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Azure.Cosmos.Routing;
using Moq;
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.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Documents.Collections;
using Microsoft.Azure.Documents.Routing;
using System.Net.WebSockets;
using System.Net.Http.Headers;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
using System.Collections.Specialized;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Cosmos.Common;

Expand All @@ -37,6 +30,60 @@ public sealed class ClientRetryPolicyTests
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.IsMetadataWriteRequestMultimaster(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>
Expand Down Expand Up @@ -338,6 +385,18 @@ private GlobalEndpointManager Initialize(
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)
Expand Down