From 78e9c3910646b039ff81c4232e7876cb3a7bf77e Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Tue, 1 Dec 2026 18:18:28 +0100 Subject: [PATCH 1/3] Use the DefaultConnectionPool for the SQL connection pool Motivation: Adopt the new Vert.x connection pool implementation (eclipse-vertx/vert.x#6587) that will provide more features, one of them is getting away from a timer per acquisition since the pool owns the acquisition lifecycle (#1807, #1342). Changes: The pool checks staleness with the connection checker configured in the builder, closes the connections it evicts and times out acquisitions with a TimeoutException. As a side effect this fixes the bug addressed by #1807: a timed out query no longer keeps its slot in the wait queue, asserted by a test ported from that PR. A mandatory periodic refresh, configured by the new refresh period option (a Duration of at least one millisecond, 100 ms by default), drives all the maintenance tasks; the pool cleaner period is deprecated. The queue metric only accounts acquisitions that effectively wait. Assisted-by: Anthropic Claude (claude-fable-5) Co-Authored-By: Claude Fable 5 Signed-off-by: Julien Viet --- .../tests/mysqlclient/MySQLPoolTest.java | 3 +- .../io/vertx/tests/pgclient/PgPoolTest.java | 7 +- .../src/main/asciidoc/pool_config.adoc | 17 ++ .../java/io/vertx/sqlclient/PoolOptions.java | 40 ++++ .../vertx/sqlclient/impl/pool/PoolImpl.java | 24 +-- .../impl/pool/SqlConnectionPool.java | 184 +++++++++--------- .../spi/protocol/CommandScheduler.java | 10 + .../sqlclient/spi/backend/DriverBaseTest.java | 33 ++++ 8 files changed, 211 insertions(+), 107 deletions(-) diff --git a/vertx-mysql-client/src/test/java/io/vertx/tests/mysqlclient/MySQLPoolTest.java b/vertx-mysql-client/src/test/java/io/vertx/tests/mysqlclient/MySQLPoolTest.java index 0b6ca6bece..67fc01d88c 100644 --- a/vertx-mysql-client/src/test/java/io/vertx/tests/mysqlclient/MySQLPoolTest.java +++ b/vertx-mysql-client/src/test/java/io/vertx/tests/mysqlclient/MySQLPoolTest.java @@ -33,6 +33,7 @@ import org.junit.Test; import org.junit.runner.RunWith; +import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -238,7 +239,7 @@ public void testNoConnectionLeaks(TestContext ctx) { .setMaxSize(1) .setIdleTimeout(idleTimeout) .setIdleTimeoutUnit(TimeUnit.MILLISECONDS) - .setPoolCleanerPeriod(5); + .setRefreshPeriod(Duration.ofMillis(5)); pool = MySQLBuilder.pool(builder -> builder.with(poolOptions).connectingTo(options).using(vertx)); Async async = ctx.async(); diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTest.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTest.java index 9a5dd34c3e..9f790977cf 100644 --- a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTest.java +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgPoolTest.java @@ -35,6 +35,7 @@ import org.junit.Rule; import org.junit.Test; +import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -387,7 +388,7 @@ public void testPoolIdleTimeout(TestContext ctx) { listenLatch.awaitSuccess(20_000); poolOptions - .setPoolCleanerPeriod(poolCleanerPeriod) + .setRefreshPeriod(Duration.ofMillis(poolCleanerPeriod)) .setMaxLifetime(0) .setIdleTimeout(idleTimeout) .setIdleTimeoutUnit(TimeUnit.MILLISECONDS); @@ -430,7 +431,7 @@ public void testPoolMaxLifetime(TestContext ctx) { listenLatch.awaitSuccess(20_000); poolOptions - .setPoolCleanerPeriod(poolCleanerPeriod) + .setRefreshPeriod(Duration.ofMillis(poolCleanerPeriod)) .setIdleTimeout(0) .setMaxLifetime(maxLifetime) .setMaxLifetimeUnit(TimeUnit.MILLISECONDS); @@ -503,7 +504,7 @@ public void testNoConnectionLeaks(TestContext ctx) { .setMaxSize(1) .setIdleTimeout(idleTimeout) .setIdleTimeoutUnit(TimeUnit.MILLISECONDS) - .setPoolCleanerPeriod(5); + .setRefreshPeriod(Duration.ofMillis(5)); Pool pool = createPool(options, poolOptions); Async async = ctx.async(); diff --git a/vertx-sql-client/src/main/asciidoc/pool_config.adoc b/vertx-sql-client/src/main/asciidoc/pool_config.adoc index 79b876d080..20e71f5f87 100644 --- a/vertx-sql-client/src/main/asciidoc/pool_config.adoc +++ b/vertx-sql-client/src/main/asciidoc/pool_config.adoc @@ -23,6 +23,23 @@ has been created and before it is inserted in a pool. Once you are done with the connection, you should simply close it to signal the pool to use it. +=== Pool maintenance + +The pool periodically refreshes its state ({@link io.vertx.sqlclient.PoolOptions#setRefreshPeriod}): a +refresh reaps the connections that exceeded their idle timeout or maximum lifetime and times out the expired +connection acquisitions. + +NOTE: the refresh period bounds the resolution of the connection timeout +({@link io.vertx.sqlclient.PoolOptions#setConnectionTimeout}): an acquisition times out on the first refresh +following its deadline. + +=== Pool metrics + +The pool reports the number of pending connection requests to the Vert.x metrics SPI. + +NOTE: a request is accounted as pending only while it actually waits for a connection, a request satisfied +immediately by the pool is not reported. + === Dynamic connection configuration You can configure the pool connection details using a Java supplier instead of an instance of `SqlConnectOptions`. diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/PoolOptions.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/PoolOptions.java index 136692f321..465a4d0a51 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/PoolOptions.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/PoolOptions.java @@ -21,6 +21,7 @@ import io.vertx.codegen.json.annotations.JsonGen; import io.vertx.core.json.JsonObject; +import java.time.Duration; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -65,9 +66,17 @@ public class PoolOptions { /** * Default pool cleaner period = 1000 ms (1 second) + * + * @deprecated instead use {@link #DEFAULT_REFRESH_PERIOD} */ + @Deprecated public static final int DEFAULT_POOL_CLEANER_PERIOD = 1000; + /** + * Default pool refresh period = 100 ms + */ + public static final Duration DEFAULT_REFRESH_PERIOD = Duration.ofMillis(100); + /** * Default connection timeout in the pool = 30 seconds */ @@ -100,6 +109,7 @@ public class PoolOptions { private int maxLifetime = DEFAULT_MAXIMUM_LIFETIME; private TimeUnit maxLifetimeUnit = DEFAULT_MAXIMUM_LIFETIME_TIME_UNIT; private int poolCleanerPeriod = DEFAULT_POOL_CLEANER_PERIOD; + private Duration refreshPeriod = DEFAULT_REFRESH_PERIOD; private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; private TimeUnit connectionTimeoutUnit = DEFAULT_CONNECTION_TIMEOUT_TIME_UNIT; private boolean shared = DEFAULT_SHARED_POOL; @@ -121,6 +131,7 @@ public PoolOptions(PoolOptions other) { maxLifetime = other.maxLifetime; maxLifetimeUnit = other.maxLifetimeUnit; poolCleanerPeriod = other.poolCleanerPeriod; + refreshPeriod = other.refreshPeriod; connectionTimeout = other.connectionTimeout; connectionTimeoutUnit = other.connectionTimeoutUnit; shared= other.shared; @@ -248,7 +259,10 @@ public PoolOptions setMaxLifetime(int maxLifetime) { /** * @return the connection pool cleaner period in ms. + * + * @deprecated the pool cleaner period is unused, instead use {@link #getRefreshPeriod()} */ + @Deprecated public int getPoolCleanerPeriod() { return poolCleanerPeriod; } @@ -259,12 +273,38 @@ public int getPoolCleanerPeriod() { * * @param poolCleanerPeriod the pool cleaner period * @return a reference to this, so the API can be used fluently + * + * @deprecated the pool cleaner period is unused, instead use {@link #setRefreshPeriod(Duration)} */ + @Deprecated public PoolOptions setPoolCleanerPeriod(int poolCleanerPeriod) { this.poolCleanerPeriod = poolCleanerPeriod; return this; } + /** + * @return the pool refresh period + */ + public Duration getRefreshPeriod() { + return refreshPeriod; + } + + /** + * Set the period of the pool refresh timer: the refresh performs the pool maintenance tasks, it reaps the + * stale connections and times out the expired connection acquisitions. The period bounds the resolution of + * {@link #setConnectionTimeout}. + * + * @param refreshPeriod the pool refresh period, at least one millisecond + * @return a reference to this, so the API can be used fluently + */ + public PoolOptions setRefreshPeriod(Duration refreshPeriod) { + if (refreshPeriod == null || refreshPeriod.toMillis() < 1) { + throw new IllegalArgumentException("refreshPeriod must be at least one millisecond"); + } + this.refreshPeriod = refreshPeriod; + return this; + } + /** * @return the time unit of @link #setConnectionTimeout(int)} */ diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolImpl.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolImpl.java index 5a3df9494a..0be5726f2a 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolImpl.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolImpl.java @@ -52,7 +52,7 @@ public class PoolImpl extends SqlClientBase implements PoolInternal { private final long idleTimeout; private final long connectionTimeout; private final long maxLifetime; - private final long cleanerPeriod; + private final long refreshPeriod; private final boolean pipelined; private final Handler connectionInitializer; private final ConnectionWrapper connectionWrapper; @@ -85,7 +85,7 @@ public PoolImpl(VertxInternal vertx, this.idleTimeout = MILLISECONDS.convert(poolOptions.getIdleTimeout(), poolOptions.getIdleTimeoutUnit()); this.connectionTimeout = MILLISECONDS.convert(poolOptions.getConnectionTimeout(), poolOptions.getConnectionTimeoutUnit()); this.maxLifetime = MILLISECONDS.convert(poolOptions.getMaxLifetime(), poolOptions.getMaxLifetimeUnit()); - this.cleanerPeriod = poolOptions.getPoolCleanerPeriod(); + this.refreshPeriod = poolOptions.getRefreshPeriod().toMillis(); this.timerID = -1L; this.pipelined = pipelined; this.vertx = vertx; @@ -105,27 +105,27 @@ private void initializeConnection(SqlConnectionPool.PooledConnection conn) { } public Pool init() { - if ((idleTimeout > 0 || maxLifetime > 0) && cleanerPeriod > 0) { - synchronized (this) { - timerID = vertx.setTimer(cleanerPeriod, id -> { - runEviction(); - }); - } + // The periodic refresh performs all the pool maintenance tasks: it reaps the stale connections and times + // out the expired connection waiters + synchronized (this) { + timerID = vertx.setTimer(refreshPeriod, id -> { + refresh(); + }); } return this; } - private void runEviction() { + private void refresh() { synchronized (this) { if (timerID == -1) { // Cancelled return; } - timerID = vertx.setTimer(cleanerPeriod, id -> { - runEviction(); + timerID = vertx.setTimer(refreshPeriod, id -> { + refresh(); }); } - pool.evict(); + pool.refresh(); } @Override diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java index 7f82e3b420..1b4a33ba90 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java @@ -32,7 +32,9 @@ import io.vertx.sqlclient.spi.protocol.CommandBase; import io.vertx.sqlclient.spi.protocol.QueryCommandBase; +import java.time.Duration; import java.util.List; +import java.util.concurrent.TimeoutException; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -81,7 +83,11 @@ public SqlConnectionPool(Supplier> optio if (afterAcquire != null && beforeRecycle == null) { throw new IllegalArgumentException("afterAcquire and beforeRecycle hooks must be both not null"); } - this.pool = ConnectionPool.pool(connector, new int[]{maxSize}, maxWaitQueueSize); + this.pool = DefaultConnectionPool.builder(connector) + .withMaxSizes(new int[]{maxSize}) + .withMaxWaiters(maxWaitQueueSize) + .withConnectionChecker(conn -> !conn.shouldEvict(System.currentTimeMillis())) + .build(); this.connectionFactory = connectionFactory; this.metrics = metrics; this.vertx = vertx; @@ -138,9 +144,14 @@ public Future> connect(ContextInternal context, }); } - @Override public boolean isValid(PooledConnection connection) { - return true; + // The pool relies on the connection checker configured in the builder + throw new UnsupportedOperationException(); + } + + @Override + public void close(PooledConnection connection) { + connection.close(Promise.promise()); } }; @@ -152,15 +163,12 @@ public int size() { return pool.size(); } - public void evict() { - long now = System.currentTimeMillis(); - pool.evict(conn -> conn.shouldEvict(now), (res, err) -> { - if (err == null) { - for (PooledConnection conn : res) { - conn.close(Promise.promise()); - } - } - }); + /** + * Check and perform the pool maintenance tasks: the pool evicts and closes the stale connections and + * times out the expired waiters. + */ + public void refresh() { + pool.refresh(); } private Object enqueueMetric() { @@ -205,59 +213,69 @@ private void endMetric(Object metric) { } } - private static final Exception POOL_QUERY_TIMEOUT_EXCEPTION = new VertxException("Timeout waiting for connection", true); + private static final TimeoutException POOL_QUERY_TIMEOUT_EXCEPTION = new TimeoutException("Timeout waiting for connection") { + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + }; // TODO : try optimize without promise public void execute(CommandBase cmd, Completable handler, long timeout) { ContextInternal context = vertx.getOrCreateContext(); Promise> p = context.promise(); - long timerId; - if (timeout > 0) { - timerId = vertx.setTimer(timeout, t -> handler.fail(POOL_QUERY_TIMEOUT_EXCEPTION)); - } else { - timerId = -1; + // The pool settles an acquisition exactly once: either it delivers the outcome to the completable, or it + // times out the waiter and signals the listener, handling the timed out acquisition is up to the borrower. + // The queue metric is recorded when the pool signals the request effectively waits instead of on + // submission: an acquisition satisfied immediately does not inflate the queue metric. + class Listener implements PoolWaiter.Listener { + + private Object metric = NO_METRICS; + + @Override + public void onEnqueue(PoolWaiter waiter) { + metric = enqueueMetric(); + } + + @Override + public void onDequeue(PoolWaiter waiter, boolean timedOut) { + // The metric reported by the SPI can be any object, including null: NO_METRICS marks the absence of a + // recorded metric + Object m = metric; + if (m != NO_METRICS) { + metric = NO_METRICS; + dequeueMetric(m); + } + if (timedOut) { + handler.fail(POOL_QUERY_TIMEOUT_EXCEPTION); + } + } } - Object metric = enqueueMetric(); - pool.acquire(context, 0, p); + Listener listener = new Listener(); + pool.acquire(context, listener, 0, timeout > 0 ? Duration.ofMillis(timeout) : null, p); p.future().compose(lease -> { - dequeueMetric(metric); PooledConnection pooled = lease.get(); + pooled.timerMetric = beginMetric(); Future future; - if (timerId != -1 && !vertx.cancelTimer(timerId)) { - // We want to make sure the connection is released properly below - // But we don't want to record begin/end pool metrics - pooled.timerMetric = NO_METRICS; - future = Future.failedFuture(POOL_QUERY_TIMEOUT_EXCEPTION); + if (afterAcquire != null) { + Connection conn = pooled.conn; + future = afterAcquire.apply(conn) + .compose(v -> Future.future(d -> pooled.schedule(cmd, d))) + .eventually(() -> beforeRecycle.apply(conn)); } else { - pooled.timerMetric = beginMetric(); - if (afterAcquire != null) { - Connection conn = pooled.conn; - future = afterAcquire.apply(conn) - .compose(v -> Future.future(d -> pooled.schedule(cmd, d))) - .eventually(() -> beforeRecycle.apply(conn)); - } else { - PromiseInternal pp = context.promise(); - pooled.schedule(cmd, pp); - future = pp; - } + PromiseInternal pp = context.promise(); + pooled.schedule(cmd, pp); + future = pp; } return future.andThen(ar -> { endMetric(pooled.timerMetric); pooled.refresh(); lease.recycle(); }); - }, t -> { - dequeueMetric(metric); - if (timerId != -1 && !vertx.cancelTimer(timerId)) { - // The timer already failed the handler - return Future.failedFuture(POOL_QUERY_TIMEOUT_EXCEPTION); - } else { - return Future.failedFuture(t); - } }).onComplete(ar -> { if (ar.succeeded()) { handler.succeed(ar.result()); - } else if (!POOL_QUERY_TIMEOUT_EXCEPTION.equals(ar.cause())) { + } else { handler.fail(ar.cause()); } }); @@ -266,30 +284,40 @@ public void execute(CommandBase cmd, Completable handler, long timeout public void acquire(ContextInternal context, long timeout, Promise handler) { class PoolRequest implements PoolWaiter.Listener, Completable> { - private final Object metric; - private long timerID = -1L; + private Object metric = NO_METRICS; - PoolRequest(Object metric) { - this.metric = metric; + @Override + public void onEnqueue(PoolWaiter waiter) { + metric = enqueueMetric(); + } + + @Override + public void onDequeue(PoolWaiter waiter, boolean timedOut) { + // The metric reported by the SPI can be any object, including null: NO_METRICS marks the absence of a + // recorded metric + Object m = metric; + if (m != NO_METRICS) { + metric = NO_METRICS; + dequeueMetric(m); + } + if (timedOut) { + handler.fail(POOL_QUERY_TIMEOUT_EXCEPTION); + } } @Override public void complete(Lease lease, Throwable failure) { if (failure == null) { - if (timerID != -1L && !vertx.cancelTimer(timerID)) { - lease.recycle(); + if (afterAcquire != null) { + afterAcquire.apply(lease.get().conn).onComplete(ar2 -> { + if (ar2.succeeded()) { + handle(lease); + } else { + fail(lease, ar2.cause()); + } + }); } else { - if (afterAcquire != null) { - afterAcquire.apply(lease.get().conn).onComplete(ar2 -> { - if (ar2.succeeded()) { - handle(lease); - } else { - fail(lease, ar2.cause()); - } - }); - } else { - handle(lease); - } + handle(lease); } } else { fail(null, failure); @@ -300,44 +328,18 @@ private void fail(Lease lease, Throwable cause) { if (lease != null) { lease.recycle(); } - dequeueMetric(metric); handler.tryFail(cause); } private void handle(Lease lease) { - dequeueMetric(metric); PooledConnection pooled = lease.get(); pooled.timerMetric = beginMetric(); pooled.lease = lease; handler.succeed(pooled); } - - @Override - public void onEnqueue(PoolWaiter waiter) { - if (timeout > 0L && timerID == -1L) { - timerID = context.setTimer(timeout, id -> { - pool.cancel(waiter, (res, err) -> { - if (err == null) { - if (res) { - dequeueMetric(metric); - handler.fail("Timeout"); - } - } else { - // ???? - } - }); - }); - } - } - - @Override - public void onConnect(PoolWaiter waiter) { - onEnqueue(waiter); - } } - Object metric = enqueueMetric(); - PoolRequest request = new PoolRequest(metric); - pool.acquire(context, request, 0, request); + PoolRequest request = new PoolRequest(); + pool.acquire(context, request, 0, timeout > 0 ? Duration.ofMillis(timeout) : null, request); } public Future close() { diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/spi/protocol/CommandScheduler.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/spi/protocol/CommandScheduler.java index 72b5c7af59..100c6a03de 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/spi/protocol/CommandScheduler.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/spi/protocol/CommandScheduler.java @@ -24,12 +24,22 @@ @FunctionalInterface public interface CommandScheduler { + /** + * Schedule {@code cmd} and complete the returned future on {@code context}. + */ default Future schedule(ContextInternal context, CommandBase cmd) { Promise promise = context.promise(); schedule(cmd, promise); return promise.future(); } + /** + * Schedule {@code cmd} and complete {@code handler} with its outcome. + * + *

A scheduler is free to complete {@code handler} on any thread, e.g. a pool completes an acquisition + * failure on the thread reporting the failure. Callers that need the outcome on a specific context shall + * pass a context aware promise, like {@link #schedule(ContextInternal, CommandBase)} does. + */ void schedule(CommandBase cmd, Completable handler); } diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/spi/backend/DriverBaseTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/spi/backend/DriverBaseTest.java index 5512d2d775..6f09d21dc4 100644 --- a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/spi/backend/DriverBaseTest.java +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/spi/backend/DriverBaseTest.java @@ -314,4 +314,37 @@ public void testConnectFailureAfterPoolConnectionTimeout() throws Exception { vertx.close().await(); } } + + @Test + public void testPoolQueryTimeoutLeavesWaitQueue() throws Exception { + DriverBase driver = createDriver(null, null); + + Vertx vertx = Vertx.vertx(); + + try { + Pool pool = driver.createPool(vertx, () -> Future.succeededFuture(new SqlConnectOptions()), + new PoolOptions() + .setMaxSize(1) + .setMaxWaitQueueSize(1) + .setConnectionTimeout(500) + .setConnectionTimeoutUnit(MILLISECONDS), new NetClientOptions(), null); + + SqlConnection conn = pool.getConnection().await(); + + try { + pool.query("one").execute().await(); + fail("Should have timed out"); + } catch (Exception e) { + assertEquals("Timeout waiting for connection", e.getMessage()); + } + + // The timed out query no longer takes the single slot of the wait queue + Future> second = pool.query("two").execute(); + Thread.sleep(100); + conn.close().await(); + assertEquals("Hello two", second.await().iterator().next().getString(0)); + } finally { + vertx.close().await(); + } + } } From 808f5e804b263f95b46309c9f20e2625e4347bba Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 2 Dec 2026 13:51:48 +0100 Subject: [PATCH 2/3] Clarify the pool maintenance documentation Note that the default refresh period is small enough for any meaningful connection timeout, and remove the pool metrics section: the metrics a component reports belong to the metrics project documentation. Assisted-by: Anthropic Claude (claude-fable-5) Co-Authored-By: Claude Fable 5 Signed-off-by: Julien Viet --- vertx-sql-client/src/main/asciidoc/pool_config.adoc | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/vertx-sql-client/src/main/asciidoc/pool_config.adoc b/vertx-sql-client/src/main/asciidoc/pool_config.adoc index 20e71f5f87..0dd6aec05d 100644 --- a/vertx-sql-client/src/main/asciidoc/pool_config.adoc +++ b/vertx-sql-client/src/main/asciidoc/pool_config.adoc @@ -31,14 +31,8 @@ connection acquisitions. NOTE: the refresh period bounds the resolution of the connection timeout ({@link io.vertx.sqlclient.PoolOptions#setConnectionTimeout}): an acquisition times out on the first refresh -following its deadline. - -=== Pool metrics - -The pool reports the number of pending connection requests to the Vert.x metrics SPI. - -NOTE: a request is accounted as pending only while it actually waits for a connection, a request satisfied -immediately by the pool is not reported. +following its deadline. The default refresh period (100 ms) is small enough for any meaningful connection +timeout. === Dynamic connection configuration From 15546a2b2f9c52508b5ae4b79b658f48390467e2 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Wed, 2 Dec 2026 14:33:17 +0100 Subject: [PATCH 3/3] Share the pool acquisition request between the acquisition paths Extract the common code of the pooled query and connection acquisition paths into a PoolRequest: the pool waiter listener and the completable handed over to the pool, accounting the queue metric and reporting the acquisition timeout, so a fix on one path cannot be missed on the other. ExecuteRequest and AcquireRequest implement the outcome of each path in their own file. Assisted-by: Anthropic Claude (claude-fable-5) Co-Authored-By: Claude Fable 5 Signed-off-by: Julien Viet --- .../sqlclient/impl/pool/AcquireRequest.java | 62 +++++++ .../sqlclient/impl/pool/ExecuteRequest.java | 73 +++++++++ .../sqlclient/impl/pool/PoolRequest.java | 88 ++++++++++ .../impl/pool/SqlConnectionPool.java | 151 ++---------------- 4 files changed, 239 insertions(+), 135 deletions(-) create mode 100644 vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/AcquireRequest.java create mode 100644 vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ExecuteRequest.java create mode 100644 vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolRequest.java diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/AcquireRequest.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/AcquireRequest.java new file mode 100644 index 0000000000..1f5924aac1 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/AcquireRequest.java @@ -0,0 +1,62 @@ +/* + * 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.sqlclient.impl.pool; + +import io.vertx.core.Promise; +import io.vertx.core.internal.ContextInternal; +import io.vertx.core.internal.pool.Lease; +import io.vertx.sqlclient.impl.pool.SqlConnectionPool.PooledConnection; + +/** + * The acquisition request of a pooled connection: the borrowed connection is handed over to the requester, + * which gives it back to the pool when it closes it. + * + * @author Julien Viet + */ +class AcquireRequest extends PoolRequest { + + private final Promise handler; + + AcquireRequest(SqlConnectionPool pool, ContextInternal context, Promise handler) { + super(pool, context); + this.handler = handler; + } + + @Override + void handleSuccess(Lease lease) { + if (pool.afterAcquire != null) { + pool.afterAcquire.apply(lease.get().conn).onComplete((v, err) -> { + if (err == null) { + handleConnection(lease); + } else { + lease.recycle(); + handler.tryFail(err); + } + }); + } else { + handleConnection(lease); + } + } + + private void handleConnection(Lease lease) { + PooledConnection pooled = lease.get(); + pooled.timerMetric = pool.beginMetric(); + // The lease is recycled when the connection is given back to the pool, see PooledConnection#cleanup + pooled.lease = lease; + handler.succeed(pooled); + } + + @Override + void handleFailure(Throwable failure) { + handler.tryFail(failure); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ExecuteRequest.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ExecuteRequest.java new file mode 100644 index 0000000000..f0d3549095 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ExecuteRequest.java @@ -0,0 +1,73 @@ +/* + * 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.sqlclient.impl.pool; + +import io.vertx.core.Completable; +import io.vertx.core.Future; +import io.vertx.core.internal.ContextInternal; +import io.vertx.core.internal.PromiseInternal; +import io.vertx.core.internal.pool.Lease; +import io.vertx.sqlclient.impl.pool.SqlConnectionPool.PooledConnection; +import io.vertx.sqlclient.spi.connection.Connection; +import io.vertx.sqlclient.spi.protocol.CommandBase; + +/** + * The acquisition request of a pooled query: borrow a connection, schedule the command on it and give the + * connection back to the pool. + * + * @author Julien Viet + */ +class ExecuteRequest extends PoolRequest { + + private final CommandBase cmd; + private final Completable handler; + + ExecuteRequest(SqlConnectionPool pool, ContextInternal context, CommandBase cmd, Completable handler) { + super(pool, context); + this.cmd = cmd; + this.handler = handler; + } + + @Override + void handleSuccess(Lease lease) { + // The pool delivers the lease on the context of the connection: emit on the context of the requester, + // like the command outcome + context.emit(lease, this::processSuccess); + } + + private void processSuccess(Lease lease) { + PooledConnection pooled = lease.get(); + pooled.timerMetric = pool.beginMetric(); + Future future; + if (pool.afterAcquire != null) { + Connection conn = pooled.conn; + future = pool.afterAcquire.apply(conn) + .compose(v -> Future.future(d -> pooled.schedule(cmd, d))) + .eventually(() -> pool.beforeRecycle.apply(conn)); + } else { + PromiseInternal pp = context.promise(); + pooled.schedule(cmd, pp); + future = pp; + } + future.onComplete((res, err) -> { + pool.endMetric(pooled.timerMetric); + pooled.refresh(); + lease.recycle(); + handler.complete(res, err); + }); + } + + @Override + void handleFailure(Throwable failure) { + context.emit(failure, handler::fail); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolRequest.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolRequest.java new file mode 100644 index 0000000000..60f32f2a84 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolRequest.java @@ -0,0 +1,88 @@ +/* + * 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.sqlclient.impl.pool; + +import io.vertx.core.Completable; +import io.vertx.core.internal.ContextInternal; +import io.vertx.core.internal.pool.Lease; +import io.vertx.core.internal.pool.PoolWaiter; +import io.vertx.sqlclient.impl.pool.SqlConnectionPool.PooledConnection; + +import java.util.concurrent.TimeoutException; + +/** + * A connection acquisition request: the pool waiter listener and the completable handed over to the pool, + * shared by the acquisition paths so a fix on one path cannot be missed on the other. + * + *

The pool settles an acquisition exactly once: either it delivers the outcome to {@link #complete}, or + * it times out the waiter and signals {@link #onDequeue}, handling the timed out acquisition is up to the + * borrower. The queue metric is recorded when the pool signals the request effectively waits instead of on + * submission: an acquisition satisfied immediately does not inflate the queue metric. + * + * @author Julien Viet + */ +abstract class PoolRequest implements PoolWaiter.Listener, Completable> { + + private static final TimeoutException POOL_QUERY_TIMEOUT_EXCEPTION = new TimeoutException("Timeout waiting for connection") { + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + }; + + final SqlConnectionPool pool; + final ContextInternal context; + private Object metric = SqlConnectionPool.NO_METRICS; + + PoolRequest(SqlConnectionPool pool, ContextInternal context) { + this.pool = pool; + this.context = context; + } + + @Override + public final void onEnqueue(PoolWaiter waiter) { + metric = pool.enqueueMetric(); + } + + @Override + public final void onDequeue(PoolWaiter waiter, boolean timedOut) { + // The metric reported by the SPI can be any object, including null: NO_METRICS marks the absence of a + // recorded metric + Object m = metric; + if (m != SqlConnectionPool.NO_METRICS) { + metric = SqlConnectionPool.NO_METRICS; + pool.dequeueMetric(m); + } + if (timedOut) { + handleFailure(POOL_QUERY_TIMEOUT_EXCEPTION); + } + } + + @Override + public final void complete(Lease lease, Throwable failure) { + if (failure == null) { + handleSuccess(lease); + } else { + handleFailure(failure); + } + } + + /** + * Hand the acquired {@code lease} over to the requester, which becomes responsible for recycling it. + */ + abstract void handleSuccess(Lease lease); + + /** + * Fail the request, the pool rejected it, could not connect or timed it out. + */ + abstract void handleFailure(Throwable failure); +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java index 1b4a33ba90..19e2ff01e0 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/SqlConnectionPool.java @@ -14,7 +14,6 @@ import io.netty.channel.EventLoop; import io.vertx.core.*; import io.vertx.core.internal.ContextInternal; -import io.vertx.core.internal.PromiseInternal; import io.vertx.core.internal.VertxInternal; import io.vertx.core.internal.net.NetSocketInternal; import io.vertx.core.internal.pool.*; @@ -34,7 +33,6 @@ import java.time.Duration; import java.util.List; -import java.util.concurrent.TimeoutException; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -48,7 +46,7 @@ */ public class SqlConnectionPool { - private static final Object NO_METRICS = new Object(); + static final Object NO_METRICS = new Object(); private final Function> connectionProvider; private final ConnectionFactory connectionFactory; @@ -56,8 +54,8 @@ public class SqlConnectionPool { private final PoolMetrics metrics; private final ConnectionPool pool; private final Handler hook; - private final Function> afterAcquire; - private final Function> beforeRecycle; + final Function> afterAcquire; + final Function> beforeRecycle; private final boolean pipelined; private final long idleTimeout; private final long maxLifetime; @@ -171,7 +169,7 @@ public void refresh() { pool.refresh(); } - private Object enqueueMetric() { + Object enqueueMetric() { if (metrics != null) { try { return metrics.enqueue(); @@ -182,7 +180,7 @@ private Object enqueueMetric() { return NO_METRICS; } - private void dequeueMetric(Object metric) { + void dequeueMetric(Object metric) { if (metrics != null && metric != NO_METRICS) { try { metrics.dequeue(metric); @@ -192,7 +190,7 @@ private void dequeueMetric(Object metric) { } } - private Object beginMetric() { + Object beginMetric() { if (metrics != null) { try { return metrics.begin(); @@ -203,7 +201,7 @@ private Object beginMetric() { return NO_METRICS; } - private void endMetric(Object metric) { + void endMetric(Object metric) { if (metrics != null && metric != NO_METRICS) { try { metrics.end(metric); @@ -213,133 +211,16 @@ private void endMetric(Object metric) { } } - private static final TimeoutException POOL_QUERY_TIMEOUT_EXCEPTION = new TimeoutException("Timeout waiting for connection") { - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } - }; + private void acquire(PoolRequest request, long timeout) { + pool.acquire(request.context, request, 0, timeout > 0 ? Duration.ofMillis(timeout) : null, request); + } - // TODO : try optimize without promise public void execute(CommandBase cmd, Completable handler, long timeout) { - ContextInternal context = vertx.getOrCreateContext(); - Promise> p = context.promise(); - // The pool settles an acquisition exactly once: either it delivers the outcome to the completable, or it - // times out the waiter and signals the listener, handling the timed out acquisition is up to the borrower. - // The queue metric is recorded when the pool signals the request effectively waits instead of on - // submission: an acquisition satisfied immediately does not inflate the queue metric. - class Listener implements PoolWaiter.Listener { - - private Object metric = NO_METRICS; - - @Override - public void onEnqueue(PoolWaiter waiter) { - metric = enqueueMetric(); - } - - @Override - public void onDequeue(PoolWaiter waiter, boolean timedOut) { - // The metric reported by the SPI can be any object, including null: NO_METRICS marks the absence of a - // recorded metric - Object m = metric; - if (m != NO_METRICS) { - metric = NO_METRICS; - dequeueMetric(m); - } - if (timedOut) { - handler.fail(POOL_QUERY_TIMEOUT_EXCEPTION); - } - } - } - Listener listener = new Listener(); - pool.acquire(context, listener, 0, timeout > 0 ? Duration.ofMillis(timeout) : null, p); - p.future().compose(lease -> { - PooledConnection pooled = lease.get(); - pooled.timerMetric = beginMetric(); - Future future; - if (afterAcquire != null) { - Connection conn = pooled.conn; - future = afterAcquire.apply(conn) - .compose(v -> Future.future(d -> pooled.schedule(cmd, d))) - .eventually(() -> beforeRecycle.apply(conn)); - } else { - PromiseInternal pp = context.promise(); - pooled.schedule(cmd, pp); - future = pp; - } - return future.andThen(ar -> { - endMetric(pooled.timerMetric); - pooled.refresh(); - lease.recycle(); - }); - }).onComplete(ar -> { - if (ar.succeeded()) { - handler.succeed(ar.result()); - } else { - handler.fail(ar.cause()); - } - }); + acquire(new ExecuteRequest<>(this, vertx.getOrCreateContext(), cmd, handler), timeout); } public void acquire(ContextInternal context, long timeout, Promise handler) { - class PoolRequest implements PoolWaiter.Listener, Completable> { - - private Object metric = NO_METRICS; - - @Override - public void onEnqueue(PoolWaiter waiter) { - metric = enqueueMetric(); - } - - @Override - public void onDequeue(PoolWaiter waiter, boolean timedOut) { - // The metric reported by the SPI can be any object, including null: NO_METRICS marks the absence of a - // recorded metric - Object m = metric; - if (m != NO_METRICS) { - metric = NO_METRICS; - dequeueMetric(m); - } - if (timedOut) { - handler.fail(POOL_QUERY_TIMEOUT_EXCEPTION); - } - } - - @Override - public void complete(Lease lease, Throwable failure) { - if (failure == null) { - if (afterAcquire != null) { - afterAcquire.apply(lease.get().conn).onComplete(ar2 -> { - if (ar2.succeeded()) { - handle(lease); - } else { - fail(lease, ar2.cause()); - } - }); - } else { - handle(lease); - } - } else { - fail(null, failure); - } - } - - private void fail(Lease lease, Throwable cause) { - if (lease != null) { - lease.recycle(); - } - handler.tryFail(cause); - } - - private void handle(Lease lease) { - PooledConnection pooled = lease.get(); - pooled.timerMetric = beginMetric(); - pooled.lease = lease; - handler.succeed(pooled); - } - } - PoolRequest request = new PoolRequest(); - pool.acquire(context, request, 0, timeout > 0 ? Duration.ofMillis(timeout) : null, request); + acquire(new AcquireRequest(this, context, handler), timeout); } public Future close() { @@ -364,12 +245,12 @@ public Future close() { public class PooledConnection implements Connection, ConnectionContext { private final ConnectionFactory factory; - private final Connection conn; + final Connection conn; private final PoolConnector.Listener listener; private ConnectionContext holder; private Promise> poolCallback; - private Lease lease; - private Object timerMetric; + Lease lease; + Object timerMetric; public long idleEvictionTimestamp; public long lifetimeEvictionTimestamp; @@ -465,7 +346,7 @@ private void close(Promise promise) { conn.close(this, promise); } - private void refresh() { + void refresh() { this.idleEvictionTimestamp = idleTimeout > 0 ? System.currentTimeMillis() + idleTimeout : Long.MAX_VALUE; }