From a4a5c1bb29809689cbfea887d45f625412713eac Mon Sep 17 00:00:00 2001 From: Ravi Khadiwala Date: Tue, 27 Oct 2026 17:22:41 -0500 Subject: [PATCH] Add connection pooling for the gRPC omnibus backend --- .../textsecuregcm/WhisperServerService.java | 4 +- .../grpc/net/H2ConnectionFactory.java | 6 +- .../grpc/net/OmnibusH2StreamHandler.java | 17 +- .../grpc/net/PooledH2ConnectionFactory.java | 187 +++++++++++++++ .../grpc/net/UnpooledH2ConnectionFactory.java | 23 +- .../grpc/net/OmnibusH2ServerTest.java | 128 ++++++++-- .../net/PooledH2ConnectionFactoryTest.java | 218 ++++++++++++++++++ 7 files changed, 547 insertions(+), 36 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactory.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactoryTest.java diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 6b76f8964..f8b678e2c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -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 { 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; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactory.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactory.java new file mode 100644 index 000000000..192364381 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactory.java @@ -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 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 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 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); + } + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/UnpooledH2ConnectionFactory.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/UnpooledH2ConnectionFactory.java index f154becba..9c11d57f7 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/UnpooledH2ConnectionFactory.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/net/UnpooledH2ConnectionFactory.java @@ -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 channelClass; private final EventLoopGroup eventLoopGroup; private final Set 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; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java index 777a0d349..b7a53f443 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java @@ -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 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 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 backendH2Connection = new CompletableFuture<>(); + final CompletableFuture 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 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 pausedStream = new AtomicReference<>(); + final int pausedResponseSize = Math.toIntExact(DataSize.mebibytes(1).toBytes()); + final CompletableFuture 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 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); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactoryTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactoryTest.java new file mode 100644 index 000000000..6f9b2bf37 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/PooledH2ConnectionFactoryTest.java @@ -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 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 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 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 goAwayRead(final Channel connection) { + final CompletableFuture 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; + } +}