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..a3659bc1a 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
@@ -33,6 +33,7 @@
import io.vertx.sqlclient.spi.protocol.QueryCommandBase;
import java.util.List;
+import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -207,136 +208,220 @@ private void endMetric(Object metric) {
private static final Exception POOL_QUERY_TIMEOUT_EXCEPTION = new VertxException("Timeout waiting for connection", true);
- // TODO : try optimize without promise
+ /**
+ * A connection acquisition request.
+ *
+ *
The pool notifies the waiter listener and delivers the outcome of the acquisition on arbitrary threads,
+ * therefore the request lifecycle is arbitrated by the single atomically updated {@link #state} field:
+ *
+ *
+ *
{@link #NO_TIMER}: no acquisition timer has been set
+ *
a zero or positive value: the identifier of the acquisition timer
+ *
{@link #COMPLETED}: terminal state
+ *
+ *
+ *
Whoever moves the state to {@link #COMPLETED} owns the dequeue metric and the single completion of the
+ * request. Arbitrating with a single variable is necessary: relying on the combined outcome of
+ * {@code Vertx#cancelTimer} and {@code ConnectionPool#cancel} is racy because both can report a loss for the
+ * very same request, leaving it uncompleted forever.
+ */
+ private abstract static class PoolRequest implements PoolWaiter.Listener, Completable>, Handler {
+
+ private static final AtomicLongFieldUpdater STATE = AtomicLongFieldUpdater.newUpdater(PoolRequest.class, "state");
+
+ private static final long NO_TIMER = -1L;
+ private static final long COMPLETED = -2L;
+
+ private final SqlConnectionPool owner;
+ private final ContextInternal context;
+ private final long timeout;
+ private final Object metric;
+
+ private volatile long state = NO_TIMER;
+
+ // Assigned before the acquisition timer is set and only read when this timer fires
+ // It does not need to be volatile: setting the timer happens after the assignment and makes it visible to the thread firing the timer
+ private PoolWaiter waiter;
+
+ PoolRequest(SqlConnectionPool owner, ContextInternal context, long timeout) {
+ this.owner = owner;
+ this.context = context;
+ this.timeout = timeout;
+ this.metric = owner.enqueueMetric();
+ }
+
+ @Override
+ public void onEnqueue(PoolWaiter waiter) {
+ setAcquisitionTimer(waiter);
+ }
+
+ @Override
+ public void onConnect(PoolWaiter waiter) {
+ setAcquisitionTimer(waiter);
+ }
+
+ /**
+ * Set the acquisition timer of this request, unless a timer has been set already.
+ *
+ *
The timer is set from the waiter listener callbacks because this is the only moment the waiter is
+ * known, and consequently the only moment the request can be canceled. When the pool satisfies the request
+ * without notifying the listener, the connection is available immediately and no timer is needed.
+ *
+ *
A waiter is notified twice when it is enqueued first and later associated with a connection request,
+ * the state prevents a second timer.
+ *
+ *
The pool executes the listener callbacks on the thread that happens to drain its combiner, which is
+ * neither necessarily the requester thread nor the connection thread, and it can even execute them after
+ * the request has been completed. The state arbitrates both cases.
+ */
+ private void setAcquisitionTimer(PoolWaiter waiter) {
+ if (timeout > 0L && state == NO_TIMER) {
+ this.waiter = waiter;
+ long timerId = context.setTimer(timeout, this);
+ if (!STATE.compareAndSet(this, NO_TIMER, timerId)) {
+ // The request has been completed or another timer has been set concurrently
+ owner.vertx.cancelTimer(timerId);
+ }
+ }
+ }
+
+ /**
+ * The acquisition timer fired: give up the request unless it has been completed meanwhile.
+ */
+ @Override
+ public void handle(Long timerId) {
+ if (STATE.getAndSet(this, COMPLETED) == COMPLETED) {
+ return;
+ }
+ owner.dequeueMetric(metric);
+ // Leave the pool wait queue before failing, the timed out request must no longer take a slot in the wait queue
+ owner.pool.cancel(waiter, (cancelled, err) -> handleFailure(POOL_QUERY_TIMEOUT_EXCEPTION));
+ }
+
+ @Override
+ public void complete(Lease lease, Throwable failure) {
+ long previous = STATE.getAndSet(this, COMPLETED);
+ if (previous == COMPLETED) {
+ // The request has timed out, the connection is not needed anymore
+ if (failure == null) {
+ lease.get().refresh();
+ lease.recycle();
+ }
+ return;
+ }
+ if (previous != NO_TIMER) {
+ owner.vertx.cancelTimer(previous);
+ }
+ owner.dequeueMetric(metric);
+ if (failure == null) {
+ handleLease(lease);
+ } else {
+ handleFailure(failure);
+ }
+ }
+
+ /**
+ * Hand the acquired {@code lease} over to the requester, which becomes responsible for recycling it.
+ *
+ *
The pool emits a lease on the context of the connection, therefore this callback is executed on that
+ * context and not on the context of the requester: implementations must not rely on the current
+ * context and shall use {@link #context} instead, e.g. to report a command on the context of the requester.
+ *
+ *
Called at most once, and never after {@link #handleFailure}.
+ */
+ abstract void handleLease(Lease lease);
+
+ /**
+ * Fail the request.
+ *
+ *
Executed on the context of the requester when the pool rejects the request, on the context of the
+ * connection when the pool closes while connecting, and on the thread draining the pool combiner when the
+ * request times out. Implementations shall therefore complete the requester with a context aware promise
+ * when the failure must be dispatched on a specific context.
+ *
+ *
Called at most once, and never after {@link #handleLease}.
+ */
+ abstract void handleFailure(Throwable failure);
+ }
+
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 {
+ class ExecutePoolRequest extends PoolRequest {
+
+ ExecutePoolRequest() {
+ super(SqlConnectionPool.this, context, timeout);
+ }
+
+ @Override
+ void handleLease(Lease lease) {
+ PooledConnection pooled = lease.get();
pooled.timerMetric = beginMetric();
+ Future future;
if (afterAcquire != null) {
Connection conn = pooled.conn;
+ // The hooks are a pair: the connection is recycled as it was acquired when the acquisition hook fails
future = afterAcquire.apply(conn)
- .compose(v -> Future.future(d -> pooled.schedule(cmd, d)))
- .eventually(() -> beforeRecycle.apply(conn));
+ .compose(v -> Future.future(d -> pooled.schedule(context, cmd, d))
+ .eventually(() -> beforeRecycle.apply(conn)));
} else {
PromiseInternal pp = context.promise();
- pooled.schedule(cmd, pp);
+ pooled.schedule(context, cmd, pp);
future = pp;
}
+ future.onComplete((res, err) -> {
+ endMetric(pooled.timerMetric);
+ pooled.refresh();
+ lease.recycle();
+ handler.complete(res, err);
+ });
}
- 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());
+
+ @Override
+ void handleFailure(Throwable failure) {
+ handler.fail(failure);
}
- });
+ }
+ ExecutePoolRequest request = new ExecutePoolRequest();
+ pool.acquire(context, request, 0, request);
}
public void acquire(ContextInternal context, long timeout, Promise handler) {
- class PoolRequest implements PoolWaiter.Listener, Completable> {
-
- private final Object metric;
- private long timerID = -1L;
+ class AcquirePoolRequest extends PoolRequest {
- PoolRequest(Object metric) {
- this.metric = metric;
+ AcquirePoolRequest() {
+ super(SqlConnectionPool.this, context, timeout);
}
@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());
- }
- });
+ void handleLease(Lease lease) {
+ if (afterAcquire != null) {
+ afterAcquire.apply(lease.get().conn).onComplete((v, err) -> {
+ if (err == null) {
+ handleConnection(lease);
} else {
- handle(lease);
+ lease.recycle();
+ handler.fail(err);
}
- }
+ });
} else {
- fail(null, failure);
- }
- }
-
- private void fail(Lease lease, Throwable cause) {
- if (lease != null) {
- lease.recycle();
+ handleConnection(lease);
}
- dequeueMetric(metric);
- handler.tryFail(cause);
}
- private void handle(Lease lease) {
- dequeueMetric(metric);
+ private void handleConnection(Lease lease) {
PooledConnection pooled = lease.get();
pooled.timerMetric = beginMetric();
+ // The lease is recycled when the connection is given back to the pool, see PooledConnection#cleanup
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);
+ void handleFailure(Throwable failure) {
+ handler.fail(failure);
}
}
- Object metric = enqueueMetric();
- PoolRequest request = new PoolRequest(metric);
+ AcquirePoolRequest request = new AcquirePoolRequest();
pool.acquire(context, request, 0, request);
}
@@ -435,7 +520,16 @@ public DatabaseMetadata databaseMetadata() {
@Override
public void schedule(CommandBase cmd, Completable handler) {
- ContextInternal context = vertx.getOrCreateContext();
+ schedule(vertx.getOrCreateContext(), cmd, handler);
+ }
+
+ /**
+ * Schedule a command, reporting it on the specified {@code context}.
+ *
+ *
The pool hands a connection over on the context of this connection, therefore the context of the
+ * requester cannot be inferred from the current context and must be provided by the caller.
+ */
+ void schedule(ContextInternal context, CommandBase cmd, Completable handler) {
QueryReporter queryReporter;
VertxTracer tracer = vertx.tracer();
ClientMetrics metrics = conn.metrics();
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..db0c46910 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,21 @@
@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. 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..23ec259ca 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
@@ -8,6 +8,9 @@
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.spi.metrics.ClientMetrics;
+import io.vertx.core.spi.tracing.SpanKind;
+import io.vertx.core.spi.tracing.TagExtractor;
+import io.vertx.core.spi.tracing.VertxTracer;
import io.vertx.core.tracing.TracingPolicy;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
@@ -78,11 +81,11 @@ private static Connection fakeConnection() {
return new Connection() {
@Override
public TracingPolicy tracingPolicy() {
- return null;
+ return TracingPolicy.ALWAYS;
}
@Override
public SocketAddress server() {
- return null;
+ return SocketAddress.inetSocketAddress(1234, "localhost");
}
@Override
public String database() {
@@ -252,6 +255,46 @@ public void testAfterAcquireFailureReleasesConnection() {
}
}
+ @Test
+ public void testAfterAcquireFailureReleasesConnectionOfPoolQuery() {
+ AtomicBoolean shouldFail = new AtomicBoolean(true);
+ AtomicInteger beforeRecycleCount = new AtomicInteger();
+ RuntimeException hookError = new RuntimeException("afterAcquire failed");
+
+ DriverBase driver = createDriver(
+ conn -> {
+ if (shouldFail.get()) {
+ return Future.failedFuture(hookError);
+ }
+ return Future.succeededFuture();
+ },
+ conn -> {
+ beforeRecycleCount.incrementAndGet();
+ return Future.succeededFuture();
+ });
+
+ Vertx vertx = Vertx.vertx();
+
+ try {
+ Pool pool = driver.createPool(vertx, () -> Future.succeededFuture(new SqlConnectOptions()),
+ new PoolOptions().setMaxSize(1), new NetClientOptions(), null);
+
+ try {
+ pool.query("one").execute().await();
+ fail("Should have failed");
+ } catch (Exception e) {
+ assertEquals(hookError, e);
+ }
+ assertEquals(0, beforeRecycleCount.get());
+
+ shouldFail.set(false);
+ assertEquals("Hello two", pool.query("two").execute().await().iterator().next().getString(0));
+ assertEquals(1, beforeRecycleCount.get());
+ } finally {
+ vertx.close().await();
+ }
+ }
+
@Test
public void testConnectFailureCancelsPoolConnectionTimeout() throws Exception {
RuntimeException connectError = new RuntimeException("connect failed");
@@ -314,4 +357,75 @@ 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());
+ }
+
+ 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();
+ }
+ }
+
+ @Test
+ public void testPoolQueryReportedOnCallerContext() throws Exception {
+ DriverBase driver = createDriver(null, null);
+
+ AtomicReference requestContext = new AtomicReference<>();
+ AtomicReference responseContext = new AtomicReference<>();
+ Vertx vertx = Vertx.builder().withTracer(tracingOptions -> new VertxTracer