diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java b/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java index ce9c6d38b14..7bf6cab05ba 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/SharedHttpClientConnectionGroup.java @@ -16,8 +16,10 @@ import io.vertx.core.internal.ContextInternal; import io.vertx.core.impl.NoStackTraceTimeoutException; import io.vertx.core.internal.http.HttpClientTransport; +import io.vertx.core.http.impl.tcp.Http2UpgradeClientConnection; import io.vertx.core.internal.pool.ConnectResult; import io.vertx.core.internal.pool.ConnectionPool; +import io.vertx.core.internal.pool.DefaultConnectionPool; import io.vertx.core.internal.pool.PoolConnection; import io.vertx.core.internal.pool.PoolConnector; import io.vertx.core.internal.pool.Lease; @@ -29,6 +31,7 @@ import io.vertx.core.spi.metrics.HttpClientMetrics; import io.vertx.core.spi.metrics.PoolMetrics; +import java.time.Duration; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; @@ -102,43 +105,25 @@ private class Request implements PoolWaiter.Listener, Comp private final ContextInternal context; private final long timeout; private final Promise> promise; - private long timerID; Request(ContextInternal context, long timeout, Promise> promise) { this.context = context; this.timeout = timeout; this.promise = promise; - this.timerID = -1L; } @Override - public void onEnqueue(PoolWaiter waiter) { - onConnect(waiter); - } - - @Override - public void onConnect(PoolWaiter waiter) { - if (timeout > 0L && timerID == -1L) { - timerID = context.setTimer(timeout, id -> { - pool.pool.cancel(waiter, (res, err) -> { - if (err == null && res) - promise.fail(new NoStackTraceTimeoutException("The timeout of " + timeout + " ms has been exceeded when getting a connection to " + server)); - }); - }); - } + public void onTimeout(PoolWaiter waiter) { + promise.fail(new NoStackTraceTimeoutException("The timeout of " + timeout + " ms has been exceeded when getting a connection to " + server)); } @Override public void complete(Lease result, Throwable failure) { - if (timerID >= 0 && !context.owner().cancelTimer(timerID)) { - result.recycle(); - } else { - promise.complete(result, failure); - } + promise.complete(result, failure); } void acquire() { - pool.acquire(context,this, promise); + pool.acquire(context, this, timeout, promise); } } @@ -212,8 +197,12 @@ static class Pool implements PoolConnector { this.maxLifetimeMillis = maxLifetimeMillis; this.connectParams = connectParams; this.poolKind = initialPoolKind; - this.pool = ConnectionPool - .pool(this, new int[]{http1MaxSize, http2MaxSize}, queueMaxSize) + this.pool = DefaultConnectionPool + .builder(this) + .withMaxSizes(new int[]{http1MaxSize, http2MaxSize}) + .withMaxWaiters(queueMaxSize) + .withConnectionChecker(this::checkConnection) + .build() .connectionSelector(LIFO_SELECTOR) .contextProvider(contextProvider); } @@ -231,8 +220,12 @@ static class Pool implements PoolConnector { this.maxLifetimeMillis = maxLifetimeMillis; this.connectParams = connectParams; this.poolKind = 0; - this.pool = ConnectionPool - .pool(this, new int[]{http3MaxSize}, queueMaxSize) + this.pool = DefaultConnectionPool + .builder(this) + .withMaxSizes(new int[]{http3MaxSize}) + .withMaxWaiters(queueMaxSize) + .withConnectionChecker(this::checkConnection) + .build() .connectionSelector(LIFO_SELECTOR) .contextProvider(contextProvider); } @@ -249,7 +242,17 @@ public Future> connect(ContextInternal conte connection.concurrencyChangeHandler(listener::onConcurrencyChange); owner.init(connection); long capacity = connection.concurrency(); - int idx = connection.protocolVersion() != HttpVersion.HTTP_2 ? 0 : 1; + int idx; + if (connection instanceof Http2UpgradeClientConnection && ((Http2UpgradeClientConnection)connection).upgradePending()) { + // The clear-text upgrade rides on the first request: classify with the HTTP/2 intent + // so the pool does not dial into phantom HTTP/1 headroom, the concurrency raises with + // onConcurrencyChange when the upgrade succeeds; reclassify when it is rejected, + // returning the capacity so the pool can dial more HTTP/1 connections + idx = 1; + ((Http2UpgradeClientConnection)connection).upgradeRejectedHandler(v -> listener.onKindChange(0)); + } else { + idx = connection.protocolVersion() != HttpVersion.HTTP_2 ? 0 : 1; + } return new ConnectResult<>(connection, capacity, idx); }); if (owner.exceptionHandler != null) { @@ -264,20 +267,24 @@ public Future> connect(ContextInternal conte @Override public boolean isValid(HttpClientConnection connection) { + throw new UnsupportedOperationException(); + } + + private boolean checkConnection(HttpClientConnection connection) { return connection.isValid() && (maxLifetimeMillis == 0L || (System.currentTimeMillis() - connection.creationTimestamp()) <= maxLifetimeMillis); } + @Override + public void close(HttpClientConnection connection) { + connection.close(); + } + void checkExpired() { - pool - .evict(c -> !isValid(c), (lst, err) -> { - if (err == null) { - lst.forEach(HttpConnection::close); - } - }); + pool.refresh(); } - void acquire(ContextInternal context, PoolWaiter.Listener listener, Promise> promise) { - pool.acquire(context, listener, poolKind, promise); + void acquire(ContextInternal context, PoolWaiter.Listener listener, long timeout, Promise> promise) { + pool.acquire(context, listener, poolKind, timeout > 0L ? Duration.ofMillis(timeout) : null, promise); } void close() { diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java index 7905cc922c0..4caaa8fff0c 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2ClientConnectionImpl.java @@ -71,6 +71,7 @@ public class Http2ClientConnectionImpl extends Http2ConnectionImpl implements Ht this.authority = authority; this.creationTimestamp = System.currentTimeMillis(); this.handler = connHandler; + recycle(); } @Override diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java index 107079fb19e..cc9856fc07d 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/codec/Http2CodecClientChannelInitializer.java @@ -132,11 +132,13 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc case UPGRADE_SUCCESSFUL: // Remove Http1xClientConnection handler pipeline.remove("handler"); - // Go through + // Remove this handler + // Upgrade handler will remove itself and remove the HttpClientCodec + pipeline.remove(this); + break; case UPGRADE_REJECTED: // Remove this handler pipeline.remove(this); - // Upgrade handler will remove itself and remove the HttpClientCodec result.upgradeRejected(); break; } diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java index 4faab4177e2..ae62450e4a4 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java @@ -70,6 +70,7 @@ public Http2MultiplexClientConnection(Http2MultiplexHandler handler, this.evicted = false; this.decompressionSupported = decompressionSupported; this.creationTimestamp = System.currentTimeMillis(); + refresh(); } @Override diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java index 9caa32b7f02..4090991de90 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/http3/Http3ClientConnection.java @@ -66,6 +66,7 @@ public Http3ClientConnection(QuicConnectionInternal connection, this.keepAliveTimeoutMillis = keepAliveTimeoutMillis; this.creationTimestamp = System.currentTimeMillis(); this.concurrency = concurrency; + refresh(); } public void init() { diff --git a/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java b/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java index 277b24cc20e..b6634c37e81 100644 --- a/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java +++ b/vertx-core/src/main/java/io/vertx/core/http/impl/tcp/Http2UpgradeClientConnection.java @@ -60,6 +60,7 @@ public class Http2UpgradeClientConnection implements io.vertx.core.http.impl.Htt private final ClientMetrics clientMetrics; private io.vertx.core.http.impl.HttpClientConnection current; private boolean upgradeProcessed; + private Handler upgradeRejectedHandler; private Handler closeHandler; private Handler shutdownHandler; @@ -83,6 +84,21 @@ public io.vertx.core.http.impl.HttpClientConnection unwrap() { return current; } + /** + * @return whether the clear-text upgrade has not been resolved yet + */ + public boolean upgradePending() { + return current instanceof Http1ClientConnection && !upgradeProcessed; + } + + /** + * Set the handler signalled when the clear-text upgrade is rejected and the connection remains HTTP/1.1. + */ + public Http2UpgradeClientConnection upgradeRejectedHandler(Handler handler) { + upgradeRejectedHandler = handler; + return this; + } + @Override public MultiMap newHttpRequestHeaders() { return current.newHttpRequestHeaders(); @@ -348,6 +364,7 @@ void handleUpgrade(io.vertx.core.http.impl.HttpClientConnection conn, HttpClient pushHandler = null; closeHandler = null; upgradedConnection.current = conn; + upgradedConnection.upgradeProcessed = true; conn.closeHandler(upgradedConnection.closeHandler); conn.exceptionHandler(upgradedConnection.exceptionHandler); conn.pingHandler(upgradedConnection.pingHandler); @@ -367,6 +384,7 @@ void handleUpgrade(io.vertx.core.http.impl.HttpClientConnection conn, HttpClient upgradedConnection.evictionHandler = null; upgradedConnection.concurrencyChangeHandler = null; upgradedConnection.invalidMessageHandler = null; + upgradedConnection.upgradeRejectedHandler = null; concurrencyChangeHandler.handle(conn.concurrency()); } @@ -417,6 +435,11 @@ public void upgradeAccepted(io.vertx.core.http.impl.HttpClientConnection connect public void upgradeRejected() { UpgradingStream.this.upgradeRejected = true; UpgradingStream.this.upgradedConnection.upgradeProcessed = true; + Handler handler = UpgradingStream.this.upgradedConnection.upgradeRejectedHandler; + UpgradingStream.this.upgradedConnection.upgradeRejectedHandler = null; + if (handler != null) { + handler.handle(null); + } } @Override public void upgradeFailure(Throwable cause) { diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java index 5a4a3bad50f..8f8542b5daf 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/CombinerExecutor.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; /** * Lock free executor. @@ -30,6 +31,7 @@ public class CombinerExecutor implements Executor { private final Queue> q = PlatformDependent.newMpscQueue(); private final AtomicInteger s = new AtomicInteger(); private final S state; + private final Supplier> finalAction; protected static final class InProgressTail { @@ -46,7 +48,12 @@ public InProgressTail(CombinerExecutor combiner, Task task) { private static final FastThreadLocal> current = new FastThreadLocal<>(); public CombinerExecutor(S state) { + this(state, null); + } + + public CombinerExecutor(S state, Supplier> finalAction) { this.state = state; + this.finalAction = finalAction; } @Override @@ -55,6 +62,20 @@ public void submit(Action action) { if (s.get() != 0 || !s.compareAndSet(0, 1)) { return; } + drain(); + } + + @Override + public boolean trySubmit(Action action) { + if (s.get() != 0 || !s.compareAndSet(0, 1)) { + return false; + } + q.add(action); + drain(); + return true; + } + + private void drain() { Task head = null; Task tail = null; do { @@ -77,6 +98,23 @@ public void submit(Action action) { } } } + if (finalAction != null) { + Action a = finalAction.get(); + if (a != null) { + final Task task = a.execute(state); + if (task != null) { + Task last = task.last(); + if (head == null) { + assert tail == null; + tail = last; + head = task; + } else { + tail.next(task); + tail = last; + } + } + } + } } finally { s.set(0); } diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java index 7a7763caf6a..540d254d2d4 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/ConnectionPool.java @@ -15,6 +15,7 @@ import io.vertx.core.internal.ContextInternal; import io.vertx.core.internal.VertxInternal; +import java.time.Duration; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; @@ -70,6 +71,13 @@ static ConnectionPool pool(PoolConnector connector, int[] maxSizes, in */ ConnectionPool contextProvider(Function contextProvider); + /** + * Refresh the pool: check and perform the maintenance tasks to do, this method + * should be called periodically. Depending on the granularity of the period, + * deadlines might be passed, which is acceptable. + */ + void refresh(); + /** * Acquire a connection from the pool. * @@ -87,6 +95,23 @@ static ConnectionPool pool(PoolConnector connector, int[] maxSizes, in */ void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Completable> handler); + /** + * Like {@link #acquire(ContextInternal, int, Completable)} with a timeout: when the acquisition + * remains pending after the timeout, the pool removes the waiter from the wait queue and signals + * {@link PoolWaiter.Listener#onTimeout}, nothing else. The timeout is checked when the pool + * executes, deadlines might be passed. The default implementation ignores the timeout. + */ + default void acquire(ContextInternal context, int kind, Duration timeout, Completable> handler) { + acquire(context, kind, handler); + } + + /** + * Like {@link #acquire(ContextInternal, PoolWaiter.Listener, int, Completable)} with a timeout. + */ + default void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Duration timeout, Completable> handler) { + acquire(context, listener, kind, handler); + } + /** * Cancel a waiter. * diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java new file mode 100644 index 00000000000..2df023466a6 --- /dev/null +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/DefaultConnectionPool.java @@ -0,0 +1,1226 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.core.internal.pool; + +import io.vertx.core.*; +import io.vertx.core.http.ConnectionPoolTooBusyException; +import io.vertx.core.internal.ContextInternal; + +import java.time.Duration; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + *

The pool is a state machine that maintains a queue of waiters and a list of connections. + * + *

Pool state

+ * + *

Interactions with the pool modifies the pool state and then the pool executes actions to make progress satisfying + * the pool requests. + * + *

The pool is implemented as a non blocking state machine. + * + *

Calls to the pool are serialized to avoid race conditions and maintain its invariants. This pool can + * be called from different threads safely. The pool state is mutated exclusively by {@link Executor.Action} and actions are serialized + * by the executor. + * + *

Pool capacity

+ * + * To constrain the number of connections the pool maintains a {@link #capacity} field that must remain lesser than + * {@link #maxCapacity} to create a connection. Such capacity is used instead of counting connection because the pool + * can mix connections with different concurrency (HTTP/1 and HTTP/2) and this flexibility is necessary. + * + *

Pool connector

+ * + * The pool interacts with connections with the {@link PoolConnector}. The {@link PoolConnector.Listener} + * let the connector interact with pool: + *
    + *
  • The connector can remove connections from the pool using {@link PoolConnector.Listener#onRemove()}.
  • + *
  • The connector can signal the change of the connection capacity using {@link PoolConnector.Listener#onConcurrencyChange(long)}.
  • + *
+ * + *

Connection eviction

+ * + * Connections can be evicted from the pool with {@link ConnectionPool#evict(Predicate)}. It + * can be used to implement keep alive timeout. + * + *

Waiter lifecycle

+ * + * Connection requests are done with {@link ConnectionPool#acquire(ContextInternal, int)}. Such request + * creates a {@link PoolWaiter}. When such request is made + * + *
    + *
  • the waiter can be handed back a connection when one is immediately available
  • + *
  • a connection can be created and then handed back to the waiter that initiated the action
  • + *
  • the waiter can be enqueued when the pool is full and the wait queue is not full
  • + *
  • the waiter can be failed
  • + *
+ * + * A connection acquisition a {@link PoolWaiter.Listener} can be provided, letting the requester + * to get a reference on the waiter and later use {@link #cancel(PoolWaiter)} to cancel + * a request. + */ +public class DefaultConnectionPool implements ConnectionPool { + + private static final VertxException POOL_CLOSED_EXCEPTION = new VertxException("Pool closed", true); + + /** + * Select the first available available connection with the same event loop. + */ + private static final BiFunction, PoolConnection> SAME_EVENT_LOOP_SELECTOR = (waiter, list) -> { + int size = list.size(); + for (int i = 0;i < size;i++) { + PoolConnection slot = list.get(i); + if (slot.context().nettyEventLoop() == waiter.context().nettyEventLoop() && slot.available() > 0) { + return slot; + } + } + return null; + }; + + /** + * Select the first available connection. + */ + private static final BiFunction, PoolConnection> FIRST_AVAILABLE_SELECTOR = (waiter, list) -> { + int size = list.size(); + for (int i = 0;i < size;i++) { + PoolConnection slot = list.get(i); + if (slot.available() > 0) { + return slot; + } + } + return null; + }; + + /** + * A slot for a connection. + */ + static class Slot implements PoolConnector.Listener, PoolConnection { + + private final DefaultConnectionPool pool; + private final ContextInternal context; + private Promise result; + private C connection; // The actual connection, might be null + private int index; // The index in the pool slots array + private int usage; // The number of times this connection is acquired + private long concurrency; // The total number of times the connection can be acquired + private int capacity; // The connection capacity + + public Slot(DefaultConnectionPool pool, ContextInternal context, int index, int capacity) { + this.pool = pool; + this.context = context; + this.connection = null; + this.usage = 0; + this.index = index; + this.capacity = capacity; + this.result = context.promise(); + } + + @Override + public void onRemove() { + pool.remove(this); + } + + @Override + public void onKindChange(int kind) { + pool.setKind(this, kind); + } + + @Override + public void onConcurrencyChange(long concurrency) { + pool.setConcurrency(this, concurrency); + } + + @Override + public ContextInternal context() { + return context; + } + + @Override + public C get() { + return connection; + } + + @Override + public int usage() { + return usage; + } + + @Override + public long available() { + return concurrency - usage; + } + + @Override + public long concurrency() { + return concurrency; + } + } + + private final PoolConnector connector; + private final int maxWaiters; + private final int maxCapacity; + private final int[] capacityFactors; + private final Executor> sync; + private final ListImpl list = new ListImpl(); + + // Whether the pool is closed + private boolean closed; + + // Selectors + private BiFunction, List>, PoolConnection> selector; + private Function contextProvider; + private BiFunction, List>, PoolConnection> fallbackSelector; + + // Connection state + private final Slot[] slots; // The pool connections, this array is not sparse + private int size; // The number of non null slots + private int capacity; // The pool capacity + + // The submitted waiters, not yet acknowledged + private final Waiters submitted; + + // The waiters acknowledged in the wait queue + private final Waiters waiters; + + // Scratch structures of the progress, allocated once and reused between runs: the executor + // guarantees a single progress at a time + private final TaskList tasks; + private final Deque> admitted; + + private int connecting; + + // The recorded connect failure + private Throwable failureCause; + + // The number of connect successes since the pool creation + private long connectCount; + + // The reconnection strategy: no connect attempt before the suspension deadline, cleared at the + // round boundary when it expired or when a connect succeeded since it was armed + private final long retryDelayNanos; + private long suspendedUntilNanos; + private long suspendedConnectCount; + + // The time of the execution round, captured by its first progress: the round reasons + // against a single timestamp, assuming tasks execute quickly + private long roundNanos; + + // The connection checker owns the whole connection validity, transport validity and + // expiration policy, the pool does not use PoolConnector#isValid: an idle connection that + // does not pass the check is evicted and closed at the beginning of the execution round, + // before any demand is served + private final Predicate connectionChecker; + + // The minimum capacity, computed from the minimum sizes: missing connections are created at + // the end of each execution round with the supplied connection properties, paced by the + // reconnection strategy + private final int minCapacity; + private final int defaultKind; + private final Supplier contextSupplier; + + // Whether the next progress is the first of the execution round + private boolean first = true; + + public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes) { + return new DefaultConnectionPool<>(connector, maxSizes); + } + + public static DefaultConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return new DefaultConnectionPool<>(connector, maxSizes, maxWaiters, null, null, null, 0, null); + } + + public static Builder builder(PoolConnector connector) { + return new Builder<>(connector); + } + + public static class Builder { + + private final PoolConnector connector; + private int[] maxSizes; + private int maxWaiters = -1; + private Duration connectRetryDelay; + private int[] minSizes; + private Predicate connectionChecker; + private int defaultKind; + private Supplier contextSupplier; + + Builder(PoolConnector connector) { + this.connector = Objects.requireNonNull(connector); + } + + public Builder withMaxSizes(int[] maxSizes) { + this.maxSizes = maxSizes; + return this; + } + + public Builder withMaxWaiters(int maxWaiters) { + this.maxWaiters = maxWaiters; + return this; + } + + public Builder withConnectRetryDelay(Duration connectRetryDelay) { + this.connectRetryDelay = connectRetryDelay; + return this; + } + + public Builder withConnectionChecker(Predicate connectionChecker) { + this.connectionChecker = connectionChecker; + return this; + } + + public Builder withMinSizes(int[] minSizes) { + this.minSizes = minSizes; + return this; + } + + public Builder withDefaultKind(int defaultKind) { + this.defaultKind = defaultKind; + return this; + } + + public Builder withContextSupplier(Supplier contextSupplier) { + this.contextSupplier = contextSupplier; + return this; + } + + public DefaultConnectionPool build() { + return new DefaultConnectionPool<>(connector, Objects.requireNonNull(maxSizes), maxWaiters, connectRetryDelay, connectionChecker, minSizes, defaultKind, contextSupplier); + } + } + + DefaultConnectionPool(PoolConnector connector, int[] maxSizes) { + this(connector, maxSizes, -1, null, null, null, 0, null); + } + + DefaultConnectionPool(PoolConnector connector, int[] maxSizes, int maxWaiters, Duration connectRetryDelay, + Predicate connectionChecker, int[] minSizes, int defaultKind, + Supplier contextSupplier) { + + int[] capacities = new int[maxSizes.length]; + int maxCapacity = 1; + int numSlots = 0; + for (int i = 0;i < maxSizes.length;i++) { + int maxSize = maxSizes[i]; + if (maxSize < 1) { + throw new IllegalArgumentException(); + } + maxCapacity *= maxSize; + numSlots = Math.max(numSlots, maxSize); + } + for (int i = 0;i < maxSizes.length;i++) { + capacities[i] = maxCapacity / maxSizes[i]; + } + int minCapacity = 0; + if (minSizes != null) { + if (minSizes.length != maxSizes.length) { + throw new IllegalArgumentException("Minimum sizes must have one size per kind, like the maximum sizes"); + } + for (int i = 0;i < minSizes.length;i++) { + if (minSizes[i] < 0 || minSizes[i] > maxSizes[i]) { + throw new IllegalArgumentException("Minimum size must be between 0 and the maximum size of its kind"); + } + minCapacity = Math.max(minCapacity, minSizes[i] * capacities[i]); + } + } + if (defaultKind < 0 || defaultKind >= maxSizes.length) { + throw new IllegalArgumentException("Default kind must be an index in the maximum sizes"); + } + if (minCapacity > 0) { + if (contextSupplier == null) { + throw new IllegalArgumentException("A minimum pool size requires a context supplier"); + } + if (connectRetryDelay == null) { + throw new IllegalArgumentException("A minimum pool size requires a connect retry delay"); + } + } + + this.capacityFactors = capacities; + this.connector = connector; + this.slots = new Slot[numSlots]; + this.size = 0; + this.maxWaiters = maxWaiters; + this.capacity = 0; + this.maxCapacity = maxCapacity; + this.sync = new CombinerExecutor<>(this, this::finalAction); + this.selector = (BiFunction) SAME_EVENT_LOOP_SELECTOR; + this.fallbackSelector = (BiFunction) FIRST_AVAILABLE_SELECTOR; + this.contextProvider = EVENT_LOOP_CONTEXT_PROVIDER; + this.submitted = new Waiters<>(); + this.waiters = new Waiters<>(); + this.tasks = new TaskList(); + this.admitted = new ArrayDeque<>(); + this.retryDelayNanos = connectRetryDelay == null ? 0L : connectRetryDelay.toNanos(); + this.connectionChecker = connectionChecker == null ? c -> true : connectionChecker; + this.minCapacity = minCapacity; + this.defaultKind = defaultKind; + this.contextSupplier = contextSupplier; + } + + @Override + public ConnectionPool connectionSelector(BiFunction, List>, PoolConnection> selector) { + this.selector = selector; + return this; + } + + @Override + public ConnectionPool contextProvider(Function contextProvider) { + this.contextProvider = contextProvider; + return this; + } + + private void execute(Executor.Action> action) { + sync.submit(action); + } + + private Executor.Action> finalAction() { + return first ? null : new Cleanup<>(); + } + + private static class Cleanup implements Executor.Action> { + + @Override + public Task execute(DefaultConnectionPool pool) { + Task head = pool.last(); + pool.first = true; + return head; + } + } + + private void removeSlot(Slot slot) { + int w = slot.capacity; + slot.usage = 0; + slot.concurrency = 0; + slot.connection = null; + slot.capacity = 0; + if (size > 1) { + Slot tmp = slots[size - 1]; + tmp.index = slot.index; + slots[slot.index] = tmp; + slots[size - 1] = null; + } else { + slots[0] = null; + } + size--; + capacity -= w; + } + + private boolean isWaitersQueueFull() { + return maxWaiters != -1 && waiters.size() >= maxWaiters; + } + + private Task progress() { + progress(tasks); + Task head = tasks.first(); + tasks.clear(); + return head; + } + + private void progress(TaskList tasks) { + + // On the first progress of the execution round, evict the timed out waiters and the stale + // connections before any demand is served: a connection that is not valid is expired + if (first) { + first = false; + roundNanos = System.nanoTime(); + if (suspendedUntilNanos != 0 && (roundNanos - suspendedUntilNanos >= 0 || connectCount > suspendedConnectCount)) { + // The suspension of the reconnection strategy is over or a connect succeeded since it was armed + suspendedUntilNanos = 0; + } + PoolWaiter current = waiters.peek(); + while (current != null) { + PoolWaiter waiter = current; + current = waiters.next(current); + if (waiter.deadlineNanos != 0 && roundNanos - waiter.deadlineNanos >= 0) { + waiters.remove(waiter); + Task task = new Task() { + @Override + public void run() { + waiter.listener.onTimeout(waiter); + } + }; + tasks.append(task); + } + } + for (int i = size - 1;i >= 0;i--) { + Slot slot = slots[i]; + if (slot.connection != null && slot.usage == 0 && !connectionChecker.test(slot.connection)) { + C connection = slot.connection; + removeSlot(slot); + Task task = new Task() { + @Override + public void run() { + connector.close(connection); + } + }; + tasks.append(task); + } + } + } + + // Connect failure policy: fail one pending acquisition per recorded failure, alternative + // policies (bounded retry, fail-fast, ...) plug in here. + // Under persistent failures this signals every waiter: each failure fails the head while the + // loop below connects for the next one, until the wait queue is empty. To reconsider if the + // pool gets time based eviction of waiters, guaranteeing the signalling instead + if (failureCause != null) { + Throwable cause = failureCause; + failureCause = null; + if (retryDelayNanos > 0) { + suspendedUntilNanos = roundNanos + retryDelayNanos; + suspendedConnectCount = connectCount; + } + PoolWaiter waiter = waiters.poll(); + if (waiter != null) { + waiter.disposed = true; + Task task = new Task() { + @Override + public void run() { + waiter.handler.fail(cause); + } + }; + tasks.append(task); + } + } + + + // Satisfy the demand: peek from the wait queue, when it is exhausted peek from the submitted + // acquisitions, stop at the first demand that cannot be satisfied; the first connecting waiters + // are covered by in-flight connects: they can be granted but no connection is created for them. + // The reconnection strategy suspends connect attempts after a failure + boolean suspended = suspendedUntilNanos != 0; + int pos = 0; + PoolWaiter next = waiters.peek(); + while (true) { + boolean submission; + PoolWaiter waiter; + if (next != null) { + submission = false; + waiter = next; + next = waiters.next(next); + } else if ((waiter = submitted.poll()) != null) { + // Admit a submission in the wait queue, the bound is enforced by the move below only + // when it remains waiting: a submission served by a grant or a connect is exempted, + // like the existing pool + submission = true; + waiters.addLast(waiter); + admitted.add(waiter); + } else { + break; + } + Task task = null; + Slot slot1; + Slot slot3; + // 1. Try reuse a existing connection with the same context + if ((slot1 = (Slot) selector.apply(waiter, list)) != null) { + waiters.remove(waiter); + waiter.disposed = true; + slot1.usage++; + LeaseImpl lease = new LeaseImpl<>(slot1, waiter.handler); + task = new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } else if (pos >= connecting && capacity < maxCapacity && !suspended) { + // 2. Try create connection, the waiter joins the covered prefix of the wait queue + capacity += waiter.capacity; + ContextInternal connectionContext = contextProvider.apply(waiter.context); + Slot slot2 = new Slot<>(this, connectionContext, size, waiter.capacity); + slots[size++] = slot2; + connecting++; + pos++; + task = new Task() { + @Override + public void run() { + if (waiter.listener != null) { + waiter.listener.onConnect(waiter); + } + connect(slot2); + } + }; + } else if ((slot3 = (Slot) fallbackSelector.apply(waiter, list)) != null) { + // 3. Try use another context + waiters.remove(waiter); + waiter.disposed = true; + slot3.usage++; + LeaseImpl lease = new LeaseImpl<>(slot3, waiter.handler); + task = new Task() { + @Override + public void run() { + lease.emit(); + } + }; + } else if (pos < connecting) { + // 4. Covered by an in-flight connect, wait for it + pos++; + } else if (submission) { + // 5. Nothing is possible for the submission: give it back, the move below admits or + // rejects it with the remaining submissions + waiters.remove(waiter); + admitted.removeLast(); + submitted.addFirst(waiter); + break; + } else { + // 6. No satisfaction is possible anymore + break; + } + if (task != null) { + tasks.append(task); + } + } + + + // Move the remaining submissions to the wait queue, reject them when it is full + for (PoolWaiter extra = submitted.poll();extra != null;extra = submitted.poll()) { + if (!isWaitersQueueFull()) { + waiters.addLast(extra); + admitted.add(extra); + } else { + PoolWaiter rejected = extra; + Task task = new Task() { + @Override + public void run() { + Future> fut = rejected.context.failedFuture(new ConnectionPoolTooBusyException("Connection pool reached max wait queue size of " + maxWaiters)); + fut.onComplete(rejected.handler); + } + }; + tasks.append(task); + } + } + + + // Notify the admitted submissions still waiting + for (PoolWaiter waiter : admitted) { + if (waiter.next != null && waiter.listener != null) { + Task task = new Task() { + @Override + public void run() { + waiter.listener.onEnqueue(waiter); + } + }; + tasks.append(task); + } + } + admitted.clear(); + + + // Signal the connect results + for (int i = 0;i < size;i++) { + Slot slot = slots[i]; + if (slot.result != null && slot.connection != null) { + Promise result = slot.result; + C connection = slot.connection; + slot.result = null; + Task task = new Task() { + @Override + public void run() { + result.complete(connection); + } + }; + tasks.append(task); + } + } + } + + private Task last() { + // Satisfy the minimum capacity after all demand is served, creating one connection at a + // time of the default kind with the supplied context, when no connect is in flight: the + // actual weight of a connection is known on connect success only, connecting one at a time + // avoids overshooting the capacity. A floor connect counts as connecting, covering + // waiters arriving while it is in flight. The reconnection strategy paces the floor retries + boolean suspended = suspendedUntilNanos != 0; + if (!closed && !suspended && connecting == 0 && capacity < minCapacity) { + int floorCapacity = capacityFactors[defaultKind]; + capacity += floorCapacity; + ContextInternal connectionContext = contextProvider.apply(contextSupplier.get()); + Slot slot = new Slot<>(this, connectionContext, size, floorCapacity); + slots[size++] = slot; + connecting++; + return new Task() { + @Override + public void run() { + connect(slot); + } + }; + } + return null; + } + + public int size() { + return size; + } + + private void connect(Slot slot) { + connector.connect(slot.context, slot).onComplete(ar -> { + if (ar.succeeded()) { + execute(new ConnectSuccess<>(slot, ar.result())); + } else { + execute(new ConnectFailed<>(slot, ar.cause())); + } + }); + } + + private static class ConnectSuccess implements Executor.Action> { + + private final Slot slot; + private final ConnectResult result; + + private ConnectSuccess(Slot slot, ConnectResult result) { + this.slot = slot; + this.result = result; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + + int capacity = pool.capacityFactors[(int)result.weight()]; + + int initialCapacity = slot.capacity; + slot.connection = result.connection(); + slot.concurrency = result.concurrency(); + slot.capacity = capacity; + slot.usage = 0; + pool.connecting--; + pool.capacity += (capacity - initialCapacity); + pool.connectCount++; + if (pool.closed) { + return new Task() { + @Override + public void run() { + slot.result.complete(slot.connection); + } + }; + } + return pool.progress(); + } + } + + private static class KindChange implements Executor.Action> { + + private final Slot slot; + private final int kind; + + private KindChange(Slot slot, int kind) { + this.slot = slot; + this.kind = kind; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (slot.connection != null) { + int capacity = pool.capacityFactors[kind]; + pool.capacity += capacity - slot.capacity; + slot.capacity = capacity; + } + if (pool.closed) { + return null; + } + return pool.progress(); + } + } + + private static class ConnectFailed implements Executor.Action> { + + private final Slot removed; + private final Throwable cause; + + public ConnectFailed(Slot removed, Throwable cause) { + this.removed = removed; + this.cause = cause; + } + + public Task execute(DefaultConnectionPool pool) { + pool.connecting--; + Task task = new Task() { + @Override + public void run() { + removed.result.fail(cause); + } + }; + if (pool.closed) { + return task; + } + pool.removeSlot(removed); + pool.failureCause = cause; + Task head = pool.progress(); + if (head == null) { + head = task; + } else { + head.last().next(task); + } + return head; + } + } + + private static class Remove implements Executor.Action> { + + protected final Slot removed; + + private Remove(Slot removed) { + this.removed = removed; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed || pool.slots[removed.index] != removed) { + return null; + } + pool.removeSlot(removed); + return pool.progress(); + } + } + + private static class SetConcurrency implements Executor.Action> { + + private final Slot slot; + private final long concurrency; + + SetConcurrency(Slot slot, long concurrency) { + this.slot = slot; + this.concurrency = concurrency; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (slot.connection != null) { + slot.concurrency = concurrency; + return pool.progress(); + } + return null; + } + } + + private void setKind(Slot slot, int kind) { + execute(new KindChange<>(slot, kind)); + } + + private void setConcurrency(Slot slot, long concurrency) { + execute(new SetConcurrency<>(slot, concurrency)); + } + + private void remove(Slot removed) { + execute(new Remove<>(removed)); + } + + private static class Evict implements Executor.Action> { + + private final Predicate predicate; + private final Completable> handler; + + public Evict(Predicate predicate, Completable> handler) { + this.predicate = predicate; + this.handler = handler; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + handler.fail(POOL_CLOSED_EXCEPTION); + } + }; + } + List res = new ArrayList<>(); + for (int i = pool.size - 1;i >= 0;i--) { + Slot slot = pool.slots[i]; + if (slot.connection != null && slot.usage == 0 && predicate.test(slot.connection)) { + res.add(slot.connection); + pool.removeSlot(slot); + } + } + TaskList tasks = new TaskList(); + tasks.append(new Task() { + @Override + public void run() { + handler.succeed(res); + } + }); + Task next = pool.progress(); + if (next != null) { + tasks.append(next); + } + return tasks.first(); + } + } + + @Override + public void evict(Predicate predicate, Completable> handler) { + execute(new Evict<>(predicate, handler)); + } + + private static class Acquire extends PoolWaiter implements Executor.Action> { + + public Acquire(ContextInternal context, PoolWaiter.Listener listener, int capacity, Duration timeout, Completable> handler) { + super(listener, context, capacity, handler); + if (timeout != null) { + deadlineNanos = System.nanoTime() + timeout.toNanos(); + } + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + Future> fut = context.failedFuture("Pool closed"); + fut.onComplete(handler); + } + }; + } + pool.submitted.addLast(this); + Task head = pool.progress(); + assert pool.submitted.size() == 0; + return head; + } + } + + @Override + public void refresh() { + sync.trySubmit(new Refresh<>()); + } + + private static class Refresh implements Executor.Action> { + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return null; + } + return pool.progress(); + } + } + + @Override + public void acquire(ContextInternal context, int kind, Completable> handler) { + acquire(context, PoolWaiter.NULL_LISTENER, kind, null, handler); + } + + @Override + public void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Completable> handler) { + acquire(context, listener, kind, null, handler); + } + + @Override + public void acquire(ContextInternal context, int kind, Duration timeout, Completable> handler) { + acquire(context, PoolWaiter.NULL_LISTENER, kind, timeout, handler); + } + + @Override + public void acquire(ContextInternal context, PoolWaiter.Listener listener, int kind, Duration timeout, Completable> handler) { + execute(new Acquire<>(context, listener, capacityFactors[kind], timeout, handler)); + } + + @Override + public void cancel(PoolWaiter waiter, Completable handler) { + execute(new Cancel<>(waiter, handler)); + } + + private static class Cancel extends Task implements Executor.Action> { + + private final PoolWaiter waiter; + private final Completable handler; + private boolean cancelled; + + public Cancel(PoolWaiter waiter, Completable handler) { + this.waiter = waiter; + this.handler = handler; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + handler.fail(POOL_CLOSED_EXCEPTION); + } + }; + } + cancelled = pool.waiters.remove(waiter) || !waiter.disposed; + waiter.disposed = true; + return this; + } + + @Override + public void run() { + handler.succeed(cancelled); + } + } + + static class LeaseImpl implements Lease { + + private final Completable> handler; + private final Slot slot; + private final C connection; + private boolean recycled; + + public LeaseImpl(Slot slot, Completable> handler) { + this.handler = handler; + this.slot = slot; + this.connection = slot.connection; + } + + @Override + public C get() { + return connection; + } + + @Override + public void recycle() { + slot.pool.recycle(this); + } + + void emit() { + Future> fut = slot.context.succeededFuture(this); + fut.onComplete(handler); + } + } + + private static class Recycle implements Executor.Action> { + + private final Slot slot; + + public Recycle(Slot slot) { + this.slot = slot; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (!pool.closed && slot.connection != null) { + slot.usage--; + return pool.progress(); + } + return null; + } + } + + private void recycle(LeaseImpl lease) { + if (lease.recycled) { + throw new IllegalStateException("Attempt to recycle more than permitted"); + } + lease.recycled = true; + execute(new Recycle<>(lease.slot)); + } + + public int waiters() { + return Math.max(0, waiters.size() - connecting); + } + + public int capacity() { + return capacity; + } + + @Override + public int requests() { + return connecting; + } + + private static class Close implements Executor.Action> { + + private final Completable>> handler; + + private Close(Completable>> handler) { + this.handler = handler; + } + + @Override + public Task execute(DefaultConnectionPool pool) { + if (pool.closed) { + return new Task() { + @Override + public void run() { + handler.fail(POOL_CLOSED_EXCEPTION); + } + }; + } + pool.closed = true; + List> waiters = pool.waiters.clear(); + List> list = new ArrayList<>(); + for (int i = 0;i < pool.size;i++) { + Slot slot = pool.slots[i]; + pool.slots[i] = null; + pool.capacity -= slot.capacity; + if (slot.result != null) { + list.add(slot.result.future()); + } else { + list.add(slot.context.succeededFuture(slot.connection)); + } + } + pool.size = 0; + return new Task() { + @Override + public void run() { + waiters.forEach(w -> { + w.handler.fail(POOL_CLOSED_EXCEPTION); + }); + handler.succeed(list); + } + }; + } + } + + @Override + public void close(Completable>> handler) { + execute(new Close<>(handler)); + } + + private static class Waiters implements Iterable> { + + private final PoolWaiter head; + private int size; + + public Waiters() { + head = new PoolWaiter<>(null, null, 0, null); + head.next = head.prev = head; + } + + PoolWaiter peek() { + return head.next == head ? null : head.next; + } + + PoolWaiter next(PoolWaiter node) { + return node.next == head ? null : node.next; + } + + PoolWaiter peekLast() { + return head.prev == head ? null : head.prev; + } + + PoolWaiter poll() { + if (head.next == head) { + return null; + } + PoolWaiter node = head.next; + remove(node); + return node; + } + + void addLast(PoolWaiter node) { + if (node.next != null) { + throw new IllegalStateException(); + } + node.prev = head.prev; + node.next = head; + head.prev.next = node; + head.prev = node; + size++; + } + + void addFirst(PoolWaiter node) { + if (node.next != null) { + throw new IllegalStateException(); + } + node.prev = head; + node.next = head.next; + head.next.prev = node; + head.next = node; + size++; + } + + boolean remove(PoolWaiter node) { + if (node.next == null) { + return false; + } + node.next.prev = node.prev; + node.prev.next = node.next; + node.next = node.prev = null; + size--; + return true; + } + + List> clear() { + List> lst = new ArrayList<>(size); + this.forEach(lst::add); + for (PoolWaiter node : lst) { + node.next = node.prev = null; + } + size = 0; + head.next = head.prev = head; + return lst; + } + + int size() { + return size; + } + + @Override + public Iterator> iterator() { + return new Iterator>() { + PoolWaiter current = head; + @Override + public boolean hasNext() { + return current.next != head; + } + @Override + public PoolWaiter next() { + if (current.next == head) { + throw new NoSuchElementException(); + } + try { + return current.next; + } finally { + current = current.next; + } + } + }; + } + } + + class ListImpl extends AbstractList> { + @Override + public PoolConnection get(int index) { + return slots[index]; + } + @Override + public int size() { + return size; + } + } + + private static class TaskList { + + private Task head; + private Task tail; + + void append(Task task) { + if (head == null) { + head = task; + } else { + tail.next(task); + } + tail = task; + } + + Task first() { + return head; + } + + void clear() { + head = null; + tail = null; + } + } +} diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java index 5f74371e3ec..27ef0fe087d 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/Executor.java @@ -38,4 +38,13 @@ interface Action { */ void submit(Action action); + /** + * Submit an action to execute only when the ownership of the execution can be acquired, + * otherwise do nothing. + * + * @param action the action + * @return whether the action was executed + */ + boolean trySubmit(Action action); + } diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java index 04c31cf7204..b0b70400c41 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolConnector.java @@ -32,14 +32,23 @@ public interface PoolConnector { /** * Checks whether the connection is still valid. * - *

The pool calls this method when it checks the validity of a connection. Any connection - * will be evicted from the pool. + *

A connection that is not valid is expired: the pool evicts it when it cleans up and + * closes it with {@link #close}. The notion of expiration belongs to the connector, e.g. a + * maximum lifetime or a broken connection. * * @param connection the connection to check * @return whether the connection is valid or not */ boolean isValid(C connection); + /** + * Close a connection evicted by the pool. + * + * @param connection the connection to close + */ + default void close(C connection) { + } + /** * The contract by which the back-end can signal the pool of connection events. * @@ -59,5 +68,14 @@ interface Listener { */ void onConcurrencyChange(long concurrency); + /** + * Signals the connection kind changed to the {@code kind} value, e.g. after a clear-text + * upgrade resolution: the pool adjusts the connection capacity accordingly. + * + * @param kind the connection kind, an index in the max size array the pool is constructed with + */ + default void onKindChange(int kind) { + } + } } diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java index 5c834e64273..b2c363deb09 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/PoolWaiter.java @@ -41,6 +41,14 @@ default void onEnqueue(PoolWaiter waiter) { */ default void onConnect(PoolWaiter waiter) { } + + /** + * The waiter timed out: the pool removed it from the wait queue, nothing else. + * + * @param waiter the waiter + */ + default void onTimeout(PoolWaiter waiter) { + } } final PoolWaiter.Listener listener; @@ -51,6 +59,7 @@ default void onConnect(PoolWaiter waiter) { PoolWaiter next; boolean disposed; boolean queued; + long deadlineNanos; PoolWaiter(PoolWaiter.Listener listener, ContextInternal context, final int capacity, Completable> handler) { this.listener = listener; diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java index 5fd22b12380..ca766c39da9 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/SemaphoreExecutor.java @@ -25,6 +25,19 @@ public SemaphoreExecutor(S state) { @Override public void submit(Action action) { lock.lock(); + execute(action); + } + + @Override + public boolean trySubmit(Action action) { + if (!lock.tryLock()) { + return false; + } + execute(action); + return true; + } + + private void execute(Action action) { Task post = null; try { post = action.execute(state); diff --git a/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java b/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java index 6f65cd9a948..37ccc83d2b7 100644 --- a/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java +++ b/vertx-core/src/main/java/io/vertx/core/internal/pool/SimpleConnectionPool.java @@ -75,7 +75,6 @@ */ public class SimpleConnectionPool implements ConnectionPool { - private static final Future POOL_CLOSED = Future.failedFuture("Pool closed"); private static final VertxException POOL_CLOSED_EXCEPTION = new VertxException("Pool closed", true); /** @@ -639,6 +638,10 @@ public void run() { } } + @Override + public void refresh() { + } + @Override public void acquire(ContextInternal context, int kind, Completable> handler) { execute(new Acquire<>(context, PoolWaiter.NULL_LISTENER, capacityFactors[kind], handler)); @@ -923,79 +926,4 @@ public int size() { return size; } } - - static class LazyFuture extends io.vertx.core.impl.future.FutureBase implements Promise { - - private final List> handlers = new ArrayList<>(); - private Future fut = null; - - @Override - public boolean tryComplete(T result) { - handle(Future.succeededFuture(result)); - return true; - } - - @Override - public boolean tryFail(Throwable cause) { - handle(Future.failedFuture(cause)); - return true; - } - - @Override - public Future future() { - return this; - } - - @Override - public void handle(AsyncResult event) { - Future f = (Future) event; - List> h; - synchronized (this) { - fut = f; - h = handlers; - } - for (Completable t : h) { - t.complete(event.result(), event.cause()); - } - } - - @Override - public synchronized boolean isComplete() { - return fut != null && fut.isComplete(); - } - @Override - public synchronized T result() { - return fut != null ? fut.result() : null; - } - @Override - public Throwable cause() { - return fut != null ? fut.cause() : null; - } - @Override - public boolean succeeded() { - return fut != null && fut.succeeded(); - } - @Override - public boolean failed() { - return fut != null && fut.failed(); - } - @Override - public void addListener(Completable listener) { - Future f; - synchronized (this) { - f = fut; - if (f == null) { - handlers.add(listener); - return; - } - } - listener.complete(f.result(), f.cause()); - } - @Override - public void removeListener(Completable listener) { - synchronized (this) { - handlers.remove(listener); - } - } - } } diff --git a/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java b/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java index 2e821c38167..f76cee5ecde 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/Http1xProxyTest.java @@ -16,7 +16,6 @@ import io.vertx.core.http.*; import io.vertx.core.http.impl.CleanableHttpClient; import io.vertx.core.http.impl.HttpClientImpl; -import io.vertx.core.net.NetServer; import io.vertx.core.net.ProxyOptions; import io.vertx.core.net.ProxyType; import io.vertx.core.net.SocketAddress; @@ -37,7 +36,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; import static io.vertx.core.http.HttpMethod.GET; import static org.junit.Assert.*; @@ -635,11 +634,11 @@ private void testConnectTimeout(boolean shouldTimeout) throws Exception { @WithProxy(kind = ProxyKind.SOCKS5) @Test - public void testConnectionEstablishedAfterWaiterTimeoutIsClosed(Checkpoint checkpoint) throws Exception { - CountDownLatch latch = checkpoint.asLatch(2); - NetServer server = vertx.createNetServer(); - server.connectHandler(socket -> socket.closeHandler(v -> latch.countDown())); - server.listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST).await(); + public void testConnectionEstablishedAfterWaiterTimeoutIsPreserved() throws Exception { + AtomicInteger connections = new AtomicInteger(); + server.connectionHandler(conn -> connections.incrementAndGet()); + server.requestHandler(req -> req.response().end()); + startServer(); proxy.successDelayMillis(Duration.ofMillis(500)); client = vertx.createHttpClient(createBaseClientOptions() .setProxyOptions(new ProxyOptions() @@ -647,11 +646,15 @@ public void testConnectionEstablishedAfterWaiterTimeoutIsClosed(Checkpoint check .setHost(DEFAULT_HTTP_HOST) .setPort(proxy.port()) .setConnectTimeout(Duration.ofSeconds(5)))); - client.request(new RequestOptions(requestOptions).setConnectTimeout(100)) - .onComplete(ar -> { - assertTrue(ar.failed()); - latch.countDown(); - }); + // The connection established after the waiter timed out is preserved in the pool: the next + // request reuses it + assertThat(client.request(new RequestOptions(requestOptions).setConnectTimeout(100))) + .isFailure() + .compose(cause -> client.request(new RequestOptions(requestOptions))) + .compose(req -> req.send().compose(HttpClientResponse::end)) + .compose(v -> connections.get() == 1 ? Future.succeededFuture() + : Future.failedFuture(new AssertionError("Expected a single connection, got " + connections.get()))) + .await(); } @WithProxy(kind = ProxyKind.HTTP) diff --git a/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java b/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java index 0358b435bcc..b587723f13d 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/Http2Test.java @@ -707,6 +707,50 @@ public void testStreamWeightAndDependencyInheritancePushPromise(Checkpoint check .await(); } + @Test + public void testClearTextUpgradeConnectionConcurrency() throws Exception { + server = vertx.createHttpServer(); + server.requestHandler(req -> req.response().end()); + startServer(testAddress); + client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2)); + HttpClientConnection conn = client.connect(new HttpConnectOptions().setServer(testAddress).setSsl(false)).await(); + // The upgrade rides on the first request + conn.request(new RequestOptions(requestOptions).setSsl(false)) + .compose(req -> req.send().compose(HttpClientResponse::end)) + .await(); + // A successfully upgraded connection reports the HTTP/2 concurrency + assertTrue(((io.vertx.core.http.impl.UnpooledHttpClientConnection) conn).unwrap().concurrency() > 1); + } + + @Test + public void testClearTextUpgradeRejectedPoolGrowth() throws Exception { + // An HTTP/1.1 only server rejects the upgrade: the connection is reclassified and the pool + // dials more connections for the pending requests instead of staying capped by the HTTP/2 + // pool size + AtomicInteger connections = new AtomicInteger(); + List responses = Collections.synchronizedList(new ArrayList<>()); + server = vertx.createHttpServer(new HttpServerOptions().setHttp2ClearTextEnabled(false)); + server.connectionHandler(conn -> connections.incrementAndGet()); + server.requestHandler(req -> { + // Send the response head, defer the end: the request holds the connection while the + // upgrade resolves + HttpServerResponse resp = req.response().setChunked(true); + resp.write("x"); + responses.add(resp); + }); + startServer(testAddress); + client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2)); + Future body1 = client.request(new RequestOptions(requestOptions).setSsl(false)) + .compose(req -> req.send().compose(HttpClientResponse::body)); + Future body2 = client.request(new RequestOptions(requestOptions).setSsl(false)) + .compose(req -> req.send().compose(HttpClientResponse::body)); + AsyncTestBase.assertWaitUntil(() -> responses.size() == 2); + assertEquals(2, connections.get()); + new ArrayList<>(responses).forEach(HttpServerResponse::end); + body1.await(); + body2.await(); + } + @Test public void testClearTextUpgradeWithBody() throws Exception { server = vertx.createHttpServer().requestHandler(req -> { diff --git a/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java b/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java index 4ad7fea9d46..7619e1007c1 100644 --- a/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/http/HttpTest.java @@ -84,6 +84,15 @@ protected HttpTest(HttpConfigurator config) { super(config); } + @Test + public void testConnectionValidAfterConnect() throws Exception { + server.requestHandler(req -> req.response().end()); + startServer(testAddress); + HttpClientConnection conn = client.connect(new HttpConnectOptions().setServer(testAddress)).await(); + // A fresh connection must be valid: its keep-alive expiration starts at creation + assertTrue(((io.vertx.core.http.impl.UnpooledHttpClientConnection) conn).unwrap().isValid()); + } + @Test public void testCloseMulti() throws Exception { int num = 4; diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java index 9de5253ccbe..8df8248be9f 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/ConnectionPoolTest.java @@ -48,11 +48,19 @@ public void setUp() throws Exception { this.vertx = (VertxInternal) super.vertx; } + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { + return ConnectionPool.pool(connector, maxSizes); + } + + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return ConnectionPool.pool(connector, maxSizes, maxWaiters); + } + @Test public void testConnect() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected = new Connection(); pool .acquire(context, 0, TestUtils.onSuccess2(lease -> { @@ -71,7 +79,7 @@ public void testConnect() { public void testAcquireRecycledConnection() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }); + ConnectionPool pool = pool(mgr, new int[] { 10 }); Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); pool @@ -94,7 +102,7 @@ public void testAcquireRecycledConnection() throws Exception { public void testRecycleRemovedConnection() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected1 = new Connection(); Future> fut = Future.future(p -> pool.acquire(context, 0, p)); ConnectionRequest request1 = mgr.assertRequest(); @@ -120,7 +128,7 @@ public void testRecycleRemovedConnection() throws Exception { public void testConcurrency() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); pool @@ -140,7 +148,7 @@ public void testConcurrency() throws Exception { @Test public void testIncreaseConcurrency() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); CountDownLatch l1 = new CountDownLatch(1); @@ -166,7 +174,7 @@ public void testIncreaseConcurrency() throws Exception { public void testSatisfyPendingWaitersWithExtraConcurrency() throws Exception { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 2); Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); pool @@ -189,7 +197,7 @@ public void testSatisfyPendingWaitersWithExtraConcurrency() throws Exception { public void testEmptyConcurrency() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 2); Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); pool @@ -214,7 +222,7 @@ public void testEmptyConcurrency() { public void testEmptyConcurrencyWithManyWaiters() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 3); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 3); Connection expected = new Connection(); AtomicInteger seq = new AtomicInteger(); for (int i = 0;i < 3;i++) { @@ -238,7 +246,7 @@ public void testEmptyConcurrencyWithManyWaiters() { @Test public void testDecreaseConcurrency() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); CountDownLatch l1 = new CountDownLatch(2); @@ -278,7 +286,7 @@ public void testDecreaseConcurrency() throws Exception { public void testWaiter() throws Exception { ContextInternal ctx1 = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); @@ -303,7 +311,7 @@ public void testWaiter() throws Exception { public void testRemoveSingleConnection() throws Exception { ContextInternal ctx1 = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection conn = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool.acquire(ctx1, 0, TestUtils.onSuccess2(latch::complete)); @@ -319,7 +327,7 @@ public void testRemoveSingleConnection() throws Exception { public void testRemoveFirstConnection() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); Connection conn1 = new Connection(); CompletableFuture> latch1 = new CompletableFuture<>(); pool.acquire(ctx, 0, TestUtils.onSuccess2(latch1::complete)); @@ -340,7 +348,7 @@ public void testRemoveFirstConnection() throws Exception { public void testRemoveSingleConnectionWithWaiter() throws Exception { ContextInternal ctx1 = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); Connection connection1 = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); pool @@ -370,7 +378,7 @@ public void testRemoveSingleConnectionWithWaiter() throws Exception { @Test public void testConnectFailureWithPendingWaiter() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1, 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 1, 2 }, 2); Throwable failure = new Throwable(); Connection expected = new Connection(); CountDownLatch latch = new CountDownLatch(1); @@ -424,7 +432,7 @@ public void testExpireSome() throws Exception { private List testExpire(int num, int max, int... recycled) throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { max }, max); + ConnectionPool pool = pool(mgr, new int[] { max }, max); CountDownLatch latch = new CountDownLatch(num); List> leases = new ArrayList<>(); ContextInternal ctx = vertx.createEventLoopContext(); @@ -461,7 +469,7 @@ private List testExpire(int num, int max, int... recycled) throws Excep @Test public void testRemoveEvicted() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); // List> leases = new ArrayList<>(); ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch1 = new CountDownLatch(1); @@ -484,7 +492,7 @@ public void testRemoveEvicted() throws Exception { @Test public void testSynchronousEviction() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(1); @@ -520,7 +528,7 @@ public void testSynchronousEviction() throws Exception { @Test public void testConnectionInProgressShouldNotBeEvicted() { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 5); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 5); ContextInternal ctx = vertx.createEventLoopContext(); pool.acquire(ctx, 0, (res, err) -> {}); mgr.assertRequest(); @@ -535,7 +543,7 @@ public void testConnectionInProgressShouldNotBeEvicted() { @Test public void testRecycleRemoveConnection() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); ContextInternal ctx1 = vertx.createEventLoopContext(); @@ -552,7 +560,7 @@ public void testRecycleRemoveConnection() throws Exception { @Test public void testRecycleMultiple() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); Connection expected = new Connection(); CompletableFuture> latch = new CompletableFuture<>(); ContextInternal ctx1 = vertx.createEventLoopContext(); @@ -571,7 +579,7 @@ public void testRecycleMultiple() throws Exception { @Test public void testMaxWaiters() { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 5); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 5); ContextInternal ctx = vertx.createEventLoopContext(); for (int i = 0;i < (5);i++) { pool @@ -588,7 +596,7 @@ public void testMaxWaiters() { @Test public void testHeterogeneousSizes() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 5, 2 }); + ConnectionPool pool = pool(mgr, new int[] { 5, 2 }); ContextInternal ctx = vertx.createEventLoopContext(); CountDownLatch latch = new CountDownLatch(5); for (int i = 0;i < 5;i++) { @@ -605,10 +613,36 @@ public void testHeterogeneousSizes() throws Exception { Assert.assertEquals(1, pool.waiters()); } + @Test + public void testCapacityOvershoot() throws Exception { + // This tests an expected outlier of the capacity bound: concurrent acquisitions bet on a + // kind, the actual kind is known on connect success only + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 5, 1 }); + ContextInternal ctx = vertx.createEventLoopContext(); + CountDownLatch latch = new CountDownLatch(5); + for (int i = 0;i < 5;i++) { + pool.acquire(ctx, 0, TestUtils.onSuccess2(lease -> latch.countDown())); + } + // The back-end establishes connections of the heavier kind: the pool temporarily exceeds + // its maximum capacity, this is accepted + for (int i = 0;i < 5;i++) { + mgr.assertRequest().connect(new Connection(), 1); + } + TestUtils.awaitLatch(latch); + Assert.assertEquals(5, pool.size()); + Assert.assertEquals(25, pool.capacity()); + // Nothing is created while the pool is over capacity: the next acquisition waits + pool.acquire(ctx, 0, TestUtils.onSuccess2(lease -> { + })); + Assert.assertEquals(1, pool.waiters()); + Assert.assertEquals(0, pool.requests()); + } + @Test public void testClose() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); ContextInternal ctx = vertx.createEventLoopContext(); Connection conn1 = new Connection(); pool @@ -632,7 +666,7 @@ public void testClose() throws Exception { public void testCloseTwice() throws Exception { AtomicBoolean isReentrant = new AtomicBoolean(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }, 2); + ConnectionPool pool = pool(mgr, new int[] { 2 }, 2); CountDownLatch latch = new CountDownLatch(1); pool .close(TestUtils.onSuccess2(lst -> { @@ -651,7 +685,7 @@ public void testCloseTwice() throws Exception { public void testUseAfterClose() throws Exception { waitFor(3); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); CompletableFuture> waiterFut = new CompletableFuture<>(); pool.acquire(ctx, new PoolWaiter.Listener<>() { @@ -678,7 +712,7 @@ public void onConnect(PoolWaiter waiter) { @Test public void testAcquireClosedConnection() throws Exception { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal context = vertx.createEventLoopContext(); pool.acquire(context, 0, TestUtils.onSuccess2(Lease::recycle)); Connection expected = new Connection(); @@ -728,7 +762,7 @@ public void testConnectFailureAfterClose() { private void testConnectResultAfterClose(boolean success) { ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); ContextInternal ctx = vertx.createEventLoopContext(); AtomicInteger acquired = new AtomicInteger(); pool @@ -763,7 +797,7 @@ public void testCancelQueuedWaiters() throws Exception { waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }); + ConnectionPool pool = pool(mgr, new int[] { 1 }); CompletableFuture> w = new CompletableFuture<>(); pool .acquire(context, 0, TestUtils.onSuccess2(lease -> { @@ -811,7 +845,7 @@ public void testCancelWaiterBeforeConnection(boolean success, int extra) throws waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1 + extra); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1 + extra); CompletableFuture> waiterLatch = new CompletableFuture<>(); pool.acquire(context, new PoolWaiter.Listener<>() { @Override @@ -874,7 +908,7 @@ public void testCancelWaiterAfterConnectionSuccess(boolean success) throws Excep waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 1 }, 1); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 1); CompletableFuture> w = new CompletableFuture<>(); CountDownLatch latch = new CountDownLatch(1); pool.acquire(context, new PoolWaiter.Listener<>() { @@ -906,7 +940,7 @@ public void testCancelWaiterDispatchedByRecycle() throws Exception { waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[]{1}); + ConnectionPool pool = pool(mgr, new int[]{1}); // Step 1: Acquire and establish a connection CountDownLatch connectedLatch = new CountDownLatch(1); @@ -946,7 +980,7 @@ public void testConnectionSelector() throws Exception { waitFor(1); ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 2 }); + ConnectionPool pool = pool(mgr, new int[] { 2 }); CountDownLatch latch1 = new CountDownLatch(1); pool .acquire(context, 0, TestUtils.onSuccess2(lease -> { @@ -977,7 +1011,7 @@ public void testConnectionSelector() throws Exception { public void testDefaultSelector() throws Exception { ContextImpl context1 = (ContextImpl) vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); CountDownLatch latch1 = new CountDownLatch(1); pool .acquire(context1, 0, TestUtils.onSuccess2(lease -> { @@ -1017,7 +1051,7 @@ public void testDefaultSelector() throws Exception { public void testDefaultContextProviderUnwrap() { ContextInternal context = vertx.createEventLoopContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); pool .acquire(context.duplicate(), 0, TestUtils.onSuccess2(lease -> { })); @@ -1030,7 +1064,7 @@ public void testDefaultContextProviderUnwrap() { public void testDefaultContextProviderReusesSameEventLoop() { ContextInternal context = vertx.createWorkerContext(); ConnectionManager mgr = new ConnectionManager(); - ConnectionPool pool = ConnectionPool.pool(mgr, new int[] { 10 }, 10); + ConnectionPool pool = pool(mgr, new int[] { 10 }, 10); pool .acquire(context.duplicate(), 0, TestUtils.onSuccess2(lease -> { })); @@ -1048,7 +1082,7 @@ public void testPostTasksTrampoline() throws Exception { AtomicInteger seq = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(1 + numAcquires); int[] count = new int[1]; - ConnectionPool pool = ConnectionPool.pool(new PoolConnector() { + ConnectionPool pool = pool(new PoolConnector() { int reentrancy = 0; @Override public Future> connect(ContextInternal context, Listener listener) { @@ -1100,7 +1134,7 @@ public void testConcurrentPostTasksTrampoline() throws Exception { ContextInternal ctx = vertx.createEventLoopContext(); List res = Collections.synchronizedList(new LinkedList<>()); CountDownLatch latch = new CountDownLatch(4); - ConnectionPool pool1 = ConnectionPool.pool(new PoolConnector<>() { + ConnectionPool pool1 = pool(new PoolConnector<>() { int count = 0; int reentrancy = 0; @Override @@ -1132,7 +1166,7 @@ public boolean isValid(Connection connection) { return true; } }, new int[]{1}, 2); - ConnectionPool pool2 = ConnectionPool.pool(new PoolConnector<>() { + ConnectionPool pool2 = pool(new PoolConnector<>() { int count = 0; int reentrancy = 0; @Override @@ -1172,6 +1206,8 @@ public boolean isValid(Connection connection) { } static class Connection { + boolean valid = true; + boolean closed; public Connection() { } } @@ -1213,6 +1249,24 @@ public void fail(Throwable cause) { } } + @Test + public void testMaxWaitersDoesNotBoundConnectionCreation() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }, 0); + Connection expected = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(expected, lease.get()); + // The pool is full and waiting is not permitted + pool.acquire(context, 0, TestUtils.onFailure2(err -> { + Assert.assertTrue(err instanceof ConnectionPoolTooBusyException); + testComplete(); + })); + })); + mgr.assertRequest().connect(expected, 0); + await(); + } + class ConnectionManager implements PoolConnector { private final Queue requests = new ArrayBlockingQueue<>(100); @@ -1226,7 +1280,12 @@ public Future> connect(ContextInternal context, Listen @Override public boolean isValid(Connection connection) { - return true; + return connection.valid; + } + + @Override + public void close(Connection connection) { + connection.closed = true; } ConnectionRequest assertRequest() { @@ -1234,5 +1293,13 @@ ConnectionRequest assertRequest() { Assert.assertNotNull(request); return request; } + + void assertNoRequest() { + Assert.assertNull(requests.peek()); + } + + boolean hasRequest() { + return requests.peek() != null; + } } } diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java new file mode 100644 index 00000000000..b5ce8367917 --- /dev/null +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolStressTest.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.tests.pool; + +import io.vertx.core.internal.pool.ConnectionPool; +import io.vertx.core.internal.pool.DefaultConnectionPool; +import io.vertx.core.internal.pool.PoolConnector; + +public class DefaultConnectionPoolStressTest extends StressTest { + + @Override + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return DefaultConnectionPool.pool(connector, maxSizes, maxWaiters); + } +} diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java new file mode 100644 index 00000000000..222e8e8b2a9 --- /dev/null +++ b/vertx-core/src/test/java/io/vertx/tests/pool/DefaultConnectionPoolTest.java @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.tests.pool; + +import io.vertx.core.internal.ContextInternal; +import io.vertx.core.internal.pool.Lease; +import io.vertx.core.internal.pool.ConnectionPool; +import io.vertx.core.internal.pool.PoolConnector; +import io.vertx.core.internal.pool.PoolWaiter; +import io.vertx.core.internal.pool.DefaultConnectionPool; +import io.vertx.test.core.TestUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.time.Duration; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +public class DefaultConnectionPoolTest extends ConnectionPoolTest { + + @Test + public void testStaleConnectionEviction() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + // The checker owns the whole connection validity, the pool does not use PoolConnector#isValid + ConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withConnectionChecker(conn -> conn.valid) + .build(); + Connection conn1 = new Connection(); + Connection conn2 = new Connection(); + CountDownLatch latch = new CountDownLatch(2); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + lease.recycle(); + latch.countDown(); + })); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + lease.recycle(); + latch.countDown(); + })); + mgr.assertRequest().connect(conn1, 0); + mgr.assertRequest().connect(conn2, 0); + TestUtils.awaitLatch(latch); + // A refresh does not evict valid connections + pool.refresh(); + Assert.assertEquals(2, pool.size()); + Assert.assertFalse(conn1.closed); + Assert.assertFalse(conn2.closed); + // A refresh evicts stale connections + conn1.valid = false; + pool.refresh(); + assertWaitUntil(() -> pool.size() == 1); + Assert.assertTrue(conn1.closed); + Assert.assertFalse(conn2.closed); + Assert.assertEquals(1, pool.capacity()); + // Borrowing evicts stale connections before serving: the acquisition gets a fresh connection + conn2.valid = false; + Connection conn3 = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn3, lease.get()); + Assert.assertTrue(conn2.closed); + testComplete(); + })); + mgr.assertRequest().connect(conn3, 0); + await(); + } + + @Test + public void testInvalidConnectionRetainedWhileBusy() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withConnectionChecker(conn -> conn.valid) + .build(); + Connection conn = new Connection(); + AtomicReference> leaseRef = new AtomicReference<>(); + pool.acquire(context, 0, TestUtils.onSuccess2(leaseRef::set)); + mgr.assertRequest().connect(conn, 0); + assertWaitUntil(() -> leaseRef.get() != null); + // A busy connection finishes its leases + conn.valid = false; + pool.refresh(); + Assert.assertEquals(1, pool.size()); + Assert.assertFalse(conn.closed); + // Once idle it is evicted + leaseRef.get().recycle(); + assertWaitUntil(() -> pool.size() == 0); + Assert.assertTrue(conn.closed); + mgr.assertNoRequest(); + } + + @Test + public void testConnectionRotation() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .withConnectionChecker(conn -> conn.valid) + .build(); + pool.refresh(); + Connection conn1 = new Connection(); + mgr.assertRequest().connect(conn1, 0); + assertWaitUntil(() -> pool.size() == 1); + // Evicting the invalid connection refills the floor in the same round: rotation + conn1.valid = false; + pool.refresh(); + Connection conn2 = new Connection(); + mgr.assertRequest().connect(conn2, 0); + Assert.assertTrue(conn1.closed); + assertWaitUntil(() -> pool.size() == 1); + mgr.assertNoRequest(); + } + + @Test + public void testConnectRetryDelay() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 1 }) + .withMaxWaiters(10) + .withConnectRetryDelay(Duration.ofMillis(20)) + .build(); + pool.acquire(context, 0, (res, err) -> { + // Fails with the connect failure + }); + AtomicBoolean served = new AtomicBoolean(); + Connection expected = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(expected, lease.get()); + served.set(true); + })); + mgr.assertRequest().fail(new Exception("not yet")); + // The connect attempts are suspended + pool.refresh(); + mgr.assertNoRequest(); + // Until the delay has passed + assertWaitUntil(() -> { + pool.refresh(); + return mgr.hasRequest(); + }); + mgr.assertRequest().connect(expected, 0); + assertWaitUntil(served::get); + } + + @Test + public void testConnectSuccessClearsRetryDelay() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 2 }) + .withMaxWaiters(10) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + pool.acquire(context, 0, (res, err) -> { + // Fails with the connect failure + }); + Connection conn1 = new Connection(); + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn1, lease.get()); + served.set(true); + })); + ConnectionRequest request1 = mgr.assertRequest(); + ConnectionRequest request2 = mgr.assertRequest(); + // The failure triggers the delay + request1.fail(new Exception("failure")); + mgr.assertNoRequest(); + // A third acquisition falls in the wait queue, the delay suspends the connect + Connection conn2 = new Connection(); + AtomicBoolean served2 = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn2, lease.get()); + served2.set(true); + })); + mgr.assertNoRequest(); + // The success clears the delay: it serves the covered waiter and connects for the waiting one + request2.connect(conn1, 0); + assertWaitUntil(served::get); + mgr.assertRequest().connect(conn2, 0); + assertWaitUntil(served2::get); + } + + @Test + public void testKindChange() { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 5, 1 }); + Connection conn1 = new Connection(); + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 1, TestUtils.onSuccess2(lease -> { + served.set(true); + })); + ConnectionRequest request1 = mgr.assertRequest(); + // A second acquisition waits: the pool is at capacity + Connection conn2 = new Connection(); + AtomicBoolean served2 = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(conn2, lease.get()); + served2.set(true); + })); + request1.connect(conn1, 1); + assertWaitUntil(served::get); + mgr.assertNoRequest(); + // The kind change returns the capacity: the pool connects for the waiting acquisition + request1.listener.onKindChange(0); + mgr.assertRequest().connect(conn2, 0); + assertWaitUntil(served2::get); + } + + @Test + public void testAcquireTimeout() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }); + Connection conn1 = new Connection(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + // The connection is held, the next acquisition waits + })); + mgr.assertRequest().connect(conn1, 0); + AtomicBoolean timedOut = new AtomicBoolean(); + pool.acquire(context, new PoolWaiter.Listener<>() { + @Override + public void onTimeout(PoolWaiter waiter) { + timedOut.set(true); + } + }, 0, Duration.ofMillis(20), (res, err) -> Assert.fail()); + assertWaitUntil(() -> pool.waiters() == 1); + assertWaitUntil(() -> { + pool.refresh(); + return timedOut.get(); + }); + Assert.assertEquals(0, pool.waiters()); + } + + + @Test + public void testConnectFailureRetainsWaiterTimeout() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + ConnectionPool pool = pool(mgr, new int[] { 1 }); + // A first acquisition connects + AtomicBoolean failed = new AtomicBoolean(); + pool.acquire(context, 0, (res, err) -> { + if (err != null) { + failed.set(true); + } + }); + ConnectionRequest request = mgr.assertRequest(); + // A second acquisition waits with a deadline, a third one waits + AtomicBoolean timedOut = new AtomicBoolean(); + pool.acquire(context, new PoolWaiter.Listener<>() { + @Override + public void onTimeout(PoolWaiter waiter) { + timedOut.set(true); + } + }, 0, Duration.ofMillis(10), (res, err) -> { + }); + pool.acquire(context, 0, (res, err) -> { + }); + Thread.sleep(20); + // The connect failure opens the round: the timed out waiter eviction and the connect failure + // policy are both signalled + request.fail(new Exception("failure")); + assertWaitUntil(failed::get); + Assert.assertTrue(timedOut.get()); + } + + @Test + public void testMinSizeRequiresConnectRetryDelay() { + ConnectionManager mgr = new ConnectionManager(); + try { + DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> vertx.createEventLoopContext()) + .build(); + Assert.fail(); + } catch (IllegalArgumentException expected) { + } + } + + @Test + public void testMinSize() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 3 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + // The floor is satisfied one connection at a time from the first execution round, extra + // refreshes do not trigger extra connect requests while one is in flight + pool.refresh(); + pool.refresh(); + pool.refresh(); + ConnectionRequest request = mgr.assertRequest(); + mgr.assertNoRequest(); + request.connect(new Connection(), 0); + mgr.assertRequest().connect(new Connection(), 0); + mgr.assertRequest().connect(new Connection(), 0); + mgr.assertNoRequest(); + assertWaitUntil(() -> pool.size() == 3); + // An acquisition is served from the pooled connections + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + served.set(true); + })); + assertWaitUntil(served::get); + mgr.assertNoRequest(); + } + + @Test + public void testMinSizeCoversWaiter() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + pool.refresh(); + ConnectionRequest request = mgr.assertRequest(); + // A waiter arriving while the floor connect is in flight is covered by it + Connection expected = new Connection(); + AtomicBoolean served = new AtomicBoolean(); + pool.acquire(context, 0, TestUtils.onSuccess2(lease -> { + Assert.assertSame(expected, lease.get()); + served.set(true); + })); + mgr.assertNoRequest(); + request.connect(expected, 0); + assertWaitUntil(served::get); + Assert.assertEquals(1, pool.size()); + } + + @Test + public void testMinSizeConnectRetryDelay() throws Exception { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(new int[] { 5 }) + .withMinSizes(new int[] { 1 }) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofMillis(20)) + .build(); + pool.refresh(); + mgr.assertRequest().fail(new Exception("not yet")); + // The failure suspends the floor + pool.refresh(); + mgr.assertNoRequest(); + // Until the delay has passed + assertWaitUntil(() -> { + pool.refresh(); + return mgr.hasRequest(); + }); + // The retry fails: the floor is suspended again + mgr.assertRequest().fail(new Exception("not yet")); + pool.refresh(); + mgr.assertNoRequest(); + // The next retry succeeds + assertWaitUntil(() -> { + pool.refresh(); + return mgr.hasRequest(); + }); + Connection conn = new Connection(); + mgr.assertRequest().connect(conn, 0); + assertWaitUntil(() -> pool.size() == 1); + } + + @Test + public void testMinCapacity() { + // HTTP/1 floor: an HTTP/1 back-end converges to the minimum connections one at a time, + // a single HTTP/2 connection satisfies the floor without overshooting + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 0, 0, 3, 3); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 0, 1, 1, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 1, 0, 3, 3); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 3, 0 }, 1, 1, 1, 5); + // HTTP/2 floor: an HTTP/1 back-end converges from below to the equivalent capacity, an + // HTTP/2 back-end is satisfied by one connection + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 0, 0, 5, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 0, 1, 1, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 1, 0, 5, 5); + assertMinCapacity(new int[] { 5, 1 }, new int[] { 0, 1 }, 1, 1, 1, 5); + } + + private void assertMinCapacity(int[] maxSizes, int[] minSizes, int defaultKind, int connectKind, + int expectedSize, int expectedCapacity) { + ContextInternal context = vertx.createEventLoopContext(); + ConnectionManager mgr = new ConnectionManager(); + DefaultConnectionPool pool = DefaultConnectionPool.builder(mgr) + .withMaxSizes(maxSizes) + .withMinSizes(minSizes) + .withDefaultKind(defaultKind) + .withContextSupplier(() -> context) + .withConnectRetryDelay(Duration.ofSeconds(10)) + .build(); + while (true) { + pool.refresh(); + if (!mgr.hasRequest()) { + break; + } + mgr.assertRequest().connect(new Connection(), connectKind); + } + Assert.assertEquals(expectedSize, pool.size()); + Assert.assertEquals(expectedCapacity, pool.capacity()); + } + + @Override + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes) { + return DefaultConnectionPool.pool(connector, maxSizes); + } + + @Override + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return DefaultConnectionPool.pool(connector, maxSizes, maxWaiters); + } +} diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java index 930adde2ee4..1997775a560 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/StressTest.java @@ -28,12 +28,16 @@ */ public class StressTest extends VertxTestBase { + protected ConnectionPool pool(PoolConnector connector, int[] maxSizes, int maxWaiters) { + return ConnectionPool.pool(connector, maxSizes, maxWaiters); + } + class FakeConnectionPool implements PoolConnector { private ConnectionPool pool; FakeConnectionPool(int queueMaxSize, int poolMaxSize) { - this.pool = ConnectionPool.pool(this, new int[]{ poolMaxSize }, queueMaxSize); + this.pool = pool(this, new int[]{ poolMaxSize }, queueMaxSize); } void getConnection(FakeWaiter waiter) { diff --git a/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java b/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java index 7a02dc42977..28b0df588ea 100644 --- a/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java +++ b/vertx-core/src/test/java/io/vertx/tests/pool/SynchronizationTest.java @@ -234,4 +234,82 @@ public void run() { } assertEquals(expected, io.netty.util.internal.InternalThreadLocalMap.lastVariableIndex()); } + + @Test + public void testTrySubmit() { + AtomicInteger state = new AtomicInteger(); + Executor sync = new CombinerExecutor<>(state); + boolean executed = sync.trySubmit(s -> { + s.incrementAndGet(); + return null; + }); + assertTrue(executed); + assertEquals(1, state.get()); + } + + @Test + public void testTrySubmitWhileExecuting() { + AtomicInteger state = new AtomicInteger(); + Executor sync = new CombinerExecutor<>(state); + AtomicBoolean executed = new AtomicBoolean(true); + sync.submit(s1 -> { + executed.set(sync.trySubmit(s2 -> { + s2.incrementAndGet(); + return null; + })); + return null; + }); + assertFalse(executed.get()); + assertEquals(0, state.get()); + } + + @Test + public void testFinalAction() { + List log = new LinkedList<>(); + AtomicInteger state = new AtomicInteger(); + CombinerExecutor sync = new CombinerExecutor<>(state, () -> s -> { + log.add("last:" + s.get()); + return new Task() { + @Override + public void run() { + log.add("last-task"); + } + }; + }); + sync.submit(s1 -> { + sync.submit(s2 -> { + s2.set(2); + log.add("action2"); + return null; + }); + s1.set(1); + log.add("action1"); + return new Task() { + @Override + public void run() { + log.add("task1"); + } + }; + }); + // The final action executes once per round, after the submitted actions, seeing the settled state, + // its tasks run after the other tasks + assertEquals(Arrays.asList("action1", "action2", "last:2", "task1", "last-task"), log); + } + + @Test + public void testTrySubmitFinalAction() { + List log = new LinkedList<>(); + AtomicInteger state = new AtomicInteger(); + CombinerExecutor sync = new CombinerExecutor<>(state, () -> s -> { + log.add("last:" + s.get()); + return null; + }); + boolean executed = sync.trySubmit(s -> { + s.set(1); + log.add("action"); + return null; + }); + assertTrue(executed); + assertEquals(Arrays.asList("action", "last:1"), log); + } }