Add connection pooling for the gRPC omnibus backend

This commit is contained in:
Ravi Khadiwala committed 2026-11-04 14:19:32 -06:00
1 parent 2220f750dd
commit a4a5c1bb29
7 files changed
+547 -36

No files matched your search

@@ -199,6 +199,7 @@ import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
import org.whispersystems.textsecuregcm.grpc.net.PooledH2ConnectionFactory;
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
import org.whispersystems.textsecuregcm.grpc.net.UnpooledH2ConnectionFactory;
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
@@ -1220,7 +1221,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final SocketAddress websocketAddress =
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
final H2ConnectionFactory grpcH2ConnectionFactory = new UnpooledH2ConnectionFactory(grpcLocalAddress, omnibusLocalEventLoopGroup.getEventLoopGroup());
final H2ConnectionFactory grpcH2ConnectionFactory = new PooledH2ConnectionFactory(grpcLocalAddress,
omnibusLocalEventLoopGroup.getEventLoopGroup());
final H2ConnectionFactory websocketH2ConnectionFactory = new UnpooledH2ConnectionFactory(websocketAddress, omnibusNioEventLoopGroup.getEventLoopGroup());
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
websocketServletPath, websocketH2ConnectionFactory,
@@ -4,6 +4,7 @@
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import java.net.SocketAddress;
@@ -14,7 +15,10 @@ public interface H2ConnectionFactory {
/// Retrieve a h2 connection to [#address()]
///
/// @param callerEventLoop The event loop of the channel making this call
ChannelFuture getConnection(final EventLoop callerEventLoop);
ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop);
/// Release a connection previously acquired via [#getConnectionChannelFuture]
void release(final Channel connection);
/// @return The [SocketAddress] that this factory targets
SocketAddress address();
@@ -32,7 +32,7 @@ import org.slf4j.LoggerFactory;
///
/// When this handler receives an H2 header for a new stream-id=X on our parent H2 connection it will
/// - Receive the stream-id=X header and check the path to determine the correct backend
/// - Make a new H2 connection to the backend
/// - Get or create an H2 connection to the backend
/// - Forward the header with stream-id=Y to the backend
/// - Install a [H2FrameProxyHandler] on the backend stream pipeline that forwards the received stream-id=Y frames from
/// the backend back to the client on stream-id=X
@@ -84,7 +84,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
: ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
// Make an H2 connection to the target backend
connectionFactory.getConnection(ctx.channel().eventLoop())
connectionFactory.getConnectionChannelFuture(ctx.channel().eventLoop())
.addListener((ChannelFuture connectFuture) -> {
if (!connectFuture.isSuccess()) {
// Close the client stream with a 502: Bad Gateway if the backend wasn't available
@@ -93,25 +93,28 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
.writeAndFlush(new DefaultHttp2HeadersFrame(
new DefaultHttp2Headers().status("502"), true))
.addListener(ChannelFutureListener.CLOSE);
connectionFactory.release(connectFuture.channel());
return;
}
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
logger.trace("Opening a HTTP/2 stream to the backend {}", backendTag);
final Channel backendConnection = connectFuture.channel();
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
createBackendProxyStream(ctx, connectionFactory, backendConnection, headersFrame, backendTag);
});
}
/// Create a proxy stream on the provided `backendConnection` that forwards H2 frames to/from the client H2 stream.
///
/// @param clientStreamCtx The context for a client H2 stream that targets the backend
/// @param connectionFactory The factory `backendConnection` came from
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
/// backend stream
/// @param backendTag The backend this stream targets, for metrics
private void createBackendProxyStream(
final ChannelHandlerContext clientStreamCtx,
final H2ConnectionFactory connectionFactory,
final Channel backendConnection,
final Http2HeadersFrame headersFrame,
final String backendTag) {
@@ -125,15 +128,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
clientStreamCtx.channel()
.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.INTERNAL_ERROR))
.addListener(ChannelFutureListener.CLOSE);
backendConnection.close();
connectionFactory.release(backendConnection);
return;
}
final Http2StreamChannel backendStream = streamFuture.getNow();
// Close the entire H2 connection whenever the stream we just opened closes. We only plan on using
// a single stream on this connection.
backendStream.closeFuture().addListener(_ -> backendConnection.close());
backendStream.closeFuture().addListener(_ -> connectionFactory.release(backendConnection));
// We're going to modify the inbound H2 stream channel, which runs on a different eventloop than the
// outbound channel we've made to the backend. We have to submit our updates back to the inbound
@@ -142,7 +143,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
if (!clientStreamCtx.channel().isActive()) {
// The client disconnected already and the client pipeline is already torn down.
backendConnection.close();
backendStream.close();
return;
}
@@ -0,0 +1,187 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.whispersystems.textsecuregcm.util.ClosableEpoch;
/// An [H2ConnectionFactory] that creates one shared h2 connection per calling event loop.
///
/// A connection is replaced the next time it's requested if it failed to connect, has closed, has received a GOAWAY, or
/// is older than `retireAfterNanos`. Retiring connections bounds how many stream IDs a connection uses since eventually
/// stream-ids are exhausted.
///
/// A replaced connection is never handed out again, and is closed once every stream it was handed out for has been
/// [#release]ed.
public class PooledH2ConnectionFactory implements H2ConnectionFactory {
private static final AttributeKey<Boolean> GOAWAY_RECEIVED =
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "goawayReceived");
// Key for a [ClosableEpoch] attached to every new connection's channel. When the connection is replaced,
// [ClosableEpoch#close] is called, and when all streams are released the underlying netty channel is closed.
private static final AttributeKey<ClosableEpoch> CONNECTION_EPOCH =
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "connection_epoch");
private static final PooledConnectionHandler POOLED_CONNECTION_HANDLER = new PooledConnectionHandler();
private static final String CONNECTION_REPLACED_COUNTER_NAME =
name(PooledH2ConnectionFactory.class, "connectionReplaced");
private static final String OPEN_CONNECTIONS_GAUGE_NAME = name(PooledH2ConnectionFactory.class, "openConnections");
// How long to use a pooled connection for
private static final Duration RETIRE_AFTER = Duration.ofMinutes(30);
private final UnpooledH2ConnectionFactory connectionFactory;
private final long retireAfterNanos;
private final ConcurrentHashMap<EventLoop, PooledConnection> connectionsByCallerEventLoop = new ConcurrentHashMap<>();
// Count of all open connections (including replaced ones waiting for outstanding streams to terminate)
private final AtomicInteger openConnections;
private record PooledConnection(ChannelFuture connectFuture, long createdNanos) {}
/// Create a pooled H2 connection factory
///
/// @param targetAddress The [SocketAddress] connections should target
/// @param eventLoopGroup The eventLoopGroup on which connections will be made. Must match the type of the [SocketAddress]
public PooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
this(targetAddress, eventLoopGroup, RETIRE_AFTER);
}
@VisibleForTesting
PooledH2ConnectionFactory(final SocketAddress targetAddress,
final EventLoopGroup eventLoopGroup,
final Duration retireAfter) {
this.connectionFactory = new UnpooledH2ConnectionFactory(targetAddress, eventLoopGroup, POOLED_CONNECTION_HANDLER);
this.retireAfterNanos = retireAfter.toNanos();
this.openConnections = Metrics.gauge(OPEN_CONNECTIONS_GAUGE_NAME, Tags.of("backend", targetAddress.toString()),
new AtomicInteger());
}
@Override
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
assert callerEventLoop.inEventLoop();
final ChannelFuture connection = connectionsByCallerEventLoop.compute(callerEventLoop, (_, existing) -> {
if (existing == null) {
return newConnection(callerEventLoop);
} else if (!isUsable(existing)) {
existing.connectFuture().channel().attr(CONNECTION_EPOCH).get().close();
return newConnection(callerEventLoop);
} else {
return existing;
}
})
.connectFuture();
// Compute always hands us a connection with an open epoch and we can't race with anyone because we're in
// callerEventLoop, so we should always be able to enter the epoch
final boolean arrived = connection.channel().attr(CONNECTION_EPOCH).get().tryArrive();
assert arrived;
return connection;
}
private PooledConnection newConnection(final EventLoop callerEventLoop) {
final ChannelFuture connectFuture = connectionFactory.getConnectionChannelFuture(callerEventLoop);
final Channel channel = connectFuture.channel();
channel.attr(CONNECTION_EPOCH).set(new ClosableEpoch(channel::close));
openConnections.incrementAndGet();
channel.closeFuture().addListener(_ -> openConnections.decrementAndGet());
return new PooledConnection(connectFuture, System.nanoTime());
}
/// Whether a pooled connection can still be handed out
private boolean isUsable(final PooledConnection pooledConnection) {
final ChannelFuture connectionFuture = pooledConnection.connectFuture();
if (!connectionFuture.isDone()) {
return true;
}
final Channel connection = connectionFuture.channel();
// We know the future is done, see if we actually connected or if we've since disconnected
final boolean active = connection.isActive();
// We might still be connected but have gotten a GOAWAY indicating we shouldn't open new streams
final boolean goawayReceived = Boolean.TRUE.equals(connection.attr(GOAWAY_RECEIVED).get());
// The connection might be fine but old enough that we want a fresh one
final boolean retired = System.nanoTime() - pooledConnection.createdNanos() > retireAfterNanos;
final boolean usable = active && !goawayReceived && !retired;
if (!usable) {
Metrics.counter(CONNECTION_REPLACED_COUNTER_NAME,
"backend", address().toString(),
"active", String.valueOf(active),
"goaway", String.valueOf(goawayReceived),
"retired", String.valueOf(retired))
.increment();
}
return usable;
}
@Override
public void release(final Channel connection) {
connection.attr(CONNECTION_EPOCH).get().depart();
}
@Override
public SocketAddress address() {
return connectionFactory.address();
}
/// Initializes the connection with a large window, and marks a connection as draining when the backend sends a GOAWAY
@ChannelHandler.Sharable
private static class PooledConnectionHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
// Every new H2 connection starts with a connection flow-control window of 64K. Each stream on the connection also
// starts with a per-stream window of 64K. See https://www.rfc-editor.org/rfc/rfc9113.html#section-6.9.2.
//
// Because we're pooling many distinct, h2 streams from different remote clients may share this single h2
// connection to the backend. So, by default, if a single stream is slow to receive a large response from the
// backend, they could consume the entire connection window.
//
// To avoid this, as soon as we open the connection tell the server we're willing to accept more at the connection
// level. We update the connection window to the max value by sending a WINDOW_UPDATE (6.9) to add enough credit
// to reach the max connection window size of INT_MAX. The individual streams still retain the default window-size
// of 64K.
ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE));
ctx.fireChannelActive();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
if (msg instanceof Http2GoAwayFrame) {
ctx.channel().attr(GOAWAY_RECEIVED).set(true);
ReferenceCountUtil.release(msg);
return;
}
ctx.fireChannelRead(msg);
}
}
}
@@ -12,6 +12,7 @@ import io.micrometer.core.instrument.Timer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
@@ -27,6 +28,7 @@ import io.netty.util.concurrent.EventExecutor;
import java.net.SocketAddress;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -44,16 +46,26 @@ public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
private final Class<? extends Channel> channelClass;
private final EventLoopGroup eventLoopGroup;
private final Set<EventExecutor> eventLoops;
@Nullable
private final ChannelHandler connectionHandler;
public UnpooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
this(targetAddress, eventLoopGroup, null);
}
UnpooledH2ConnectionFactory(
final SocketAddress targetAddress,
final EventLoopGroup eventLoopGroup,
@Nullable final ChannelHandler connectionHandler) {
this.targetAddress = targetAddress;
this.channelClass = targetAddress instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class;
this.eventLoopGroup = eventLoopGroup;
this.eventLoops = ImmutableSet.copyOf(eventLoopGroup);
this.connectionHandler = connectionHandler;
}
@Override
public ChannelFuture getConnection(final EventLoop callerEventLoop) {
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
// Make a new H2 connection to the target backend
final Timer.Sample connectSample = Timer.start();
@@ -70,6 +82,9 @@ public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
if (connectionHandler != null) {
ch.pipeline().addLast(connectionHandler);
}
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
}
})
@@ -81,6 +96,12 @@ public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
.register(Metrics.globalRegistry)));
}
@Override
public void release(final Channel connection) {
// Each connection only ever carries one stream
connection.close();
}
@Override
public SocketAddress address() {
return targetAddress;
@@ -38,6 +38,8 @@ import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
@@ -176,11 +178,14 @@ class OmnibusH2ServerTest {
ReferenceCountUtil.release(sniMapping.map(TEST_DOMAIN));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void defaultBackend(final boolean localChannel) throws Exception {
@CartesianTest
void defaultBackend(
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
@CartesianTest.Values(booleans = {false, true}) final boolean pooled)
throws Exception {
final OmnibusH2Server server = omnibusServer()
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
.pooled(pooled)
.addDefault(backendServer().localChannel(localChannel))
.start();
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), "/a/different/path");
@@ -203,9 +208,11 @@ class OmnibusH2ServerTest {
@CartesianTest
void pathBackend(
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
@CartesianTest.Values(booleans = {false, true}) final boolean pooled,
@CartesianTest.Values(strings = {"/v1/path/", "/v1/path/?foo=bar", "/v1/path/?foo=bar&baz=quux"}) final String path) throws Exception {
final OmnibusH2Server server = omnibusServer()
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
.pooled(pooled)
.start();
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), path);
assertEquals(PATH_BACKEND_IDENTITY, response);
@@ -240,11 +247,12 @@ class OmnibusH2ServerTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void backendDownStreamReset(final boolean localChannel) throws Exception {
@CartesianTest
void backendDownStreamReset(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final BackendServerBuilder backend = backendServer().localChannel(localChannel);
final OmnibusH2Server server = omnibusServer().addDefault(backend).start();
final OmnibusH2Server server = omnibusServer().addDefault(backend).pooled(pooled).start();
// Kill the default backend so connection attempts from the omnibus fail
backend.channel().close().syncUninterruptibly();
@@ -278,8 +286,12 @@ class OmnibusH2ServerTest {
@CartesianTest
void backendCloseClosesClientStream(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled,
@CartesianTest.Values(strings = {"/goaway", "/reset"}) final String path) throws Exception {
final OmnibusH2Server server = omnibusServer().addDefault(backendServer().localChannel(localChannel)).start();
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer().localChannel(localChannel))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
final CompletableFuture<Http2ResetFrame> resetFuture = new CompletableFuture<>();
@@ -302,10 +314,14 @@ class OmnibusH2ServerTest {
assertTrue(h2Connection.isActive());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void queuedDataFrames(final boolean localChannel) throws Exception {
final OmnibusH2Server server = omnibusServer().addDefault(backendServer().localChannel(localChannel)).start();
@CartesianTest
void queuedDataFrames(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer().localChannel(localChannel))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
@@ -341,14 +357,18 @@ class OmnibusH2ServerTest {
h2Connection.close().syncUninterruptibly();
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void clientDisconnectClosesBackendConnections(final boolean localChannel) throws Exception {
@CartesianTest
void clientDisconnectClosesBackendStreams(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final CompletableFuture<Channel> backendH2Connection = new CompletableFuture<>();
final CompletableFuture<Channel> backendH2Stream = new CompletableFuture<>();
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer()
.localChannel(localChannel)
.h2ChannelInit(backendH2Connection::complete))
.h2ChannelInit(backendH2Connection::complete)
.h2StreamInit(backendH2Stream::complete))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
@@ -367,18 +387,20 @@ class OmnibusH2ServerTest {
.authority("localhost");
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false)).syncUninterruptibly();
assertFalse(
backendH2Connection.join().closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS),
"Channel should be open");
final Channel backendStream = backendH2Stream.get(5, TimeUnit.SECONDS);
assertFalse(backendStream.closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS), "Stream should be open");
// All backend connections the omnibus opened on behalf of this client should close if we disconnect the client
// All backend streams the omnibus opened on behalf of this client should close if we disconnect the client
h2Connection.close().syncUninterruptibly();
assertTrue(backendH2Connection.join().closeFuture().await(5, TimeUnit.SECONDS));
assertTrue(backendStream.closeFuture().await(5, TimeUnit.SECONDS));
// Pooled connections are shared with other clients, so only unpooled connections should close
assertEquals(!pooled, backendH2Connection.join().closeFuture().await(pooled ? 100 : 5000, TimeUnit.MILLISECONDS));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void requestBackpressure(final boolean localChannel) throws Exception {
@CartesianTest
void requestBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final AtomicReference<Channel> backendStreamChannel = new AtomicReference<>();
final OmnibusH2Server omnibusH2Server = omnibusServer()
.addDefault(backendServer()
@@ -388,6 +410,7 @@ class OmnibusH2ServerTest {
ch.config().setAutoRead(false);
backendStreamChannel.set(ch);
}))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(omnibusH2Server, null);
@@ -455,6 +478,7 @@ class OmnibusH2ServerTest {
@CartesianTest
void responseBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled,
@CartesianTest.Values(ints = {193, 512, 2048}) final int responseSizeKib) throws Exception {
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
@@ -485,6 +509,7 @@ class OmnibusH2ServerTest {
});
backendStreamInitialized.countDown();
}))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
@@ -513,6 +538,49 @@ class OmnibusH2ServerTest {
h2Connection.close().syncUninterruptibly();
}
@Test
void pausedStreamDoesNotStallPooledConnection() throws Exception {
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer()
.h2StreamInit(ch -> ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext ctx) {
if (!ctx.channel().isWritable()) {
backendStreamUnwritable.countDown();
}
ctx.fireChannelWritabilityChanged();
}
})))
.pooled(true)
.start();
final Channel h2Connection = connectToOmnibus(server);
// Open our own connection-level window, so the paused stream doesn't stall our connection to the omnibus
h2Connection.writeAndFlush(
new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE)).syncUninterruptibly();
// Force one of the streams to go unwritable
final AtomicReference<Channel> pausedStream = new AtomicReference<>();
final int pausedResponseSize = Math.toIntExact(DataSize.mebibytes(1).toBytes());
final CompletableFuture<byte[]> pausedResponse = request(h2Connection, pausedResponseSize, (byte) 1, ch -> {
ch.config().setAutoRead(false);
pausedStream.set(ch);
});
assertTrue(backendStreamUnwritable.await(5, TimeUnit.SECONDS), "failed to introduce backpressure");
// A different stream should not be affected
final int responseSize = Math.toIntExact(DataSize.kibibytes(1).toBytes());
assertArrayEquals(expectedBody(responseSize, (byte) 2),
request(h2Connection, responseSize, (byte) 2, _ -> {}).get(5, TimeUnit.SECONDS));
assertFalse(pausedResponse.isDone());
pausedStream.get().eventLoop().execute(() -> pausedStream.get().config().setAutoRead(true));
assertArrayEquals(expectedBody(pausedResponseSize, (byte) 1), pausedResponse.get(5, TimeUnit.SECONDS));
h2Connection.close().syncUninterruptibly();
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void idleTest(final boolean localChannel) throws Exception {
@@ -600,6 +668,7 @@ class OmnibusH2ServerTest {
final OmnibusH2Server server = omnibusServer()
.eventLoopGroups(nioEventLoopGroup, localEventLoopGroup)
.addDefault(backendServer().localChannel(localChannel))
.pooled(false)
.start();
for (int i = 0; i < connections; i++) {
@@ -675,6 +744,7 @@ class OmnibusH2ServerTest {
private final Map<String, BackendServerBuilder> routes = new HashMap<>();
private BackendServerBuilder defaultBackend = backendServer();
private Duration idleTimeout = Duration.ofMinutes(1);
private boolean pooled = true;
private EventLoopGroup nioEventLoopGroup = OmnibusH2ServerTest.nioEventLoopGroup;
private EventLoopGroup localEventLoopGroup = OmnibusH2ServerTest.localEventLoopGroup;
@@ -696,6 +766,12 @@ class OmnibusH2ServerTest {
return this;
}
/// Whether to connect to backends via pooled h2 connections. Defaults to true.
OmnibusServerBuilder pooled(final boolean pooled) {
this.pooled = pooled;
return this;
}
/// The event loop groups used by the omnibus and its backends. Defaults to the shared event loop groups.
OmnibusServerBuilder eventLoopGroups(final EventLoopGroup nioEventLoopGroup,
final EventLoopGroup localEventLoopGroup) {
@@ -727,7 +803,9 @@ class OmnibusH2ServerTest {
final EventLoopGroup eventLoopGroup = backend.localChannel ? localEventLoopGroup : nioEventLoopGroup;
final Channel channel = backend.start(eventLoopGroup);
backendChannelsToShutDown.add(channel);
return new UnpooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup);
return pooled
? new PooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup, Duration.ofDays(1))
: new UnpooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup);
}
}
@@ -0,0 +1,218 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.test.LeakPresenceExtension;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(LeakPresenceExtension.class)
class PooledH2ConnectionFactoryTest {
private static EventLoopGroup backendEventLoopGroup;
private static EventLoopGroup callerEventLoopGroup;
private LocalAddress backendAddress;
private Channel backendServer;
private BlockingQueue<Channel> newBackendConnections;
private ChannelGroup allBackendConnections;
private PooledH2ConnectionFactory factory;
@BeforeAll
static void setUpBeforeAll() {
backendEventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
callerEventLoopGroup = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
}
@BeforeEach
void setUp() {
backendAddress = new LocalAddress(PooledH2ConnectionFactoryTest.class);
newBackendConnections = new LinkedBlockingQueue<>();
allBackendConnections = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
startBackend();
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ofDays(1));
}
@AfterEach
void tearDown() {
backendServer.close().syncUninterruptibly();
allBackendConnections.close().syncUninterruptibly();
}
@AfterAll
static void tearDownAfterAll() throws InterruptedException {
backendEventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
callerEventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
}
@Test
void reuseConnection() throws Exception {
final EventLoop eventLoop1 = callerEventLoopGroup.next();
final EventLoop eventLoop2 = callerEventLoopGroup.next();
final Channel connection = getConnection(eventLoop1).channel();
assertSame(connection, getConnection(eventLoop1).channel());
assertNotSame(connection, getConnection(eventLoop2).channel());
}
@Test
void shareConnectionWhileConnecting() throws Exception {
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final List<ChannelFuture> connectFutures = callerEventLoop.submit(() -> List.of(
factory.getConnectionChannelFuture(callerEventLoop),
factory.getConnectionChannelFuture(callerEventLoop)))
.get();
assertSame(connectFutures.get(0), connectFutures.get(1));
}
@Test
void replaceClosedConnection() throws Exception {
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
backendConnection().close().syncUninterruptibly();
connection.closeFuture().syncUninterruptibly();
final Channel replacement = getConnection(callerEventLoop).channel();
assertNotSame(connection, replacement);
assertTrue(replacement.isActive());
}
@Test
void replaceFailedConnection() throws Exception {
backendServer.close().syncUninterruptibly();
final EventLoop callerEventLoop = callerEventLoopGroup.next();
assertFalse(getConnection(callerEventLoop).isSuccess());
startBackend();
assertTrue(getConnection(callerEventLoop).isSuccess());
}
@Test
void replaceConnectionAfterGoAway() throws Exception {
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
final CompletableFuture<Void> goAwayRead = goAwayRead(connection);
backendConnection().writeAndFlush(new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR)).syncUninterruptibly();
goAwayRead.get(5, TimeUnit.SECONDS);
assertNotSame(connection, getConnection(callerEventLoop).channel());
assertTrue(connection.isActive());
factory.release(connection);
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
}
@Test
void retireConnection() throws Exception {
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ZERO);
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
assertNotSame(connection, getConnection(callerEventLoop).channel());
assertTrue(connection.isActive());
factory.release(connection);
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
}
@Test
void closeUnusedConnectionWhenReplaced() throws Exception {
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ZERO);
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
factory.release(connection);
assertTrue(connection.isActive());
getConnection(callerEventLoop);
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
}
private void startBackend() {
backendServer = new ServerBootstrap()
.group(backendEventLoopGroup)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
newBackendConnections.add(ch);
allBackendConnections.add(ch);
}
})
.bind(backendAddress)
.syncUninterruptibly()
.channel();
}
/// Get a connection from the factory on `callerEventLoop`, waiting for it to finish connecting
private ChannelFuture getConnection(final EventLoop callerEventLoop) throws Exception {
return callerEventLoop.submit(() -> factory.getConnectionChannelFuture(callerEventLoop)).get().await();
}
/// The backend's side of the next connection the factory made
private Channel backendConnection() throws InterruptedException {
final Channel backendConnection = newBackendConnections.poll(5, TimeUnit.SECONDS);
assertNotNull(backendConnection);
return backendConnection;
}
/// A future that completes once the factory has seen a GOAWAY on `connection`
private static CompletableFuture<Void> goAwayRead(final Channel connection) {
final CompletableFuture<Void> goAwayRead = new CompletableFuture<>();
connection.pipeline().addAfter(connection.pipeline().context(Http2MultiplexHandler.class).name(), null,
new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
ctx.fireChannelRead(msg);
if (msg instanceof Http2GoAwayFrame) {
goAwayRead.complete(null);
}
}
});
return goAwayRead;
}
}