xcapdevila commented on code in PR #3328:
URL: 
https://github.com/apache/httpcomponents-client/pull/3328#discussion_r4753403127


##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRequestRetryStrategy.java:
##########
@@ -0,0 +1,243 @@
+/*
+ * ====================================================================
+ * 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
+ * <http://www.apache.org/>.
+ *
+ */
+
+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 {
+
+    /**
+     * Default instance of {@link DefaultRequestRetryStrategy}.
+     */
+    public static final DefaultRequestRetryStrategy INSTANCE = new 
DefaultRequestRetryStrategy(1, TimeValue.ofSeconds(1));
+
+    private static final List<Class<? extends IOException>> 
NON_RETRIABLE_ERRORS_LIST =
+            Arrays.asList(
+                    InterruptedIOException.class,
+                    UnknownHostException.class,
+                    ConnectException.class,
+                    ConnectionClosedException.class,
+                    NoRouteToHostException.class,
+                    SSLException.class);
+    private static final Set<Class<? extends IOException>> 
NON_RETRIABLE_ERRORS_SET =
+            new HashSet<>(NON_RETRIABLE_ERRORS_LIST);
+
+    /**
+     * Maximum number of allowed retries
+     */
+    private final int maxRetries;
+
+    /**
+     * Retry interval between subsequent retries
+     */
+    private final TimeValue defaultRetryInterval;
+
+    /**
+     * Create the HTTP request retry strategy using the following list of
+     * non-retriable exception:<br>
+     * <ul>
+     * <li>{@link InterruptedIOException}</li>
+     * <li>{@link UnknownHostException}</li>
+     * <li>{@link ConnectException}</li>
+     * <li>{@link ConnectionClosedException}</li>
+     * <li>{@link NoRouteToHostException}</li>
+     * <li>{@link SSLException}</li>
+     * </ul>
+     * and retriable HTTP status codes:<br>
+     * <ul>
+     * <li>SC_TOO_MANY_REQUESTS (429)</li>
+     * <li>SC_SERVICE_UNAVAILABLE (503)</li>
+     * </ul>
+     * @param maxRetries how many times to retry; 0 means no retries
+     * @param defaultRetryInterval the default retry interval between
+     * subsequent retries if the {@code Retry-After} header is not set
+     * or invalid.
+     */
+    public DefaultRequestRetryStrategy(
+            final int maxRetries,
+            final TimeValue defaultRetryInterval) {
+        Args.notNegative(maxRetries, "maxRetries");
+        Args.notNull(defaultRetryInterval, "defaultRetryInterval");
+        Args.check(TimeValue.isNonNegative(defaultRetryInterval), "Default 
retry interval is negative");
+        this.maxRetries = maxRetries;
+        this.defaultRetryInterval = defaultRetryInterval;
+    }
+
+    @Override
+    public Optional<TimeValue> retryRequest(
+            final HttpRequest request,
+            final IOException exception,
+            final int execCount,
+            final HttpContext context) {
+        Args.notNull(request, "request");
+        Args.notNull(exception, "exception");
+
+        if (execCount > this.maxRetries) {
+            // Do not retry if over max retries
+            return Optional.empty();
+        }
+        if (request instanceof CancellableDependency && 
((CancellableDependency) request).isCancelled()) {
+            return Optional.empty();
+        }
+        if (handleAsRetriable(exception) && handleAsIdempotent(request)) {
+            return Optional.of(defaultRetryInterval);
+        }

Review 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`).
   1. Is this `0 ms` -> `1 s` change on recoverable I/O errors intentional (so 
`defaultRetryInterval` governs both overloads), or should I/O retries still 
default to `TimeValue.ZERO_MILLISECONDS` to avoid adding `1 s` latency on stale 
keep-alive recovery?
   2. 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`)?



##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/HttpRequestRetryStrategyAdaptor.java:
##########
@@ -0,0 +1,69 @@
+/*
+ * ====================================================================
+ * 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
+ * <http://www.apache.org/>.
+ *
+ */
+
+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<TimeValue> retryRequest(final HttpRequest request, final 
IOException exception, final int execCount, final HttpContext context) {
+        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();

Review 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:
   
   ```suggestion
           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();
   ```



##########
httpclient5/src/main/java/org/apache/hc/client5/http/RequestRetryStrategy.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * ====================================================================
+ * 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
+ * <http://www.apache.org/>.
+ *
+ */
+
+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 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
+     */

Review 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>`:
   
   ```suggestion
    * 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
        */
   ```



##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultRequestRetryStrategy.java:
##########
@@ -0,0 +1,243 @@
+/*
+ * ====================================================================
+ * 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
+ * <http://www.apache.org/>.
+ *
+ */
+
+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 {
+
+    /**
+     * Default instance of {@link DefaultRequestRetryStrategy}.
+     */
+    public static final DefaultRequestRetryStrategy INSTANCE = new 
DefaultRequestRetryStrategy(1, TimeValue.ofSeconds(1));
+
+    private static final List<Class<? extends IOException>> 
NON_RETRIABLE_ERRORS_LIST =
+            Arrays.asList(
+                    InterruptedIOException.class,
+                    UnknownHostException.class,
+                    ConnectException.class,
+                    ConnectionClosedException.class,
+                    NoRouteToHostException.class,
+                    SSLException.class);
+    private static final Set<Class<? extends IOException>> 
NON_RETRIABLE_ERRORS_SET =
+            new HashSet<>(NON_RETRIABLE_ERRORS_LIST);
+
+    /**
+     * Maximum number of allowed retries
+     */
+    private final int maxRetries;
+
+    /**
+     * Retry interval between subsequent retries
+     */
+    private final TimeValue defaultRetryInterval;
+
+    /**
+     * Create the HTTP request retry strategy using the following list of
+     * non-retriable exception:<br>
+     * <ul>
+     * <li>{@link InterruptedIOException}</li>
+     * <li>{@link UnknownHostException}</li>
+     * <li>{@link ConnectException}</li>
+     * <li>{@link ConnectionClosedException}</li>
+     * <li>{@link NoRouteToHostException}</li>
+     * <li>{@link SSLException}</li>
+     * </ul>
+     * and retriable HTTP status codes:<br>
+     * <ul>
+     * <li>SC_TOO_MANY_REQUESTS (429)</li>
+     * <li>SC_SERVICE_UNAVAILABLE (503)</li>
+     * </ul>
+     * @param maxRetries how many times to retry; 0 means no retries
+     * @param defaultRetryInterval the default retry interval between
+     * subsequent retries if the {@code Retry-After} header is not set
+     * or invalid.
+     */
+    public DefaultRequestRetryStrategy(
+            final int maxRetries,
+            final TimeValue defaultRetryInterval) {
+        Args.notNegative(maxRetries, "maxRetries");
+        Args.notNull(defaultRetryInterval, "defaultRetryInterval");
+        Args.check(TimeValue.isNonNegative(defaultRetryInterval), "Default 
retry interval is negative");
+        this.maxRetries = maxRetries;
+        this.defaultRetryInterval = defaultRetryInterval;
+    }
+
+    @Override
+    public Optional<TimeValue> retryRequest(
+            final HttpRequest request,
+            final IOException exception,
+            final int execCount,
+            final HttpContext context) {
+        Args.notNull(request, "request");
+        Args.notNull(exception, "exception");
+
+        if (execCount > this.maxRetries) {
+            // Do not retry if over max retries
+            return Optional.empty();
+        }
+        if (request instanceof CancellableDependency && 
((CancellableDependency) request).isCancelled()) {
+            return Optional.empty();
+        }
+        if (handleAsRetriable(exception) && handleAsIdempotent(request)) {
+            return Optional.of(defaultRetryInterval);
+        }
+        return Optional.empty();
+    }
+
+    @Override
+    public Optional<TimeValue> retryRequest(
+            final HttpRequest request,
+            final HttpResponse response,
+            final int execCount,
+            final HttpContext context) {
+        Args.notNull(response, "response");
+
+        if (execCount > this.maxRetries) {
+            // Do not retry if over max retries
+            return Optional.empty();
+        }

Review 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.)*
   
   ```suggestion
           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();
           }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to