-
Notifications
You must be signed in to change notification settings - Fork 2k
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
Add Redirect Policy to Azure core #23617
Merged
Merged
Changes from 5 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
0e22fac
initial commit
samvaity 02895a5
default retry strategy
samvaity 2a519a6
add testing, clean up
samvaity 7898117
update interface + add tests
samvaity 8b4fb3c
review comments
samvaity bbbeafc
terminate recursion for null redirect
samvaity dffd1a7
update docs
samvaity 0b7b358
use string concatenation and add comments
samvaity a19036e
clear attemptedRedirectUrl set between request, varargs usage update
samvaity File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
198 changes: 198 additions & 0 deletions
198
sdk/core/azure-core/src/main/java/com/azure/core/http/policy/DefaultRedirectStrategy.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,198 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
package com.azure.core.http.policy; | ||
|
||
import com.azure.core.http.HttpHeaders; | ||
import com.azure.core.http.HttpMethod; | ||
import com.azure.core.http.HttpPipelineCallContext; | ||
import com.azure.core.http.HttpRequest; | ||
import com.azure.core.http.HttpResponse; | ||
import com.azure.core.util.CoreUtils; | ||
import com.azure.core.util.logging.ClientLogger; | ||
|
||
import java.net.HttpURLConnection; | ||
import java.util.HashSet; | ||
import java.util.Set; | ||
|
||
/** | ||
* A default implementation of {@link RedirectStrategy} that uses the provided maximum retry attempts, | ||
* header name to look up redirect url value for, http methods and a known set of | ||
* redirect status response code (301, 302, 307, 308) to determine if request should be redirected. | ||
*/ | ||
public final class DefaultRedirectStrategy implements RedirectStrategy { | ||
private final ClientLogger logger = new ClientLogger(DefaultRedirectStrategy.class); | ||
|
||
private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; | ||
private static final String DEFAULT_REDIRECT_LOCATION_HEADER_NAME = "Location"; | ||
private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; | ||
private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; | ||
private static final Set<HttpMethod> DEFAULT_REDIRECT_ALLOWED_METHODS = new HashSet<HttpMethod>() { | ||
{ | ||
add(HttpMethod.GET); | ||
add(HttpMethod.HEAD); | ||
} | ||
}; | ||
|
||
private final int maxAttempts; | ||
private final String locationHeader; | ||
private final Set<HttpMethod> redirectMethods; | ||
|
||
/** | ||
* Creates an instance of {@link DefaultRedirectStrategy} with a maximum number of redirect attempts 3, | ||
* header name "Location" to locate the redirect url in the response headers and {@link HttpMethod#GET} | ||
* and {@link HttpMethod#HEAD} as allowed methods for performing the redirect. | ||
* | ||
* @throws IllegalArgumentException if {@code maxAttempts} is less than 0. | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
public DefaultRedirectStrategy() { | ||
this(DEFAULT_MAX_REDIRECT_ATTEMPTS, DEFAULT_REDIRECT_LOCATION_HEADER_NAME, DEFAULT_REDIRECT_ALLOWED_METHODS); | ||
} | ||
|
||
/** | ||
* Creates an instance of {@link DefaultRedirectStrategy} with the provided number of redirect attempts and | ||
* default header name "Location" to locate the redirect url in the response headers and {@link HttpMethod#GET} | ||
* and {@link HttpMethod#HEAD} as allowed methods for performing the redirect. | ||
* | ||
* @param maxAttempts The max number of redirect attempts that can be made. | ||
* @throws IllegalArgumentException if {@code maxAttempts} is less than 0. | ||
*/ | ||
public DefaultRedirectStrategy(int maxAttempts) { | ||
this(maxAttempts, DEFAULT_REDIRECT_LOCATION_HEADER_NAME, DEFAULT_REDIRECT_ALLOWED_METHODS); | ||
} | ||
|
||
/** | ||
* Creates an instance of {@link DefaultRedirectStrategy}. | ||
* | ||
* @param maxAttempts The max number of redirect attempts that can be made. | ||
* @param locationHeader The header name containing the redirect URL. | ||
* @param allowedMethods The set of {@link HttpMethod} that are allowed to be redirected. | ||
* @throws IllegalArgumentException if {@code maxAttempts} is less than 0. | ||
*/ | ||
public DefaultRedirectStrategy(int maxAttempts, String locationHeader, Set<HttpMethod> allowedMethods) { | ||
if (maxAttempts < 0) { | ||
throw logger.logExceptionAsError(new IllegalArgumentException("Max attempts cannot be less than 0.")); | ||
} | ||
this.maxAttempts = maxAttempts; | ||
this.locationHeader = locationHeader == null ? DEFAULT_REDIRECT_LOCATION_HEADER_NAME : locationHeader; | ||
this.redirectMethods = allowedMethods == null ? DEFAULT_REDIRECT_ALLOWED_METHODS : allowedMethods; | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
@Override | ||
public boolean shouldAttemptRedirect(HttpPipelineCallContext context, | ||
HttpResponse httpResponse, int tryCount, | ||
Set<String> attemptedRedirectUrls) { | ||
String redirectUrl = | ||
tryGetRedirectHeader(httpResponse.getHeaders(), this.getLocationHeader()); | ||
|
||
if (isValidRedirectCount(tryCount) | ||
&& !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls) | ||
&& isValidRedirectStatusCode(httpResponse.getStatusCode()) | ||
&& isAllowedRedirectMethod(httpResponse.getRequest().getHttpMethod())) { | ||
logger.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", tryCount, | ||
attemptedRedirectUrls.toString()); | ||
attemptedRedirectUrls.add(redirectUrl); | ||
return true; | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} else { | ||
return false; | ||
} | ||
} | ||
|
||
@Override | ||
public HttpRequest createRedirect(HttpResponse httpResponse) { | ||
String responseLocation = | ||
tryGetRedirectHeader(httpResponse.getHeaders(), this.getLocationHeader()); | ||
if (responseLocation != null) { | ||
return httpResponse.getRequest().setUrl(responseLocation); | ||
} else { | ||
return httpResponse.getRequest(); | ||
} | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
@Override | ||
public int getMaxAttempts() { | ||
return maxAttempts; | ||
} | ||
|
||
@Override | ||
public String getLocationHeader() { | ||
return locationHeader; | ||
} | ||
|
||
@Override | ||
public Set<HttpMethod> getAllowedMethods() { | ||
return redirectMethods; | ||
} | ||
|
||
/** | ||
* Check if the redirect url provided in the response headers is already attempted. | ||
* | ||
* @param redirectUrl the redirect url provided in the response header. | ||
* @param attemptedRedirectUrls the set containing a list of attempted redirect locations. | ||
* @return {@code true} if the redirectUrl provided in the response header is already being attempted for redirect | ||
* , {@code false} otherwise. | ||
*/ | ||
private boolean alreadyAttemptedRedirectUrl(String redirectUrl, | ||
Set<String> attemptedRedirectUrls) { | ||
if (attemptedRedirectUrls.contains(redirectUrl)) { | ||
logger.error(String.format("Request was redirected more than once to: %s", redirectUrl)); | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return true; | ||
} | ||
return false; | ||
} | ||
|
||
/** | ||
* Check if the attempt count of the redirect is less than the {@code maxAttempts} | ||
* | ||
* @param tryCount the try count for the HTTP request associated to the HTTP response. | ||
* @return {@code true} if the {@code tryCount} is greater than the {@code maxAttempts}, {@code false} otherwise. | ||
*/ | ||
private boolean isValidRedirectCount(int tryCount) { | ||
if (tryCount >= getMaxAttempts()) { | ||
logger.error(String.format("Request has been redirected more than %d times.", getMaxAttempts())); | ||
return false; | ||
} | ||
return true; | ||
} | ||
|
||
/** | ||
* Check if the request http method is a valid redirect method. | ||
* | ||
* @param httpMethod the http method of the request. | ||
* @return {@code true} if the request {@code httpMethod} is a valid http redirect method, {@code false} otherwise. | ||
*/ | ||
private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { | ||
if (getAllowedMethods().contains(httpMethod)) { | ||
return true; | ||
} else { | ||
logger.error( | ||
String.format("Request was redirected from a non redirect-able method: %s", httpMethod)); | ||
return false; | ||
} | ||
} | ||
|
||
/** | ||
* Checks if the incoming request status code is a valid redirect status code. | ||
* | ||
* @param statusCode the status code of the incoming request. | ||
* @return {@code true} if the request {@code statusCode} is a valid http redirect method, {@code false} otherwise. | ||
*/ | ||
private boolean isValidRedirectStatusCode(int statusCode) { | ||
return statusCode == HttpURLConnection.HTTP_MOVED_TEMP | ||
|| statusCode == HttpURLConnection.HTTP_MOVED_PERM | ||
|| statusCode == PERMANENT_REDIRECT_STATUS_CODE | ||
|| statusCode == TEMPORARY_REDIRECT_STATUS_CODE; | ||
} | ||
|
||
/** | ||
* Gets the redirect url from the response headers. | ||
* | ||
* @param headers the http response headers. | ||
* @param headerName the header name to look up value for. | ||
* @return the header value for the provided header name, {@code null} otherwise. | ||
*/ | ||
private static String tryGetRedirectHeader(HttpHeaders headers, String headerName) { | ||
String headerValue = headers.getValue(headerName); | ||
return CoreUtils.isNullOrEmpty(headerValue) ? null : headerValue; | ||
} | ||
} |
70 changes: 70 additions & 0 deletions
70
sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RedirectPolicy.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
package com.azure.core.http.policy; | ||
|
||
import com.azure.core.http.HttpPipelineCallContext; | ||
import com.azure.core.http.HttpPipelineNextPolicy; | ||
import com.azure.core.http.HttpRequest; | ||
import com.azure.core.http.HttpResponse; | ||
import reactor.core.publisher.Mono; | ||
|
||
import java.util.HashSet; | ||
import java.util.Objects; | ||
import java.util.Set; | ||
|
||
/** | ||
* A {@link HttpPipelinePolicy} that redirects a {@link HttpRequest} when an HTTP Redirect is received as response. | ||
*/ | ||
public final class RedirectPolicy implements HttpPipelinePolicy { | ||
private final RedirectStrategy redirectStrategy; | ||
private final Set<String> attemptedRedirectUrls = new HashSet<>(); | ||
|
||
/** | ||
* Creates {@link RedirectPolicy} with default {@link DefaultRedirectStrategy} as {@link RedirectStrategy} and | ||
* uses the redirect status response code (301, 302, 307, 308) to determine if this request should be redirected. | ||
*/ | ||
public RedirectPolicy() { | ||
this(new DefaultRedirectStrategy()); | ||
} | ||
|
||
/** | ||
* Creates {@link RedirectPolicy} with the provided {@code redirectStrategy} as {@link RedirectStrategy} and | ||
* uses the redirect status response code (301, 302, 307, 308) to determine if this request should be redirected. | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* @param redirectStrategy The {@link RedirectStrategy} used for redirection. | ||
* @throws NullPointerException When {@code redirectStrategy} is null. | ||
*/ | ||
public RedirectPolicy(RedirectStrategy redirectStrategy) { | ||
this.redirectStrategy = Objects.requireNonNull(redirectStrategy, "'redirectStrategy' cannot be null."); | ||
} | ||
|
||
@Override | ||
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { | ||
return attemptRedirect(context, next, context.getHttpRequest(), 1); | ||
} | ||
|
||
/** | ||
* Function to process through the HTTP Response received in the pipeline | ||
* and redirect sending the request with new redirect url. | ||
*/ | ||
private Mono<HttpResponse> attemptRedirect(final HttpPipelineCallContext context, | ||
final HttpPipelineNextPolicy next, | ||
final HttpRequest originalHttpRequest, | ||
final int redirectAttempt) { | ||
context.setHttpRequest(originalHttpRequest.copy()); | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return next.clone().process() | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.flatMap(httpResponse -> { | ||
if (redirectStrategy.shouldAttemptRedirect(context, httpResponse, redirectAttempt, attemptedRedirectUrls)) { | ||
HttpRequest redirectRequestCopy = redirectStrategy.createRedirect(httpResponse); | ||
return httpResponse.getBody() | ||
.ignoreElements() | ||
.then(attemptRedirect(context, next, redirectRequestCopy, redirectAttempt + 1)); | ||
} else { | ||
return Mono.just(httpResponse); | ||
} | ||
}); | ||
} | ||
|
||
} |
57 changes: 57 additions & 0 deletions
57
sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RedirectStrategy.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
package com.azure.core.http.policy; | ||
|
||
import com.azure.core.http.HttpMethod; | ||
import com.azure.core.http.HttpPipelineCallContext; | ||
import com.azure.core.http.HttpRequest; | ||
import com.azure.core.http.HttpResponse; | ||
|
||
import java.util.Set; | ||
|
||
/** | ||
* The interface for determining the {@link RedirectStrategy redirect strategy} used in {@link RedirectPolicy}. | ||
*/ | ||
public interface RedirectStrategy { | ||
/** | ||
* Max number of redirect attempts to be made. | ||
* | ||
* @return The max number of redirect attempts. | ||
*/ | ||
int getMaxAttempts(); | ||
|
||
/** | ||
* The header name to look up the value for the redirect url in response headers. | ||
* | ||
* @return the value of the header, or null if the header doesn't exist in the response. | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
String getLocationHeader(); | ||
|
||
/** | ||
* The {@link HttpMethod http methods} that are allowed to be redirected. | ||
* | ||
* @return the set of redirect allowed methods. | ||
*/ | ||
Set<HttpMethod> getAllowedMethods(); | ||
|
||
/** | ||
* Determines if the url should be redirected between each try. | ||
* | ||
* @param context the {@link HttpPipelineCallContext HTTP pipeline context}. | ||
* @param httpResponse the {@link HttpRequest} containing the redirect url present in the response headers | ||
* @param tryCount redirect attempts so far | ||
* @param attemptedRedirectUrls attempted redirect locations used so far. | ||
* @return {@code true} if the request should be redirected, {@code false} otherwise | ||
*/ | ||
boolean shouldAttemptRedirect(HttpPipelineCallContext context, HttpResponse httpResponse, int tryCount, | ||
Set<String> attemptedRedirectUrls); | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Creates the {@link HttpRequest request} for the redirect attempt. | ||
* | ||
* @param httpResponse the {@link HttpRequest} containing the redirect url present in the response headers | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* @return the modified {@link HttpRequest} to redirect the incoming request. | ||
*/ | ||
HttpRequest createRedirect(HttpResponse httpResponse); | ||
samvaity marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.