retryRequest(HttpRequest request, HttpResponse response, int execCount, HttpContext context);
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java b/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java
new file mode 100644
index 0000000000..7ad272e3f6
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java
@@ -0,0 +1,72 @@
+/*
+ * ====================================================================
+ * 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.config;
+
+/**
+ * Protocol family preference for outbound connections.
+ *
+ * Used by connection initiation code to filter or order destination
+ * addresses and, when enabled, to interleave families during staggered attempts.
+ *
+ * @since 5.7
+ */
+public enum ProtocolFamilyPreference {
+
+ /**
+ * No family bias. Preserve RFC 6724 order.
+ */
+ DEFAULT,
+
+ /**
+ * Prefer IPv4 addresses (stable: preserves RFC order within each family).
+ */
+ PREFER_IPV4,
+
+ /**
+ * Prefer IPv6 addresses (stable: preserves RFC order within each family).
+ */
+ PREFER_IPV6,
+
+ /**
+ * Filter out all non-IPv4 addresses.
+ */
+ IPV4_ONLY,
+
+ /**
+ * Filter out all non-IPv6 addresses.
+ */
+ IPV6_ONLY,
+
+ /**
+ * Interleave address families (v6, then v4, then v6, …) when multiple
+ * addresses are available, preserving the relative order within each family
+ * as produced by RFC 6724 sorting.
+ */
+ INTERLEAVE
+
+}
+
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/HttpRFC7578Multipart.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/HttpRFC7578Multipart.java
index c4e21e667a..e2e0ba5c21 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/HttpRFC7578Multipart.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/HttpRFC7578Multipart.java
@@ -98,7 +98,9 @@ protected void formatMultipartHeader(final MultipartPart part, final OutputStrea
final String value = parameter.getValue();
writeBytes("; ", out);
writeBytes(name, out);
- writeBytes("=\"", out);
+ // RFC 8187 ext-value must not be quoted
+ final boolean quoted = !name.equalsIgnoreCase(MimeConsts.FIELD_PARAM_FILENAME_START);
+ writeBytes(quoted ? "=\"" : "=", out);
if (value != null) {
if (name.equalsIgnoreCase(MimeConsts.FIELD_PARAM_FILENAME_START)) {
if (value.startsWith("UTF-8''")) {
@@ -122,7 +124,9 @@ protected void formatMultipartHeader(final MultipartPart part, final OutputStrea
writeBytes(stripLineBreaks(escapeQuoted(value)), out);
}
}
- writeBytes("\"", out);
+ if (quoted) {
+ writeBytes("\"", out);
+ }
}
writeBytes(CR_LF, out);
} else {
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MimeField.java b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MimeField.java
index 6ad6359b25..5aa7d0fcc8 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MimeField.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MimeField.java
@@ -111,8 +111,13 @@ public String getBody() {
parameters.forEach(parameter -> {
sb.append("; ");
sb.append(parameter.getName());
- sb.append("=\"");
final String v = parameter.getValue();
+ if (MimeConsts.FIELD_PARAM_FILENAME_START.equalsIgnoreCase(parameter.getName()) && v.startsWith("UTF-8''")) {
+ // RFC 8187 ext-value must not be quoted
+ sb.append("=").append(v);
+ return;
+ }
+ sb.append("=\"");
for (int n = 0; n < v.length(); n++) {
final char ch = v.charAt(n);
if (ch == '"' || ch == '\\' ) {
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 extends IOException> 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 6c1b8bb492..d09471eda6 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/auth/AuthenticationHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java
index 04e34466e8..bfa9998896 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java
@@ -28,13 +28,13 @@
package org.apache.hc.client5.http.impl.auth;
import java.util.ArrayList;
-import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
-import java.util.stream.Collectors;
import org.apache.hc.client5.http.AuthenticationStrategy;
import org.apache.hc.client5.http.auth.AuthChallenge;
@@ -164,37 +164,30 @@ public boolean isChallengeExpected(final AuthExchange authExchange) {
return authScheme != null && authScheme.isChallengeExpected();
}
- private Map extractChallengeMap(
- final ChallengeType challengeType,
- final HttpResponse response) throws ParseException {
- final List authChallenges = new ArrayList<>(10);
- MessageSupport.parseHeadersStrict(
- response,
- challengeType == ChallengeType.PROXY ? HttpHeaders.PROXY_AUTHENTICATE : HttpHeaders.WWW_AUTHENTICATE,
- (buffer, cursor) ->
- parser.parse(challengeType, authChallenges, buffer, cursor));
-
- return authChallenges.stream()
- .collect(Collectors.toMap(
- c -> c.getSchemeName().toLowerCase(Locale.ROOT),
- c -> c,
- (c1, c2) -> c1));
- }
-
public Map extractChallengeMap(
final ChallengeType challengeType,
final HttpResponse response,
final HttpClientContext context) {
- try {
- return extractChallengeMap(challengeType, response);
- } catch (final ParseException ex) {
- if (LOG.isWarnEnabled()) {
- final HttpClientContext clientContext = HttpClientContext.cast(context);
- final String exchangeId = clientContext.getExchangeId();
- LOG.warn("{} Malformed challenge", exchangeId);
+ final Map challengeMap = new HashMap<>();
+ final Iterator it = response.headerIterator(
+ challengeType == ChallengeType.PROXY ? HttpHeaders.PROXY_AUTHENTICATE : HttpHeaders.WWW_AUTHENTICATE);
+ while (it.hasNext()) {
+ try {
+ final List authChallenges = new ArrayList<>();
+ MessageSupport.parseHeaderStrict(it.next(), (buffer, cursor) ->
+ parser.parse(challengeType, authChallenges, buffer, cursor));
+ for (final AuthChallenge authChallenge : authChallenges) {
+ challengeMap.putIfAbsent(authChallenge.getSchemeName().toLowerCase(Locale.ROOT), authChallenge);
+ }
+ } catch (final ParseException ex) {
+ if (LOG.isWarnEnabled()) {
+ final HttpClientContext clientContext = HttpClientContext.cast(context);
+ final String exchangeId = clientContext.getExchangeId();
+ LOG.warn("{} Malformed challenge", exchangeId);
+ }
}
- return Collections.emptyMap();
}
+ return challengeMap;
}
/**
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 1ee1bbd4c8..2071d40dc1 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;
@@ -543,15 +544,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/main/java/org/apache/hc/client5/http/impl/classic/ProxyClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ProxyClient.java
index 651f352bb0..710499e9e2 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ProxyClient.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ProxyClient.java
@@ -202,8 +202,11 @@ public Socket tunnel(
final int status = response.getCode();
if (status > 299) {
- EntityUtils.consume(response.getEntity());
- conn.close();
+ try {
+ EntityUtils.consume(response.getEntity());
+ } finally {
+ conn.close();
+ }
throw new HttpException("Tunnel refused: " + new StatusLine(response));
}
return conn.getSocket();
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java
index a5f616865f..062d861d93 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java
@@ -32,6 +32,7 @@
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.file.Path;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -89,11 +90,24 @@ public class DefaultHttpClientConnectionOperator implements HttpClientConnection
static final DetachedSocketFactory PLAIN_SOCKET_FACTORY = socksProxy -> socksProxy == null ? new Socket() : new Socket(socksProxy);
+ /**
+ * RFC 8305, Section 8: "When a reasonable value is unknown, implementations SHOULD use a
+ * Connection Attempt Delay of 250 milliseconds".
+ */
+ static final TimeValue DEFAULT_CONNECTION_ATTEMPT_DELAY = TimeValue.ofMilliseconds(250);
+
+ /**
+ * RFC 8305, Section 8: "this value SHOULD NOT be below 10 ms".
+ */
+ private static final long MIN_CONNECTION_ATTEMPT_DELAY_MS = 10;
+
private final DetachedSocketFactory detachedSocketFactory;
private final UnixDomainSocketFactory unixDomainSocketFactory = UnixDomainSocketFactory.getSocketFactory();
private final Lookup tlsSocketStrategyLookup;
private final SchemePortResolver schemePortResolver;
private final DnsResolver dnsResolver;
+ private final boolean happyEyeballsEnabled;
+ private final TimeValue connectionAttemptDelay;
/**
* @deprecated Provided for backward compatibility
@@ -115,6 +129,19 @@ public DefaultHttpClientConnectionOperator(
final SchemePortResolver schemePortResolver,
final DnsResolver dnsResolver,
final Lookup tlsSocketStrategyLookup) {
+ this(detachedSocketFactory, schemePortResolver, dnsResolver, tlsSocketStrategyLookup, false, null);
+ }
+
+ /**
+ * @since 5.7
+ */
+ public DefaultHttpClientConnectionOperator(
+ final DetachedSocketFactory detachedSocketFactory,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final Lookup tlsSocketStrategyLookup,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
super();
this.detachedSocketFactory = Args.notNull(detachedSocketFactory, "Plain socket factory");
this.tlsSocketStrategyLookup = Args.notNull(tlsSocketStrategyLookup, "Socket factory registry");
@@ -122,6 +149,13 @@ public DefaultHttpClientConnectionOperator(
DefaultSchemePortResolver.INSTANCE;
this.dnsResolver = dnsResolver != null ? dnsResolver :
SystemDefaultDnsResolver.INSTANCE;
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ final TimeValue delay = connectionAttemptDelay != null ? connectionAttemptDelay : DEFAULT_CONNECTION_ATTEMPT_DELAY;
+ if (happyEyeballsEnabled) {
+ Args.check(delay.toMilliseconds() >= MIN_CONNECTION_ATTEMPT_DELAY_MS,
+ "Connection attempt delay must be at least %s ms (RFC 8305, Section 8)", MIN_CONNECTION_ATTEMPT_DELAY_MS);
+ }
+ this.connectionAttemptDelay = delay;
}
/**
@@ -200,6 +234,105 @@ public void connect(
final int port = this.schemePortResolver.resolve(endpointHost.getSchemeName(), endpointHost);
remoteAddresses = this.dnsResolver.resolve(endpointHost.getHostName(), port);
}
+
+ // A specific, non-ephemeral local port can only ever be bound by one socket at a
+ // time; racing would bind several attempts to it concurrently, and the OS would
+ // reject all but one with a bind conflict instead of a real connect failure. Fall
+ // back to the existing sequential path in that case, exactly as before this feature,
+ // since only one attempt is ever in flight there.
+ final boolean canRace = localAddress == null || localAddress.getPort() == 0;
+ if (happyEyeballsEnabled && canRace && remoteAddresses.size() > 1) {
+ onBeforeSocketConnect(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} racing connection attempts across {} ({})", endpointHost, remoteAddresses, connectTimeout);
+ }
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(connectionAttemptDelay);
+ final Socket socket = connector.connect(endpointHost, remoteAddresses, (remoteAddress, socketConsumer) -> {
+ final Socket attemptSocket = detachedSocketFactory.create(endpointHost.getSchemeName(), socksProxy);
+ socketConsumer.accept(attemptSocket);
+ try {
+ if (localAddress != null) {
+ attemptSocket.bind(localAddress);
+ }
+ configureSocket(attemptSocket, socketConfig, true);
+ attemptSocket.connect(remoteAddress, TimeValue.isPositive(connectTimeout) ? connectTimeout.toMillisecondsIntBound() : 0);
+ return attemptSocket;
+ } catch (final IOException | RuntimeException ex) {
+ Closer.closeQuietly(attemptSocket);
+ throw ex;
+ }
+ });
+ // The winner is already TCP-connected; identify its address so a TLS failure
+ // below can fall back to whichever addresses the race did not settle on,
+ // without retrying this one.
+ final InetSocketAddress winnerAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
+ try {
+ conn.bind(socket);
+ onAfterSocketConnect(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} {} connected {}->{}", ConnPoolSupport.getId(conn), endpointHost, conn.getLocalAddress(), conn.getRemoteAddress());
+ }
+ final TlsSocketStrategy tlsSocketStrategy = tlsSocketStrategyLookup != null ? tlsSocketStrategyLookup.lookup(endpointHost.getSchemeName()) : null;
+ if (tlsSocketStrategy != null) {
+ upgradeToTls(conn, endpointHost, endpointName, connectTimeout, attachment, context, tlsSocketStrategy, socket);
+ }
+ } catch (final RuntimeException ex) {
+ Closer.closeQuietly(socket);
+ throw ex;
+ } catch (final IOException ex) {
+ Closer.closeQuietly(socket);
+ final List remaining = withoutAddress(remoteAddresses, winnerAddress);
+ if (remaining.isEmpty()) {
+ throw ConnectExceptionSupport.enhance(ex, endpointHost);
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} connection to {} failed after racing ({}); retrying connection to the remaining address(es)", endpointHost, winnerAddress, ex.getClass());
+ }
+ connectSequentially(conn, endpointHost, endpointName, localAddress, remaining, connectTimeout, socketConfig, attachment, context, socksProxy);
+ return;
+ }
+ return;
+ }
+
+ connectSequentially(conn, endpointHost, endpointName, localAddress, remoteAddresses, connectTimeout, socketConfig, attachment, context, socksProxy);
+ }
+
+ /**
+ * Removes the first occurrence of {@code excluded} from {@code addresses}, preserving the
+ * order of the rest.
+ */
+ private static List withoutAddress(
+ final List addresses, final InetSocketAddress excluded) {
+ final List remaining = new ArrayList<>(addresses.size());
+ boolean removedOne = false;
+ for (final InetSocketAddress address : addresses) {
+ if (!removedOne && address.equals(excluded)) {
+ removedOne = true;
+ continue;
+ }
+ remaining.add(address);
+ }
+ return remaining;
+ }
+
+ /**
+ * Connects to each of {@code remoteAddresses} in turn, stopping at the first one that
+ * completes both the TCP connection and, where configured, the TLS handshake. An
+ * {@link IOException} from either step moves on to the next address; the last address's
+ * failure is rethrown, enhanced via {@link ConnectExceptionSupport}. A {@link
+ * RuntimeException} is never retried, exactly as on the address it was thrown for.
+ */
+ private void connectSequentially(
+ final ManagedHttpClientConnection conn,
+ final HttpHost endpointHost,
+ final NamedEndpoint endpointName,
+ final InetSocketAddress localAddress,
+ final List remoteAddresses,
+ final Timeout connectTimeout,
+ final SocketConfig socketConfig,
+ final Object attachment,
+ final HttpContext context,
+ final Proxy socksProxy) throws IOException {
for (int i = 0; i < remoteAddresses.size(); i++) {
final InetSocketAddress remoteAddress = remoteAddresses.get(i);
final boolean last = i == remoteAddresses.size() - 1;
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java
new file mode 100644
index 0000000000..ffbc0cf640
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java
@@ -0,0 +1,293 @@
+/*
+ * ====================================================================
+ * 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.io;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+
+import org.apache.hc.client5.http.ConnectExceptionSupport;
+import org.apache.hc.core5.concurrent.DefaultThreadFactory;
+import org.apache.hc.core5.io.Closer;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.util.TimeValue;
+
+/**
+ * Races a blocking connect attempt against each of a host's resolved addresses (RFC 8305,
+ * Happy Eyeballs v2) for the Classic (blocking) client. A single dispatcher, running on the
+ * calling thread, starts the first address immediately and each subsequent one on its own
+ * worker thread, bounded to the number of resolved addresses: it waits up to
+ * {@link #connectionAttemptDelay} for an outstanding attempt to finish before starting the
+ * next one, but starts the next one immediately, at the RFC 8305 Section 5 minimum spacing
+ * (10ms), as soon as an attempt fails. No thread ever sleeps out a delay itself.
+ *
+ * The first attempt to connect successfully wins the race. Because closing a socket is
+ * the only reliable way to abort a blocking {@link Socket#connect}, every other socket, be it
+ * already connecting, about to be registered, or not yet created, must end up closed; a
+ * worker thread registers its socket through a shared, atomic registry rather than a bare
+ * reference, so a socket created in the brief window around the race being decided is always
+ * either excluded from cleanup because it does not exist yet, or closed by the registry the
+ * instant it is registered. {@code ExecutorService#shutdownNow()} only interrupts threads; it
+ * does not itself abort a blocking connect, so it is never relied on for that.
+ *
+ * @since 5.7
+ */
+final class HappyEyeballsSocketConnector {
+
+ /**
+ * RFC 8305, Section 5: the minimum spacing between the start of successive connection
+ * attempts, including one started promptly after an earlier attempt's failure.
+ */
+ private static final long MIN_CONNECTION_ATTEMPT_DELAY_MS = 10;
+
+ /**
+ * Connects a single socket to {@code remoteAddress}, registering the socket via
+ * {@code socketConsumer} as soon as it is created and before the (blocking) connect
+ * call, so that a concurrent winner can close it even while still connecting.
+ */
+ @FunctionalInterface
+ interface ConnectAttempt {
+ Socket connect(InetSocketAddress remoteAddress, Consumer socketConsumer) throws IOException;
+ }
+
+ /**
+ * Registers each attempt's socket so it can be closed by whichever happens first: this
+ * race deciding a winner, or the socket being registered. {@link #decide} and
+ * {@link #register} coordinate purely through {@link #decided} and the per-slot
+ * {@link AtomicReference}, so neither a socket registered just before {@link #decide}
+ * runs nor one registered just after is ever left open: {@link #decide} closes whatever
+ * it finds already registered, and {@link #register} closes its own socket immediately
+ * if it finds the registry already decided, including re-checking right after
+ * registering to catch a {@link #decide} that ran in between.
+ */
+ private static final class SocketRegistry {
+
+ private final AtomicReference[] slots;
+ private final AtomicBoolean decided = new AtomicBoolean(false);
+
+ @SuppressWarnings("unchecked")
+ SocketRegistry(final int n) {
+ slots = new AtomicReference[n];
+ for (int i = 0; i < n; i++) {
+ slots[i] = new AtomicReference<>();
+ }
+ }
+
+ void register(final int index, final Socket socket) {
+ if (decided.get()) {
+ Closer.closeQuietly(socket);
+ return;
+ }
+ slots[index].set(socket);
+ if (decided.get() && slots[index].compareAndSet(socket, null)) {
+ Closer.closeQuietly(socket);
+ }
+ }
+
+ /** Closes every registered socket except {@code winner} (may be {@code null}). */
+ void decide(final Socket winner) {
+ decided.set(true);
+ for (final AtomicReference slot : slots) {
+ final Socket socket = slot.getAndSet(null);
+ if (socket != null && socket != winner) {
+ Closer.closeQuietly(socket);
+ }
+ }
+ }
+ }
+
+ private final TimeValue connectionAttemptDelay;
+
+ HappyEyeballsSocketConnector(final TimeValue connectionAttemptDelay) {
+ this.connectionAttemptDelay = connectionAttemptDelay;
+ }
+
+ Socket connect(
+ final NamedEndpoint remoteEndpoint,
+ final List remoteAddresses,
+ final ConnectAttempt connectAttempt) throws IOException {
+ final int n = remoteAddresses.size();
+ final ExecutorService executor = Executors.newFixedThreadPool(
+ n, new DefaultThreadFactory("Happy-eyeballs-classic-connect", true));
+ final SocketRegistry registry = new SocketRegistry(n);
+ final List> futures = new ArrayList<>(n);
+ Socket winner = null;
+ try {
+ final ExecutorCompletionService completionService = new ExecutorCompletionService<>(executor);
+ futures.add(submit(completionService, 0, remoteAddresses, connectAttempt, registry));
+ int started = 1;
+ long lastStartNanos = System.nanoTime();
+ IOException lastFailure = null;
+
+ for (int received = 0; received < n && winner == null; ) {
+ final Future completed;
+ if (started < n) {
+ final long waitMs = pendingDelayMs(lastStartNanos, connectionAttemptDelay.toMilliseconds());
+ completed = poll(completionService, waitMs);
+ if (completed == null) {
+ // Nothing finished within the delay: start the next address now.
+ futures.add(submit(completionService, started, remoteAddresses, connectAttempt, registry));
+ started++;
+ lastStartNanos = System.nanoTime();
+ continue;
+ }
+ } else {
+ completed = take(completionService);
+ }
+ received++;
+
+ final Outcome outcome;
+ try {
+ outcome = completed.get();
+ } catch (final ExecutionException ex) {
+ final Throwable cause = ex.getCause();
+ lastFailure = cause instanceof IOException ? (IOException) cause : new IOException(cause);
+ continue;
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ if (outcome.socket != null) {
+ winner = outcome.socket;
+ for (final Future future : futures) {
+ future.cancel(true);
+ }
+ break;
+ }
+ if (outcome.failure != null) {
+ lastFailure = outcome.failure;
+ }
+ if (started < n) {
+ // Advance as promptly as RFC 8305 allows, but never closer than the
+ // minimum spacing to the most recently started attempt.
+ final long waitMs = pendingDelayMs(lastStartNanos, MIN_CONNECTION_ATTEMPT_DELAY_MS);
+ if (waitMs > 0) {
+ sleepOrAbort(waitMs);
+ }
+ futures.add(submit(completionService, started, remoteAddresses, connectAttempt, registry));
+ started++;
+ lastStartNanos = System.nanoTime();
+ }
+ }
+ if (winner != null) {
+ return winner;
+ }
+ throw lastFailure != null ?
+ ConnectExceptionSupport.enhance(lastFailure, remoteEndpoint) :
+ new IOException("Connection to " + remoteEndpoint + " failed for an unknown reason");
+ } finally {
+ // The single point of truth for cleanup, covering every exit path (winner found,
+ // every address failed, or this method itself was interrupted): closes every
+ // socket except the winner (if any), including ones registered concurrently with
+ // this call. shutdownNow() only interrupts worker threads; it cannot itself abort
+ // a blocking Socket#connect, so the registry above is what actually does that.
+ registry.decide(winner);
+ executor.shutdownNow();
+ }
+ }
+
+ private static long pendingDelayMs(final long lastStartNanos, final long targetDelayMs) {
+ final long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastStartNanos);
+ return Math.max(0, targetDelayMs - elapsedMs);
+ }
+
+ /**
+ * Blocks the dispatcher thread itself for a bounded, short minimum-spacing gap (at most
+ * {@link #MIN_CONNECTION_ATTEMPT_DELAY_MS}). Unlike the per-address stagger this replaces,
+ * this never delays a worker thread's connect attempt and never exceeds a few
+ * milliseconds, so it does not amount to the blocking the rest of this class avoids. An
+ * interruption here must abort racing immediately, exactly like one during {@link #poll}
+ * or {@link #take}: it is propagated rather than swallowed, so the caller's {@code finally}
+ * block runs cleanup and no further attempt is started.
+ */
+ private static void sleepOrAbort(final long millis) throws InterruptedIOException {
+ try {
+ Thread.sleep(millis);
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ }
+
+ private static Future poll(final ExecutorCompletionService completionService, final long timeoutMs) throws InterruptedIOException {
+ try {
+ return completionService.poll(timeoutMs, TimeUnit.MILLISECONDS);
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ }
+
+ private static Future take(final ExecutorCompletionService completionService) throws InterruptedIOException {
+ try {
+ return completionService.take();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ }
+
+ private static Future submit(
+ final ExecutorCompletionService completionService,
+ final int index,
+ final List remoteAddresses,
+ final ConnectAttempt connectAttempt,
+ final SocketRegistry registry) {
+ final InetSocketAddress remoteAddress = remoteAddresses.get(index);
+ return completionService.submit(() -> {
+ try {
+ final Socket socket = connectAttempt.connect(remoteAddress, socket1 -> registry.register(index, socket1));
+ return new Outcome(socket, null);
+ } catch (final IOException ex) {
+ return new Outcome(null, ex);
+ }
+ });
+ }
+
+ private static final class Outcome {
+ final Socket socket;
+ final IOException failure;
+
+ Outcome(final Socket socket, final IOException failure) {
+ this.socket = socket;
+ this.failure = failure;
+ }
+ }
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java
index 5256d32033..4fe6a21ca4 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java
@@ -65,6 +65,8 @@ public class PoolingHttpClientConnectionManagerBuilder {
private TlsSocketStrategy tlsSocketStrategy;
private SchemePortResolver schemePortResolver;
private DnsResolver dnsResolver;
+ private boolean happyEyeballsEnabled;
+ private TimeValue connectionAttemptDelay;
private PoolConcurrencyPolicy poolConcurrencyPolicy;
private PoolReusePolicy poolReusePolicy;
private Resolver socketConfigResolver;
@@ -145,6 +147,41 @@ public final PoolingHttpClientConnectionManagerBuilder setDnsResolver(final DnsR
return this;
}
+ /**
+ * Enables RFC 8305 (Happy Eyeballs v2) connection racing for hosts that resolve to more
+ * than one address: the first address is tried immediately, on its own thread, and each
+ * subsequent one on its own thread after {@link #setConnectionAttemptDelay(TimeValue)}
+ * unless an outstanding attempt fails first. The first successful connection wins; every
+ * other attempt's socket is closed. Disabled ({@code false}) by default, in which case
+ * addresses continue to be tried sequentially on the calling thread.
+ * This feature is considered experimental and may be discontinued in the future.
+ *
+ * @param happyEyeballsEnabled whether to race connection attempts.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingHttpClientConnectionManagerBuilder setHappyEyeballsEnabled(final boolean happyEyeballsEnabled) {
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ return this;
+ }
+
+ /**
+ * Sets the delay between the start of successive connection attempts when
+ * {@link #setHappyEyeballsEnabled(boolean)} is enabled. RFC 8305 Section 8 recommends
+ * 250ms and requires at least 10ms. Has no effect unless Happy Eyeballs racing is enabled.
+ *
+ * @param connectionAttemptDelay the delay, or {@code null} to use the RFC 8305
+ * recommended default of 250ms.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingHttpClientConnectionManagerBuilder setConnectionAttemptDelay(final TimeValue connectionAttemptDelay) {
+ this.connectionAttemptDelay = connectionAttemptDelay;
+ return this;
+ }
+
/**
* Sets {@link SchemePortResolver} instance.
*
@@ -346,7 +383,9 @@ protected HttpClientConnectionOperator createConnectionOperator(
dnsResolver,
RegistryBuilder.create()
.register(URIScheme.HTTPS.id, tlsSocketStrategy)
- .build());
+ .build(),
+ happyEyeballsEnabled,
+ connectionAttemptDelay);
}
public PoolingHttpClientConnectionManager build() {
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java
index 64b7dbe9bb..4bdcf06189 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java
@@ -33,6 +33,8 @@
import java.net.SocketAddress;
import java.nio.file.Path;
import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SchemePortResolver;
@@ -45,10 +47,10 @@
import org.apache.hc.client5.http.routing.RoutingSupport;
import org.apache.hc.core5.annotation.Internal;
import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.concurrent.ComplexCancellable;
import org.apache.hc.core5.concurrent.ComplexFuture;
import org.apache.hc.core5.concurrent.FutureCallback;
-import org.apache.hc.core5.concurrent.FutureContribution;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.Lookup;
@@ -60,6 +62,7 @@
import org.apache.hc.core5.reactor.IOSession;
import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,9 +88,21 @@ protected DefaultAsyncClientConnectionOperator(
final Lookup tlsStrategyLookup,
final SchemePortResolver schemePortResolver,
final DnsResolver dnsResolver) {
+ this(tlsStrategyLookup, schemePortResolver, dnsResolver, false, null);
+ }
+
+ /**
+ * @since 5.7
+ */
+ protected DefaultAsyncClientConnectionOperator(
+ final Lookup tlsStrategyLookup,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
this.tlsStrategyLookup = Args.notNull(tlsStrategyLookup, "TLS strategy lookup");
this.schemePortResolver = schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE;
- this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver);
+ this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver, happyEyeballsEnabled, connectionAttemptDelay);
}
@Override
@@ -146,10 +161,24 @@ public Future connect(
LOG.debug("{} connecting {}->{} ({})", endpointHost, localAddress, remoteAddress, connectTimeout);
}
+ // Set by the validator once an attempt is accepted; may run more than once with
+ // racing or multiple resolved addresses.
+ final AtomicReference acceptedConnection = new AtomicReference<>();
+
// The session request may complete before connect returns, and its callback can register the
// TLS handshake with the future. Install a holder first so the session request cannot replace it.
final ComplexCancellable sessionCancellable = new ComplexCancellable();
future.setDependency(sessionCancellable);
+ // sessionFuture is not available yet when the validator below is built; this holder lets
+ // cancelSessionFuture reach it once connect() returns.
+ final AtomicReference> sessionFutureRef = new AtomicReference<>();
+ final Cancellable cancelSessionFuture = () -> {
+ final Future sf = sessionFutureRef.get();
+ return sf != null && sf.cancel(true);
+ };
+ // Set before connect() is called: a synchronous ConnectionInitiator can invoke the
+ // validator, which moves the dependency on, before connect() returns.
+ sessionCancellable.setDependency(cancelSessionFuture);
final Future sessionFuture = sessionRequester.connect(
connectionInitiator,
remoteEndpoint,
@@ -157,56 +186,96 @@ public Future connect(
localAddress,
connectTimeout,
tlsConfig.getHttpVersionPolicy(),
- new FutureCallback() {
+ (session, validated) -> {
+ // Runs the TLS handshake as the session requester's validation step; see
+ // MultihomeIOSessionRequester.SessionValidator.
+ final DefaultManagedAsyncClientConnection connection = new DefaultManagedAsyncClientConnection(session);
+ onAfterSocketConnect(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} {} connected {}->{}", ConnPoolSupport.getId(connection), endpointHost,
+ connection.getLocalAddress(), connection.getRemoteAddress());
+ }
+ final TlsStrategy tlsStrategy = tlsStrategyLookup != null ? tlsStrategyLookup.lookup(endpointHost.getSchemeName()) : null;
+ if (tlsStrategy != null) {
+ // Guards against a TlsStrategy that reports and then throws: only the
+ // first signal counts, not a double-advance of the fallback.
+ final AtomicBoolean settled = new AtomicBoolean();
+ try {
+ final Timeout socketTimeout = connection.getSocketTimeout();
+ final Timeout handshakeTimeout = tlsConfig.getHandshakeTimeout() != null ? tlsConfig.getHandshakeTimeout() : connectTimeout;
+ final NamedEndpoint tlsName = endpointName != null ? endpointName : endpointHost;
+ // The session request is already done; track closing this connection
+ // instead while the handshake is in flight. Reverts to
+ // cancelSessionFuture on rejection.
+ sessionCancellable.setDependency(() -> {
+ connection.close(CloseMode.IMMEDIATE);
+ return true;
+ });
+ onBeforeTlsHandshake(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} {} upgrading to TLS", ConnPoolSupport.getId(connection), tlsName);
+ }
+ tlsStrategy.upgrade(
+ connection,
+ tlsName,
+ attachment,
+ handshakeTimeout,
+ new FutureCallback() {
- @Override
- public void completed(final IOSession session) {
- final DefaultManagedAsyncClientConnection connection = new DefaultManagedAsyncClientConnection(session);
- onAfterSocketConnect(context, endpointHost);
- if (LOG.isDebugEnabled()) {
- LOG.debug("{} {} connected {}->{}", ConnPoolSupport.getId(connection), endpointHost,
- connection.getLocalAddress(), connection.getRemoteAddress());
- }
- final TlsStrategy tlsStrategy = tlsStrategyLookup != null ? tlsStrategyLookup.lookup(endpointHost.getSchemeName()) : null;
- if (tlsStrategy != null) {
- try {
- final Timeout socketTimeout = connection.getSocketTimeout();
- final Timeout handshakeTimeout = tlsConfig.getHandshakeTimeout() != null ? tlsConfig.getHandshakeTimeout() : connectTimeout;
- final NamedEndpoint tlsName = endpointName != null ? endpointName : endpointHost;
- // The session request is already done, so cancelling it would not stop
- // the handshake. Close the connection instead.
- future.setDependency(() -> {
- connection.close(CloseMode.IMMEDIATE);
- return true;
- });
- onBeforeTlsHandshake(context, endpointHost);
- if (LOG.isDebugEnabled()) {
- LOG.debug("{} {} upgrading to TLS", ConnPoolSupport.getId(connection), tlsName);
- }
- tlsStrategy.upgrade(
- connection,
- tlsName,
- attachment,
- handshakeTimeout,
- new FutureContribution(future) {
-
- @Override
- public void completed(final TransportSecurityLayer transportSecurityLayer) {
- connection.setSocketTimeout(socketTimeout);
- future.completed(connection);
- onAfterTlsHandshake(context, endpointHost);
- if (LOG.isDebugEnabled()) {
- LOG.debug("{} {} upgraded to TLS", ConnPoolSupport.getId(connection), tlsName);
- }
+ @Override
+ public void completed(final TransportSecurityLayer transportSecurityLayer) {
+ if (!settled.compareAndSet(false, true)) {
+ return;
+ }
+ // Report before the hook runs, so a throwing hook cannot
+ // orphan an already-accepted result.
+ connection.setSocketTimeout(socketTimeout);
+ acceptedConnection.set(connection);
+ validated.completed(session);
+ onAfterTlsHandshake(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} {} upgraded to TLS", ConnPoolSupport.getId(connection), tlsName);
+ }
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ if (!settled.compareAndSet(false, true)) {
+ return;
+ }
+ sessionCancellable.setDependency(cancelSessionFuture);
+ validated.failed(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ if (!settled.compareAndSet(false, true)) {
+ return;
}
+ // Unlike #failed, cancellation is terminal: nothing
+ // tries another address afterward.
+ validated.cancelled();
+ }
- });
- } catch (final Exception ex) {
- future.failed(ex);
+ });
+ } catch (final Exception ex) {
+ if (!settled.compareAndSet(false, true)) {
+ return;
}
- } else {
- future.completed(connection);
+ sessionCancellable.setDependency(cancelSessionFuture);
+ validated.failed(ex);
}
+ } else {
+ acceptedConnection.set(connection);
+ validated.completed(session);
+ }
+ },
+ new FutureCallback() {
+
+ @Override
+ public void completed(final IOSession session) {
+ // The validator already built and TLS-upgraded whichever attempt was accepted.
+ future.completed(acceptedConnection.get());
}
@Override
@@ -220,7 +289,8 @@ public void cancelled() {
}
});
- sessionCancellable.setDependency(() -> sessionFuture.cancel(true));
+ // Does not move sessionCancellable's dependency; the validator may already have.
+ sessionFutureRef.set(sessionFuture);
return future;
}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java
index 2e8e00bbf0..04ff6e09e1 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java
@@ -38,6 +38,7 @@
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
/**
@@ -58,6 +59,36 @@ public MultihomeConnectionInitiator(
this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver);
}
+ /**
+ * Creates a multi-home connection initiator that, for hosts resolving to more than one
+ * address, optionally races connection attempts per RFC 8305 (Happy Eyeballs v2) instead
+ * of trying each address sequentially: the first address is tried immediately, and each
+ * subsequent one after {@code connectionAttemptDelay} unless an outstanding attempt fails
+ * first. The first successful connection wins; every other attempt is cancelled, and a
+ * connection that completes after a winner was already decided is closed rather than kept
+ * open. When {@code happyEyeballsEnabled} is {@code false}, behavior is identical to
+ * {@link #MultihomeConnectionInitiator(ConnectionInitiator, DnsResolver)}.
+ *
+ * @param connectionInitiator the connection initiator.
+ * @param dnsResolver the DNS resolver to use.
+ * @param happyEyeballsEnabled whether to race connection attempts instead of trying them
+ * sequentially.
+ * @param connectionAttemptDelay delay between the start of successive connection attempts
+ * (RFC 8305 Section 8 recommends 250ms; must be at least
+ * 10ms). Ignored when {@code happyEyeballsEnabled} is
+ * {@code false}. May be {@code null} to use the RFC 8305
+ * recommended default.
+ * @since 5.7
+ */
+ public MultihomeConnectionInitiator(
+ final ConnectionInitiator connectionInitiator,
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
+ this.connectionInitiator = Args.notNull(connectionInitiator, "Connection initiator");
+ this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver, happyEyeballsEnabled, connectionAttemptDelay);
+ }
+
@Override
public Future connect(
final NamedEndpoint remoteEndpoint,
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java
index 4b8172c4ce..0197d5d338 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java
@@ -32,18 +32,31 @@
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
+import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Consumer;
import org.apache.hc.client5.http.ConnectExceptionSupport;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
+import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.concurrent.ComplexFuture;
+import org.apache.hc.core5.concurrent.DefaultThreadFactory;
import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.net.NamedEndpoint;
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -51,10 +64,65 @@
final class MultihomeIOSessionRequester {
private static final Logger LOG = LoggerFactory.getLogger(MultihomeIOSessionRequester.class);
+
+ /**
+ * RFC 8305, Section 8: "When a reasonable value is unknown, implementations SHOULD use a
+ * Connection Attempt Delay of 250 milliseconds".
+ */
+ static final TimeValue DEFAULT_CONNECTION_ATTEMPT_DELAY = TimeValue.ofMilliseconds(250);
+
+ /**
+ * RFC 8305, Section 8: "this value SHOULD NOT be below 10 ms".
+ */
+ private static final long MIN_CONNECTION_ATTEMPT_DELAY_MS = 10;
+
+ /**
+ * Lazily initialized, process-wide, single daemon-thread scheduler used solely to pace
+ * staggered connection attempts (RFC 8305 connection racing). Shared across all instances
+ * so that enabling this feature never adds a thread per connection manager, let alone per
+ * connection or per request.
+ */
+ private static final class LazyStaggerScheduler {
+ static final ScheduledExecutorService INSTANCE = Executors.newSingleThreadScheduledExecutor(
+ new DefaultThreadFactory("Connection-attempt-stagger", true));
+ }
+
private final DnsResolver dnsResolver;
+ private final boolean happyEyeballsEnabled;
+ private final TimeValue connectionAttemptDelay;
+ private final ScheduledExecutorService staggerScheduler;
MultihomeIOSessionRequester(final DnsResolver dnsResolver) {
+ this(dnsResolver, false, DEFAULT_CONNECTION_ATTEMPT_DELAY);
+ }
+
+ MultihomeIOSessionRequester(
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
+ this(dnsResolver, happyEyeballsEnabled, connectionAttemptDelay, null);
+ }
+
+ // Package-private: allows unit tests to supply a deterministic, synchronous scheduler
+ // instead of the real, time-based one.
+ MultihomeIOSessionRequester(
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay,
+ final ScheduledExecutorService staggerScheduler) {
this.dnsResolver = dnsResolver != null ? dnsResolver : SystemDefaultDnsResolver.INSTANCE;
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ final TimeValue delay = connectionAttemptDelay != null ? connectionAttemptDelay : DEFAULT_CONNECTION_ATTEMPT_DELAY;
+ if (happyEyeballsEnabled) {
+ Args.check(delay.toMilliseconds() >= MIN_CONNECTION_ATTEMPT_DELAY_MS,
+ "Connection attempt delay must be at least %s ms (RFC 8305, Section 8)", MIN_CONNECTION_ATTEMPT_DELAY_MS);
+ }
+ this.connectionAttemptDelay = delay;
+ this.staggerScheduler = staggerScheduler;
+ }
+
+ private ScheduledExecutorService staggerScheduler() {
+ return staggerScheduler != null ? staggerScheduler : LazyStaggerScheduler.INSTANCE;
}
public Future connect(
@@ -65,6 +133,27 @@ public Future connect(
final Timeout connectTimeout,
final Object attachment,
final FutureCallback callback) {
+ return connect(connectionInitiator, remoteEndpoint, remoteAddress, localAddress, connectTimeout, attachment, null, callback);
+ }
+
+ /**
+ * Same as {@link #connect(ConnectionInitiator, NamedEndpoint, SocketAddress, SocketAddress,
+ * Timeout, Object, FutureCallback)}, but every session this call connects is first passed to
+ * {@code validator}, if one is given, before being reported as the final outcome.
+ *
+ * @param validator accepts or rejects a freshly connected session; may be {@code null} to
+ * accept every connected session unconditionally, as the overload without
+ * this parameter does.
+ */
+ Future connect(
+ final ConnectionInitiator connectionInitiator,
+ final NamedEndpoint remoteEndpoint,
+ final SocketAddress remoteAddress,
+ final SocketAddress localAddress,
+ final Timeout connectTimeout,
+ final Object attachment,
+ final SessionValidator validator,
+ final FutureCallback callback) {
final ComplexFuture future = new ComplexFuture<>(callback);
if (remoteAddress != null) {
@@ -75,7 +164,12 @@ public Future connect(
final Future sessionFuture = connectionInitiator.connect(remoteEndpoint, remoteAddress, localAddress, connectTimeout, attachment, new FutureCallback() {
@Override
public void completed(final IOSession session) {
- future.completed(session);
+ acceptOrReject(session, validator, future,
+ // A single, explicitly given address has no fallback to offer.
+ cause -> enhanceAndFail(future, remoteEndpoint, cause,
+ (remoteAddress instanceof InetSocketAddress) ?
+ new InetAddress[] { ((InetSocketAddress) remoteAddress).getAddress() } :
+ new InetAddress[] {}));
}
@Override
@@ -84,14 +178,10 @@ public void failed(final Exception cause) {
LOG.debug("{}:{} connection to {} failed ({}); terminating operation",
remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
}
- if (cause instanceof IOException) {
- future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint,
- (remoteAddress instanceof InetSocketAddress) ?
- new InetAddress[] { ((InetSocketAddress) remoteAddress).getAddress() } :
- new InetAddress[] {}));
- } else {
- future.failed(cause);
- }
+ enhanceAndFail(future, remoteEndpoint, cause,
+ (remoteAddress instanceof InetSocketAddress) ?
+ new InetAddress[] { ((InetSocketAddress) remoteAddress).getAddress() } :
+ new InetAddress[] {});
}
@Override
@@ -123,11 +213,139 @@ public void cancelled() {
LOG.debug("{} resolved to {}", remoteEndpoint.getHostName(), remoteAddresses);
}
+ if (happyEyeballsEnabled && remoteAddresses.size() > 1) {
+ final Race race = new Race(connectionInitiator, remoteEndpoint, remoteAddresses, localAddress,
+ connectTimeout, attachment, validator, future);
+ race.start();
+ return future;
+ }
+
+ connectSequentially(connectionInitiator, remoteEndpoint, remoteAddresses, localAddress,
+ connectTimeout, attachment, validator, future);
+ return future;
+ }
+
+ public Future connect(
+ final ConnectionInitiator connectionInitiator,
+ final NamedEndpoint remoteEndpoint,
+ final SocketAddress localAddress,
+ final Timeout connectTimeout,
+ final Object attachment,
+ final FutureCallback callback) {
+ return connect(connectionInitiator, remoteEndpoint, null, localAddress, connectTimeout, attachment, null, callback);
+ }
+
+ /**
+ * Accepts or rejects a session that has just connected, before {@link #connect} reports it
+ * as the final outcome. A rejected session is closed and {@link #connect} tries the next
+ * address, if one remains, the same as a TCP-level connect failure. Within a race, a
+ * rejection ends racing; the remaining addresses, if any, are tried sequentially (see
+ * {@link Race#onWinnerRejected}).
+ */
+ @FunctionalInterface
+ interface SessionValidator {
+ void validate(IOSession session, FutureCallback callback);
+ }
+
+ private static void enhanceAndFail(
+ final ComplexFuture future,
+ final NamedEndpoint remoteEndpoint,
+ final Exception cause,
+ final InetAddress[] addresses) {
+ if (cause instanceof IOException) {
+ future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, addresses));
+ } else {
+ future.failed(cause);
+ }
+ }
+
+ /**
+ * Runs {@code validator} against a freshly connected {@code session}, if one is given;
+ * otherwise accepts the session unconditionally. On rejection, closes the session and
+ * invokes {@code onRejected} with the rejection cause so the caller can fall back to
+ * another address, or fail outright if none remains.
+ */
+ private static void acceptOrReject(
+ final IOSession session,
+ final SessionValidator validator,
+ final ComplexFuture future,
+ final Consumer onRejected) {
+ if (validator == null) {
+ deliver(session, future);
+ return;
+ }
+ validator.validate(session, new FutureCallback() {
+ @Override
+ public void completed(final IOSession validatedSession) {
+ deliver(validatedSession, future);
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ session.close(CloseMode.IMMEDIATE);
+ onRejected.accept(cause);
+ }
+
+ @Override
+ public void cancelled() {
+ session.close(CloseMode.IMMEDIATE);
+ future.cancel();
+ }
+ });
+ }
+
+ /**
+ * Completes {@code future} with {@code session}, unless it was already completed or
+ * cancelled by something else (for example the caller, concurrently) in the brief window
+ * before this call: {@link ComplexFuture#completed} reports that by returning {@code false},
+ * in which case the session must still be closed here rather than silently leaked.
+ */
+ private static void deliver(final IOSession session, final ComplexFuture future) {
+ if (!future.completed(session)) {
+ session.close(CloseMode.IMMEDIATE);
+ }
+ }
+
+ /**
+ * Connects to each of {@code remoteAddresses} in turn, stopping at the first one that
+ * completes both the TCP connection and, where {@code validator} is given, its check. A
+ * TCP-level failure or a validator rejection moves on to the next address; the last
+ * address's failure is reported via {@code future}, enhanced via
+ * {@link ConnectExceptionSupport}.
+ */
+ private void connectSequentially(
+ final ConnectionInitiator connectionInitiator,
+ final NamedEndpoint remoteEndpoint,
+ final List remoteAddresses,
+ final SocketAddress localAddress,
+ final Timeout connectTimeout,
+ final Object attachment,
+ final SessionValidator validator,
+ final ComplexFuture future) {
+
final Runnable runnable = new Runnable() {
private final AtomicInteger attempt = new AtomicInteger(0);
+ // Guards executeNext() against a cross-thread rejection racing the attempt-index
+ // check below. A same-thread, reentrant rejection is fine either way: ReentrantLock
+ // permits the recursive re-entry, and the index check still catches it.
+ private final ReentrantLock lock = new ReentrantLock();
+
void executeNext() {
+ lock.lock();
+ try {
+ executeNextLocked();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void executeNextLocked() {
+ if (future.isDone()) {
+ // Already cancelled or completed; starting another attempt would leak it.
+ return;
+ }
final int index = attempt.getAndIncrement();
final InetSocketAddress remoteAddress = remoteAddresses.get(index);
@@ -150,32 +368,12 @@ public void completed(final IOSession session) {
LOG.debug("{}:{} connected {}->{} as {}",
remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId());
}
- future.completed(session);
+ acceptOrReject(session, validator, future, cause -> onFailure(remoteAddress, cause));
}
@Override
public void failed(final Exception cause) {
- if (attempt.get() >= remoteAddresses.size()) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("{}:{} connection to {} failed ({}); terminating operation",
- remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
- }
- if (cause instanceof IOException) {
- final InetAddress[] addresses = remoteAddresses.stream()
- .filter(addr -> addr instanceof InetSocketAddress)
- .map(addr -> ((InetSocketAddress) addr).getAddress())
- .toArray(InetAddress[]::new);
- future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, addresses));
- } else {
- future.failed(cause);
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("{}:{} connection to {} failed ({}); retrying connection to the next address",
- remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
- }
- executeNext();
- }
+ onFailure(remoteAddress, cause);
}
@Override
@@ -184,7 +382,37 @@ public void cancelled() {
}
});
- future.setDependency(sessionFuture);
+ // A reentrant rejection above may already have started the next attempt and set
+ // its dependency; skip this now-stale assignment in that case.
+ if (attempt.get() == index + 1) {
+ // ComplexFuture#setDependency's isDone()-then-set is not atomic; a cancel()
+ // landing between the two is lost. Fixing that needs a change to ComplexFuture.
+ future.setDependency(sessionFuture);
+ }
+ }
+
+ private void onFailure(final InetSocketAddress remoteAddress, final Exception cause) {
+ if (future.isDone()) {
+ // Already cancelled or completed; starting another attempt would leak it.
+ return;
+ }
+ if (attempt.get() >= remoteAddresses.size()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection to {} failed ({}); terminating operation",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
+ }
+ final InetAddress[] addresses = remoteAddresses.stream()
+ .filter(addr -> addr instanceof InetSocketAddress)
+ .map(addr -> ((InetSocketAddress) addr).getAddress())
+ .toArray(InetAddress[]::new);
+ enhanceAndFail(future, remoteEndpoint, cause, addresses);
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection to {} failed ({}); retrying connection to the next address",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
+ }
+ executeNext();
+ }
}
@Override
@@ -194,17 +422,347 @@ public void run() {
};
runnable.run();
- return future;
}
- public Future connect(
- final ConnectionInitiator connectionInitiator,
- final NamedEndpoint remoteEndpoint,
- final SocketAddress localAddress,
- final Timeout connectTimeout,
- final Object attachment,
- final FutureCallback callback) {
- return connect(connectionInitiator, remoteEndpoint, null, localAddress, connectTimeout, attachment, callback);
+ /**
+ * RFC 8305 connection racing: the first address is tried immediately; each subsequent
+ * address is tried after {@link #connectionAttemptDelay} unless an outstanding attempt
+ * fails first, in which case the next address is tried immediately. The first successful
+ * connection wins: all other outstanding attempts are cancelled, and any connection that
+ * completes successfully after a winner has already been decided is closed rather than
+ * leaked. Exactly one terminal callback (success or aggregated failure) ever reaches
+ * {@code future}.
+ */
+ private final class Race implements Cancellable {
+
+ private final ConnectionInitiator connectionInitiator;
+ private final NamedEndpoint remoteEndpoint;
+ private final List remoteAddresses;
+ private final SocketAddress localAddress;
+ private final Timeout connectTimeout;
+ private final Object attachment;
+ private final SessionValidator validator;
+ private final ComplexFuture future;
+
+ private final ReentrantLock lock = new ReentrantLock();
+ private final List> inFlight = new ArrayList<>();
+ private int nextIndex;
+ private int outstanding;
+ private boolean decided;
+ private boolean cancelled;
+ private ScheduledFuture> pendingStagger;
+ private long lastAttemptStartNanos = -1L;
+
+ Race(
+ final ConnectionInitiator connectionInitiator,
+ final NamedEndpoint remoteEndpoint,
+ final List remoteAddresses,
+ final SocketAddress localAddress,
+ final Timeout connectTimeout,
+ final Object attachment,
+ final SessionValidator validator,
+ final ComplexFuture future) {
+ this.connectionInitiator = connectionInitiator;
+ this.remoteEndpoint = remoteEndpoint;
+ this.remoteAddresses = remoteAddresses;
+ this.localAddress = localAddress;
+ this.connectTimeout = connectTimeout;
+ this.attachment = attachment;
+ this.validator = validator;
+ this.future = future;
+ // A single Cancellable dependency covers every attempt this race ever starts,
+ // including ones not yet started when the caller cancels (see #cancel()).
+ this.future.setDependency(this);
+ }
+
+ void start() {
+ lock.lock();
+ try {
+ scheduleNextPromptlyLocked();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * Starts the next address now if at least the RFC 8305 Section 5 minimum
+ * inter-attempt spacing (10ms) has passed since the last attempt was started,
+ * including one that just failed or was unexpectedly cancelled; otherwise schedules
+ * it for exactly the remaining part of that minimum. Used whenever an attempt should
+ * advance as promptly as RFC 8305 allows, rather than waiting out the full
+ * {@link #connectionAttemptDelay}.
+ *
+ * Must be called while holding {@code lock}.
+ */
+ private void scheduleNextPromptlyLocked() {
+ if (decided || cancelled || nextIndex >= remoteAddresses.size()) {
+ return;
+ }
+ if (lastAttemptStartNanos < 0) {
+ startNextLocked();
+ return;
+ }
+ final long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastAttemptStartNanos);
+ if (elapsedMs >= MIN_CONNECTION_ATTEMPT_DELAY_MS) {
+ startNextLocked();
+ } else {
+ pendingStagger = staggerScheduler().schedule(
+ this::onStaggerElapsed, MIN_CONNECTION_ATTEMPT_DELAY_MS - elapsedMs, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ // Must be called while holding `lock`.
+ private void startNextLocked() {
+ if (decided || cancelled || nextIndex >= remoteAddresses.size()) {
+ return;
+ }
+ final int index = nextIndex++;
+ final InetSocketAddress remoteAddress = remoteAddresses.get(index);
+ outstanding++;
+ lastAttemptStartNanos = System.nanoTime();
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} racing attempt {} {}->{} ({})",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), index, localAddress, remoteAddress, connectTimeout);
+ }
+
+ final Future attemptFuture = connectionInitiator.connect(
+ remoteEndpoint,
+ remoteAddress,
+ localAddress,
+ connectTimeout,
+ attachment,
+ new FutureCallback() {
+
+ @Override
+ public void completed(final IOSession session) {
+ onAttemptCompleted(remoteAddress, session);
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ onAttemptFailed(remoteAddress, cause);
+ }
+
+ @Override
+ public void cancelled() {
+ onAttemptCancelled(remoteAddress);
+ }
+
+ });
+ inFlight.add(attemptFuture);
+
+ // pendingStagger != null here means the attempt above already completed
+ // synchronously and its own failure/cancellation handler already scheduled the
+ // next advance (possibly at the shorter minimum spacing): don't overwrite it.
+ if (!decided && !cancelled && pendingStagger == null && nextIndex < remoteAddresses.size()) {
+ pendingStagger = staggerScheduler().schedule(
+ this::onStaggerElapsed, connectionAttemptDelay.getDuration(), connectionAttemptDelay.getTimeUnit());
+ }
+ }
+
+ private void onStaggerElapsed() {
+ lock.lock();
+ try {
+ pendingStagger = null;
+ startNextLocked();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOSession session) {
+ final boolean won;
+ final List> losers;
+ lock.lock();
+ try {
+ outstanding--;
+ won = !decided && !cancelled;
+ if (won) {
+ decided = true;
+ cancelPendingStaggerLocked();
+ losers = new ArrayList<>(inFlight);
+ } else {
+ losers = null;
+ }
+ } finally {
+ lock.unlock();
+ }
+ if (won) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} race won by {}->{} as {}",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId());
+ }
+ for (final Future loser : losers) {
+ loser.cancel(true);
+ }
+ acceptOrReject(session, validator, future, cause -> onWinnerRejected(remoteAddress, cause));
+ } else {
+ // A duplicate winner (concurrent success) or a late completion after the
+ // race was already decided/cancelled: never leak the socket.
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} discarding late successful connection {}->{} ({})",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId());
+ }
+ session.close(CloseMode.IMMEDIATE);
+ }
+ }
+
+ /**
+ * The race's winner failed {@link #validator}'s check. Racing is over: every other
+ * in-flight attempt was already cancelled, and any address not yet attempted is tried
+ * sequentially from here on, the same as the non-racing path.
+ */
+ private void onWinnerRejected(final InetSocketAddress winnerAddress, final Exception cause) {
+ final List remaining = withoutAddress(remoteAddresses, winnerAddress);
+ if (remaining.isEmpty()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection to {} failed validation after racing ({}); no address remains",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), winnerAddress, cause.getClass());
+ }
+ enhanceAndFail(future, remoteEndpoint, cause, new InetAddress[] { winnerAddress.getAddress() });
+ return;
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection to {} failed validation after racing ({}); retrying connection to the remaining address(es)",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), winnerAddress, cause.getClass());
+ }
+ connectSequentially(connectionInitiator, remoteEndpoint, remaining, localAddress,
+ connectTimeout, attachment, validator, future);
+ }
+
+ private void onAttemptFailed(final InetSocketAddress remoteAddress, final Exception cause) {
+ boolean advance = false;
+ boolean last = false;
+ lock.lock();
+ try {
+ outstanding--;
+ if (decided || cancelled) {
+ return;
+ }
+ cancelPendingStaggerLocked();
+ if (nextIndex < remoteAddresses.size()) {
+ advance = true;
+ } else if (outstanding == 0) {
+ decided = true;
+ last = true;
+ }
+ if (advance) {
+ // RFC 8305 Section 5: advance to the next address as promptly as possible
+ // after a failure, never waiting out the full connection attempt delay,
+ // but still respecting the minimum inter-attempt spacing.
+ scheduleNextPromptlyLocked();
+ }
+ } finally {
+ lock.unlock();
+ }
+ if (last) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection to {} failed ({}); all addresses exhausted",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
+ }
+ finish(cause);
+ }
+ }
+
+ /**
+ * An attempt may be cancelled by something other than this race itself deciding a
+ * winner or being cancelled as a whole, for example an external close of the
+ * connection manager. Treat it exactly like a failure so the overall future never
+ * stays pending forever: advance to the next address if one remains, or finish with a
+ * failure if none does.
+ */
+ private void onAttemptCancelled(final InetSocketAddress remoteAddress) {
+ boolean advance = false;
+ boolean last = false;
+ lock.lock();
+ try {
+ outstanding--;
+ if (decided || cancelled) {
+ // Expected: either this race decided a winner and cancelled every other
+ // attempt itself, or the whole race was cancelled from the outside.
+ return;
+ }
+ cancelPendingStaggerLocked();
+ if (nextIndex < remoteAddresses.size()) {
+ advance = true;
+ } else if (outstanding == 0) {
+ decided = true;
+ last = true;
+ }
+ if (advance) {
+ scheduleNextPromptlyLocked();
+ }
+ } finally {
+ lock.unlock();
+ }
+ if (last) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection attempt to {} was unexpectedly cancelled; all addresses exhausted",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress);
+ }
+ finish(new CancellationException(
+ "Connection attempt to " + remoteAddress + " was cancelled"));
+ }
+ }
+
+ private void finish(final Exception cause) {
+ if (cause instanceof IOException) {
+ final InetAddress[] addresses = remoteAddresses.stream()
+ .map(InetSocketAddress::getAddress)
+ .toArray(InetAddress[]::new);
+ future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, addresses));
+ } else {
+ future.failed(cause);
+ }
+ }
+
+ @Override
+ public boolean cancel() {
+ final List> toCancel;
+ lock.lock();
+ try {
+ if (decided || cancelled) {
+ return false;
+ }
+ cancelled = true;
+ cancelPendingStaggerLocked();
+ toCancel = new ArrayList<>(inFlight);
+ } finally {
+ lock.unlock();
+ }
+ for (final Future attemptFuture : toCancel) {
+ attemptFuture.cancel(true);
+ }
+ return true;
+ }
+
+ // Must be called while holding `lock`.
+ private void cancelPendingStaggerLocked() {
+ if (pendingStagger != null) {
+ pendingStagger.cancel(false);
+ pendingStagger = null;
+ }
+ }
+
+ }
+
+ /**
+ * Removes the first occurrence of {@code excluded} from {@code addresses}, preserving the
+ * order of the rest.
+ */
+ private static List withoutAddress(
+ final List addresses, final InetSocketAddress excluded) {
+ final List remaining = new ArrayList<>(addresses.size());
+ boolean removedOne = false;
+ for (final InetSocketAddress address : addresses) {
+ if (!removedOne && address.equals(excluded)) {
+ removedOne = true;
+ continue;
+ }
+ remaining.add(address);
+ }
+ return remaining;
}
}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java
index a4e1b8fe48..17900c9017 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java
@@ -35,6 +35,7 @@
import org.apache.hc.client5.http.nio.AsyncClientConnectionOperator;
import org.apache.hc.client5.http.ssl.ConscryptClientTlsStrategy;
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
+import org.apache.hc.core5.annotation.Experimental;
import org.apache.hc.core5.annotation.Internal;
import org.apache.hc.core5.function.Resolver;
import org.apache.hc.core5.http.HttpHost;
@@ -57,6 +58,8 @@ public class PoolingAsyncClientConnectionManagerBuilder {
private TlsStrategy tlsStrategy;
private SchemePortResolver schemePortResolver;
private DnsResolver dnsResolver;
+ private boolean happyEyeballsEnabled;
+ private TimeValue connectionAttemptDelay;
private PoolConcurrencyPolicy poolConcurrencyPolicy;
private PoolReusePolicy poolReusePolicy;
@@ -99,6 +102,40 @@ public final PoolingAsyncClientConnectionManagerBuilder setDnsResolver(final Dns
return this;
}
+ /**
+ * Enables RFC 8305 (Happy Eyeballs v2) connection racing for hosts that resolve to more
+ * than one address: the first address is tried immediately, and each subsequent one after
+ * {@link #setConnectionAttemptDelay(TimeValue)} unless an outstanding attempt fails first.
+ * The first successful connection wins; every other attempt is cancelled. Disabled
+ * ({@code false}) by default, in which case addresses continue to be tried sequentially.
+ * This feature is considered experimental and may be discontinued in the future.
+ *
+ * @param happyEyeballsEnabled whether to race connection attempts.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingAsyncClientConnectionManagerBuilder setHappyEyeballsEnabled(final boolean happyEyeballsEnabled) {
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ return this;
+ }
+
+ /**
+ * Sets the delay between the start of successive connection attempts when
+ * {@link #setHappyEyeballsEnabled(boolean)} is enabled. RFC 8305 Section 8 recommends
+ * 250ms and requires at least 10ms. Has no effect unless Happy Eyeballs racing is enabled.
+ *
+ * @param connectionAttemptDelay the delay, or {@code null} to use the RFC 8305
+ * recommended default of 250ms.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingAsyncClientConnectionManagerBuilder setConnectionAttemptDelay(final TimeValue connectionAttemptDelay) {
+ this.connectionAttemptDelay = connectionAttemptDelay;
+ return this;
+ }
+
/**
* Sets {@link SchemePortResolver} instance.
*
@@ -267,12 +304,27 @@ protected AsyncClientConnectionOperator createConnectionOperator(
final TlsStrategy tlsStrategy,
final SchemePortResolver schemePortResolver,
final DnsResolver dnsResolver) {
+ return createConnectionOperator(tlsStrategy, schemePortResolver, dnsResolver, false, null);
+ }
+
+ /**
+ * @since 5.7
+ */
+ @Internal
+ protected AsyncClientConnectionOperator createConnectionOperator(
+ final TlsStrategy tlsStrategy,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
return new DefaultAsyncClientConnectionOperator(
RegistryBuilder.create()
.register(URIScheme.HTTPS.getId(), tlsStrategy)
.build(),
schemePortResolver,
- dnsResolver);
+ dnsResolver,
+ happyEyeballsEnabled,
+ connectionAttemptDelay);
}
public PoolingAsyncClientConnectionManager build() {
@@ -287,7 +339,8 @@ public PoolingAsyncClientConnectionManager build() {
}
}
final PoolingAsyncClientConnectionManager poolingmgr = new PoolingAsyncClientConnectionManager(
- createConnectionOperator(tlsStrategyCopy, schemePortResolver, dnsResolver),
+ createConnectionOperator(tlsStrategyCopy, schemePortResolver, dnsResolver,
+ happyEyeballsEnabled, connectionAttemptDelay),
poolConcurrencyPolicy,
poolReusePolicy,
null,
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java
new file mode 100644
index 0000000000..ee42db20f5
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java
@@ -0,0 +1,657 @@
+/*
+ * ====================================================================
+ * 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 static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.hc.client5.http.config.ProtocolFamilyPreference;
+import org.apache.hc.client5.http.impl.InMemoryDnsResolver;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class AddressSelectingDnsResolverTest {
+
+ private static final AddressSelectingDnsResolver.SourceAddressResolver NO_SOURCE_ADDR =
+ (final InetSocketAddress dest) -> null;
+
+ private InMemoryDnsResolver delegate;
+
+ @BeforeEach
+ void setUp() {
+ delegate = new InMemoryDnsResolver();
+ }
+
+ @Test
+ void ipv4Only_filtersOutIPv6() throws Exception {
+ final InetAddress v4 = inet("203.0.113.10"); // TEST-NET-3
+ final InetAddress v6 = inet("2001:db8::10"); // documentation prefix
+
+ delegate.add("dual.example", v6, v4);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ final InetAddress[] ordered = r.resolve("dual.example");
+ assertEquals(1, ordered.length);
+ assertInstanceOf(Inet4Address.class, ordered[0]);
+ assertEquals(v4, ordered[0]);
+ }
+
+ @Test
+ void ipv6Only_filtersOutIPv4() throws Exception {
+ final InetAddress v4 = inet("192.0.2.1"); // TEST-NET-1
+ final InetAddress v6 = inet("2001:db8::1");
+
+ delegate.add("dual.example", v4, v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV6_ONLY, NO_SOURCE_ADDR);
+
+ final InetAddress[] ordered = r.resolve("dual.example");
+ assertEquals(1, ordered.length);
+ assertInstanceOf(Inet6Address.class, ordered[0]);
+ assertEquals(v6, ordered[0]);
+ }
+
+ @Test
+ void ipv4Only_emptyWhenNoIPv4Candidates() throws Exception {
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v6b = inet("2001:db8::2");
+
+ delegate.add("v6only.example", v6a, v6b);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ final InetAddress[] ordered = r.resolve("v6only.example");
+ assertNull(ordered);
+ }
+
+ @Test
+ void default_hasNoFamilyBias() throws Exception {
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v6b = inet("2001:db8::2");
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v4b = inet("203.0.113.10");
+
+ delegate.add("dual.example", v6a, v6b, v4a, v4b);
+
+ final AddressSelectingDnsResolver r1 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+ final AddressSelectingDnsResolver r2 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+
+ final InetAddress[] out1 = r1.resolve("dual.example");
+ final InetAddress[] out2 = r2.resolve("dual.example");
+
+ assertArrayEquals(out1, out2);
+ assertEquals(4, out1.length);
+ }
+
+ @Test
+ void interleave_alternatesFamilies_preservingRelativeOrder_whenRfcSortIsNoop() throws Exception {
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v6b = inet("2001:db8::2");
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v4b = inet("203.0.113.10");
+
+ // With NO_SOURCE_ADDR, RFC sort becomes a stable no-op; deterministic interleave.
+ delegate.add("dual.example", v6a, v6b, v4a, v4b);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = r.resolve("dual.example");
+ assertEquals(Arrays.asList(v6a, v4a, v6b, v4b), Arrays.asList(out));
+ }
+
+ @Test
+ void preferIpv6_groupsAllV6First_preservingRelativeOrder_whenRfcSortIsNoop() throws Exception {
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v4b = inet("203.0.113.10");
+ final InetAddress v6b = inet("2001:db8::2");
+
+ delegate.add("dual.example", v4a, v6a, v4b, v6b);
+
+ final AddressSelectingDnsResolver preferV6 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.PREFER_IPV6, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = preferV6.resolve("dual.example");
+ assertEquals(Arrays.asList(v6a, v6b, v4a, v4b), Arrays.asList(out));
+ assertInstanceOf(Inet6Address.class, out[0]);
+ }
+
+ @Test
+ void filtersOutMulticastDestinations() throws Exception {
+ final InetAddress multicastV6 = inet("ff02::1");
+ final InetAddress v6 = inet("2001:db8::1");
+
+ delegate.add("mcast.example", multicastV6, v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = r.resolve("mcast.example");
+ assertEquals(1, out.length);
+ assertEquals(v6, out[0]);
+ }
+
+ // -------------------------------------------------------------------------
+ // Direct tests for classifyScope(..) and Scope.fromValue(..)
+ // -------------------------------------------------------------------------
+
+ @Test
+ void classifyScope_ipv6Loopback_isLinkLocal() throws Exception {
+ // ::1 maps to link-local scope; interface-local (0x1) is multicast-only (RFC 4291 §2.7).
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("::1")));
+ }
+
+ @Test
+ void classifyScope_ipv4Loopback_isLinkLocal() throws Exception {
+ // IPv4 127/8 maps to link-local, NOT interface-local (RFC 6724 §3.1).
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("127.0.0.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("127.255.255.255")));
+ }
+
+ @Test
+ void classifyScope_linkLocal() throws Exception {
+ // IPv4 169.254/16 → link-local.
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("169.254.0.1")));
+ // IPv6 fe80::/10 → link-local.
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("fe80::1")));
+ }
+
+ @Test
+ void classifyScope_ipv4Private_isGlobal() throws Exception {
+ // RFC 6724: all IPv4 except 127/8 and 169.254/16 are global,
+ // including RFC1918 (10/8, 172.16/12, 192.168/16) and 100.64/10.
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("10.0.0.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("172.16.0.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("192.168.1.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("100.64.0.1")));
+ }
+
+ @Test
+ void classifyScope_ipv6SiteLocal() throws Exception {
+ // IPv6 deprecated site-local (fec0::/10) still classified as site-local per RFC 6724.
+ assertEquals(AddressSelectingDnsResolver.Scope.SITE_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("fec0::1")));
+ }
+
+ @Test
+ void classifyScope_global() throws Exception {
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("8.8.8.8")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("2003::1")));
+ }
+
+ @Test
+ void classifyScope_ipv6Multicast_usesLowNibbleScope() throws Exception {
+ // ff01::1 -> scope 0x1 -> INTERFACE_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.INTERFACE_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff01::1")));
+ // ff02::1 -> scope 0x2 -> LINK_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff02::1")));
+ // ff04::1 -> scope 0x4 -> ADMIN_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.ADMIN_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff04::1")));
+ // ff05::1 -> scope 0x5 -> SITE_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.SITE_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff05::1")));
+ // ff08::1 -> scope 0x8 -> ORG_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.ORG_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff08::1")));
+ // ff0e::1 -> scope 0xe -> GLOBAL
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff0e::1")));
+ }
+
+ @Test
+ void scopeFromValue_mapsKnownConstants() {
+ assertEquals(AddressSelectingDnsResolver.Scope.INTERFACE_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x1));
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x2));
+ assertEquals(AddressSelectingDnsResolver.Scope.ADMIN_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x4));
+ assertEquals(AddressSelectingDnsResolver.Scope.SITE_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x5));
+ assertEquals(AddressSelectingDnsResolver.Scope.ORG_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x8));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0xe));
+ }
+
+ @Test
+ void scopeFromValue_throwsOnUnknownValue() {
+ assertThrows(IllegalArgumentException.class,
+ () -> AddressSelectingDnsResolver.Scope.fromValue(0x0));
+ assertThrows(IllegalArgumentException.class,
+ () -> AddressSelectingDnsResolver.Scope.fromValue(0x3));
+ assertThrows(IllegalArgumentException.class,
+ () -> AddressSelectingDnsResolver.Scope.fromValue(0xf));
+ }
+
+ @Test
+ void rfcRule2_prefersMatchingScope() throws Exception {
+ final InetAddress aDst = inet("2001:db8::1");
+ final InetAddress bDst = inet("2001:db8::2");
+
+ // A matches scope (GLOBAL == GLOBAL); B mismatches (GLOBAL != LINK_LOCAL)
+ final InetAddress aSrc = inet("2001:db8::abcd");
+ final InetAddress bSrc = inet("fe80::1");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule5_prefersMatchingLabel() throws Exception {
+ final InetAddress aDst = inet("2001:db8::1"); // label 5 (2001::/32)
+ final InetAddress bDst = inet("2001:db8::2"); // label 5
+
+ final InetAddress aSrc = inet("2001:db8::abcd"); // label 5 -> matches A
+ final InetAddress bSrc = inet("::ffff:192.0.2.1"); // label 4 -> does not match B
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule6_prefersHigherPrecedence() throws Exception {
+ final InetAddress aDst = inet("::1"); // precedence 50 (policy ::1)
+ final InetAddress bDst = inet("2001:db8::1"); // precedence 5 (policy 2001::/32)
+
+ final InetAddress aSrc = inet("::1");
+ final InetAddress bSrc = inet("2001:db8::abcd");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule8_prefersSmallerScope_whenPrecedenceAndLabelTie() throws Exception {
+ // Both fall to ::/0 policy -> precedence 40, label 1, but different scopes.
+ final InetAddress aDst = inet("fe80::1"); // LINK_LOCAL scope (0x2)
+ final InetAddress bDst = inet("2003::1"); // GLOBAL scope (0xe)
+
+ final InetAddress aSrc = inet("fe80::2"); // LINK_LOCAL, label 1
+ final InetAddress bSrc = inet("2003::2"); // GLOBAL, label 1
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule9_prefersLongestMatchingPrefix_ipv6Only() throws Exception {
+ // Both in same policy (::/0 -> prec 40, label 1), same scope (GLOBAL).
+ // A's source shares a longer prefix with its destination than B's.
+ final InetAddress aDst = inet("2003::1");
+ final InetAddress bDst = inet("2003::1:0:0:1");
+
+ // aSrc shares a full /64 with aDst; bSrc only shares /48.
+ final InetAddress aSrc = inet("2003::2");
+ final InetAddress bSrc = inet("2003::2:0:0:1");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ // A has longer common prefix (src=2003::2, dst=2003::1 share 127 bits)
+ // B has shorter common prefix (src=2003::2:0:0:1, dst=2003::1:0:0:1 share 79 bits)
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void classifyScope_unknownMulticastNibble_fallsBackToGlobal() throws Exception {
+ // ff03::1 -> scope nibble 0x3, which is not a known Scope constant.
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff03::1")));
+ }
+
+ @Test
+ void addr_fmt_simpleName() throws Exception {
+ assertEquals("null", AddressSelectingDnsResolver.addr(null));
+
+ final InetAddress v4 = inet("192.0.2.1");
+ final InetAddress v6 = inet("2001:db8::1");
+
+ assertEquals("IPv4(" + v4.getHostAddress() + ")", AddressSelectingDnsResolver.addr(v4));
+ assertEquals("IPv6(" + v6.getHostAddress() + ")", AddressSelectingDnsResolver.addr(v6));
+
+ assertEquals(Arrays.asList("IPv6(" + v6.getHostAddress() + ")", "IPv4(" + v4.getHostAddress() + ")"),
+ AddressSelectingDnsResolver.fmt(new InetAddress[]{v6, v4}));
+
+ assertEquals(Arrays.asList("IPv4(" + v4.getHostAddress() + ")", "IPv6(" + v6.getHostAddress() + ")"),
+ AddressSelectingDnsResolver.fmt(Arrays.asList(v4, v6)));
+
+ }
+
+ private static InetAddress inet(final String s) {
+ try {
+ return InetAddress.getByName(s);
+ } catch (final UnknownHostException ex) {
+ throw new AssertionError(ex);
+ }
+ }
+
+ private static AddressSelectingDnsResolver.SourceAddressResolver sourceMap(
+ final InetAddress aDst, final InetAddress aSrc,
+ final InetAddress bDst, final InetAddress bSrc) {
+ return (final InetSocketAddress dest) -> {
+ final InetAddress d = dest.getAddress();
+ if (aDst.equals(d)) {
+ return aSrc;
+ }
+ if (bDst.equals(d)) {
+ return bSrc;
+ }
+ return null;
+ };
+ }
+
+
+ @Test
+ void ipv4Only_filtersSingleV6Address() throws Exception {
+ // Regression: a single IPv6 address must still be filtered when IPV4_ONLY is set.
+ final InetAddress v6 = inet("2001:db8::1");
+ delegate.add("v6.example", v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ assertNull(r.resolve("v6.example"));
+ }
+
+ @Test
+ void resolveHostPort_appliesRfc6724Ordering() throws Exception {
+ final InetAddress v4 = inet("192.0.2.1");
+ final InetAddress v6 = inet("2001:db8::1");
+
+ delegate.add("dual.example", v4, v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ final List out = r.resolve("dual.example", 443);
+ assertEquals(1, out.size());
+ assertEquals(new InetSocketAddress(v4, 443), out.get(0));
+ }
+
+ @Test
+ void resolveHostPort_throwsWhenAllFilteredOut() throws Exception {
+ // Only IPv6 addresses, but IPV4_ONLY is requested.
+ // Must throw rather than returning an unresolved address that bypasses filtering.
+ delegate.add("v6.example", inet("2001:db8::1"));
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ assertThrows(UnknownHostException.class, () -> r.resolve("v6.example", 443));
+ }
+
+ @Test
+ void rfcRule9_appliesToIpv4Pairs() throws Exception {
+ // Both IPv4, same policy (::ffff:0:0/96 → prec 35, label 4), same scope (GLOBAL).
+ // Rule 9 should prefer the address whose source shares a longer prefix.
+ final InetAddress aDst = inet("192.0.2.1");
+ final InetAddress bDst = inet("203.0.113.1");
+
+ // aSrc shares 24 bits with aDst (192.0.2.x); bSrc shares only 8 bits with bDst (203 vs 203).
+ final InetAddress aSrc = inet("192.0.2.100");
+ final InetAddress bSrc = inet("203.0.114.1");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ // aSrc-aDst share more prefix bits than bSrc-bDst, so aDst should come first.
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void ipAttrOf_ipv4_usesMappedPolicyPrecedenceAndLabel() throws Exception {
+ // RFC 6724 §2.1 Table 2: ::ffff:0:0/96 -> precedence 35, label 4.
+ //
+ // Regression: InetAddress.getByName("::ffff:0:0") collapses to a 4-byte
+ // Inet4Address on the JDK. Network#contains() always compares IPv4
+ // destinations against their 16-byte mapped form, so a policy entry built
+ // from that collapsed 4-byte address never matched any IPv4 destination;
+ // every IPv4 address silently fell through to the ::/0 default
+ // (precedence 40, label 1) instead.
+ final AddressSelectingDnsResolver.Attr attr =
+ AddressSelectingDnsResolver.ipAttrOf(inet("192.0.2.1"));
+ assertEquals(35, attr.precedence);
+ assertEquals(4, attr.label);
+ }
+
+ @Test
+ void networkContains_ipv6Prefix32() throws Exception {
+ final AddressSelectingDnsResolver.Network p32 =
+ new AddressSelectingDnsResolver.Network(inet("2001:db8::").getAddress(), 32);
+
+ assertTrue(p32.contains(inet("2001:db8::1")));
+ assertTrue(p32.contains(inet("2001:db8:ffff::1")));
+
+ assertFalse(p32.contains(inet("2001:db9::1")));
+ assertFalse(p32.contains(inet("2000:db8::1")));
+ }
+
+ @Test
+ void networkContains_ipv4IsMatchedViaV4MappedWhenPrefixIsV6Mapped96() throws Exception {
+ // Build ::ffff:0:0 as raw 16 bytes. Do NOT use InetAddress.getByName(..) here:
+ // the JDK may normalize it to an Inet4Address, yielding a 4-byte array.
+ final byte[] v6mapped = new byte[16];
+ v6mapped[10] = (byte) 0xff;
+ v6mapped[11] = (byte) 0xff;
+
+ final AddressSelectingDnsResolver.Network p96 =
+ new AddressSelectingDnsResolver.Network(v6mapped, 96);
+
+ assertTrue(p96.contains(inet("192.0.2.1")));
+ assertTrue(p96.contains(inet("203.0.113.10")));
+
+ // A pure IPv6 address must not match that v4-mapped prefix.
+ assertFalse(p96.contains(inet("2001:db8::1")));
+ }
+
+ @Test
+ void networkContains_nonByteAlignedPrefix7Boundary() throws Exception {
+ // fc00::/7 (ULA) is in the policy table.
+ final AddressSelectingDnsResolver.Network p7 =
+ new AddressSelectingDnsResolver.Network(inet("fc00::").getAddress(), 7);
+
+ // Inside /7: fc00:: and fd00:: (since /7 covers fc00..fdff)
+ assertTrue(p7.contains(inet("fc00::1")));
+ assertTrue(p7.contains(inet("fd00::1")));
+
+ // Just outside /7: fe00:: (top bits 11111110 vs 1111110x)
+ assertFalse(p7.contains(inet("fe00::1")));
+ assertFalse(p7.contains(inet("2001:db8::1")));
+ }
+
+ @Test
+ void sortByRfc6724_globalIpv6IsPreferredOverGlobalIpv4() throws Exception {
+ // End-to-end regression for the ::ffff:0:0/96 construction bug: a plain global
+ // IPv4 destination (precedence 35) must rank behind a plain global IPv6
+ // destination (precedence 40, the ::/0 default), not ahead of it as it would
+ // when the broken policy entry silently fell through to precedence 40 too.
+ final InetAddress v4Dst = inet("192.0.2.1");
+ final InetAddress v6Dst = inet("2003::1");
+
+ final InetAddress v4Src = inet("192.0.2.100");
+ final InetAddress v6Src = inet("2003::2");
+
+ delegate.add("t.example", v4Dst, v6Dst);
+
+ final AddressSelectingDnsResolver r = new AddressSelectingDnsResolver(
+ delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(v6Dst, v6Src, v4Dst, v4Src));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(v6Dst, v4Dst), Arrays.asList(out));
+ }
+
+ @Test
+ void preferIpv4_groupsAllV4First_preservingRelativeOrder_whenRfcSortIsNoop() throws Exception {
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v4b = inet("203.0.113.10");
+ final InetAddress v6b = inet("2001:db8::2");
+
+ delegate.add("dual.example", v6a, v4a, v6b, v4b);
+
+ final AddressSelectingDnsResolver preferV4 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.PREFER_IPV4, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = preferV4.resolve("dual.example");
+ assertEquals(Arrays.asList(v4a, v4b, v6a, v6b), Arrays.asList(out));
+ assertInstanceOf(Inet4Address.class, out[0]);
+ }
+
+ @Test
+ void rfcRule1_bothSourcesUnusable_orderIsPreserved() throws Exception {
+ final InetAddress aDst = inet("2001:db8::1");
+ final InetAddress bDst = inet("2001:db8::2");
+
+ delegate.add("t.example", aDst, bDst);
+
+ // Every destination resolves to no usable source address.
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule1_onlyOneSourceUsable_usableDestinationIsPreferred() throws Exception {
+ final InetAddress usableDst = inet("2001:db8::1");
+ final InetAddress unusableDst = inet("2001:db8::2");
+
+ delegate.add("t.example", unusableDst, usableDst);
+
+ final AddressSelectingDnsResolver.SourceAddressResolver onlyOneUsable = dest -> {
+ if (usableDst.equals(dest.getAddress())) {
+ return inet("2001:db8::abcd");
+ }
+ return null;
+ };
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, onlyOneUsable);
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(usableDst, unusableDst), Arrays.asList(out));
+ }
+
+ @Test
+ void resolve_singleCandidateOfRequestedFamily_returnedWithoutRfcSort() throws Exception {
+ // The RFC6724 sort (and therefore source-address inference) must be skipped
+ // entirely when only one candidate is left after filtering.
+ final InetAddress v4 = inet("192.0.2.1");
+ delegate.add("single.example", v4);
+
+ final AddressSelectingDnsResolver.SourceAddressResolver failing = dest -> {
+ throw new AssertionError("source inference must not run for a single candidate");
+ };
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, failing);
+
+ final InetAddress[] out = r.resolve("single.example");
+ assertEquals(1, out.length);
+ assertEquals(v4, out[0]);
+ }
+
+ @Test
+ void resolve_doesNotMutateDelegateReturnedArray() throws Exception {
+ final InetAddress v6 = inet("2001:db8::1");
+ final InetAddress v4 = inet("192.0.2.1");
+ final InetAddress[] delegateArray = {v6, v4};
+ delegate.add("dual.example", delegateArray);
+
+ final InetAddress[] before = delegateArray.clone();
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE, NO_SOURCE_ADDR);
+ r.resolve("dual.example");
+
+ assertArrayEquals(before, delegateArray, "resolve() must not mutate the delegate's array in place");
+ }
+
+}
\ No newline at end of file
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java
index 36b3580bee..e3645e6eb6 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/entity/mime/TestMultipartEntityBuilder.java
@@ -324,7 +324,7 @@ void testMultipartWriteToRFC7578ModeWithFilenameStar() throws Exception {
entity.writeTo(out);
out.close();
Assertions.assertEquals("--xxxxxxxxxxxxxxxxxxxxxxxx\r\n" +
- "Content-Disposition: multipart/form-data; name=\"test\"; filename*=\"UTF-8''hello%20%CE%BA%CF%8C%CF%83%CE%BC%CE%B5!%25\"\r\n" +
+ "Content-Disposition: multipart/form-data; name=\"test\"; filename*=UTF-8''hello%20%CE%BA%CF%8C%CF%83%CE%BC%CE%B5!%25\r\n" +
"Content-Type: text/plain; charset=UTF-8\r\n" +
"\r\n" +
"hello \u00ce\u00ba\u00cf\u008c\u00cf\u0083\u00ce\u00bc\u00ce\u00b5!%\r\n" +
@@ -411,7 +411,7 @@ void testMultipartWriteToRFC7578ModeWithFilenameStarPreEncodedPassThrough() thro
final String wire = out.toString(StandardCharsets.ISO_8859_1.name());
// Pass-through EXACTLY the given value (no second prefix, no %25-escaping)
- Assertions.assertTrue(wire.contains("filename*=\"" + preEncoded + "\""));
+ Assertions.assertTrue(wire.contains("filename*=" + preEncoded + "\r\n"));
Assertions.assertFalse(wire.contains("UTF-8''UTF-8%27%27"));
Assertions.assertFalse(wire.contains("%25F0%9F%90%99")); // octopus emoji must not be re-escaped as %25F0...
}
@@ -441,12 +441,29 @@ void testExtendedModeAddBinaryBodyAddsFilenameAndFilenameStar_NoDoubleEncoding()
Assertions.assertTrue(wire.contains("filename=\"" + pct + "\""));
// filename* param (single RFC 5987 value, no double prefix / no %25-escaping)
- Assertions.assertTrue(wire.contains("filename*=\"UTF-8''" + pct + "\""));
+ Assertions.assertTrue(wire.contains("filename*=UTF-8''" + pct + "\r\n"));
// Guard against regressions
Assertions.assertFalse(wire.contains("UTF-8''UTF-8%27%27"));
Assertions.assertFalse(wire.contains("%25F0%9F%90%99"));
}
+ @Test
+ void testDefaultModeNonLatinFilenameWritesUnquotedFilenameStar() throws Exception {
+ // RFC 8187 ext-value must not be quoted, servers such as busboy (multer) drop the part otherwise
+ final MultipartFormEntity entity = MultipartEntityBuilder.create()
+ .setBoundary("xxxxxxxxxxxxxxxxxxxxxxxx")
+ .addBinaryBody("file", new byte[]{1, 2}, ContentType.APPLICATION_OCTET_STREAM,
+ "\uC6D4\uAC04 \uBCF4\uACE0\uC11C.pdf")
+ .buildEntity();
+
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ entity.writeTo(out);
+ out.close();
+ final String wire = out.toString(StandardCharsets.ISO_8859_1.name());
+
+ Assertions.assertTrue(wire.contains("Content-Disposition: form-data; name=\"file\"; filename=\"?? ???.pdf\"; " +
+ "filename*=UTF-8''%EC%9B%94%EA%B0%84%20%EB%B3%B4%EA%B3%A0%EC%84%9C.pdf\r\n"), wire);
+ }
}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java
new file mode 100644
index 0000000000..a7c6656da7
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java
@@ -0,0 +1,79 @@
+/*
+ * ====================================================================
+ * 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.examples;
+
+import java.net.InetAddress;
+
+import org.apache.hc.client5.http.DnsResolver;
+import org.apache.hc.client5.http.AddressSelectingDnsResolver;
+import org.apache.hc.client5.http.SystemDefaultDnsResolver;
+import org.apache.hc.client5.http.config.ProtocolFamilyPreference;
+
+public final class AddressSelectingDnsResolverExample {
+
+ public static void main(final String[] args) throws Exception {
+ final String host = args.length > 0 ? args[0] : "localhost";
+ final ProtocolFamilyPreference pref = args.length > 1
+ ? ProtocolFamilyPreference.valueOf(args[1])
+ : ProtocolFamilyPreference.DEFAULT;
+
+ System.out.println("Host: " + host);
+ System.out.println("Preference: " + pref);
+ System.out.println();
+
+ // Before: raw system resolver output (no RFC 6724 ordering).
+ final InetAddress[] raw = SystemDefaultDnsResolver.INSTANCE.resolve(host);
+ System.out.println("Before (system resolver):");
+ printAddresses(raw);
+
+ // After: RFC 6724 ordered + family preference applied.
+ final DnsResolver resolver = new AddressSelectingDnsResolver(SystemDefaultDnsResolver.INSTANCE, pref);
+ final InetAddress[] out = resolver.resolve(host);
+ System.out.println("After (AddressSelectingDnsResolver, " + pref + "):");
+ printAddresses(out);
+ }
+
+ private static void printAddresses(final InetAddress[] addresses) {
+ if (addresses == null) {
+ System.out.println(" null");
+ return;
+ }
+ if (addresses.length == 0) {
+ System.out.println(" []");
+ return;
+ }
+ for (final InetAddress a : addresses) {
+ final String family = a instanceof java.net.Inet6Address ? "IPv6" : "IPv4";
+ System.out.println(" " + family + " " + a.getHostAddress());
+ }
+ System.out.println();
+ }
+
+ private AddressSelectingDnsResolverExample() {
+ }
+}
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/auth/TestAuthenticationHandler.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java
index db2a0015f1..d809336a1e 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java
@@ -208,6 +208,30 @@ void testAuthenticationCredentialsForBasic() throws AuthenticationException, Mal
Assertions.assertNull(options.poll());
}
+ @Test
+ void testAuthenticationMalformedChallengeIgnored() throws AuthenticationException, MalformedChallengeException {
+ final HttpHost host = new HttpHost("somehost", 80);
+ final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
+ response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.BASIC + " realm=\"test\""));
+ response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, ""));
+
+ final Credentials credentials = new UsernamePasswordCredentials("user", "pass".toCharArray());
+ Mockito.when(this.credentialsProvider.getCredentials(Mockito.any(), Mockito.any())).thenReturn(credentials);
+
+ final DefaultAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy();
+
+ Assertions.assertTrue(this.httpAuthenticator.handleResponse(host, ChallengeType.TARGET, response, authStrategy,
+ this.authExchange, this.context));
+ Assertions.assertEquals(AuthExchange.State.CHALLENGED, this.authExchange.getState());
+
+ final Queue options = this.authExchange.getAuthOptions();
+ Assertions.assertNotNull(options);
+ final AuthScheme authScheme1 = options.poll();
+ Assertions.assertNotNull(authScheme1);
+ Assertions.assertEquals(StandardAuthScheme.BASIC, authScheme1.getName());
+ Assertions.assertNull(options.poll());
+ }
+
@Test
void testAuthenticationNoChallenges() throws AuthenticationException, MalformedChallengeException {
final HttpHost host = new HttpHost("somehost", 80);
@@ -529,6 +553,35 @@ void testAuthenticationInfoProcessedOnSuccessResponse() throws Exception {
Assertions.assertEquals("dj1hYmM", getParam(challenge, "data"));
}
+ @Test
+ void testAuthenticationInfoProcessedWithMalformedChallenge() throws Exception {
+ final HttpHost host = new HttpHost("somehost", 80);
+ final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
+ response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, ""));
+ response.addHeader(new BasicHeader("Authentication-Info", "rspauth=\"abc\""));
+
+ final AuthScheme authScheme = Mockito.mock(AuthScheme.class);
+ Mockito.when(authScheme.getName()).thenReturn(StandardAuthScheme.DIGEST);
+ Mockito.when(authScheme.isChallengeExpected()).thenReturn(Boolean.TRUE);
+ Mockito.when(authScheme.isChallengeComplete()).thenReturn(Boolean.FALSE);
+
+ this.authExchange.select(authScheme);
+ this.authExchange.setState(AuthExchange.State.HANDSHAKE);
+
+ final DefaultAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy();
+
+ this.httpAuthenticator.handleResponse(
+ host, ChallengeType.TARGET, response, authStrategy, this.authExchange, this.context);
+
+ final ArgumentCaptor challengeCaptor = ArgumentCaptor.forClass(AuthChallenge.class);
+ Mockito.verify(authScheme).processChallenge(
+ Mockito.eq(host),
+ Mockito.eq(false),
+ challengeCaptor.capture(),
+ Mockito.same(this.context));
+ Assertions.assertEquals("abc", getParam(challengeCaptor.getValue(), "rspauth"));
+ }
+
@Test
void testAuthenticationInfoCombinesMultipleFieldLines() throws Exception {
final HttpHost host = new HttpHost("somehost", 80);
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());
}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestProxyClient.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestProxyClient.java
index 4c14e2c5eb..b049554b32 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestProxyClient.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/classic/TestProxyClient.java
@@ -29,13 +29,17 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
+import java.io.InputStream;
import java.net.Socket;
import org.apache.hc.client5.http.auth.Credentials;
@@ -43,6 +47,7 @@
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.io.ManagedHttpClientConnection;
import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.impl.io.HttpRequestExecutor;
@@ -110,4 +115,32 @@ void testSuccessfulTunnel() throws IOException, HttpException {
assertEquals(mockSocket, resultSocket, "Expected the mock socket to be returned");
}
-}
\ No newline at end of file
+ @Test
+ void testTunnelClosesConnectionWhenConsumingErrorResponseFails() throws IOException, HttpException {
+ final HttpConnectionFactory connFactory = mock(HttpConnectionFactory.class);
+ final ManagedHttpClientConnection managedConnection = mock(ManagedHttpClientConnection.class);
+ when(managedConnection.isOpen()).thenReturn(true);
+ when(connFactory.createConnection(null)).thenReturn(managedConnection);
+
+ final IOException consumeFailure = new IOException("Failed to consume proxy response");
+ final InputStream content = mock(InputStream.class);
+ doThrow(consumeFailure).when(content).close();
+ final HttpEntity entity = mock(HttpEntity.class);
+ when(entity.isStreaming()).thenReturn(true);
+ when(entity.getContent()).thenReturn(content);
+ final ClassicHttpResponse response = mock(ClassicHttpResponse.class);
+ when(response.getCode()).thenReturn(500);
+ when(response.getEntity()).thenReturn(entity);
+ when(managedConnection.receiveResponseHeader()).thenReturn(response);
+
+ final ProxyClient client = new ProxyClient(connFactory, null, null, RequestConfig.DEFAULT);
+ final HttpHost proxy = new HttpHost("proxy.example.com", 8080);
+ final HttpHost target = new HttpHost("target.example.com", 80);
+ final Credentials credentials = new UsernamePasswordCredentials("user", "pass".toCharArray());
+
+ assertSame(consumeFailure, assertThrows(IOException.class,
+ () -> client.tunnel(proxy, target, credentials)));
+ verify(managedConnection).close();
+ }
+
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java
new file mode 100644
index 0000000000..f2d1a33a28
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java
@@ -0,0 +1,277 @@
+/*
+ * ====================================================================
+ * 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.io;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.net.ssl.SSLSocket;
+
+import org.apache.hc.client5.http.DnsResolver;
+import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
+import org.apache.hc.client5.http.io.DetachedSocketFactory;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.http.ssl.TlsSocketStrategy;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.config.Lookup;
+import org.apache.hc.core5.http.io.SocketConfig;
+import org.apache.hc.core5.util.TimeValue;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
+
+class DefaultHttpClientConnectionOperatorTest {
+
+ /**
+ * Regression test: when {@code localAddress} specifies a non-zero (explicit) local port,
+ * Happy Eyeballs racing must not bind more than one socket to it concurrently, which the
+ * OS would reject for all but one attempt as a bind conflict rather than a real connect
+ * failure. The operator falls back to the existing sequential path in that case, so a
+ * dead first address followed by a real, reachable second address must still succeed,
+ * exactly as it would against master without this feature.
+ */
+ @Test
+ void happyEyeballsWithExplicitLocalPort_fallsBackToSequential_stillSucceeds() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ ServerSocket deadPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = deadPortProbe.getLocalPort();
+ deadPortProbe.close(); // nothing listens here once closed: instant refusal
+
+ final int explicitLocalPort;
+ try (ServerSocket localPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ explicitLocalPort = localPortProbe.getLocalPort();
+ }
+
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ DefaultHttpClientConnectionOperator.PLAIN_SOCKET_FACTORY,
+ DefaultSchemePortResolver.INSTANCE,
+ dnsResolver,
+ (Lookup) name -> null,
+ true,
+ TimeValue.ofMilliseconds(20));
+
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+ final InetSocketAddress localAddress = new InetSocketAddress(
+ InetAddress.getLoopbackAddress(), explicitLocalPort);
+
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("http", "somehost", 80), localAddress,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create()));
+
+ assertEquals(listeningPort, ((InetSocketAddress) conn.getRemoteAddress()).getPort());
+ assertEquals(explicitLocalPort, ((InetSocketAddress) conn.getLocalAddress()).getPort());
+ conn.close();
+ }
+ }
+
+ /**
+ * Regression test: on the Happy Eyeballs racing path, a TLS handshake failure after the
+ * TCP race has already picked a winner must still close that winning socket, exactly as
+ * the sequential path's own try/catch around bind + TLS upgrade already does.
+ */
+ @Test
+ void happyEyeballsRacing_tlsHandshakeFailure_closesWinningSocket() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ ServerSocket deadPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = deadPortProbe.getLocalPort();
+ deadPortProbe.close();
+
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final AtomicReference winningSocket = new AtomicReference<>();
+ final DetachedSocketFactory trackingFactory = (final Proxy proxy) -> {
+ final Socket s = new Socket();
+ winningSocket.set(s);
+ return s;
+ };
+
+ final TlsSocketStrategy failingTls = Mockito.mock(TlsSocketStrategy.class);
+ Mockito.when(failingTls.upgrade(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
+ .thenThrow(new IOException("handshake failed"));
+ final Lookup tlsLookup = scheme -> failingTls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ trackingFactory, DefaultSchemePortResolver.INSTANCE, dnsResolver, tlsLookup, true, TimeValue.ofMilliseconds(20));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ assertThrows(IOException.class, () ->
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())));
+
+ assertTrue(winningSocket.get().isClosed(), "the winning socket must be closed when the TLS handshake fails");
+ }
+ }
+
+ /** Same as above, but the TLS strategy throws a RuntimeException rather than an IOException. */
+ @Test
+ void happyEyeballsRacing_tlsHandshakeRuntimeFailure_closesWinningSocket() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ ServerSocket deadPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = deadPortProbe.getLocalPort();
+ deadPortProbe.close();
+
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final AtomicReference winningSocket = new AtomicReference<>();
+ final DetachedSocketFactory trackingFactory = (final Proxy proxy) -> {
+ final Socket s = new Socket();
+ winningSocket.set(s);
+ return s;
+ };
+
+ final TlsSocketStrategy failingTls = Mockito.mock(TlsSocketStrategy.class);
+ Mockito.when(failingTls.upgrade(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
+ .thenThrow(new IllegalStateException("handshake blew up"));
+ final Lookup tlsLookup = scheme -> failingTls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ trackingFactory, DefaultSchemePortResolver.INSTANCE, dnsResolver, tlsLookup, true, TimeValue.ofMilliseconds(20));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ assertThrows(IllegalStateException.class, () ->
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())));
+
+ assertTrue(winningSocket.get().isClosed(), "the winning socket must be closed when the TLS handshake throws unexpectedly");
+ }
+ }
+
+ /**
+ * Regression test (reviewer-supplied probe, PR #936): a TLS failure on the address that
+ * won the TCP race must fall back to the remaining, untried address, exactly as the
+ * sequential (non-racing) path already does. Passes for both {@code happyEyeballs} values.
+ */
+ @ParameterizedTest(name = "happyEyeballs={0}")
+ @ValueSource(booleans = {false, true})
+ void tlsFailureOnFirstAddressFallsBackToNextAddress(final boolean happyEyeballs) throws Exception {
+ try (ServerSocket broken = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ ServerSocket healthy = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), broken.getLocalPort()),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), healthy.getLocalPort()));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final AtomicInteger handshakes = new AtomicInteger();
+ final AtomicInteger upgradedPort = new AtomicInteger();
+ final TlsSocketStrategy tls = (socket, target, port, attachment, context) -> {
+ handshakes.incrementAndGet();
+ if (socket.getPort() == broken.getLocalPort()) {
+ throw new IOException("handshake failed on " + socket.getRemoteSocketAddress());
+ }
+ upgradedPort.set(socket.getPort());
+ return Mockito.mock(SSLSocket.class);
+ };
+ final Lookup tlsLookup = scheme -> tls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ proxy -> new Socket(), DefaultSchemePortResolver.INSTANCE, dnsResolver, tlsLookup,
+ happyEyeballs, TimeValue.ofMilliseconds(250));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create()));
+
+ assertEquals(healthy.getLocalPort(), upgradedPort.get());
+ assertEquals(2, handshakes.get());
+ }
+ }
+
+ /**
+ * Regression test: when the race winner is the only address (no address left to fall
+ * back to), a TLS failure on it still propagates immediately, exactly as before this fix.
+ */
+ @Test
+ void happyEyeballsRacing_tlsHandshakeFailure_noRemainingAddress_propagatesImmediately() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final List remoteAddresses = Collections.singletonList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final TlsSocketStrategy failingTls = Mockito.mock(TlsSocketStrategy.class);
+ Mockito.when(failingTls.upgrade(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
+ .thenThrow(new IOException("handshake failed"));
+ final Lookup tlsLookup = scheme -> failingTls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ DefaultHttpClientConnectionOperator.PLAIN_SOCKET_FACTORY, DefaultSchemePortResolver.INSTANCE,
+ dnsResolver, tlsLookup, true, TimeValue.ofMilliseconds(20));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ // Happy Eyeballs only races when there is more than one address; with a single
+ // address this exercises the sequential path, which is the baseline this fix must
+ // not change when there is nothing left to fall back to.
+ assertThrows(IOException.class, () ->
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())));
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java
new file mode 100644
index 0000000000..eec39052ec
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java
@@ -0,0 +1,340 @@
+/*
+ * ====================================================================
+ * 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.io;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.util.TimeValue;
+import org.junit.jupiter.api.Test;
+
+class HappyEyeballsSocketConnectorTest {
+
+ /** A socket whose {@link #connect} blocks until {@link #close} is called, then fails, matching the real behavior of closing a socket mid-connect. */
+ private static final class BlockingSocket extends Socket {
+
+ private final CountDownLatch closed = new CountDownLatch(1);
+ volatile boolean connectAttempted;
+
+ @Override
+ public void connect(final SocketAddress endpoint, final int timeout) throws IOException {
+ connectAttempted = true;
+ try {
+ closed.await();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ throw new SocketException("Socket closed");
+ }
+
+ @Override
+ public synchronized void close() throws IOException {
+ closed.countDown();
+ super.close();
+ }
+ }
+
+ private static List addresses(final int count) throws Exception {
+ final List out = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ out.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, (byte) i}), 8080));
+ }
+ return out;
+ }
+
+ @Test
+ void singleAddress_connectsWithoutRacing() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final Socket expected = new Socket();
+ final AtomicInteger attempts = new AtomicInteger();
+
+ final Socket actual = connector.connect(new HttpHost("somehost"), addresses(1), (remoteAddress, socketConsumer) -> {
+ attempts.incrementAndGet();
+ socketConsumer.accept(expected);
+ return expected;
+ });
+
+ assertEquals(expected, actual);
+ assertEquals(1, attempts.get());
+ }
+
+ @Test
+ void secondAddressWinsWhileFirstStalls_loserSocketIsClosed() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final BlockingSocket firstSocket = new BlockingSocket();
+ final Socket secondSocket = new Socket();
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ socketConsumer.accept(firstSocket);
+ firstSocket.connect(remoteAddress, 0); // blocks until closed by the race, then throws
+ return firstSocket;
+ }
+ socketConsumer.accept(secondSocket);
+ return secondSocket;
+ }));
+
+ assertEquals(secondSocket, winner);
+ assertTrue(firstSocket.connectAttempted, "the first attempt must have genuinely started connecting");
+ assertTrue(firstSocket.isClosed(), "the losing, still-connecting socket must be closed rather than leaked");
+ }
+
+ @Test
+ void allAddressesFail_aggregatedFailure() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+
+ final IOException ex = assertThrows(IOException.class, () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ throw new IOException("refused: " + remoteAddress);
+ }));
+ assertTrue(ex.getMessage() != null);
+ }
+
+ @Test
+ void firstAddressFailsFast_secondStartsWithoutWaitingOutTheFullDelay() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(250));
+ final Socket winnerSocket = new Socket();
+
+ final long start = System.nanoTime();
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ throw new IOException("refused");
+ }
+ socketConsumer.accept(winnerSocket);
+ return winnerSocket;
+ }));
+ final long elapsedMs = (System.nanoTime() - start) / 1_000_000;
+
+ // The 2nd address must not have had to wait out the 250ms stagger delay, since the
+ // 1st address failed fast rather than merely being slow: it only waits the RFC 8305
+ // minimum inter-attempt spacing (10ms).
+ assertEquals(winnerSocket, winner);
+ assertTrue(elapsedMs < 200, "must advance well before the full stagger delay elapses, took " + elapsedMs + "ms");
+ }
+
+ @Test
+ void interruptionWhileStillRacing_closesLoserSocket() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final BlockingSocket firstSocket = new BlockingSocket();
+ final Socket secondSocket = new Socket();
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ socketConsumer.accept(firstSocket);
+ firstSocket.connect(remoteAddress, 0);
+ return firstSocket;
+ }
+ socketConsumer.accept(secondSocket);
+ return secondSocket;
+ }));
+
+ assertEquals(secondSocket, winner);
+ // The executor's shutdownNow() (called in the finally block) interrupts the still
+ // "connecting" worker; its socket must still end up closed, not leaked.
+ assertTrue(firstSocket.isClosed());
+ }
+
+ @Test
+ void interruptionDuringMinimumSpacingWait_abortsBeforeStartingNextAddress() throws Exception {
+ // Regression test: sleepOrAbort() (the minimum-spacing wait after a fast failure) must
+ // propagate an interruption instead of swallowing it and continuing the race.
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(250));
+ final AtomicInteger attempts = new AtomicInteger();
+ final CountDownLatch firstFailed = new CountDownLatch(1);
+ final AtomicReference thrown = new AtomicReference<>();
+
+ final Thread caller = new Thread(() -> {
+ try {
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ attempts.incrementAndGet();
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ firstFailed.countDown();
+ throw new IOException("refused");
+ }
+ return new Socket();
+ });
+ } catch (final Throwable ex) {
+ thrown.set(ex);
+ }
+ });
+ caller.start();
+ assertTrue(firstFailed.await(5, TimeUnit.SECONDS));
+ caller.interrupt(); // races the <=10ms minimum-spacing wait that follows the failure
+ caller.join(5000);
+
+ assertFalse(caller.isAlive());
+ // Best-effort timing: if the interruption landed while connect() was still running, it
+ // must be reported as InterruptedIOException, never silently swallowed.
+ if (thrown.get() != null) {
+ assertTrue(thrown.get() instanceof InterruptedIOException,
+ "an interruption during racing must surface as InterruptedIOException: " + thrown.get());
+ }
+ }
+
+ @Test
+ void interruptingTheCallingThread_abortsAndClosesTheStillConnectingSocket() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final BlockingSocket onlySocket = new BlockingSocket();
+ final CountDownLatch connecting = new CountDownLatch(1);
+ final AtomicReference thrown = new AtomicReference<>();
+
+ final Thread caller = new Thread(() -> {
+ try {
+ connector.connect(new HttpHost("somehost"), addresses(1), (remoteAddress, socketConsumer) -> {
+ socketConsumer.accept(onlySocket);
+ connecting.countDown();
+ onlySocket.connect(remoteAddress, 0); // blocks until closed or interrupted
+ return onlySocket;
+ });
+ } catch (final Throwable ex) {
+ thrown.set(ex);
+ }
+ });
+ caller.start();
+ assertTrue(connecting.await(5, TimeUnit.SECONDS), "the attempt must have genuinely started connecting");
+ caller.interrupt();
+ caller.join(5000);
+
+ assertFalse(caller.isAlive(), "the calling thread must have returned after being interrupted");
+ assertTrue(thrown.get() instanceof InterruptedIOException,
+ "connect() must report the interruption rather than silently returning: was " + thrown.get());
+ assertTrue(onlySocket.isClosed(), "the still-connecting socket must be closed, not leaked, on interruption");
+ }
+
+ @Test
+ void registrationAfterRaceDecided_closesSocketImmediately() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final Socket winnerSocket = new Socket();
+ final CountDownLatch registerNow = new CountDownLatch(1);
+ final CountDownLatch registered = new CountDownLatch(1);
+ final AtomicReference lateSocketRef = new AtomicReference<>();
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ // Registers strictly after the race below has already picked a winner.
+ awaitUninterruptibly(registerNow);
+ final Socket lateSocket = new Socket();
+ lateSocketRef.set(lateSocket);
+ socketConsumer.accept(lateSocket);
+ registered.countDown();
+ throw new IOException("too late");
+ }
+ socketConsumer.accept(winnerSocket);
+ return winnerSocket;
+ }));
+
+ assertEquals(winnerSocket, winner);
+ registerNow.countDown();
+ assertTrue(registered.await(5, TimeUnit.SECONDS));
+ assertTrue(lateSocketRef.get().isClosed(),
+ "a socket registered strictly after the race is decided must be closed immediately, not left open");
+ }
+
+ private static void awaitUninterruptibly(final CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ @Test
+ void doesNotRejectSingleAddressBelowStaggerIndex() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final Socket socket = new Socket();
+
+ final Socket result = connector.connect(new HttpHost("somehost"), addresses(1), (remoteAddress, socketConsumer) -> {
+ socketConsumer.accept(socket);
+ return socket;
+ });
+
+ assertEquals(socket, result);
+ assertFalse(socket.isClosed());
+ }
+
+ /**
+ * Real-socket integration test (no mocks, no fakes): one address has nothing listening
+ * (genuine, OS-level immediate connection refusal) and the other is a real local server
+ * that accepts. Proves actual fallover over real loopback TCP, not just that the first
+ * address happens to succeed.
+ */
+ @Test
+ void realSockets_unreachableAddressFailsOver_toRealListeningServer() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = findUnusedLoopbackPort();
+
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final List targets = new ArrayList<>();
+ targets.add(new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort));
+ targets.add(new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("localhost"), targets, (remoteAddress, socketConsumer) -> {
+ final Socket s = new Socket();
+ socketConsumer.accept(s);
+ s.connect(remoteAddress, 2000);
+ return s;
+ }));
+
+ assertEquals(listeningPort, winner.getPort());
+ assertFalse(winner.isClosed());
+ winner.close();
+ }
+ }
+
+ /** Finds a loopback TCP port nothing is listening on, by briefly binding then closing it. */
+ private static int findUnusedLoopbackPort() throws IOException {
+ try (ServerSocket probe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ return probe.getLocalPort();
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java
index 20c065e6ec..2431fa1eac 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java
@@ -26,22 +26,36 @@
*/
package org.apache.hc.client5.http.impl.nio;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLHandshakeException;
+
+import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.nio.ManagedAsyncClientConnection;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class DefaultAsyncClientConnectionOperatorTest {
@@ -71,4 +85,306 @@ void testCancelDuringTlsHandshakeClosesSession() throws Exception {
Mockito.verify(ioSession).close(CloseMode.IMMEDIATE);
}
+ @Test
+ void testHookThrowingAfterSuccessDoesNotHangFuture() throws Exception {
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ Mockito.doAnswer(invocation -> {
+ final FutureCallback callback = invocation.getArgument(4);
+ callback.completed(Mockito.mock(TransportSecurityLayer.class));
+ return null;
+ }).when(tlsStrategy).upgrade(any(), any(), any(), any(), any());
+
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, null) {
+ @Override
+ protected void onAfterTlsHandshake(final HttpContext context, final HttpHost endpointHost) {
+ throw new IllegalStateException("broken onAfterTlsHandshake hook");
+ }
+ };
+
+ final IOSession ioSession = Mockito.mock(IOSession.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(ioSession);
+ return CompletableFuture.completedFuture(ioSession);
+ });
+
+ final HttpHost target = new HttpHost("https", InetAddress.getLoopbackAddress(), "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ // Bounded wait: a regression here would hang instead of failing fast.
+ final ManagedAsyncClientConnection connection = future.get(5, TimeUnit.SECONDS);
+ assertNotNull(connection);
+ Mockito.verify(ioSession, Mockito.never()).close(any(CloseMode.class));
+ }
+
+ @Test
+ void testCancelDuringFallbackAfterTlsRejectionCancelsNextAttempt() throws Exception {
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443);
+ final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443);
+ Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2));
+
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver);
+
+ final IOSession firstSession = Mockito.mock(IOSession.class);
+ @SuppressWarnings("unchecked")
+ final Future secondAttempt = Mockito.mock(Future.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ // Address #1 connects at the TCP level immediately.
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(firstSession);
+ return CompletableFuture.completedFuture(firstSession);
+ })
+ .thenAnswer(invocation -> secondAttempt); // Address #2's TCP connect never resolves in this test.
+
+ final HttpHost target = new HttpHost("https", null, "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ // Reject address #1's TLS handshake, triggering fallback to address #2.
+ @SuppressWarnings("unchecked")
+ final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class);
+ Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture());
+ tlsCallbackCaptor.getValue().failed(new SSLHandshakeException("untrusted certificate"));
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+
+ // Address #2 is now the in-flight fallback attempt; cancelling here must reach it.
+ future.cancel(true);
+ Mockito.verify(secondAttempt).cancel(true);
+ }
+
+ @Test
+ void testTlsHandshakeCancellationDoesNotFallBackToNextAddress() throws Exception {
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443);
+ final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443);
+ Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2));
+
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver);
+
+ final IOSession firstSession = Mockito.mock(IOSession.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(firstSession);
+ return CompletableFuture.completedFuture(firstSession);
+ });
+
+ final HttpHost target = new HttpHost("https", null, "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ @SuppressWarnings("unchecked")
+ final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class);
+ Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture());
+ tlsCallbackCaptor.getValue().cancelled();
+
+ Mockito.verify(connectionInitiator, Mockito.times(1)).connect(any(), any(), any(), any(), any(), any());
+ assertTrue(future.isCancelled());
+ }
+
+ @Test
+ void testCancelDuringFirstConnectAttemptReachesIt() throws Exception {
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, null);
+
+ @SuppressWarnings("unchecked")
+ final Future firstAttempt = Mockito.mock(Future.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> firstAttempt); // Never calls back: the connect itself is still pending.
+
+ final HttpHost target = new HttpHost("https", InetAddress.getLoopbackAddress(), "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ future.cancel(true);
+ Mockito.verify(firstAttempt).cancel(true);
+ Mockito.verify(tlsStrategy, Mockito.never()).upgrade(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void testTlsStrategyFailingThenThrowingAdvancesFallbackOnlyOnce() throws Exception {
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443);
+ final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443);
+ final InetSocketAddress address3 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 3}), 443);
+ Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2, address3));
+
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ Mockito.doAnswer(invocation -> {
+ final FutureCallback callback = invocation.getArgument(4);
+ callback.failed(new SSLHandshakeException("untrusted certificate"));
+ throw new IllegalStateException("broken TlsStrategy: throws after reporting failure");
+ }).when(tlsStrategy).upgrade(any(), any(), any(), any(), any());
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver);
+
+ @SuppressWarnings("unchecked")
+ final Future secondAttempt = Mockito.mock(Future.class);
+ @SuppressWarnings("unchecked")
+ final Future thirdAttempt = Mockito.mock(Future.class);
+ final IOSession firstSession = Mockito.mock(IOSession.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ // Address #1: connects, then rejected twice by the broken strategy above.
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(firstSession);
+ return CompletableFuture.completedFuture(firstSession);
+ })
+ .thenAnswer(invocation -> secondAttempt) // Address #2: the correct, single fallback target.
+ // Address #3: must never be reached. With only two addresses, a double-advance
+ // would land past the list and be absorbed as ordinary exhaustion, masking the bug.
+ .thenAnswer(invocation -> thirdAttempt);
+
+ final HttpHost target = new HttpHost("https", null, "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ // One address rejected (reported twice by the broken strategy) still falls back to
+ // exactly the next address, not two addresses further.
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+ assertFalse(future.isDone());
+ }
+
+ @Test
+ void testTlsStrategyThrowingWithoutCallbackFallsBackAndStaysCancellable() throws Exception {
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443);
+ final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443);
+ Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2));
+
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ Mockito.doThrow(new IllegalStateException("synchronous upgrade failure"))
+ .when(tlsStrategy).upgrade(any(), any(), any(), any(), any());
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver);
+
+ final IOSession firstSession = Mockito.mock(IOSession.class);
+ @SuppressWarnings("unchecked")
+ final Future secondAttempt = Mockito.mock(Future.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(firstSession);
+ return CompletableFuture.completedFuture(firstSession);
+ })
+ .thenAnswer(invocation -> secondAttempt); // Address #2's TCP connect never resolves in this test.
+
+ final HttpHost target = new HttpHost("https", null, "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+ future.cancel(true);
+ Mockito.verify(secondAttempt).cancel(true);
+ }
+
+ @Test
+ void testCancelDuringFallbackAfterRacingWinnerTlsRejectionCancelsNextAttempt() throws Exception {
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443);
+ final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443);
+ Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2));
+
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver,
+ true, TimeValue.ofMilliseconds(250));
+
+ final IOSession firstSession = Mockito.mock(IOSession.class);
+ @SuppressWarnings("unchecked")
+ final Future secondAttempt = Mockito.mock(Future.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ // Address #1 wins immediately, before address #2's stagger delay fires.
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(firstSession);
+ return CompletableFuture.completedFuture(firstSession);
+ })
+ .thenAnswer(invocation -> secondAttempt); // Address #2's TCP connect never resolves in this test.
+
+ final HttpHost target = new HttpHost("https", null, "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ // Reject the racing winner's TLS handshake, triggering fallback to address #2.
+ @SuppressWarnings("unchecked")
+ final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class);
+ Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture());
+ tlsCallbackCaptor.getValue().failed(new SSLHandshakeException("untrusted certificate"));
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+
+ // Address #2 is now the in-flight fallback attempt; cancelling here must reach it.
+ future.cancel(true);
+ Mockito.verify(secondAttempt).cancel(true);
+ }
+
+ /**
+ * Cancelling mid-handshake, before the strategy reports any outcome, must stop the
+ * operation outright: once the strategy later reports failure (the connection it was
+ * using got closed), no new attempt must start. Only the racing variant exercises the
+ * {@code isDone()} guard at the top of {@code executeNext()}; without racing,
+ * {@code onFailure()}'s own guard stops it first.
+ */
+ private int cancelDuringHandshakeThenReportedFailed(final boolean happyEyeballs) throws Exception {
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443);
+ final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443);
+ Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2));
+
+ final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class);
+ final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator(
+ RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver,
+ happyEyeballs, TimeValue.ofMilliseconds(250));
+
+ final IOSession firstSession = Mockito.mock(IOSession.class);
+ final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback callback = invocation.getArgument(5);
+ callback.completed(firstSession);
+ return CompletableFuture.completedFuture(firstSession);
+ });
+
+ final HttpHost target = new HttpHost("https", null, "somehost", 443);
+ final Future future = operator.connect(
+ connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null);
+
+ @SuppressWarnings("unchecked")
+ final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class);
+ Mockito.verify(tlsStrategy).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture());
+
+ future.cancel(true);
+ assertTrue(future.isCancelled());
+ // The cancel above closed the connection; the strategy learns the handshake failed only now.
+ tlsCallbackCaptor.getValue().failed(new SSLHandshakeException("connection closed"));
+ return Mockito.mockingDetails(connectionInitiator).getInvocations().size();
+ }
+
+ @Test
+ void testCancelDuringHandshakeDoesNotStartNewAttemptSequential() throws Exception {
+ assertEquals(1, cancelDuringHandshakeThenReportedFailed(false));
+ }
+
+ @Test
+ void testCancelDuringHandshakeDoesNotStartNewAttemptRacing() throws Exception {
+ assertEquals(1, cancelDuringHandshakeThenReportedFailed(true));
+ }
+
}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java
index e2ec5696b8..fdd2651656 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java
@@ -28,29 +28,46 @@
package org.apache.hc.client5.http.impl.nio;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Deque;
import java.util.List;
+import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.net.NamedEndpoint;
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
+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.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class MultihomeIOSessionRequesterTest {
@@ -158,4 +175,555 @@ void testConnectSuccessfulAfterRetries() throws Exception {
fail("Did not expect an ExecutionException", ex);
}
}
+
+ @Test
+ void testCancelAfterSynchronousFailureReachesNextAttempt() throws Exception {
+ final InetAddress address1 = InetAddress.getByAddress(new byte[]{10, 0, 0, 1});
+ final InetAddress address2 = InetAddress.getByAddress(new byte[]{10, 0, 0, 2});
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(address1, 8080),
+ new InetSocketAddress(address2, 8080));
+
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final AtomicBoolean secondAttemptCancelled = new AtomicBoolean();
+ final CompletableFuture secondAttemptFuture = new CompletableFuture() {
+ @Override
+ public boolean cancel(final boolean mayInterruptIfRunning) {
+ secondAttemptCancelled.set(true);
+ return super.cancel(mayInterruptIfRunning);
+ }
+ };
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ // Address 1 fails synchronously: the fallback to address 2 recurses and
+ // returns before this call does.
+ final FutureCallback callback = invocation.getArgument(5);
+ final CompletableFuture future = new CompletableFuture<>();
+ callback.failed(new IOException("connection refused"));
+ future.completeExceptionally(new IOException("connection refused"));
+ return future;
+ })
+ .thenAnswer(invocation -> secondAttemptFuture); // Address 2: left pending.
+
+ final Future future = sessionRequester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(30), null, null);
+
+ future.cancel(true);
+ assertTrue(secondAttemptCancelled.get(),
+ "cancellation did not reach the in-flight second attempt");
+ }
+
+ // -------------------------------------------------------------------------
+ // RFC 8305 connection racing (Happy Eyeballs v2)
+ // -------------------------------------------------------------------------
+
+ /** Captures scheduled stagger tasks instead of running them on a timer, for determinism. */
+ private static final class FakeScheduler {
+ final ScheduledExecutorService mock = Mockito.mock(ScheduledExecutorService.class);
+ final Deque pending = new ArrayDeque<>();
+
+ @SuppressWarnings("unchecked")
+ FakeScheduler() {
+ Mockito.when(mock.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
+ .thenAnswer(invocation -> {
+ pending.add(invocation.getArgument(0));
+ return Mockito.mock(ScheduledFuture.class);
+ });
+ }
+
+ /** Runs the next pending stagger task, as if its delay had elapsed. */
+ void fireNext() {
+ final Runnable task = pending.poll();
+ assertNotNull(task, "no stagger task was scheduled");
+ task.run();
+ }
+
+ int pendingCount() {
+ return pending.size();
+ }
+ }
+
+ private static List addresses(final int count) throws Exception {
+ final List out = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ out.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, (byte) i}), 8080));
+ }
+ return out;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static FutureCallback[] captureCallbacks(final ConnectionInitiator connectionInitiator, final int expected) {
+ final ArgumentCaptor captor = ArgumentCaptor.forClass(FutureCallback.class);
+ Mockito.verify(connectionInitiator, Mockito.times(expected))
+ .connect(any(), any(), any(), any(), any(), captor.capture());
+ return captor.getAllValues().toArray(new FutureCallback[0]);
+ }
+
+ @Test
+ void happyEyeballs_firstAddressSucceedsImmediately_noStaggerNeeded() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+ // Only the first address was ever attempted; the second was never needed.
+ Mockito.verify(connectionInitiator, Mockito.times(1)).connect(any(), any(), any(), any(), any(), any());
+ Mockito.verify(winnerSession, Mockito.never()).close(any(CloseMode.class));
+ }
+
+ @Test
+ void happyEyeballs_firstAddressStalls_secondWinsAfterStagger() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ final Future firstAttempt = Mockito.mock(Future.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> firstAttempt) // 1st call: stalls, no callback invoked yet.
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertFalse(future.isDone(), "must not complete before the stalled first attempt or the stagger fires");
+ assertEquals(1, scheduler.pendingCount());
+
+ scheduler.fireNext(); // simulate the 250ms stagger elapsing
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+
+ // The still-stalled first attempt must have been cancelled, not left to leak.
+ Mockito.verify(firstAttempt).cancel(true);
+ }
+
+ @Test
+ void happyEyeballs_firstAddressFailsFast_advancesPromptlyAtMinimumSpacingNotFullStagger() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.failed(new IOException("refused"));
+ return CompletableFuture.completedFuture(null);
+ })
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ // The 1st address failed immediately: the 2nd must be scheduled at the RFC 8305
+ // Section 5 minimum inter-attempt spacing (10ms), not the full 250ms stagger delay.
+ assertFalse(future.isDone());
+ final ArgumentCaptor delayCaptor = ArgumentCaptor.forClass(Long.class);
+ Mockito.verify(scheduler.mock).schedule(any(Runnable.class), delayCaptor.capture(), eq(TimeUnit.MILLISECONDS));
+ assertTrue(delayCaptor.getValue() <= 10L && delayCaptor.getValue() > 0L,
+ "must advance at the minimum spacing (<=10ms), not the full stagger delay: was " + delayCaptor.getValue());
+
+ scheduler.fireNext();
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void happyEyeballs_bothAttemptsSucceed_loserSessionIsClosedNotLeaked() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession secondSession = Mockito.mock(IOSession.class);
+ final Future