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/PoolRequest.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolRequest.java
new file mode 100644
index 000000000..60f32f2a8
--- /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 7f82e3b42..19e2ff01e 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.*;
@@ -32,6 +31,7 @@
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.function.Function;
import java.util.function.Supplier;
@@ -46,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;
@@ -54,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;
@@ -81,7 +81,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 +142,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,18 +161,15 @@ 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() {
+ Object enqueueMetric() {
if (metrics != null) {
try {
return metrics.enqueue();
@@ -174,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);
@@ -184,7 +190,7 @@ private void dequeueMetric(Object metric) {
}
}
- private Object beginMetric() {
+ Object beginMetric() {
if (metrics != null) {
try {
return metrics.begin();
@@ -195,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);
@@ -205,139 +211,16 @@ private void endMetric(Object metric) {
}
}
- private static final Exception POOL_QUERY_TIMEOUT_EXCEPTION = new VertxException("Timeout waiting for connection", true);
+ 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();
- long timerId;
- if (timeout > 0) {
- timerId = vertx.setTimer(timeout, t -> handler.fail(POOL_QUERY_TIMEOUT_EXCEPTION));
- } else {
- timerId = -1;
- }
- Object metric = enqueueMetric();
- pool.acquire(context, 0, p);
- p.future().compose(lease -> {
- dequeueMetric(metric);
- PooledConnection pooled = lease.get();
- 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);
- } 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;
- }
- }
- 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())) {
- 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 final Object metric;
- private long timerID = -1L;
-
- PoolRequest(Object metric) {
- this.metric = metric;
- }
-
- @Override
- public void complete(Lease lease, Throwable failure) {
- if (failure == null) {
- if (timerID != -1L && !vertx.cancelTimer(timerID)) {
- lease.recycle();
- } else {
- 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();
- }
- 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);
+ acquire(new AcquireRequest(this, context, handler), timeout);
}
public Future close() {
@@ -362,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;
@@ -463,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;
}
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 72b5c7af5..100c6a03d 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 5512d2d77..6f09d21dc 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();
+ }
+ }
}