View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.transport.jetty;
20  
21  import javax.net.ssl.SSLException;
22  
23  import java.io.IOException;
24  import java.io.InterruptedIOException;
25  import java.net.ConnectException;
26  import java.net.NoRouteToHostException;
27  import java.net.UnknownHostException;
28  import java.util.Set;
29  import java.util.concurrent.TimeoutException;
30  
31  import org.eclipse.aether.RepositorySystemSession;
32  import org.eclipse.aether.repository.RemoteRepository;
33  import org.eclipse.aether.transfer.TransferCancelledException;
34  import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
35  import org.eclipse.jetty.http.HttpFields;
36  import org.eclipse.jetty.http.HttpHeader;
37  import org.slf4j.Logger;
38  import org.slf4j.LoggerFactory;
39  
40  /**
41   * Decides whether a failed request is retried and how long to wait before doing so, based on the
42   * {@code aether.connector.http.retryHandler.*} configuration. The Jetty HTTP client has no retry hook of its own,
43   * therefore {@link JettyTransporter} drives the retries and consults this class.
44   */
45  final class JettyRetryHandler {
46  
47      private static final Logger LOGGER = LoggerFactory.getLogger(JettyRetryHandler.class);
48  
49      /**
50       * Classes of IOExceptions that should not be retried (because they are permanent failures).
51       * Same as in <a href="https://github.com/apache/httpcomponents-client/blob/54900db4653d7f207477e6ee40135b88e9bcf832/httpclient/src/main/java/org/apache/http/impl/client/DefaultHttpRequestRetryHandler.java#L102">
52       * Apache HttpClient's DefaultHttpRequestRetryHandler</a>.
53       */
54      private static final Set<Class<? extends IOException>> NON_RETRIABLE_IO_EXCEPTIONS = Set.of(
55              InterruptedIOException.class,
56              UnknownHostException.class,
57              ConnectException.class,
58              NoRouteToHostException.class,
59              SSLException.class);
60  
61      /**
62       * The delay before a retry together with the reason for choosing it.
63       */
64      record Delay(long millis, String reason) {}
65  
66      private final int retryCount;
67  
68      private final long retryInterval;
69  
70      private final long retryIntervalMax;
71  
72      private final Set<Integer> retriableStatusCodes;
73  
74      JettyRetryHandler(RepositorySystemSession session, RemoteRepository repository) {
75          this.retryCount = HttpTransporterUtils.getHttpRetryHandlerCount(session, repository);
76          this.retryInterval = HttpTransporterUtils.getHttpRetryHandlerInterval(session, repository);
77          this.retryIntervalMax = HttpTransporterUtils.getHttpRetryHandlerIntervalMax(session, repository);
78          this.retriableStatusCodes = HttpTransporterUtils.getHttpServiceUnavailableCodes(session, repository);
79      }
80  
81      /**
82       * The maximum number of retries, i.e. a request is attempted at most {@code getRetryCount() + 1} times.
83       */
84      int getRetryCount() {
85          return retryCount;
86      }
87  
88      /**
89       * Tells whether a request that failed with the given exception should be sent again.
90       *
91       * @param attempt the 0-based number of the attempt that failed
92       */
93      boolean shouldRetry(int attempt, Throwable failure) {
94          return attempt < retryCount && isRetriable(failure);
95      }
96  
97      /**
98       * Tells whether a request that got a response with the given status code should be sent again.
99       *
100      * @param attempt the 0-based number of the attempt that got the response
101      */
102     boolean shouldRetry(int attempt, int statusCode) {
103         return attempt < retryCount && retriableStatusCodes.contains(statusCode);
104     }
105 
106     private static boolean isRetriable(Throwable failure) {
107         if (failure instanceof TimeoutException) {
108             return true;
109         }
110         if (!(failure instanceof IOException)) {
111             return false;
112         }
113         for (Throwable t = failure; t != null; t = t.getCause()) {
114             if (t instanceof TransferCancelledException || t instanceof RedirectRefusedException) {
115                 return false;
116             }
117         }
118         return NON_RETRIABLE_IO_EXCEPTIONS.stream().noneMatch(clazz -> clazz.isInstance(failure));
119     }
120 
121     /**
122      * Computes the delay before the next attempt. A {@code Retry-After} response header is obeyed, otherwise the
123      * delay grows linearly with the number of attempts. It never exceeds the configured maximum.
124      *
125      * @param responseHeaders the headers of the response that triggered the retry
126      * @param attempt the 0-based number of the attempt that got the response
127      */
128     Delay getDelay(HttpFields responseHeaders, int attempt) {
129         long delay = -1L;
130         String reason = "";
131         String retryAfter = responseHeaders.get(HttpHeader.RETRY_AFTER);
132         if (retryAfter != null) {
133             try {
134                 if (retryAfter.contains(":")) { // is date when to retry
135                     delay = Math.max(
136                             responseHeaders.getDateField(HttpHeader.RETRY_AFTER) - System.currentTimeMillis(), 0L);
137                     reason = "Retry-After header with date value " + retryAfter;
138                 } else {
139                     delay = Long.parseLong(retryAfter.trim()) * 1000L; // is in seconds
140                     reason = "Retry-After header with seconds value " + retryAfter;
141                 }
142             } catch (IllegalArgumentException e) { // includes NumberFormatException
143                 LOGGER.warn("Invalid Retry-After header value {}", retryAfter);
144                 delay = -1L;
145             }
146         }
147         if (delay < 0L) {
148             long executionCount = attempt + 1L;
149             delay = executionCount * retryInterval;
150             reason = "retryInterval " + retryInterval + " ms multiplied by execution count " + executionCount;
151         }
152         if (delay > retryIntervalMax) {
153             delay = retryIntervalMax;
154             reason += ", capped at max value";
155         }
156         return new Delay(delay, reason);
157     }
158 }