Skip to content
Merged
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 @@ -16,8 +16,10 @@
import io.vertx.core.internal.ContextInternal;
import io.vertx.core.impl.NoStackTraceTimeoutException;
import io.vertx.core.internal.http.HttpClientTransport;
import io.vertx.core.http.impl.tcp.Http2UpgradeClientConnection;
import io.vertx.core.internal.pool.ConnectResult;
import io.vertx.core.internal.pool.ConnectionPool;
import io.vertx.core.internal.pool.DefaultConnectionPool;
import io.vertx.core.internal.pool.PoolConnection;
import io.vertx.core.internal.pool.PoolConnector;
import io.vertx.core.internal.pool.Lease;
Expand All @@ -29,6 +31,7 @@
import io.vertx.core.spi.metrics.HttpClientMetrics;
import io.vertx.core.spi.metrics.PoolMetrics;

import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
Expand Down Expand Up @@ -102,43 +105,25 @@ private class Request implements PoolWaiter.Listener<HttpClientConnection>, Comp
private final ContextInternal context;
private final long timeout;
private final Promise<Lease<HttpClientConnection>> promise;
private long timerID;

Request(ContextInternal context, long timeout, Promise<Lease<HttpClientConnection>> promise) {
this.context = context;
this.timeout = timeout;
this.promise = promise;
this.timerID = -1L;
}

@Override
public void onEnqueue(PoolWaiter<HttpClientConnection> waiter) {
onConnect(waiter);
}

@Override
public void onConnect(PoolWaiter<HttpClientConnection> waiter) {
if (timeout > 0L && timerID == -1L) {
timerID = context.setTimer(timeout, id -> {
pool.pool.cancel(waiter, (res, err) -> {
if (err == null && res)
promise.fail(new NoStackTraceTimeoutException("The timeout of " + timeout + " ms has been exceeded when getting a connection to " + server));
});
});
}
public void onTimeout(PoolWaiter<HttpClientConnection> waiter) {
promise.fail(new NoStackTraceTimeoutException("The timeout of " + timeout + " ms has been exceeded when getting a connection to " + server));
}

@Override
public void complete(Lease<HttpClientConnection> result, Throwable failure) {
if (timerID >= 0 && !context.owner().cancelTimer(timerID)) {
result.recycle();
} else {
promise.complete(result, failure);
}
promise.complete(result, failure);
}

void acquire() {
pool.acquire(context,this, promise);
pool.acquire(context, this, timeout, promise);
}
}

Expand Down Expand Up @@ -212,8 +197,12 @@ static class Pool implements PoolConnector<HttpClientConnection> {
this.maxLifetimeMillis = maxLifetimeMillis;
this.connectParams = connectParams;
this.poolKind = initialPoolKind;
this.pool = ConnectionPool
.pool(this, new int[]{http1MaxSize, http2MaxSize}, queueMaxSize)
this.pool = DefaultConnectionPool
.builder(this)
.withMaxSizes(new int[]{http1MaxSize, http2MaxSize})
.withMaxWaiters(queueMaxSize)
.withConnectionChecker(this::checkConnection)
.build()
.connectionSelector(LIFO_SELECTOR)
.contextProvider(contextProvider);
}
Expand All @@ -231,8 +220,12 @@ static class Pool implements PoolConnector<HttpClientConnection> {
this.maxLifetimeMillis = maxLifetimeMillis;
this.connectParams = connectParams;
this.poolKind = 0;
this.pool = ConnectionPool
.pool(this, new int[]{http3MaxSize}, queueMaxSize)
this.pool = DefaultConnectionPool
.builder(this)
.withMaxSizes(new int[]{http3MaxSize})
.withMaxWaiters(queueMaxSize)
.withConnectionChecker(this::checkConnection)
.build()
.connectionSelector(LIFO_SELECTOR)
.contextProvider(contextProvider);
}
Expand All @@ -249,7 +242,17 @@ public Future<ConnectResult<HttpClientConnection>> connect(ContextInternal conte
connection.concurrencyChangeHandler(listener::onConcurrencyChange);
owner.init(connection);
long capacity = connection.concurrency();
int idx = connection.protocolVersion() != HttpVersion.HTTP_2 ? 0 : 1;
int idx;
if (connection instanceof Http2UpgradeClientConnection && ((Http2UpgradeClientConnection)connection).upgradePending()) {
// The clear-text upgrade rides on the first request: classify with the HTTP/2 intent
// so the pool does not dial into phantom HTTP/1 headroom, the concurrency raises with
// onConcurrencyChange when the upgrade succeeds; reclassify when it is rejected,
// returning the capacity so the pool can dial more HTTP/1 connections
idx = 1;
((Http2UpgradeClientConnection)connection).upgradeRejectedHandler(v -> listener.onKindChange(0));
} else {
idx = connection.protocolVersion() != HttpVersion.HTTP_2 ? 0 : 1;
}
return new ConnectResult<>(connection, capacity, idx);
});
if (owner.exceptionHandler != null) {
Expand All @@ -264,20 +267,24 @@ public Future<ConnectResult<HttpClientConnection>> connect(ContextInternal conte

@Override
public boolean isValid(HttpClientConnection connection) {
throw new UnsupportedOperationException();
}

private boolean checkConnection(HttpClientConnection connection) {
return connection.isValid() && (maxLifetimeMillis == 0L || (System.currentTimeMillis() - connection.creationTimestamp()) <= maxLifetimeMillis);
}

@Override
public void close(HttpClientConnection connection) {
connection.close();
}

void checkExpired() {
pool
.evict(c -> !isValid(c), (lst, err) -> {
if (err == null) {
lst.forEach(HttpConnection::close);
}
});
pool.refresh();
}

void acquire(ContextInternal context, PoolWaiter.Listener<HttpClientConnection> listener, Promise<Lease<HttpClientConnection>> promise) {
pool.acquire(context, listener, poolKind, promise);
void acquire(ContextInternal context, PoolWaiter.Listener<HttpClientConnection> listener, long timeout, Promise<Lease<HttpClientConnection>> promise) {
pool.acquire(context, listener, poolKind, timeout > 0L ? Duration.ofMillis(timeout) : null, promise);
}

void close() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public class Http2ClientConnectionImpl extends Http2ConnectionImpl implements Ht
this.authority = authority;
this.creationTimestamp = System.currentTimeMillis();
this.handler = connHandler;
recycle();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,13 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
case UPGRADE_SUCCESSFUL:
// Remove Http1xClientConnection handler
pipeline.remove("handler");
// Go through
// Remove this handler
// Upgrade handler will remove itself and remove the HttpClientCodec
pipeline.remove(this);
break;
case UPGRADE_REJECTED:
// Remove this handler
pipeline.remove(this);
// Upgrade handler will remove itself and remove the HttpClientCodec
result.upgradeRejected();
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ public Http2MultiplexClientConnection(Http2MultiplexHandler handler,
this.evicted = false;
this.decompressionSupported = decompressionSupported;
this.creationTimestamp = System.currentTimeMillis();
refresh();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public Http3ClientConnection(QuicConnectionInternal connection,
this.keepAliveTimeoutMillis = keepAliveTimeoutMillis;
this.creationTimestamp = System.currentTimeMillis();
this.concurrency = concurrency;
refresh();
}

public void init() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public class Http2UpgradeClientConnection implements io.vertx.core.http.impl.Htt
private final ClientMetrics<?, ?, ?> clientMetrics;
private io.vertx.core.http.impl.HttpClientConnection current;
private boolean upgradeProcessed;
private Handler<Void> upgradeRejectedHandler;

private Handler<Void> closeHandler;
private Handler<Void> shutdownHandler;
Expand All @@ -83,6 +84,21 @@ public io.vertx.core.http.impl.HttpClientConnection unwrap() {
return current;
}

/**
* @return whether the clear-text upgrade has not been resolved yet
*/
public boolean upgradePending() {
return current instanceof Http1ClientConnection && !upgradeProcessed;
}

/**
* Set the handler signalled when the clear-text upgrade is rejected and the connection remains HTTP/1.1.
*/
public Http2UpgradeClientConnection upgradeRejectedHandler(Handler<Void> handler) {
upgradeRejectedHandler = handler;
return this;
}

@Override
public MultiMap newHttpRequestHeaders() {
return current.newHttpRequestHeaders();
Expand Down Expand Up @@ -348,6 +364,7 @@ void handleUpgrade(io.vertx.core.http.impl.HttpClientConnection conn, HttpClient
pushHandler = null;
closeHandler = null;
upgradedConnection.current = conn;
upgradedConnection.upgradeProcessed = true;
conn.closeHandler(upgradedConnection.closeHandler);
conn.exceptionHandler(upgradedConnection.exceptionHandler);
conn.pingHandler(upgradedConnection.pingHandler);
Expand All @@ -367,6 +384,7 @@ void handleUpgrade(io.vertx.core.http.impl.HttpClientConnection conn, HttpClient
upgradedConnection.evictionHandler = null;
upgradedConnection.concurrencyChangeHandler = null;
upgradedConnection.invalidMessageHandler = null;
upgradedConnection.upgradeRejectedHandler = null;
concurrencyChangeHandler.handle(conn.concurrency());
}

Expand Down Expand Up @@ -417,6 +435,11 @@ public void upgradeAccepted(io.vertx.core.http.impl.HttpClientConnection connect
public void upgradeRejected() {
UpgradingStream.this.upgradeRejected = true;
UpgradingStream.this.upgradedConnection.upgradeProcessed = true;
Handler<Void> handler = UpgradingStream.this.upgradedConnection.upgradeRejectedHandler;
UpgradingStream.this.upgradedConnection.upgradeRejectedHandler = null;
if (handler != null) {
handler.handle(null);
}
}
@Override
public void upgradeFailure(Throwable cause) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/**
* Lock free executor.
Expand All @@ -30,6 +31,7 @@ public class CombinerExecutor<S> implements Executor<S> {
private final Queue<Action<S>> q = PlatformDependent.newMpscQueue();
private final AtomicInteger s = new AtomicInteger();
private final S state;
private final Supplier<Action<S>> finalAction;

protected static final class InProgressTail<S> {

Expand All @@ -46,7 +48,12 @@ public InProgressTail(CombinerExecutor<S> combiner, Task task) {
private static final FastThreadLocal<InProgressTail<?>> current = new FastThreadLocal<>();

public CombinerExecutor(S state) {
this(state, null);
}

public CombinerExecutor(S state, Supplier<Action<S>> finalAction) {
this.state = state;
this.finalAction = finalAction;
}

@Override
Expand All @@ -55,6 +62,20 @@ public void submit(Action<S> action) {
if (s.get() != 0 || !s.compareAndSet(0, 1)) {
return;
}
drain();
}

@Override
public boolean trySubmit(Action<S> action) {
if (s.get() != 0 || !s.compareAndSet(0, 1)) {
return false;
}
q.add(action);
drain();
return true;
}

private void drain() {
Task head = null;
Task tail = null;
do {
Expand All @@ -77,6 +98,23 @@ public void submit(Action<S> action) {
}
}
}
if (finalAction != null) {
Action<S> a = finalAction.get();
if (a != null) {
final Task task = a.execute(state);
if (task != null) {
Task last = task.last();
if (head == null) {
assert tail == null;
tail = last;
head = task;
} else {
tail.next(task);
tail = last;
}
}
}
}
} finally {
s.set(0);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import io.vertx.core.internal.ContextInternal;
import io.vertx.core.internal.VertxInternal;

import java.time.Duration;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
Expand Down Expand Up @@ -70,6 +71,13 @@ static <C> ConnectionPool<C> pool(PoolConnector<C> connector, int[] maxSizes, in
*/
ConnectionPool<C> contextProvider(Function<ContextInternal, ContextInternal> contextProvider);

/**
* Refresh the pool: check and perform the maintenance tasks to do, this method
* should be called periodically. Depending on the granularity of the period,
* deadlines might be passed, which is acceptable.
*/
void refresh();

/**
* Acquire a connection from the pool.
*
Expand All @@ -87,6 +95,23 @@ static <C> ConnectionPool<C> pool(PoolConnector<C> connector, int[] maxSizes, in
*/
void acquire(ContextInternal context, PoolWaiter.Listener<C> listener, int kind, Completable<Lease<C>> handler);

/**
* Like {@link #acquire(ContextInternal, int, Completable)} with a timeout: when the acquisition
* remains pending after the timeout, the pool removes the waiter from the wait queue and signals
* {@link PoolWaiter.Listener#onTimeout}, nothing else. The timeout is checked when the pool
* executes, deadlines might be passed. The default implementation ignores the timeout.
*/
default void acquire(ContextInternal context, int kind, Duration timeout, Completable<Lease<C>> handler) {
acquire(context, kind, handler);
}

/**
* Like {@link #acquire(ContextInternal, PoolWaiter.Listener, int, Completable)} with a timeout.
*/
default void acquire(ContextInternal context, PoolWaiter.Listener<C> listener, int kind, Duration timeout, Completable<Lease<C>> handler) {
acquire(context, listener, kind, handler);
}

/**
* Cancel a waiter.
*
Expand Down
Loading
Loading