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 0b6ca6bec..67fc01d88 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 9a5dd34c3..9f790977c 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 79b876d08..0dd6aec05 100644 --- a/vertx-sql-client/src/main/asciidoc/pool_config.adoc +++ b/vertx-sql-client/src/main/asciidoc/pool_config.adoc @@ -23,6 +23,17 @@ 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. The default refresh period (100 ms) is small enough for any meaningful connection +timeout. + === 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 136692f32..465a4d0a5 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/AcquireRequest.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/AcquireRequest.java new file mode 100644 index 000000000..1f5924aac --- /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 000000000..f0d354909 --- /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/PoolImpl.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/PoolImpl.java index 5a3df9494..0be5726f2 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/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(); + } + } }