Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion vertx-core/src/main/asciidoc/http.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,7 @@ You can configure various pool {@link io.vertx.core.http.PoolOptions options} as
* {@link io.vertx.core.http.PoolOptions options#setHttp1MaxSize} the maximum number of opened per HTTP/1.x server (5 by default)
* {@link io.vertx.core.http.PoolOptions options#setHttp2MaxSize} the maximum number of opened per HTTP/2 server (1 by default), you *should* not change this value since a single HTTP/2 connection is capable of delivering the same performance level than multiple HTTP/1.x connections
* {@link io.vertx.core.http.PoolOptions options#setHttp3MaxSize} the maximum number of opened per HTTP/3 server (1 by default), you *should* not change this value since a single HTTP/3 connection is capable of delivering the same performance level than multiple HTTP/1.x connections
* {@link io.vertx.core.http.PoolOptions options#setCleanerPeriod} the period in milliseconds at which the pool checks expired connections (1 second by default)
* {@link io.vertx.core.http.PoolOptions options#setRefreshPeriod} the period at which the pool performs its maintenance tasks (100 milliseconds by default): expired connections are closed and expired connection acquisitions are timed out, the period bounds the resolution of the connect timeout
* {@link io.vertx.core.http.PoolOptions options#setEventLoopSize} sets the number of event loops the pool use
** the default value `0` configures the pool to use the event loop of the caller
** a positive value configures the pool load balance the creation of connection over a list of event loops determined by the value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, PoolOpt
obj.setCleanerPeriod(((Number)member.getValue()).intValue());
}
break;
case "refreshPeriod":
if (member.getValue() instanceof Number) {
obj.setRefreshPeriod(java.time.Duration.of(((Number)member.getValue()).longValue(), java.time.temporal.ChronoUnit.MILLIS));
}
break;
case "eventLoopSize":
if (member.getValue() instanceof Number) {
obj.setEventLoopSize(((Number)member.getValue()).intValue());
Expand Down Expand Up @@ -69,6 +74,9 @@ static void toJson(PoolOptions obj, java.util.Map<String, Object> json) {
}
json.put("maxLifetime", obj.getMaxLifetime());
json.put("cleanerPeriod", obj.getCleanerPeriod());
if (obj.getRefreshPeriod() != null) {
json.put("refreshPeriod", obj.getRefreshPeriod().toMillis());
}
json.put("eventLoopSize", obj.getEventLoopSize());
json.put("maxWaitQueueSize", obj.getMaxWaitQueueSize());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,12 @@ public long getConnectTimeout() {
* Sets the amount of time after which, if the request is not obtained from the client within the timeout period,
* the {@code Future<HttpClientRequest>} obtained from the client is failed with a {@link java.util.concurrent.TimeoutException}.
*
* Note this is not related to the TCP {@link HttpClientOptions#setConnectTimeout(int)} option, when a request is made against
* a pooled HTTP client, the timeout applies to the duration to obtain a connection from the pool to serve the request, the timeout
* might fire because the server does not respond in time or the pool is too busy to serve a request.
* Note this is distinct from the transport connect timeout ({@link HttpClientConfig#setConnectTimeout}), when a request is made
* against a pooled HTTP client, the timeout applies to the duration to obtain a connection from the pool to serve the request, the
* timeout might fire because the server does not respond in time or the pool is too busy to serve a request.
*
* When the timeout is not set, it defaults to the connect timeout of the transport being connected to, so that every
* request waits a bounded amount of time for a connection.
*
* @param timeout the amount of time in milliseconds.
* @return a reference to this, so the API can be used fluently
Expand Down
46 changes: 44 additions & 2 deletions vertx-core/src/main/java/io/vertx/core/http/PoolOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import io.vertx.core.impl.Arguments;
import io.vertx.core.json.JsonObject;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
Expand Down Expand Up @@ -58,9 +59,17 @@ public class PoolOptions {

/**
* Default pool cleaner period = 1000 ms (1 second)
*
* @deprecated the pool cleaner period is unused, superseded by {@link #DEFAULT_REFRESH_PERIOD}
*/
@Deprecated
public static final int DEFAULT_POOL_CLEANER_PERIOD = 1000;

/**
* Default pool refresh period = 100 ms
*/
public static final Duration DEFAULT_REFRESH_PERIOD = Duration.ofMillis(100);

/**
* Default pool event loop size = 0 (reuse current event-loop)
*/
Expand All @@ -72,6 +81,7 @@ public class PoolOptions {
private int maxLifetime;
private TimeUnit maxLifetimeUnit;
private int cleanerPeriod;
private Duration refreshPeriod;
private int eventLoopSize;
private int maxWaitQueueSize;

Expand All @@ -85,6 +95,7 @@ public PoolOptions() {
maxLifetime = DEFAULT_MAXIMUM_LIFETIME;
maxLifetimeUnit = DEFAULT_MAXIMUM_LIFETIME_TIME_UNIT;
cleanerPeriod = DEFAULT_POOL_CLEANER_PERIOD;
refreshPeriod = DEFAULT_REFRESH_PERIOD;
eventLoopSize = DEFAULT_POOL_EVENT_LOOP_SIZE;
maxWaitQueueSize = DEFAULT_MAX_WAIT_QUEUE_SIZE;
}
Expand All @@ -101,6 +112,7 @@ public PoolOptions(PoolOptions other) {
this.maxLifetime = other.maxLifetime;
this.maxLifetimeUnit = other.maxLifetimeUnit;
this.cleanerPeriod = other.cleanerPeriod;
this.refreshPeriod = other.refreshPeriod;
this.eventLoopSize = other.eventLoopSize;
this.maxWaitQueueSize = other.maxWaitQueueSize;
}
Expand Down Expand Up @@ -224,23 +236,53 @@ public PoolOptions setMaxLifetime(int maxLifetime) {

/**
* @return the connection pool cleaner period in ms.
*
* @deprecated the pool cleaner period is unused, superseded by {@link #getRefreshPeriod()}
*/
@Deprecated
public int getCleanerPeriod() {
return cleanerPeriod;
}

/**
* Set the connection pool cleaner period in milli seconds, a non positive value disables expiration checks and connections
* will remain in the pool until they are closed.
* Set the connection pool cleaner period in milli seconds.
*
* @param cleanerPeriod the pool cleaner period
* @return a reference to this, so the API can be used fluently
*
* @deprecated the pool cleaner period is unused, superseded by {@link #setRefreshPeriod(Duration)}
*/
@Deprecated
public PoolOptions setCleanerPeriod(int cleanerPeriod) {
this.cleanerPeriod = cleanerPeriod;
return this;
}

/**
* @return the connection pool refresh period
*/
public Duration getRefreshPeriod() {
return refreshPeriod;
}

/**
* Set the connection pool refresh period, the period must be positive.
* <p/>
* The pool is refreshed periodically to perform its maintenance tasks: connections that exceeded their keep alive
* timeout or maximum lifetime are closed and expired connection acquisitions are timed out. The refresh period
* bounds the resolution of the connect timeout.
*
* @param refreshPeriod the pool refresh period
* @return a reference to this, so the API can be used fluently
*/
public PoolOptions setRefreshPeriod(Duration refreshPeriod) {
if (refreshPeriod == null || refreshPeriod.isZero() || refreshPeriod.isNegative()) {
throw new IllegalArgumentException("refreshPeriod must be > 0");
}
this.refreshPeriod = refreshPeriod;
return this;
}

/**
* @return the max number of event-loop a pool will use, the default value is {@code 0} which implies
* to reuse the current event-loop
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,9 @@ public LegacyHttpClient(
HttpClientOptions options) {
super(vertx, resolver, redirectHandler, httpMetrics, poolOptions, defaultProxyOptions, nonProxyHosts, loadBalancer,
followAlternativeServices, resolverKeepAlive, resolverMaxTtl, verifyHost, validateUri, defaultSsl, defaultHost, defaultPort,
maxRedirects, maxRedirectBufferSize, versions, sslOptions, connectHandler, tcpTransport, quicTransport);
maxRedirects, maxRedirectBufferSize, versions, sslOptions, connectHandler, tcpTransport, quicTransport,
config.getTcpConfig().getConnectTimeout() != null ? config.getTcpConfig().getConnectTimeout().toMillis() : 0L,
config.getQuicConfig().getConnectTimeout() != null ? config.getQuicConfig().getConnectTimeout().toMillis() : 0L);
this.config = config;
this.options = options;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,14 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal
private final ResourceManager<EndpointKey, SharedHttpClientConnectionGroup> resourceManager;
private final Function<HttpClientResponse, Future<RequestOptions>> redirectHandler;
private long timerID;
private final long refreshPeriod;
private final Function<ContextInternal, ContextInternal> contextProvider;
private final long maxLifetime;
private final HttpClientTransport tcpTransport;
private final HttpClientTransport quicTransport;
private final HttpClientTransport defaultTransport;
private final long tcpConnectTimeout;
private final long quicConnectTimeout;
private final EndpointResolverInternal resolver;
private final OriginResolver<Object> originEndpoints;
private final EndpointResolverInternal originResolver;
Expand Down Expand Up @@ -100,7 +103,9 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal
ClientSSLOptions sslOptions,
Handler<HttpConnection> connectHandler,
HttpClientTransport tcpTransport,
HttpClientTransport quicTransport) {
HttpClientTransport quicTransport,
long tcpConnectTimeout,
long quicConnectTimeout) {
super(vertx, httpMetrics, defaultProxyOptions, nonProxyHosts);

if (sslOptions != null) {
Expand All @@ -109,8 +114,16 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal

boolean resolveAll = loadBalancer != null;

if (tcpTransport != null && tcpConnectTimeout <= 0L) {
throw new IllegalArgumentException("The connect timeout must be positive: it is the default acquisition timeout of the pool");
}
if (quicTransport != null && quicConnectTimeout <= 0L) {
throw new IllegalArgumentException("The connect timeout must be positive: it is the default acquisition timeout of the pool");
}
this.tcpTransport = tcpTransport;
this.quicTransport = quicTransport;
this.tcpConnectTimeout = tcpConnectTimeout;
this.quicConnectTimeout = quicConnectTimeout;
this.defaultTransport = tcpTransport != null ? tcpTransport : quicTransport;
this.originEndpoints = new OriginResolver<>(vertx, resolveAll, this);
this.resolver = (EndpointResolverInternal) resolver;
Expand Down Expand Up @@ -145,11 +158,14 @@ public class HttpClientImpl extends HttpClientBase implements HttpClientInternal
this.contextProvider = ConnectionPool.EVENT_LOOP_CONTEXT_PROVIDER;
}

// Init time
if (poolOptions.getCleanerPeriod() > 0) {
// The periodic refresh performs all the pool maintenance tasks: it reaps the expired connections
// and times out the expired connection waiters
Duration refreshPeriod = poolOptions.getRefreshPeriod();
this.refreshPeriod = refreshPeriod != null ? refreshPeriod.toMillis() : 0;
if (this.refreshPeriod > 0) {
PoolChecker checker = new PoolChecker(this);
ContextInternal timerContext = vertx.createEventLoopContext();
timerID = timerContext.setTimer(poolOptions.getCleanerPeriod(), checker);
timerID = timerContext.setTimer(this.refreshPeriod, checker);
}
}

Expand Down Expand Up @@ -184,7 +200,7 @@ public EndpointResolverInternal resolver() {
protected void checkExpired(Handler<Long> checker) {
synchronized (this) {
if (!closeSequence.started()) {
timerID = vertx.setTimer(poolOptions.getCleanerPeriod(), checker);
timerID = vertx.setTimer(refreshPeriod, checker);
}
}
originResolver.checkExpired();
Expand Down Expand Up @@ -457,6 +473,14 @@ private HttpClientTransport transport(HttpVersion version) {
return version == HttpVersion.HTTP_3 ? quicTransport : tcpTransport;
}

private long connectTimeout(HttpVersion version, long timeout) {
if (timeout <= 0L) {
HttpClientTransport transport = version != null ? transport(version) : defaultTransport;
timeout = transport instanceof TcpHttpClientTransport ? tcpConnectTimeout : quicConnectTimeout;
}
return timeout;
}

private Future<ConnectionRequest> acquireConnection(RequestOptions request, ContextInternal ctx) {
HttpVersion version = request.getProtocolVersion();
if (version != null && !versions.contains(version)) {
Expand All @@ -476,7 +500,7 @@ private Future<ConnectionRequest> acquireConnection(RequestOptions request, Cont
(SocketAddress) connectionRequest.server,
connectionRequest.authority,
connectionRequest.proxyOptions,
group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectionRequest.connectTimeout), null, null));
group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectTimeout(connectionRequest.version, connectionRequest.connectTimeout)), null, null));
} else {
PromiseInternal<Endpoint> promise = vertx.promise();
connectionRequest.endpointResolver.lookupEndpoint(connectionRequest.address, promise);
Expand All @@ -496,7 +520,7 @@ private Future<ConnectionRequest> acquireConnection(RequestOptions request, Cont
serverAddress,
authority,
null,
group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectionRequest.connectTimeout), selection.server, selection.alternative));
group -> connectionRequest.acquire(group.requestConnection(connectionRequest.ctx, connectTimeout(selectedVersion, connectionRequest.connectTimeout)), selection.server, selection.alternative));
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ private void progress(TaskList tasks) {
while (current != null) {
PoolWaiter<C> waiter = current;
current = waiters.next(current);
if (waiter.deadlineNanos != 0 && roundNanos - waiter.deadlineNanos >= 0) {
if (roundNanos - waiter.deadlineNanos >= 0) {
waiters.remove(waiter);
boolean dequeued = waiter.queued;
Task task = new Task() {
Expand Down Expand Up @@ -943,6 +943,11 @@ public void acquire(ContextInternal context, int kind, Duration timeout, Complet

@Override
public void acquire(ContextInternal context, PoolWaiter.Listener<C> listener, int kind, Duration timeout, Completable<Lease<C>> handler) {
if (timeout == null || timeout.isZero() || timeout.isNegative()) {
Future<Lease<C>> fut = context.failedFuture(new IllegalArgumentException("A positive acquire timeout is required: every pool waiter has a deadline"));
fut.onComplete(handler);
return;
}
execute(new Acquire<>(context, listener, capacityFactors[kind], timeout, handler));
}

Expand Down
27 changes: 27 additions & 0 deletions vertx-core/src/test/java/io/vertx/tests/http/Http1xTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6353,4 +6353,31 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
tracking.future().await();
return request;
}

@Test
public void testDisabledConnectTimeoutRejected() {
// A disabled transport connect timeout cannot default the pool acquisition timeout: the
// pooled client creation fails
assertThatThrownBy(() -> vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(0)))
.isInstanceOf(IllegalArgumentException.class);
}

@Test
public void testConnectTimeoutDefaultsToTransportConnectTimeout() throws Exception {
server.requestHandler(req -> {
// Hold the connection: the next request waits
});
startServer(testAddress);
client = vertx.createHttpClient(new HttpClientOptions().setConnectTimeout(200), new PoolOptions().setHttp1MaxSize(1));
client.request(new RequestOptions(requestOptions)).compose(HttpClientRequest::send);
// A request without connect timeout gets the transport connect timeout as acquisition
// deadline
long begin = System.currentTimeMillis();
assertThat(client.request(new RequestOptions(requestOptions)))
.isFailure()
.asInstanceOf(java.util.concurrent.TimeoutException.class)
.compose(cause -> System.currentTimeMillis() - begin >= 200 ? Future.succeededFuture()
: Future.failedFuture(new AssertionError("The acquisition failed before the default timeout")))
.await();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public void testKeepAliveTimeout(Vertx vertx) {
.await();

HttpClientConfig clientConfig = new HttpClientConfig().setResolverConfig(new ClientResolverConfig().setKeepAliveTimeout(Duration.ofMillis(50)));
HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setCleanerPeriod(50));
HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setRefreshPeriod(Duration.ofMillis(50)));

// Create a connection to the server first (warm-up) before
// we test the origin resolver
Expand Down Expand Up @@ -187,7 +187,7 @@ public void testMaxKeepAlive() throws Exception {
.await();

HttpClientConfig clientConfig = new HttpClientConfig().setResolverConfig(new ClientResolverConfig().setMaxKeepAlive(Duration.ofMillis(500)));
HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setCleanerPeriod(10));
HttpClient client = vertx.createHttpClient(clientConfig, new PoolOptions().setRefreshPeriod(Duration.ofMillis(10)));
long now = System.currentTimeMillis();
while (true) {
assertTrue((System.currentTimeMillis() - now) < 20_000);
Expand Down
Loading
Loading