Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
* <p>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:
*
* <ul>
* <li>{@link #NO_TIMER}: no acquisition timer has been set</li>
* <li>a zero or positive value: the identifier of the acquisition timer</li>
* <li>{@link #COMPLETED}: terminal state</li>
* </ul>
*
* <p>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<PooledConnection>, Completable<Lease<PooledConnection>>, Handler<Long> {

private static final AtomicLongFieldUpdater<PoolRequest> 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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we simply use an AtomicLong here ? atomic field updates are useful under intensive usage, here we care mostly about visibility and correctness

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To my knowledge, the field updater is useful when many instances are created, which is the case here: one PoolRequest per pool query or connection acquisition. But I have no strong opinion, if you prefer AtomicLong I will change it.


// 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<PooledConnection> 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<PooledConnection> waiter) {
setAcquisitionTimer(waiter);
}

@Override
public void onConnect(PoolWaiter<PooledConnection> waiter) {
setAcquisitionTimer(waiter);
}

/**
* Set the acquisition timer of this request, unless a timer has been set already.
*
* <p>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.
*
* <p>A waiter is notified twice when it is enqueued first and later associated with a connection request,
* the state prevents a second timer.
*
* <p>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<PooledConnection> 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<PooledConnection> 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.
*
* <p>The pool emits a lease on the context of the connection, therefore this callback is executed on that
* context and <i>not</i> 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.
*
* <p>Called at most once, and never after {@link #handleFailure}.
*/
abstract void handleLease(Lease<PooledConnection> lease);

/**
* Fail the request.
*
* <p>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.
*
* <p>Called at most once, and never after {@link #handleLease}.
*/
abstract void handleFailure(Throwable failure);
}

public <R> void execute(CommandBase<R> cmd, Completable<R> handler, long timeout) {
ContextInternal context = vertx.getOrCreateContext();
Promise<Lease<PooledConnection>> 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<R> 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<PooledConnection> lease) {
PooledConnection pooled = lease.get();
pooled.timerMetric = beginMetric();
Future<R> 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.<R>future(d -> pooled.schedule(cmd, d)))
.eventually(() -> beforeRecycle.apply(conn));
.compose(v -> Future.<R>future(d -> pooled.schedule(context, cmd, d))
.eventually(() -> beforeRecycle.apply(conn)));
} else {
PromiseInternal<R> 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<PooledConnection> handler) {
class PoolRequest implements PoolWaiter.Listener<PooledConnection>, Completable<Lease<PooledConnection>> {

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<PooledConnection> 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<PooledConnection> 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<PooledConnection> lease, Throwable cause) {
if (lease != null) {
lease.recycle();
handleConnection(lease);
}
dequeueMetric(metric);
handler.tryFail(cause);
}

private void handle(Lease<PooledConnection> lease) {
dequeueMetric(metric);
private void handleConnection(Lease<PooledConnection> 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<PooledConnection> 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<PooledConnection> 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);
}

Expand Down Expand Up @@ -435,7 +520,16 @@ public DatabaseMetadata databaseMetadata() {

@Override
public <R> void schedule(CommandBase<R> cmd, Completable<R> handler) {
ContextInternal context = vertx.getOrCreateContext();
schedule(vertx.getOrCreateContext(), cmd, handler);
}

/**
* Schedule a command, reporting it on the specified {@code context}.
*
* <p>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.
*/
<R> void schedule(ContextInternal context, CommandBase<R> cmd, Completable<R> handler) {
QueryReporter queryReporter;
VertxTracer tracer = vertx.tracer();
ClientMetrics metrics = conn.metrics();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,21 @@
@FunctionalInterface
public interface CommandScheduler {

/**
* Schedule {@code cmd} and complete the returned future on {@code context}.
*/
default <R> Future<R> schedule(ContextInternal context, CommandBase<R> cmd) {
Promise<R> promise = context.promise();
schedule(cmd, promise);
return promise.future();
}

/**
* Schedule {@code cmd} and complete {@code handler} with its outcome.
*
* <p>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.
*/
<R> void schedule(CommandBase<R> cmd, Completable<R> handler);

}
Loading
Loading