Repository navigation
Conversation
| @SuppressWarnings("deprecation") | ||
| public class HttpRequestRetryStrategyAdaptor implements RequestRetryStrategy { | ||
|
|
||
| private final org.apache.hc.client5.http.HttpRequestRetryStrategy strategy; |
There was a problem hiding this comment.
@arturobernalg Yes, I know. But this is to avoid deprecation warnings that cannot be avoided otherwise. Suppress deprecation annotation does not apply to imports.
xcapdevila
left a comment
There was a problem hiding this comment.
Thanks @ok2c for merging #3326 into 5.6.x and for the ping to review this redesign! I fetched 2b4428868 locally, ran the unit/checkstyle/japicmp checks, and left one design question on the I/O retry delay plus three small inline suggestions.
Overall design & Optional<TimeValue> vs. custom value object
Big +1 to collapsing the two-step contract (boolean retryRequest + TimeValue getRetryInterval) into a single method, and to adding HttpRequest request to the HTTP response overload (retryRequest(HttpRequest, HttpResponse, int, HttpContext)):
- Single-pass decision & interval calculation: Computing and validating the delay once eliminates the class of drift between the eligibility check and the actual pause, and also avoids parsing
Retry-Aftertwice (which previously calledSystem.currentTimeMillis()twice whenRetry-Afterwas an HTTP-date, creating a small TOCTOU window aroundresponseTimeout). HttpRequestavailable on429/503responses: Havingrequestin the response overload makes it straightforward for custom strategies or subclasses to inspect the HTTP method, headers, or idempotency markers without reaching intoHttpContext.- On
Optional<TimeValue>vs. a custom value object: I agreeOptional<TimeValue>is a good fit here. Since "do not retry" carries no state and "retry" carries a single non-negativeTimeValue(0 msfor immediate retry,> 0for delayed retry),Optional<TimeValue>makes illegal states(retry = false, delay = 5s)unrepresentable without introducing another public type. The only reason to prefer a dedicated value object (e.g.RetryDecision.noRetry()/RetryDecision.retryAfter(TimeValue)) would be if you anticipate attaching extra metadata in the future (reason, attributes, etc.) or avoidingOptionalwrapper allocation on hot error paths.
Minor non-inline notes
- Source-compatibility / release notes:
HttpClientBuilder,HttpAsyncClientBuilder, andH2AsyncClientBuildernow overloadsetRetryStrategy(HttpRequestRetryStrategy)(@Deprecated) andsetRetryStrategy(RequestRetryStrategy). Binary compatibility (japicmpagainst5.6) and typed arguments are unaffected, though a literalbuilder.setRetryStrategy(null)call becomes ambiguous at compile time unless cast (or unless the new setter is namedsetRequestRetryStrategy). Worth a small mention in the5.7migration/release notes if keeping the overloaded name. - Test naming / adaptor coverage:
TestDefaultHttpRequestRetryStrategy.javanow testsDefaultRequestRetryStrategyrather than the deprecatedDefaultHttpRequestRetryStrategy—might be worth renaming toTestDefaultRequestRetryStrategy(and optionally keeping a small test coveringHttpRequestRetryStrategyAdaptor+DefaultHttpRequestRetryStrategy).
| if (handleAsRetriable(exception) && handleAsIdempotent(request)) { | ||
| return Optional.of(defaultRetryInterval); | ||
| } |
There was a problem hiding this comment.
Previously, HttpRequestRetryStrategy#getRetryInterval(HttpRequest, IOException, int, HttpContext) defaulted to TimeValue.ZERO_MILLISECONDS (not overridden by DefaultHttpRequestRetryStrategy), so recoverable I/O errors on idempotent requests—most notably NoHttpResponseException on stale keep-alive connections—were retried immediately (0 ms).
With DefaultRequestRetryStrategy.INSTANCE, those I/O retries will now pause for defaultRetryInterval (1 s).
- Is this
0 ms->1 schange on recoverable I/O errors intentional (sodefaultRetryIntervalgoverns both overloads), or should I/O retries still default toTimeValue.ZERO_MILLISECONDSto avoid adding1 slatency on stale keep-alive recovery? - If using
defaultRetryIntervalhere is intentional, would it also make sense to guard againstdefaultRetryInterval.compareTo(responseTimeout) > 0as in theHttpResponseoverload below (L164-171)?
There was a problem hiding this comment.
Is this 0 ms -> 1 s change on recoverable I/O errors intentional
@xcapdevila Yes, it is intentional. I think the old behavior of retrying the request immediately in case of a I/O error is wrong. This also makes the i/o error recovery consistent between with that of 429 and 503 responses.
There was a problem hiding this comment.
If using defaultRetryInterval here is intentional, would it also make sense to guard against defaultRetryInterval.compareTo(responseTimeout) > 0 as in the HttpResponse overload below (L164-171)?
@xcapdevila defaultRetryInterval is set by the user explicitly or 1 second by default and cannot be influenced by the opposite endpoint. I do not think the responseTimeout applies here.
There was a problem hiding this comment.
Fair point on both counts @ok2c — keeping responseTimeout strictly as a guard against untrusted server-supplied Retry-After values, and defaulting to 1 s in DefaultRequestRetryStrategy.INSTANCE, makes sense for 5.7.
One small API ergonomics suggestion while DefaultRequestRetryStrategy is still new: since a single defaultRetryInterval now governs both IOException retries and headerless 429/503 responses, callers who still want 0 ms on I/O retries (e.g. classic HTTP/1.1 clients hitting NoHttpResponseException on half-closed pooled connections reused within the 2 s validateAfterInactivity window) cannot pass TimeValue.ZERO_MILLISECONDS without also making headerless 429/503 retry at 0 ms.
Would you consider adding an overload DefaultRequestRetryStrategy(int maxRetries, TimeValue defaultIoRetryInterval, TimeValue defaultResponseRetryInterval) — plus a default no-arg public DefaultRequestRetryStrategy() like DefaultHttpRequestRetryStrategy had for subclasses? Totally your call either way, the PR looks great!
| Args.notNull(response, "response"); | ||
|
|
||
| if (execCount > this.maxRetries) { | ||
| // Do not retry if over max retries | ||
| return Optional.empty(); | ||
| } |
There was a problem hiding this comment.
In the IOException overload above (L134-143), request is validated with Args.notNull(request, "request") and checked for CancellableDependency#isCancelled(). Adding the same checks here avoids sleeping/retrying an already cancelled request when a 429/503 arrives.
(Also confirming: keeping 429/503 retries independent of handleAsIdempotent(request) by default remains intentional, while subclasses can now easily enforce handleAsIdempotent(request) thanks to the new request parameter.)
| Args.notNull(response, "response"); | |
| if (execCount > this.maxRetries) { | |
| // Do not retry if over max retries | |
| return Optional.empty(); | |
| } | |
| Args.notNull(request, "request"); | |
| Args.notNull(response, "response"); | |
| if (execCount > this.maxRetries) { | |
| // Do not retry if over max retries | |
| return Optional.empty(); | |
| } | |
| if (request instanceof CancellableDependency && ((CancellableDependency) request).isCancelled()) { | |
| return Optional.empty(); | |
| } |
There was a problem hiding this comment.
@xcapdevila Request validation is now done consistently in case of an i/o error and recoverable status.
| if (strategy.retryRequest(request, exception, execCount, context)) { | ||
| return Optional.of(strategy.getRetryInterval(request, exception, execCount, context)); | ||
| } | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| @Override | ||
| public Optional<TimeValue> retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) { | ||
| if (strategy.retryRequest(response, execCount, context)) { | ||
| return Optional.of(strategy.getRetryInterval(response, execCount, context)); | ||
| } | ||
| return Optional.empty(); |
There was a problem hiding this comment.
Previously, if a legacy custom HttpRequestRetryStrategy returned null (or a negative TimeValue) from getRetryInterval(...), HttpRequestRetryExec / AsyncHttpRequestRetryExec guarded it via TimeValue.isPositive(delay) and retried immediately without failing. With Optional.of(...), a null return from a legacy strategy will throw NullPointerException (and Optional.ofNullable cannot be used since Optional.empty() means "do not retry").
Normalizing with the same idiom used in AsyncHttpRequestRetryExec preserves the exact legacy behavior for both overloads:
| if (strategy.retryRequest(request, exception, execCount, context)) { | |
| return Optional.of(strategy.getRetryInterval(request, exception, execCount, context)); | |
| } | |
| return Optional.empty(); | |
| } | |
| @Override | |
| public Optional<TimeValue> retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) { | |
| if (strategy.retryRequest(response, execCount, context)) { | |
| return Optional.of(strategy.getRetryInterval(response, execCount, context)); | |
| } | |
| return Optional.empty(); | |
| if (strategy.retryRequest(request, exception, execCount, context)) { | |
| final TimeValue interval = strategy.getRetryInterval(request, exception, execCount, context); | |
| return Optional.of(TimeValue.isPositive(interval) ? interval : TimeValue.ZERO_MILLISECONDS); | |
| } | |
| return Optional.empty(); | |
| } | |
| @Override | |
| public Optional<TimeValue> retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) { | |
| if (strategy.retryRequest(response, execCount, context)) { | |
| final TimeValue interval = strategy.getRetryInterval(response, execCount, context); | |
| return Optional.of(TimeValue.isPositive(interval) ? interval : TimeValue.ZERO_MILLISECONDS); | |
| } | |
| return Optional.empty(); |
There was a problem hiding this comment.
@xcapdevila Makes sense. Made the classic exec behave the same way.
There was a problem hiding this comment.
Thanks @ok2c! Guarding in HttpRequestRetryExec is even better since it covers any RequestRetryStrategy implementation.
Just two small spots left in d3dccf3109:
HttpRequestRetryExecL159 (IOExceptionbranch) still usesfinal TimeValue delay = retryPeriod.get();without theTimeValue.isPositive(...)check added on L128 (unlikeAsyncHttpRequestRetryExecL193).HttpRequestRetryStrategyAdaptor(L56, L64) still callsOptional.of(...)directly, which would throwNPEbefore reaching the exec handler if a legacyHttpRequestRetryStrategy#getRetryIntervalreturnsnull(the suggestion above on the adaptor still applies if you want to guard that too).
| * Strategy interface to determine if the request should be retied in case | ||
| * of an i/o error or a 4xx or 5xx status response. | ||
| * | ||
| * @since 5.7 | ||
| */ | ||
| @Contract(threading = ThreadingBehavior.STATELESS) | ||
| public interface RequestRetryStrategy { | ||
|
|
||
| /** | ||
| * Determines if a method should be retried after an I/O exception | ||
| * occurred during execution. | ||
| * | ||
| * @param request the request failed due to an I/O exception | ||
| * @param exception the exception that occurred | ||
| * @param execCount the number of times this method has been | ||
| * unsuccessfully executed | ||
| * @param context the context for the request execution | ||
| * | ||
| * @return {@code true} if the request should be retried, {@code false} | ||
| * otherwise | ||
| */ | ||
| Optional<TimeValue> retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context); | ||
|
|
||
| /** | ||
| * Determines if a method should be retried given the response from | ||
| * the target server. | ||
| * | ||
| * @param response the response from the target server | ||
| * @param execCount the number of times this method has been | ||
| * unsuccessfully executed | ||
| * @param context the context for the request execution | ||
| * | ||
| * @return {@code true} if the request should be retried, {@code false} | ||
| * otherwise | ||
| */ |
There was a problem hiding this comment.
Minor Javadoc fixes: typo retied -> retried, missing @param request on the second overload, and updating @return from the old boolean contract to Optional<TimeValue>:
| * Strategy interface to determine if the request should be retied in case | |
| * of an i/o error or a 4xx or 5xx status response. | |
| * | |
| * @since 5.7 | |
| */ | |
| @Contract(threading = ThreadingBehavior.STATELESS) | |
| public interface RequestRetryStrategy { | |
| /** | |
| * Determines if a method should be retried after an I/O exception | |
| * occurred during execution. | |
| * | |
| * @param request the request failed due to an I/O exception | |
| * @param exception the exception that occurred | |
| * @param execCount the number of times this method has been | |
| * unsuccessfully executed | |
| * @param context the context for the request execution | |
| * | |
| * @return {@code true} if the request should be retried, {@code false} | |
| * otherwise | |
| */ | |
| Optional<TimeValue> retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context); | |
| /** | |
| * Determines if a method should be retried given the response from | |
| * the target server. | |
| * | |
| * @param response the response from the target server | |
| * @param execCount the number of times this method has been | |
| * unsuccessfully executed | |
| * @param context the context for the request execution | |
| * | |
| * @return {@code true} if the request should be retried, {@code false} | |
| * otherwise | |
| */ | |
| * Strategy interface to determine if the request should be retried in case | |
| * of an I/O error or a 4xx or 5xx status response. | |
| * | |
| * @since 5.7 | |
| */ | |
| @Contract(threading = ThreadingBehavior.STATELESS) | |
| public interface RequestRetryStrategy { | |
| /** | |
| * Determines if a method should be retried after an I/O exception | |
| * occurred during execution. | |
| * | |
| * @param request the request failed due to an I/O exception | |
| * @param exception the exception that occurred | |
| * @param execCount the number of times this method has been | |
| * unsuccessfully executed | |
| * @param context the context for the request execution | |
| * | |
| * @return an {@link Optional} containing the retry delay if the request | |
| * should be retried, or {@link Optional#empty()} otherwise | |
| */ | |
| Optional<TimeValue> retryRequest(HttpRequest request, IOException exception, int execCount, HttpContext context); | |
| /** | |
| * Determines if a method should be retried given the response from | |
| * the target server. | |
| * | |
| * @param request the request executed | |
| * @param response the response from the target server | |
| * @param execCount the number of times this method has been | |
| * unsuccessfully executed | |
| * @param context the context for the request execution | |
| * | |
| * @return an {@link Optional} containing the retry delay if the request | |
| * should be retried, or {@link Optional#empty()} otherwise | |
| */ |
253fc63 to
ade5ebc
Compare
@xcapdevila OK. I renamed the new setter to avoid the conflict with the deprecated method |
ade5ebc to
46b1ac9
Compare
46b1ac9 to
d3dccf3
Compare
@arturobernalg Please review.
Remark: I am not a particularly big fan of
Optionalgiven how terribly it gets abused. In this instance however i believe its use is appropriate. I am open to suggestions of different approaches such as using a custom value object to represent the result of the strategy methods.