diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1RequestReExecution.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1RequestReExecution.java index ca741c0b67..f9ae568278 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1RequestReExecution.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttp1RequestReExecution.java @@ -31,7 +31,7 @@ import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; -import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; +import org.apache.hc.client5.http.impl.DefaultRequestRetryStrategy; import org.apache.hc.client5.testing.extension.async.ClientProtocolLevel; import org.apache.hc.client5.testing.extension.async.ServerProtocolLevel; import org.apache.hc.client5.testing.extension.async.TestAsyncClient; @@ -79,7 +79,7 @@ void testGiveUpAfterOneRetry() throws Exception { final HttpHost target = startServer(); configureClient(builder -> builder - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(1, TimeValue.ofSeconds(1)))); + .setRequestRetryStrategy(new DefaultRequestRetryStrategy(1, TimeValue.ofSeconds(1)))); final TestAsyncClient client = startClient(); final Future future = client.execute( @@ -98,7 +98,7 @@ void testDoNotGiveUpEasily() throws Exception { final HttpHost target = startServer(); configureClient(builder -> builder - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(5, TimeValue.ofSeconds(1)))); + .setRequestRetryStrategy(new DefaultRequestRetryStrategy(5, TimeValue.ofSeconds(1)))); final TestAsyncClient client = startClient(); final Future future = client.execute( diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java index ee2aa06f74..21bbe57b54 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/async/StandardTestClientBuilder.java @@ -31,7 +31,7 @@ import java.util.Collection; import org.apache.hc.client5.http.AuthenticationStrategy; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.auth.AuthSchemeFactory; import org.apache.hc.client5.http.auth.CredentialsProvider; @@ -153,8 +153,8 @@ public TestAsyncClientBuilder setDefaultHeaders(final Collection de throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel()); } - default TestAsyncClientBuilder setRetryStrategy(HttpRequestRetryStrategy retryStrategy) { + default TestAsyncClientBuilder setRequestRetryStrategy(RequestRetryStrategy retryStrategy) { throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel()); } diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/StandardTestClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/StandardTestClientBuilder.java index 44bae7ab15..ba388e2b33 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/StandardTestClientBuilder.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/StandardTestClientBuilder.java @@ -31,7 +31,7 @@ import java.util.Collection; import org.apache.hc.client5.http.AuthenticationStrategy; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.auth.AuthSchemeFactory; import org.apache.hc.client5.http.auth.CredentialsProvider; @@ -119,8 +119,8 @@ public TestClientBuilder setDefaultHeaders(final Collection de } @Override - public TestClientBuilder setRetryStrategy(final HttpRequestRetryStrategy retryStrategy) { - this.clientBuilder.setRetryStrategy(retryStrategy); + public TestClientBuilder setRequestRetryStrategy(final RequestRetryStrategy retryStrategy) { + this.clientBuilder.setRequestRetryStrategy(retryStrategy); return this; } diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java index 8cf7162d43..ee5bf53f80 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/extension/sync/TestClientBuilder.java @@ -31,7 +31,7 @@ import java.util.Collection; import org.apache.hc.client5.http.AuthenticationStrategy; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.auth.AuthSchemeFactory; import org.apache.hc.client5.http.auth.CredentialsProvider; @@ -77,7 +77,7 @@ default TestClientBuilder setDefaultHeaders(Collection default throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel()); } - default TestClientBuilder setRetryStrategy(HttpRequestRetryStrategy retryStrategy) { + default TestClientBuilder setRequestRetryStrategy(RequestRetryStrategy retryStrategy) { throw new UnsupportedOperationException("Operation not supported by " + getProtocolLevel()); } diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java index 0eb8de18fa..94344c6421 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestExecution.java @@ -29,12 +29,13 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; +import java.util.Optional; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; @@ -141,31 +142,16 @@ void testAutoGeneratedHeaders() throws Exception { final HttpRequestInterceptor interceptor = (request, entityDetails, context) -> request.addHeader("my-header", "stuff"); - final HttpRequestRetryStrategy requestRetryStrategy = new HttpRequestRetryStrategy() { + final RequestRetryStrategy requestRetryStrategy = new RequestRetryStrategy() { @Override - public boolean retryRequest( - final HttpRequest request, - final IOException exception, - final int executionCount, - final HttpContext context) { - return true; + public Optional retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) { + return Optional.empty(); } @Override - public boolean retryRequest( - final HttpResponse response, - final int executionCount, - final HttpContext context) { - return false; - } - - @Override - public TimeValue getRetryInterval( - final HttpResponse response, - final int executionCount, - final HttpContext context) { - return TimeValue.ofSeconds(1L); + public Optional retryRequest(final HttpRequest request, final IOException exception, final int execCount, final HttpContext context) { + return Optional.of(TimeValue.ofSeconds(1)); } }; @@ -173,7 +159,7 @@ public TimeValue getRetryInterval( configureClient(builder -> builder .addRequestInterceptorFirst(interceptor) .setRequestExecutor(new FaultyHttpRequestExecutor("Oppsie")) - .setRetryStrategy(requestRetryStrategy) + .setRequestRetryStrategy(requestRetryStrategy) ); final TestClient client = client(); @@ -199,38 +185,23 @@ void testNonRepeatableEntity() throws Exception { configureServer(bootstrap -> bootstrap.register("*", new SimpleService())); final HttpHost target = startServer(); - final HttpRequestRetryStrategy requestRetryStrategy = new HttpRequestRetryStrategy() { - - @Override - public boolean retryRequest( - final HttpRequest request, - final IOException exception, - final int executionCount, - final HttpContext context) { - return true; - } + final RequestRetryStrategy requestRetryStrategy = new RequestRetryStrategy() { @Override - public boolean retryRequest( - final HttpResponse response, - final int executionCount, - final HttpContext context) { - return false; + public Optional retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) { + return Optional.empty(); } @Override - public TimeValue getRetryInterval( - final HttpResponse response, - final int executionCount, - final HttpContext context) { - return TimeValue.ofSeconds(1L); + public Optional retryRequest(final HttpRequest request, final IOException exception, final int execCount, final HttpContext context) { + return Optional.of(TimeValue.ofSeconds(1)); } }; configureClient(builder -> builder .setRequestExecutor(new FaultyHttpRequestExecutor("a message showing that this failed")) - .setRetryStrategy(requestRetryStrategy) + .setRequestRetryStrategy(requestRetryStrategy) ); final TestClient client = client(); diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestReExecution.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestReExecution.java index 8e9cf807fc..31fe9bbabb 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestReExecution.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestClientRequestReExecution.java @@ -27,7 +27,8 @@ package org.apache.hc.client5.testing.sync; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; + +import org.apache.hc.client5.http.impl.DefaultRequestRetryStrategy; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.testing.classic.RandomHandler; import org.apache.hc.client5.testing.classic.ServiceUnavailableDecorator; @@ -77,7 +78,7 @@ void testGiveUpAfterOneRetry() throws Exception { final HttpHost target = startServer(); configureClient(builder -> builder - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(1, TimeValue.ofSeconds(1)))); + .setRequestRetryStrategy(new DefaultRequestRetryStrategy(1, TimeValue.ofSeconds(1)))); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); @@ -98,7 +99,7 @@ void testDoNotGiveUpEasily() throws Exception { final HttpHost target = startServer(); configureClient(builder -> builder - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(5, TimeValue.ofSeconds(1)))); + .setRequestRetryStrategy(new DefaultRequestRetryStrategy(5, TimeValue.ofSeconds(1)))); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestRedirects.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestRedirects.java index 8649e9e8e6..3896417fec 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestRedirects.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestRedirects.java @@ -27,18 +27,15 @@ package org.apache.hc.client5.testing.sync; import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.ConnectException; import java.net.InetSocketAddress; -import java.net.NoRouteToHostException; import java.net.URI; -import java.net.UnknownHostException; -import java.util.Arrays; import java.util.Collections; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; +import javax.net.ssl.SSLException; + import org.apache.hc.client5.http.CircularRedirectException; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.client5.http.RedirectException; @@ -47,7 +44,7 @@ import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.cookie.BasicCookieStore; import org.apache.hc.client5.http.cookie.CookieStore; -import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; +import org.apache.hc.client5.http.impl.DefaultRequestRetryStrategy; import org.apache.hc.client5.http.impl.LaxRedirectStrategy; import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; import org.apache.hc.client5.http.protocol.HttpClientContext; @@ -63,7 +60,6 @@ import org.apache.hc.client5.testing.redirect.Redirect; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; -import org.apache.hc.core5.http.ConnectionClosedException; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHeaders; @@ -652,19 +648,19 @@ public void handle(final ClassicHttpRequest request, @Test void testRetryUponRedirect() throws Exception { configureClient(builder -> builder - .setRetryStrategy(new DefaultHttpRequestRetryStrategy( + .setRequestRetryStrategy(new DefaultRequestRetryStrategy( 3, - TimeValue.ofSeconds(1), - Arrays.asList( - InterruptedIOException.class, - UnknownHostException.class, - ConnectException.class, - ConnectionClosedException.class, - NoRouteToHostException.class), - Arrays.asList( - HttpStatus.SC_TOO_MANY_REQUESTS, - HttpStatus.SC_SERVICE_UNAVAILABLE)) { + TimeValue.ofSeconds(1)) { + + @Override + protected boolean isRetriable(final Exception exception) { + if (exception instanceof SSLException) { + return true; + } + return super.isRetriable(exception); + } }) + ); configureServer(bootstrap -> bootstrap diff --git a/httpclient5/pom.xml b/httpclient5/pom.xml index 7b8834c72d..e09f968845 100644 --- a/httpclient5/pom.xml +++ b/httpclient5/pom.xml @@ -99,6 +99,11 @@ junit-platform-launcher test + + org.assertj + assertj-core + test + org.mockito mockito-core diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRequestRetryStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRequestRetryStrategy.java index 3fcd9912c5..c2bea5dd1f 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRequestRetryStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/HttpRequestRetryStrategy.java @@ -42,7 +42,10 @@ * it should be done and so on. * * @since 5.0 + * + * @deprecated Use {@link RequestRetryStrategy}. */ +@Deprecated @Contract(threading = ThreadingBehavior.STATELESS) public interface HttpRequestRetryStrategy { diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/RequestRetryStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/RequestRetryStrategy.java new file mode 100644 index 0000000000..444b20a0d5 --- /dev/null +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/RequestRetryStrategy.java @@ -0,0 +1,77 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package org.apache.hc.client5.http; + +import java.io.IOException; +import java.util.Optional; + +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.util.TimeValue; + +/** + * 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 optional retry interval. + */ + Optional 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 failed with an error status. + * @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 optional retry interval. + */ + Optional retryRequest(HttpRequest request, HttpResponse response, int execCount, HttpContext context); + +} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultHttpRequestRetryStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultHttpRequestRetryStrategy.java index c755a92aca..b773d318ac 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultHttpRequestRetryStrategy.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultHttpRequestRetryStrategy.java @@ -40,7 +40,6 @@ import javax.net.ssl.SSLException; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.utils.DateUtils; @@ -60,12 +59,15 @@ import org.apache.hc.core5.util.Timeout; /** - * Default implementation of the {@link HttpRequestRetryStrategy} interface. + * Default implementation of the {@link org.apache.hc.client5.http.HttpRequestRetryStrategy} interface. * * @since 5.0 + * + * @deprecated Use {@link DefaultRequestRetryStrategy} */ +@Deprecated @Contract(threading = ThreadingBehavior.STATELESS) -public class DefaultHttpRequestRetryStrategy implements HttpRequestRetryStrategy { +public class DefaultHttpRequestRetryStrategy implements org.apache.hc.client5.http.HttpRequestRetryStrategy { /** * Default instance of {@link DefaultHttpRequestRetryStrategy}. diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRequestRetryStrategy.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRequestRetryStrategy.java new file mode 100644 index 0000000000..843efc6b5e --- /dev/null +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRequestRetryStrategy.java @@ -0,0 +1,252 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package org.apache.hc.client5.http.impl; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.ConnectException; +import java.net.NoRouteToHostException; +import java.net.UnknownHostException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import javax.net.ssl.SSLException; + +import org.apache.hc.client5.http.RequestRetryStrategy; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.client5.http.utils.DateUtils; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.concurrent.CancellableDependency; +import org.apache.hc.core5.http.ConnectionClosedException; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.Method; +import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.util.Args; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; + +/** + * Default implementation of the {@link RequestRetryStrategy} interface. + * + * @since 5.7 + */ +@Contract(threading = ThreadingBehavior.STATELESS) +public class DefaultRequestRetryStrategy implements RequestRetryStrategy { + + private static final TimeValue DEFAULT_TIMEOUT = TimeValue.ofSeconds(1); + + public static final DefaultRequestRetryStrategy INSTANCE = new DefaultRequestRetryStrategy(1, DEFAULT_TIMEOUT); + + private static final List> NON_RETRIABLE_ERRORS_LIST = + Arrays.asList( + InterruptedIOException.class, + UnknownHostException.class, + ConnectException.class, + ConnectionClosedException.class, + NoRouteToHostException.class, + SSLException.class); + private static final Set> NON_RETRIABLE_ERRORS_SET = + new HashSet<>(NON_RETRIABLE_ERRORS_LIST); + + private final int maxRetries; + private final TimeValue defaultIoRetryInterval; + private final TimeValue defaultResponseRetryInterval; + + /** + * Create the HTTP request retry strategy using the following list of + * non-retriable exception:
+ *
    + *
  • {@link InterruptedIOException}
  • + *
  • {@link UnknownHostException}
  • + *
  • {@link ConnectException}
  • + *
  • {@link ConnectionClosedException}
  • + *
  • {@link NoRouteToHostException}
  • + *
  • {@link SSLException}
  • + *
+ * and retriable HTTP status codes:
+ *
    + *
  • SC_TOO_MANY_REQUESTS (429)
  • + *
  • SC_SERVICE_UNAVAILABLE (503)
  • + *
+ * @param maxRetries how many times to retry; 0 means no retries + * @param defaultIoRetryInterval the default I/O error retry interval between + * subsequent retries. + * @param defaultResponseRetryInterval the default response retry interval between + * subsequent retries if the {@code Retry-After} header is not set + * or invalid. + */ + public DefaultRequestRetryStrategy( + final int maxRetries, + final TimeValue defaultIoRetryInterval, + final TimeValue defaultResponseRetryInterval) { + Args.notNegative(maxRetries, "maxRetries"); + Args.notNull(defaultIoRetryInterval, "defaultIoRetryInterval"); + Args.notNull(defaultResponseRetryInterval, "defaultResponseRetryInterval"); + Args.check(TimeValue.isNonNegative(defaultIoRetryInterval), "Default I/O error retry interval is negative"); + Args.check(TimeValue.isNonNegative(defaultResponseRetryInterval), "Default response retry interval is negative"); + this.maxRetries = maxRetries; + this.defaultIoRetryInterval = defaultIoRetryInterval; + this.defaultResponseRetryInterval = defaultResponseRetryInterval; + } + + public DefaultRequestRetryStrategy( + final int maxRetries, + final TimeValue defaultRetryInterval) { + this(maxRetries, defaultRetryInterval, defaultRetryInterval); + } + + @Override + public Optional retryRequest( + final HttpRequest request, + final IOException exception, + final int execCount, + final HttpContext context) { + Args.notNull(request, "request"); + Args.notNull(exception, "exception"); + + if (!isCancelled(request) && isRetriable(execCount) && isIdempotent(request) && isRetriable(exception)) { + return Optional.of(defaultIoRetryInterval); + } + return Optional.empty(); + } + + @Override + public Optional retryRequest( + final HttpRequest request, + final HttpResponse response, + final int execCount, + final HttpContext context) { + Args.notNull(request, "request"); + Args.notNull(response, "response"); + if (!isCancelled(request) && isRetriable(execCount) && isRecoverable(response)) { + final TimeValue retryInterval = parseRetryAfter(response); + if (context != null) { + final HttpClientContext clientContext = HttpClientContext.cast(context); + final RequestConfig requestConfig = clientContext.getRequestConfigOrDefault(); + final Timeout responseTimeout = requestConfig.getResponseTimeout(); + if (TimeValue.isPositive(responseTimeout) && retryInterval.compareTo(responseTimeout) > 0) { + return Optional.empty(); + } + } + return Optional.of(retryInterval); + } + return Optional.empty(); + } + + private boolean isCancelled(final HttpRequest request) { + return request instanceof CancellableDependency && ((CancellableDependency) request).isCancelled(); + } + + /** + * Determines if the request with the given execution count is retriable. + */ + protected boolean isRetriable(final int execCount) { + // Do not retry if over max retries + return execCount <= this.maxRetries; + } + + protected TimeValue parseRetryAfter(final HttpResponse response) { + final Header header = response.getFirstHeader(HttpHeaders.RETRY_AFTER); + TimeValue retryAfter = null; + if (header != null) { + final String value = header.getValue(); + try { + retryAfter = TimeValue.ofSeconds(Long.parseLong(value)); + } catch (final NumberFormatException ignore) { + final Instant retryAfterDate = DateUtils.parseStandardDate(value); + if (retryAfterDate != null) { + retryAfter = + TimeValue.ofMilliseconds(retryAfterDate.toEpochMilli() - System.currentTimeMillis()); + } + } + + if (TimeValue.isPositive(retryAfter)) { + return retryAfter; + } + } + return this.defaultResponseRetryInterval; + } + + /** + * Determines if the given exception is retriable. + * The following exceptions are considered non-retriable:
+ *
    + *
  • {@link InterruptedIOException}
  • + *
  • {@link UnknownHostException}
  • + *
  • {@link ConnectException}
  • + *
  • {@link ConnectionClosedException}
  • + *
  • {@link NoRouteToHostException}
  • + *
  • {@link SSLException}
  • + *
+ */ + protected boolean isRetriable(final Exception exception) { + if (NON_RETRIABLE_ERRORS_SET.contains(exception.getClass())) { + return false; + } + for (final Class rejectException : NON_RETRIABLE_ERRORS_LIST) { + if (rejectException.isInstance(exception)) { + return false; + } + } + return true; + } + + /** + * Determines if the given request is considered idempotent. + * Handles methods defined as idempotent in the HTTP specification as idempotent. + * + * @see Method + */ + protected boolean isIdempotent(final HttpRequest request) { + return Method.isIdempotent(request.getMethod()); + } + + /** + * Determines if the given response is recoverable. + * The following response status codes are considered recoverable:
+ *
    + *
  • SC_TOO_MANY_REQUESTS (429)
  • + *
  • SC_SERVICE_UNAVAILABLE (503)
  • + *
+ */ + protected boolean isRecoverable(final HttpResponse response) { + final int code = response.getCode(); + return code == HttpStatus.SC_TOO_MANY_REQUESTS || code == HttpStatus.SC_SERVICE_UNAVAILABLE; + } + +} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/HttpRequestRetryStrategyAdaptor.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/HttpRequestRetryStrategyAdaptor.java new file mode 100644 index 0000000000..4c1376f6c6 --- /dev/null +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/HttpRequestRetryStrategyAdaptor.java @@ -0,0 +1,71 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package org.apache.hc.client5.http.impl; + +import java.io.IOException; +import java.util.Optional; + +import org.apache.hc.client5.http.RequestRetryStrategy; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.Internal; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.protocol.HttpContext; +import org.apache.hc.core5.util.TimeValue; + +@Internal +@Contract(threading = ThreadingBehavior.STATELESS) +@SuppressWarnings("deprecation") +public class HttpRequestRetryStrategyAdaptor implements RequestRetryStrategy { + + private final org.apache.hc.client5.http.HttpRequestRetryStrategy strategy; + + public HttpRequestRetryStrategyAdaptor(final org.apache.hc.client5.http.HttpRequestRetryStrategy strategy) { + this.strategy = strategy; + } + + @Override + public Optional retryRequest(final HttpRequest request, final IOException exception, final int execCount, final HttpContext context) { + if (strategy.retryRequest(request, exception, execCount, context)) { + final TimeValue retryInterval = strategy.getRetryInterval(request, exception, execCount, context); + return Optional.of(retryInterval != null ? retryInterval : TimeValue.ZERO_MILLISECONDS); + } + return Optional.empty(); + } + + @Override + public Optional retryRequest(final HttpRequest request, final HttpResponse response, final int execCount, final HttpContext context) { + if (strategy.retryRequest(response, execCount, context)) { + final TimeValue retryInterval = strategy.getRetryInterval(response, execCount, context); + return Optional.of(retryInterval != null ? retryInterval : TimeValue.ZERO_MILLISECONDS); + } + return Optional.empty(); + } + +} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncHttpRequestRetryExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncHttpRequestRetryExec.java index 325567cd6e..d4e1c357e7 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncHttpRequestRetryExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncHttpRequestRetryExec.java @@ -27,8 +27,9 @@ package org.apache.hc.client5.http.impl.async; import java.io.IOException; +import java.util.Optional; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.async.AsyncExecCallback; import org.apache.hc.client5.http.async.AsyncExecChain; import org.apache.hc.client5.http.async.AsyncExecChainHandler; @@ -86,9 +87,9 @@ public final class AsyncHttpRequestRetryExec implements AsyncExecChainHandler { private static final Logger LOG = LoggerFactory.getLogger(AsyncHttpRequestRetryExec.class); - private final HttpRequestRetryStrategy retryStrategy; + private final RequestRetryStrategy retryStrategy; - public AsyncHttpRequestRetryExec(final HttpRequestRetryStrategy retryStrategy) { + public AsyncHttpRequestRetryExec(final RequestRetryStrategy retryStrategy) { Args.notNull(retryStrategy, "retryStrategy"); this.retryStrategy = retryStrategy; } @@ -124,13 +125,16 @@ public AsyncDataConsumer handleResponse( } return asyncExecCallback.handleResponse(response, entityDetails); } - state.retrying = retryStrategy.retryRequest(response, scope.execCount.get(), clientContext); - if (state.retrying) { + final Optional retryPeriod = retryStrategy.retryRequest(request, response, scope.execCount.get(), clientContext); + if (retryPeriod.isPresent()) { + state.retrying = true; state.status = response.getCode(); - state.delay = retryStrategy.getRetryInterval(response, scope.execCount.get(), clientContext); + state.delay = retryPeriod.get(); return new DiscardingEntityConsumer<>(); + } else { + state.retrying = false; + return asyncExecCallback.handleResponse(response, entityDetails); } - return asyncExecCallback.handleResponse(response, entityDetails); } @Override @@ -173,31 +177,36 @@ public void failed(final Exception cause) { if (LOG.isDebugEnabled()) { LOG.debug("{} cannot retry non-repeatable request", exchangeId); } - } else if (retryStrategy.retryRequest(request, (IOException) cause, scope.execCount.get(), clientContext)) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} {}", exchangeId, cause.getMessage(), cause); - } - scope.execRuntime.discardEndpoint(); - if (entityProducer != null) { - entityProducer.releaseResources(); - } - state.retrying = true; - final int execCount = scope.execCount.incrementAndGet(); - state.delay = retryStrategy.getRetryInterval(request, (IOException) cause, execCount - 1, clientContext); - final TimeValue delay = TimeValue.isPositive(state.delay) ? state.delay : TimeValue.ZERO_MILLISECONDS; - if (LOG.isInfoEnabled()) { - LOG.info("{} recoverable I/O exception ({}) caught when sending request to {};" + - "request will be automatically re-executed in {} (exec count {})", - exchangeId, cause.getClass().getName(), target, delay, execCount); + } else { + final Optional retryPeriod = retryStrategy.retryRequest(request, (IOException) cause, scope.execCount.get(), clientContext); + if (retryPeriod.isPresent()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} {}", exchangeId, cause.getMessage(), cause); + } + scope.execRuntime.discardEndpoint(); + if (entityProducer != null) { + entityProducer.releaseResources(); + } + state.retrying = true; + final int execCount = scope.execCount.incrementAndGet(); + state.delay = retryPeriod.get(); + final TimeValue delay = TimeValue.isPositive(state.delay) ? state.delay : TimeValue.ZERO_MILLISECONDS; + if (LOG.isInfoEnabled()) { + LOG.info("{} recoverable I/O exception ({}) caught when sending request to {};" + + "request will be automatically re-executed in {} (exec count {})", + exchangeId, cause.getClass().getName(), target, delay, execCount); + } + scope.scheduler.scheduleExecution( + request, + entityProducer, + scope, + (r, e, s, c) -> execute(r, e, s, chain, c), + asyncExecCallback, + delay); + return; + } else { + state.retrying = false; } - scope.scheduler.scheduleExecution( - request, - entityProducer, - scope, - (r, e, s, c) -> execute(r, e, s, chain, c), - asyncExecCallback, - delay); - return; } } asyncExecCallback.failed(cause); diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java index 6965a05873..10b874f4c2 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java @@ -40,7 +40,7 @@ import org.apache.hc.client5.http.AuthenticationStrategy; import org.apache.hc.client5.http.DnsResolver; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.SchemePortResolver; import org.apache.hc.client5.http.async.AsyncExecChainHandler; import org.apache.hc.client5.http.auth.AuthSchemeFactory; @@ -55,9 +55,10 @@ import org.apache.hc.client5.http.impl.CookieSpecSupport; import org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy; import org.apache.hc.client5.http.impl.DefaultExchangeIdGenerator; -import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.impl.DefaultRequestRetryStrategy; import org.apache.hc.client5.http.impl.DefaultSchemePortResolver; +import org.apache.hc.client5.http.impl.HttpRequestRetryStrategyAdaptor; import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory; import org.apache.hc.client5.http.impl.auth.BearerSchemeFactory; import org.apache.hc.client5.http.impl.auth.DigestSchemeFactory; @@ -191,7 +192,7 @@ private ExecInterceptorEntry( private Supplier exchangeIdGenerator; private HttpRoutePlanner routePlanner; private RedirectStrategy redirectStrategy; - private HttpRequestRetryStrategy retryStrategy; + private RequestRetryStrategy retryStrategy; private Lookup authSchemeRegistry; private Lookup cookieSpecRegistry; @@ -493,15 +494,34 @@ public final H2AsyncClientBuilder addRequestInterceptorLast(final HttpRequestInt } /** - * Sets {@link HttpRequestRetryStrategy} instance. + * Sets {@link org.apache.hc.client5.http.HttpRequestRetryStrategy} instance. *

* Please note this value can be overridden by the {@link #disableAutomaticRetries()} * method. *

* * @return this instance. + * + * @deprecated Use {@link #setRequestRetryStrategy(RequestRetryStrategy)} + */ + @Deprecated + public final H2AsyncClientBuilder setRetryStrategy(final org.apache.hc.client5.http.HttpRequestRetryStrategy retryStrategy) { + this.retryStrategy = retryStrategy != null ? new HttpRequestRetryStrategyAdaptor(retryStrategy) : null; + return this; + } + + /** + * Sets {@link RequestRetryStrategy} instance. + *

+ * Please note this value can be overridden by the {@link #disableAutomaticRetries()} + * method. + *

+ * + * @return this instance. + * + * @since 5.7 */ - public final H2AsyncClientBuilder setRetryStrategy(final HttpRequestRetryStrategy retryStrategy) { + public final H2AsyncClientBuilder setRequestRetryStrategy(final RequestRetryStrategy retryStrategy) { this.retryStrategy = retryStrategy; return this; } @@ -884,9 +904,9 @@ public CloseableHttpAsyncClient build() { // Add request retry executor, if not disabled if (!automaticRetriesDisabled) { - HttpRequestRetryStrategy retryStrategyCopy = this.retryStrategy; + RequestRetryStrategy retryStrategyCopy = this.retryStrategy; if (retryStrategyCopy == null) { - retryStrategyCopy = DefaultHttpRequestRetryStrategy.INSTANCE; + retryStrategyCopy = DefaultRequestRetryStrategy.INSTANCE; } execChainDefinition.addFirst( new AsyncHttpRequestRetryExec(retryStrategyCopy), diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClientBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClientBuilder.java index 82b38fa864..e00d903976 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClientBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClientBuilder.java @@ -43,7 +43,7 @@ import org.apache.hc.client5.http.AuthenticationStrategy; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; import org.apache.hc.client5.http.EarlyHintsListener; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.SchemePortResolver; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.async.AsyncExecChainHandler; @@ -62,10 +62,11 @@ import org.apache.hc.client5.http.impl.DefaultClientConnectionReuseStrategy; import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy; import org.apache.hc.client5.http.impl.DefaultExchangeIdGenerator; -import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.impl.DefaultRequestRetryStrategy; import org.apache.hc.client5.http.impl.DefaultSchemePortResolver; import org.apache.hc.client5.http.impl.DefaultUserTokenHandler; +import org.apache.hc.client5.http.impl.HttpRequestRetryStrategyAdaptor; import org.apache.hc.client5.http.impl.IdleConnectionEvictor; import org.apache.hc.client5.http.impl.NoopUserTokenHandler; import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory; @@ -224,7 +225,7 @@ private ExecInterceptorEntry( private Supplier exchangeIdGenerator; private HttpRoutePlanner routePlanner; private RedirectStrategy redirectStrategy; - private HttpRequestRetryStrategy retryStrategy; + private RequestRetryStrategy retryStrategy; private ConnectionReuseStrategy reuseStrategy; @@ -602,15 +603,34 @@ public final HttpAsyncClientBuilder addRequestInterceptorLast(final HttpRequestI } /** - * Sets {@link HttpRequestRetryStrategy} instance. + * Sets {@link org.apache.hc.client5.http.HttpRequestRetryStrategy} instance. *

* Please note this value can be overridden by the {@link #disableAutomaticRetries()} * method. *

* * @return this instance. + * + * @deprecated Use {@link #setRequestRetryStrategy(RequestRetryStrategy)} + */ + @Deprecated + public final HttpAsyncClientBuilder setRetryStrategy(final org.apache.hc.client5.http.HttpRequestRetryStrategy retryStrategy) { + this.retryStrategy = retryStrategy != null ? new HttpRequestRetryStrategyAdaptor(retryStrategy) : null; + return this; + } + + /** + * Sets {@link RequestRetryStrategy} instance. + *

+ * Please note this value can be overridden by the {@link #disableAutomaticRetries()} + * method. + *

+ * + * @return this instance. + * + * @since 5.7 */ - public final HttpAsyncClientBuilder setRetryStrategy(final HttpRequestRetryStrategy retryStrategy) { + public final HttpAsyncClientBuilder setRequestRetryStrategy(final RequestRetryStrategy retryStrategy) { this.retryStrategy = retryStrategy; return this; } @@ -1129,9 +1149,9 @@ public CloseableHttpAsyncClient build() { // Add request retry executor, if not disabled if (!automaticRetriesDisabled) { - HttpRequestRetryStrategy retryStrategyCopy = this.retryStrategy; + RequestRetryStrategy retryStrategyCopy = this.retryStrategy; if (retryStrategyCopy == null) { - retryStrategyCopy = DefaultHttpRequestRetryStrategy.INSTANCE; + retryStrategyCopy = DefaultRequestRetryStrategy.INSTANCE; } execChainDefinition.addFirst( new AsyncHttpRequestRetryExec(retryStrategyCopy), diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java index d2d70ed7d4..c44827ff50 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.java @@ -40,7 +40,7 @@ import org.apache.hc.client5.http.AuthenticationStrategy; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.SchemePortResolver; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.auth.AuthSchemeFactory; @@ -61,10 +61,11 @@ import org.apache.hc.client5.http.impl.DefaultClientConnectionReuseStrategy; import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy; import org.apache.hc.client5.http.impl.DefaultExchangeIdGenerator; -import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; +import org.apache.hc.client5.http.impl.DefaultRequestRetryStrategy; import org.apache.hc.client5.http.impl.DefaultSchemePortResolver; import org.apache.hc.client5.http.impl.DefaultUserTokenHandler; +import org.apache.hc.client5.http.impl.HttpRequestRetryStrategyAdaptor; import org.apache.hc.client5.http.impl.IdleConnectionEvictor; import org.apache.hc.client5.http.impl.NoopUserTokenHandler; import org.apache.hc.client5.http.impl.auth.BasicSchemeFactory; @@ -187,7 +188,7 @@ private ExecInterceptorEntry( private LinkedList responseInterceptors; private LinkedList execInterceptors; - private HttpRequestRetryStrategy retryStrategy; + private RequestRetryStrategy retryStrategy; private HttpRoutePlanner routePlanner; private RedirectStrategy redirectStrategy; private ConnectionBackoffStrategy connectionBackoffStrategy; @@ -544,15 +545,34 @@ public final HttpClientBuilder disableAuthCaching() { } /** - * Sets {@link HttpRequestRetryStrategy} instance. + * Sets {@link org.apache.hc.client5.http.HttpRequestRetryStrategy} instance. *

* Please note this value can be overridden by the {@link #disableAutomaticRetries()} * method. *

* * @return this instance. + * + * @deprecated Use {@link #setRequestRetryStrategy(RequestRetryStrategy)} + */ + @Deprecated + public final HttpClientBuilder setRetryStrategy(final org.apache.hc.client5.http.HttpRequestRetryStrategy retryStrategy) { + this.retryStrategy = retryStrategy != null ? new HttpRequestRetryStrategyAdaptor(retryStrategy) : null; + return this; + } + + /** + * Sets {@link RequestRetryStrategy} instance. + *

+ * Please note this value can be overridden by the {@link #disableAutomaticRetries()} + * method. + *

+ * + * @return this instance. + * + * @since 5.7 */ - public final HttpClientBuilder setRetryStrategy(final HttpRequestRetryStrategy retryStrategy) { + public final HttpClientBuilder setRequestRetryStrategy(final RequestRetryStrategy retryStrategy) { this.retryStrategy = retryStrategy; return this; } @@ -999,9 +1019,9 @@ public CloseableHttpClient build() { // Add request retry executor, if not disabled if (!automaticRetriesDisabled) { - HttpRequestRetryStrategy retryStrategyCopy = this.retryStrategy; + RequestRetryStrategy retryStrategyCopy = this.retryStrategy; if (retryStrategyCopy == null) { - retryStrategyCopy = DefaultHttpRequestRetryStrategy.INSTANCE; + retryStrategyCopy = DefaultRequestRetryStrategy.INSTANCE; } execChainDefinition.addFirst( new HttpRequestRetryExec(retryStrategyCopy), diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestRetryExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestRetryExec.java index 3dc801dd36..fa9592498c 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestRetryExec.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/HttpRequestRetryExec.java @@ -28,9 +28,10 @@ import java.io.IOException; import java.io.InterruptedIOException; +import java.util.Optional; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; import org.apache.hc.client5.http.HttpRoute; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.classic.ExecChain; import org.apache.hc.client5.http.classic.ExecChain.Scope; import org.apache.hc.client5.http.classic.ExecChainHandler; @@ -86,10 +87,13 @@ public class HttpRequestRetryExec implements ExecChainHandler { private static final Logger LOG = LoggerFactory.getLogger(HttpRequestRetryExec.class); - private final HttpRequestRetryStrategy retryStrategy; + private final RequestRetryStrategy retryStrategy; + /** + * @since 5.7 + */ public HttpRequestRetryExec( - final HttpRequestRetryStrategy retryStrategy) { + final RequestRetryStrategy retryStrategy) { Args.notNull(retryStrategy, "retryStrategy"); this.retryStrategy = retryStrategy; } @@ -118,9 +122,10 @@ public ClassicHttpResponse execute( } return response; } - if (retryStrategy.retryRequest(response, execCount, context)) { + final Optional retryPeriod = retryStrategy.retryRequest(request, response, execCount, context); + if (retryPeriod.isPresent()) { response.close(); - final TimeValue delay = retryStrategy.getRetryInterval(response, execCount, context); + final TimeValue delay = TimeValue.isPositive(retryPeriod.get()) ? retryPeriod.get() : TimeValue.ZERO_MILLISECONDS; if (LOG.isInfoEnabled()) { LOG.info("{} {} responded with status {}; " + "request will be automatically re-executed in {} (exec count {})", @@ -146,11 +151,12 @@ public ClassicHttpResponse execute( } throw ex; } - if (retryStrategy.retryRequest(request, ex, execCount, context)) { + final Optional retryPeriod = retryStrategy.retryRequest(request, ex, execCount, context); + if (retryPeriod.isPresent()) { if (LOG.isDebugEnabled()) { LOG.debug("{} {}", exchangeId, ex.getMessage(), ex); } - final TimeValue delay = retryStrategy.getRetryInterval(request, ex, execCount, context); + final TimeValue delay = TimeValue.isPositive(retryPeriod.get()) ? retryPeriod.get() : TimeValue.ZERO_MILLISECONDS; if (LOG.isInfoEnabled()) { LOG.info("{} recoverable I/O exception ({}) caught when sending request to {};" + "request will be automatically re-executed in {} (exec count {})", diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultHttpRequestRetryStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultHttpRequestRetryStrategy.java deleted file mode 100644 index 0e335cbcda..0000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultHttpRequestRetryStrategy.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.hc.client5.http.impl; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.NoRouteToHostException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import javax.net.ssl.SSLException; -import org.apache.hc.client5.http.classic.methods.HttpGet; -import org.apache.hc.client5.http.classic.methods.HttpQuery; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.apache.hc.client5.http.utils.DateUtils; -import org.apache.hc.core5.http.ConnectionClosedException; -import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.HttpResponse; -import org.apache.hc.core5.http.message.BasicHttpResponse; -import org.apache.hc.core5.util.TimeValue; -import org.apache.hc.core5.util.Timeout; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestDefaultHttpRequestRetryStrategy { - - private DefaultHttpRequestRetryStrategy retryStrategy; - - @BeforeEach - void setup() { - this.retryStrategy = new DefaultHttpRequestRetryStrategy(3, TimeValue.ofMilliseconds(1234L)); - } - - @Test - void testBasics() { - final HttpResponse response1 = new BasicHttpResponse(503, "Oopsie"); - Assertions.assertTrue(this.retryStrategy.retryRequest(response1, 1, null)); - Assertions.assertTrue(this.retryStrategy.retryRequest(response1, 2, null)); - Assertions.assertTrue(this.retryStrategy.retryRequest(response1, 3, null)); - Assertions.assertFalse(this.retryStrategy.retryRequest(response1, 4, null)); - final HttpResponse response2 = new BasicHttpResponse(500, "Big Time Oopsie"); - Assertions.assertFalse(this.retryStrategy.retryRequest(response2, 1, null)); - final HttpResponse response3 = new BasicHttpResponse(429, "Oopsie"); - Assertions.assertTrue(this.retryStrategy.retryRequest(response3, 1, null)); - Assertions.assertTrue(this.retryStrategy.retryRequest(response3, 2, null)); - Assertions.assertTrue(this.retryStrategy.retryRequest(response3, 3, null)); - Assertions.assertFalse(this.retryStrategy.retryRequest(response3, 4, null)); - - Assertions.assertEquals(TimeValue.ofMilliseconds(1234L), this.retryStrategy.getRetryInterval(response1, 1, null)); - } - - @Test - void testRetryRequestWithResponseTimeout() { - final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); - - final HttpClientContext context = HttpClientContext.create(); - context.setRequestConfig(RequestConfig.custom() - .build()); - - Assertions.assertTrue(retryStrategy.retryRequest(response, 1, context)); - - context.setRequestConfig(RequestConfig.custom() - .setResponseTimeout(Timeout.ofMilliseconds(1234L)) - .build()); - - Assertions.assertTrue(retryStrategy.retryRequest(response, 1, context)); - - context.setRequestConfig(RequestConfig.custom() - .setResponseTimeout(Timeout.ofMilliseconds(1233L)) - .build()); - - Assertions.assertFalse(retryStrategy.retryRequest(response, 1, context)); - } - - @Test - void testRetryAfterHeaderAsLong() { - final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); - response.setHeader(HttpHeaders.RETRY_AFTER, "321"); - - Assertions.assertEquals(TimeValue.ofSeconds(321L), this.retryStrategy.getRetryInterval(response, 3, null)); - } - - @Test - void testRetryAfterHeaderAsDate() { - this.retryStrategy = new DefaultHttpRequestRetryStrategy(3, TimeValue.ZERO_MILLISECONDS); - final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); - response.setHeader(HttpHeaders.RETRY_AFTER, DateUtils.formatStandardDate(Instant.now().plus(100, ChronoUnit.SECONDS))); - - Assertions.assertTrue(this.retryStrategy.getRetryInterval(response, 3, null).compareTo(TimeValue.ZERO_MILLISECONDS) > 0); - } - - @Test - void testRetryAfterHeaderAsPastDate() { - final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); - response.setHeader(HttpHeaders.RETRY_AFTER, DateUtils.formatStandardDate(Instant.now().minus(100, ChronoUnit.SECONDS))); - - Assertions.assertEquals(TimeValue.ofMilliseconds(1234L), this.retryStrategy.getRetryInterval(response, 3, null)); - } - - @Test - void testInvalidRetryAfterHeader() { - final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); - response.setHeader(HttpHeaders.RETRY_AFTER, "Stuff"); - - Assertions.assertEquals(TimeValue.ofMilliseconds(1234L), retryStrategy.getRetryInterval(response, 3, null)); - } - - @Test - void noRetryOnConnectTimeout() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new SocketTimeoutException(), 1, null)); - } - - @Test - void noRetryOnConnect() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new ConnectException(), 1, null)); - } - - @Test - void noRetryOnConnectionClosed() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new ConnectionClosedException(), 1, null)); - } - - @Test - void noRetryForNoRouteToHostException() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new NoRouteToHostException(), 1, null)); - } - - @Test - void noRetryOnSSLFailure() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new SSLException("encryption failed"), 1, null)); - } - - @Test - void noRetryOnUnknownHost() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new UnknownHostException(), 1, null)); - } - - @Test - void noRetryOnAbortedRequests() { - final HttpGet request = new HttpGet("/"); - request.cancel(); - - Assertions.assertFalse(retryStrategy.retryRequest(request, new IOException(), 1, null)); - } - - @Test - void retryOnNonAbortedRequests() { - final HttpGet request = new HttpGet("/"); - - Assertions.assertTrue(retryStrategy.retryRequest(request, new IOException(), 1, null)); - } - - @Test - void retryOnQueryRequests() { - final HttpQuery request = new HttpQuery("/"); - - Assertions.assertTrue(retryStrategy.retryRequest(request, new IOException(), 1, null)); - } - - @Test - void testRetryRequestWithResponseTimeoutAndRetryAfterHeader() { - final HttpResponse response = new BasicHttpResponse(429, "Too Many Requests"); - response.setHeader(HttpHeaders.RETRY_AFTER, "321"); - - final HttpClientContext context = HttpClientContext.create(); - context.setRequestConfig(RequestConfig.custom() - .setResponseTimeout(Timeout.ofSeconds(2L)) - .build()); - - Assertions.assertFalse(retryStrategy.retryRequest(response, 1, context)); - } - -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRequestRetryStrategy.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRequestRetryStrategy.java new file mode 100644 index 0000000000..188cae6c64 --- /dev/null +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/TestDefaultRequestRetryStrategy.java @@ -0,0 +1,325 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ +package org.apache.hc.client5.http.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.NoRouteToHostException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Optional; +import java.util.stream.Stream; + +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLProtocolException; + +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.client5.http.utils.DateUtils; +import org.apache.hc.core5.http.ConnectionClosedException; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.Method; +import org.apache.hc.core5.http.message.BasicHttpRequest; +import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +class TestDefaultRequestRetryStrategy { + + private static final TimeValue TIMEOUT = TimeValue.ofMilliseconds(1234L); + + private DefaultRequestRetryStrategy retryStrategy; + + @BeforeEach + void setup() { + retryStrategy = new DefaultRequestRetryStrategy(3, TIMEOUT); + } + + private static Stream nonRecoverableExceptions() { + return Stream.of( + Arguments.arguments(new SocketTimeoutException()), + Arguments.arguments(new ConnectException()), + Arguments.arguments(new ConnectionClosedException()), + Arguments.arguments(new NoRouteToHostException()), + Arguments.arguments(new SSLException("boom")), + Arguments.arguments(new SSLHandshakeException("boom")), + Arguments.arguments(new SSLProtocolException("boom")), + Arguments.arguments(new UnknownHostException()) + ); + } + + @ParameterizedTest + @MethodSource("nonRecoverableExceptions") + void testNonRetriableException(final IOException exception) { + assertThat(retryStrategy.isRetriable(exception)).isFalse(); + } + + @Test + void testRetriableException() { + assertThat(retryStrategy.isRetriable(new IOException())).isTrue(); + } + + @ParameterizedTest + @EnumSource(value = Method.class, mode = EnumSource.Mode.INCLUDE, + names = {"GET", "HEAD", "PUT", "DELETE", "TRACE", "OPTIONS", "QUERY"}) + void testIdempotentRequest(final Method httpMethod) { + assertThat(retryStrategy.isIdempotent(new BasicHttpRequest(httpMethod, "/"))) + .isTrue(); + } + + @ParameterizedTest + @EnumSource(value = Method.class, mode = EnumSource.Mode.INCLUDE, + names = {"POST", "CONNECT", "PATCH"}) + void testNonIdempotentRequest(final Method httpMethod) { + assertThat(retryStrategy.isIdempotent(new BasicHttpRequest(httpMethod, "/"))) + .isFalse(); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 2, 3}) + void testNonRetriableExecCount(final int execCount) { + assertThat(retryStrategy.isRetriable(execCount)).isTrue(); + } + + @Test + void testRetriableExecCount() { + assertThat(retryStrategy.isRetriable(4)).isFalse(); + } + + @ParameterizedTest + @ValueSource(ints = {429, 503}) + void testRecoverableResponse(final int code) { + assertThat(retryStrategy.isRecoverable(new BasicHttpResponse(code))).isTrue(); + } + + @ParameterizedTest + @ValueSource(ints = {300, 400, 500}) + void testNonRecoverableResponse(final int code) { + assertThat(retryStrategy.isRecoverable(new BasicHttpResponse(code))).isFalse(); + } + + @ParameterizedTest + @ValueSource(ints = {300, 400, 401, 403, 404, 429, 500, 503}) + void testRetryRequestByResponseStatus(final int code) { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(code, "Oopsie"); + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, null); + + if (retryStrategy.isRecoverable(response)) { + assertThat(retryInterval).isPresent().hasValue(TIMEOUT); + } else { + assertThat(retryInterval).isNotPresent(); + } + } + + @ParameterizedTest + @ValueSource(ints = {0, 2, 3, 4, 10}) + void testRetryRequestByExecCount(final int execCount) { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + final Optional retryInterval = retryStrategy.retryRequest(request, response, execCount, null); + + if (retryStrategy.isRetriable(execCount)) { + assertThat(retryInterval).isPresent().hasValue(TIMEOUT); + } else { + assertThat(retryInterval).isNotPresent(); + } + } + + @Test + void testRetryRequestNoRetryOnAbortedRequests() { + final HttpGet request = new HttpGet("/"); + request.cancel(); + + final Optional retryInterval = retryStrategy.retryRequest(request, new IOException(), 1, null); + assertThat(retryInterval).isNotPresent(); + } + + @ParameterizedTest + @MethodSource("nonRecoverableExceptions") + void testRetryRequestNoRetryByNonRecoverableException(final IOException exception) { + final HttpGet request = new HttpGet("/"); + + final Optional retryInterval = retryStrategy.retryRequest(request, exception, 1, null); + assertThat(retryInterval).isNotPresent(); + } + + @Test + void testRetryRequestRetryOnRecoverableException() { + final HttpGet request = new HttpGet("/"); + + final Optional retryInterval = retryStrategy.retryRequest(request, new IOException(), 1, null); + assertThat(retryInterval).isPresent().hasValue(TIMEOUT); + } + + @ParameterizedTest + @EnumSource(value = Method.class, mode = EnumSource.Mode.MATCH_ALL) + void testRetryRequestRetryOnMethod(final Method httpMethod) { + final HttpRequest request = new BasicHttpRequest(httpMethod, "/"); + + final Optional retryInterval = retryStrategy.retryRequest(request, new IOException(), 1, null); + if (retryStrategy.isIdempotent(request)) { + assertThat(retryInterval).isPresent().hasValue(TIMEOUT); + } else { + assertThat(retryInterval).isNotPresent(); + } + } + + @Test + void testParseRetryAfterNoHeader() { + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + + final TimeValue timeValue = retryStrategy.parseRetryAfter(response); + assertThat(timeValue).isEqualTo(TIMEOUT); + } + + @Test + void testParseRetryAfterAsLong() { + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "321"); + + final TimeValue timeValue = retryStrategy.parseRetryAfter(response); + assertThat(timeValue).isEqualTo(TimeValue.ofSeconds(321)); + } + + @Test + void testParseRetryAfterAsDate() { + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, DateUtils.formatStandardDate(Instant.now().plus(100, ChronoUnit.SECONDS))); + + final TimeValue timeValue = retryStrategy.parseRetryAfter(response); + assertThat(timeValue).isGreaterThan(TimeValue.ZERO_MILLISECONDS).isNotEqualByComparingTo(TIMEOUT); + } + + @Test + void testRetryAfterHeaderAsPastDate() { + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, DateUtils.formatStandardDate(Instant.now().minus(100, ChronoUnit.SECONDS))); + + final TimeValue timeValue = retryStrategy.parseRetryAfter(response); + assertThat(timeValue).isEqualTo(TIMEOUT); + } + + @Test + void testRetryAfterHeaderInvalidHeader() { + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "Stuff"); + + final TimeValue timeValue = retryStrategy.parseRetryAfter(response); + assertThat(timeValue).isEqualTo(TIMEOUT); + } + + @Test + void testRetryRequestByResponseWithRetryAfter() { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "321"); + + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, null); + assertThat(retryInterval).isPresent().hasValue(TimeValue.ofSeconds(321)); + } + + @Test + void testRetryRequestByResponseWithNoResponseTimeout() { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "321"); + + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, null); + assertThat(retryInterval).isPresent().hasValue(TimeValue.ofSeconds(321)); + } + + @Test + void testRetryRequestByResponseWithResponseTimeout() { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "321"); + + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, null); + assertThat(retryInterval).isPresent().hasValue(TimeValue.ofSeconds(321)); + } + + @Test + void testRetryRequestWithResponseTimeoutLessRetryAfter() { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "321"); + + final HttpClientContext context = HttpClientContext.create(); + context.setRequestConfig(RequestConfig.custom() + .setResponseTimeout(Timeout.ofSeconds(10)) + .build()); + + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, context); + assertThat(retryInterval).isNotPresent(); + } + + @Test + void testRetryRequestWithResponseTimeoutLessDefaultInterval() { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + + final HttpClientContext context = HttpClientContext.create(); + context.setRequestConfig(RequestConfig.custom() + .setResponseTimeout(Timeout.ofSeconds(1)) + .build()); + + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, context); + assertThat(retryInterval).isNotPresent(); + } + + @Test + void testRetryRequestWithResponseTimeoutGreaterRetryAfter() { + final HttpGet request = new HttpGet("/"); + final HttpResponse response = new BasicHttpResponse(503, "Oopsie"); + response.setHeader(HttpHeaders.RETRY_AFTER, "321"); + + final HttpClientContext context = HttpClientContext.create(); + context.setRequestConfig(RequestConfig.custom() + .setResponseTimeout(Timeout.ofSeconds(322)) + .build()); + + final Optional retryInterval = retryStrategy.retryRequest(request, response, 1, context); + assertThat(retryInterval).isPresent().hasValue(TimeValue.ofSeconds(321)); + } + +} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestHttpRequestRetryExec.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestHttpRequestRetryExec.java index 08c440b4a6..022d563a22 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestHttpRequestRetryExec.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestHttpRequestRetryExec.java @@ -29,9 +29,10 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.util.Optional; -import org.apache.hc.client5.http.HttpRequestRetryStrategy; import org.apache.hc.client5.http.HttpRoute; +import org.apache.hc.client5.http.RequestRetryStrategy; import org.apache.hc.client5.http.classic.ExecChain; import org.apache.hc.client5.http.classic.ExecRuntime; import org.apache.hc.client5.http.classic.methods.HttpGet; @@ -43,6 +44,8 @@ import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpRequest; +import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.hc.core5.util.TimeValue; import org.junit.jupiter.api.Assertions; @@ -58,7 +61,7 @@ class TestHttpRequestRetryExec { @Mock - private HttpRequestRetryStrategy retryStrategy; + private RequestRetryStrategy retryStrategy; @Mock private ExecChain chain; @Mock @@ -88,13 +91,10 @@ void testFundamentals1() throws Exception { Mockito.same(request), Mockito.any())).thenReturn(response); Mockito.when(retryStrategy.retryRequest( - Mockito.any(), - Mockito.anyInt(), - Mockito.any())).thenReturn(Boolean.TRUE, Boolean.FALSE); - Mockito.when(retryStrategy.getRetryInterval( - Mockito.any(), + Mockito.any(HttpRequest.class), + Mockito.any(HttpResponse.class), Mockito.anyInt(), - Mockito.any())).thenReturn(TimeValue.ZERO_MILLISECONDS); + Mockito.any())).thenReturn(Optional.of(TimeValue.ZERO_MILLISECONDS), Optional.empty()); final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context); retryExec.execute(request, scope, chain); @@ -117,15 +117,10 @@ void testRetrySleepOnIOException() throws Exception { Mockito.same(request), Mockito.any())).thenThrow(new IOException("Ka-boom")); Mockito.when(retryStrategy.retryRequest( - Mockito.any(), - Mockito.any(), - Mockito.anyInt(), - Mockito.any())).thenReturn(Boolean.TRUE, Boolean.FALSE); - Mockito.when(retryStrategy.getRetryInterval( - Mockito.any(), - Mockito.any(), + Mockito.any(HttpRequest.class), + Mockito.any(IOException.class), Mockito.anyInt(), - Mockito.any())).thenReturn(nextInterval); + Mockito.any())).thenReturn(Optional.of(nextInterval), Optional.empty()); Mockito.when(nextInterval.getDuration()).thenReturn(100L); final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context); @@ -152,13 +147,10 @@ void testRetryIntervalResponseTimeoutNull() throws Exception { Mockito.same(request), Mockito.any())).thenReturn(response); Mockito.when(retryStrategy.retryRequest( - Mockito.any(), - Mockito.anyInt(), - Mockito.any())).thenReturn(Boolean.TRUE, Boolean.FALSE); - Mockito.when(retryStrategy.getRetryInterval( - Mockito.any(), + Mockito.any(HttpRequest.class), + Mockito.any(HttpResponse.class), Mockito.anyInt(), - Mockito.any())).thenReturn(TimeValue.ofSeconds(1)); + Mockito.any())).thenReturn(Optional.of(TimeValue.ofSeconds(1)), Optional.empty()); final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context); retryExec.execute(request, scope, chain); @@ -180,7 +172,8 @@ void testStrategyRuntimeException() throws Exception { Mockito.any(), Mockito.any())).thenReturn(response); Mockito.doThrow(new RuntimeException("Ooopsie")).when(retryStrategy).retryRequest( - Mockito.any(), + Mockito.any(HttpRequest.class), + Mockito.any(HttpResponse.class), Mockito.anyInt(), Mockito.any()); final ExecChain.Scope scope = new ExecChain.Scope("test", route, request, endpoint, context); @@ -232,10 +225,10 @@ void testFundamentals2() throws Exception { throw new IOException("Ka-boom"); }); Mockito.when(retryStrategy.retryRequest( - Mockito.any(), - Mockito.any(), + Mockito.any(HttpRequest.class), + Mockito.any(IOException.class), Mockito.eq(1), - Mockito.any())).thenReturn(Boolean.TRUE); + Mockito.any())).thenReturn(Optional.of(TimeValue.ofSeconds(1))); final ExecChain.Scope scope = new ExecChain.Scope("test", route, originalRequest, endpoint, context); final ClassicHttpRequest request = ClassicRequestBuilder.copy(originalRequest).build(); Assertions.assertThrows(IOException.class, () -> @@ -265,8 +258,8 @@ void testAbortedRequest() throws Exception { Mockito.same(request), Mockito.same(scope)); Mockito.verify(retryStrategy, Mockito.never()).retryRequest( - Mockito.any(), - Mockito.any(), + Mockito.any(HttpRequest.class), + Mockito.any(IOException.class), Mockito.anyInt(), Mockito.any()); }