GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add tests for response backpressure and concurrent, large, responses · signalapp/Signal-Server@9bbd04a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • service/src/test/java/org/whispersystems/textsecuregcm/grpc/net
    • OmnibusH2ServerTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java‎

Copy file name to clipboardExpand all lines: service/src/test/java/org/whispersystems/textsecuregcm/grpc/net/OmnibusH2ServerTest.java
+233-17Lines changed: 233 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package org.whispersystems.textsecuregcm.grpc.net;
22

3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
35
import static org.junit.jupiter.api.Assertions.assertEquals;
46
import static org.junit.jupiter.api.Assertions.assertFalse;
57
import static org.junit.jupiter.api.Assertions.assertTrue;
68

9+
import io.dropwizard.util.DataSize;
710
import io.netty.bootstrap.Bootstrap;
811
import io.netty.bootstrap.ServerBootstrap;
912
import io.netty.buffer.ByteBuf;
@@ -61,13 +64,16 @@
6164
import java.time.Duration;
6265
import java.time.Instant;
6366
import java.util.ArrayList;
67+
import java.util.Arrays;
6468
import java.util.Collections;
6569
import java.util.List;
6670
import java.util.Map;
6771
import java.util.Optional;
6872
import java.util.concurrent.CompletableFuture;
73+
import java.util.concurrent.CountDownLatch;
6974
import java.util.concurrent.TimeUnit;
7075
import java.util.concurrent.atomic.AtomicBoolean;
76+
import java.util.concurrent.atomic.AtomicLong;
7177
import java.util.concurrent.atomic.AtomicReference;
7278
import java.util.function.Consumer;
7379
import java.util.stream.Collectors;
@@ -91,7 +97,19 @@ class OmnibusH2ServerTest {
9197
// URIs targeting PATH should go to the path backend, everything else to default.
9298
private static final String PATH_BACKEND_IDENTITY = "path-backend";
9399
private static final String PATH = "/v1/path/";
100+
101+
/// The default backend implements dynamic behavior for various test scenarios, such as
102+
///
103+
/// - resets
104+
/// - GOAWAY
105+
/// - echo
106+
/// - etc.
107+
///
108+
/// @see TestHandler#channelRead
94109
private static final String DEFAULT_BACKEND_IDENTITY = "default-backend";
110+
/// Requests to default backend at `/fixed-response/<n>/<b>` get an `n`-byte response body from the backend
111+
/// filled with the byte `b`
112+
private static final String FIXED_RESPONSE_PATH_PREFIX = "/fixed-response/";
95113

96114
private static NioEventLoopGroup nioEventLoopGroup;
97115
private static DefaultEventLoopGroup localEventLoopGroup;
@@ -100,6 +118,7 @@ class OmnibusH2ServerTest {
100118

101119
private List<Channel> backendChannelsToShutDown;
102120
private List<OmnibusH2Server> omnibusH2ServersToShutDown;
121+
private List<EventLoopGroup> groupsToShutDown;
103122
private AtomicReference<DynamicOmnibusConfiguration> dynamicConfiguration;
104123

105124
@BeforeAll
@@ -133,13 +152,15 @@ static void setUpBeforeAll() throws Exception {
133152
void setUp() {
134153
backendChannelsToShutDown = new ArrayList<>();
135154
omnibusH2ServersToShutDown = new ArrayList<>();
155+
groupsToShutDown = new ArrayList<>();
136156
dynamicConfiguration = new AtomicReference<>(new DynamicOmnibusConfiguration(BigDecimal.ZERO));
137157
}
138158

139159
@AfterEach
140160
void tearDown() {
141161
omnibusH2ServersToShutDown.forEach(OmnibusH2Server::stop);
142162
backendChannelsToShutDown.forEach(c -> c.close().syncUninterruptibly());
163+
groupsToShutDown.forEach(g -> g.shutdownGracefully(0, 1000, TimeUnit.MILLISECONDS).syncUninterruptibly());
143164
}
144165

145166
@AfterAll
@@ -277,9 +298,9 @@ void backendCloseClosesClientStream(
277298
void queuedDataFrames(final boolean localChannel) throws Exception {
278299
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
279300
final Channel h2Connection = connectToOmnibus(server);
280-
final CompletableFuture<String> responseFuture = new CompletableFuture<>();
301+
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
281302
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
282-
.handler(new ResponseCollectorHandler(responseFuture))
303+
.handler(new BodyCollectorHandler(responseFuture))
283304
.open()
284305
.syncUninterruptibly()
285306
.getNow();
@@ -305,7 +326,7 @@ void queuedDataFrames(final boolean localChannel) throws Exception {
305326
stream.flush();
306327
final String expected = expectedBuilder.toString();
307328

308-
final String response = responseFuture.get(10, TimeUnit.SECONDS);
329+
final String response = responseFuture.thenApply(OmnibusH2ServerTest::stringFromUtfBytes).get(10, TimeUnit.SECONDS);
309330
assertEquals(expected, response);
310331

311332
h2Connection.close().syncUninterruptibly();
@@ -321,7 +342,7 @@ void clientDisconnectClosesBackendConnections(final boolean localChannel) throws
321342

322343
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
323344
final Http2StreamChannel stream = streamBootstrap
324-
.handler(new ResponseCollectorHandler(new CompletableFuture<>()))
345+
.handler(new BodyCollectorHandler(new CompletableFuture<>()))
325346
.open()
326347
.syncUninterruptibly()
327348
.getNow();
@@ -345,9 +366,9 @@ void clientDisconnectClosesBackendConnections(final boolean localChannel) throws
345366

346367
@ParameterizedTest
347368
@ValueSource(booleans = {true, false})
348-
void backpressure(final boolean localChannel) throws Exception {
369+
void requestBackpressure(final boolean localChannel) throws Exception {
349370
final AtomicReference<Channel> backendStreamChannel = new AtomicReference<>();
350-
final Channel backendServer = startBackendServer(localChannel, "backpressure", _ -> {
371+
final Channel backendServer = startBackendServer(localChannel, "request-backpressure", _ -> {
351372
}, ch -> {
352373
ch.config().setAutoRead(false);
353374
backendStreamChannel.set(ch);
@@ -417,6 +438,62 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
417438
h2Connection.close().syncUninterruptibly();
418439
}
419440

441+
@CartesianTest
442+
void responseBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
443+
@CartesianTest.Values(ints = {193, 512, 2048}) final int responseSizeKib) throws Exception {
444+
445+
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
446+
447+
// various windows and buffers (it appears to be 3 * 64kiB) in the stack mean the backend only reaches the backpressure point for
448+
// large-ish responses
449+
assertTrue(responseSize > DataSize.kibibytes(192).toBytes());
450+
451+
final CountDownLatch backendStreamInitialized = new CountDownLatch(1);
452+
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
453+
final AtomicLong pendingWhenUnwritable = new AtomicLong();
454+
455+
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, "response-backpressure",
456+
_ -> {}, ch -> {
457+
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
458+
@Override
459+
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
460+
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
461+
// A change in writability on the backend stream means we introduced backpressure
462+
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
463+
backendStreamUnwritable.countDown();
464+
}
465+
backendStreamCtx.fireChannelWritabilityChanged();
466+
}
467+
});
468+
backendStreamInitialized.countDown();
469+
}));
470+
final Channel h2Connection = connectToOmnibus(server);
471+
472+
final AtomicReference<Http2StreamChannel> clientStream = new AtomicReference<>();
473+
final CompletableFuture<byte[]> response = request(h2Connection, responseSize, (byte) 1, ch -> {
474+
ch.config().setAutoRead(false);
475+
clientStream.set(ch);
476+
});
477+
478+
assertTrue(backendStreamInitialized.await(1, TimeUnit.SECONDS));
479+
480+
assertTrue(backendStreamUnwritable.await(3, TimeUnit.SECONDS), "failed to introduce backpressure within 3 seconds");
481+
482+
final long pendingWhilePaused = pendingWhenUnwritable.get();
483+
assertTrue(pendingWhilePaused > 0);
484+
assertTrue(pendingWhilePaused < responseSize, "only a partial write is expected");
485+
486+
assertFalse(response.isDone(), "response is blocked while the client stream is not reading");
487+
488+
// Restarting reads on the client stream will, in turn, re-enable auto-read on the backend stream and complete
489+
// the response
490+
clientStream.get().config().setAutoRead(true);
491+
492+
assertArrayEquals(expectedBody(responseSize, (byte) 1), response.get(5, TimeUnit.SECONDS));
493+
494+
h2Connection.close().syncUninterruptibly();
495+
}
496+
420497
@ParameterizedTest
421498
@ValueSource(booleans = {true, false})
422499
void idleTest(final boolean localChannel) throws Exception {
@@ -469,12 +546,120 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
469546
assertEquals(OmnibusLoadShedHandler.LOAD_SHED_ERROR_CODE, frame.errorCode());
470547
}
471548

549+
/// This is a regression test for issues observed for responses >64 kiB (the HTTP/2 window size):
550+
/// - stalls, fixed by [netty/netty#17279](https://github.com/netty/netty/pull/17279)
551+
/// - response truncations, fixed by ensuring `setAutoRead()` always happens on the channel's event loop
552+
///
553+
/// In this test, concurrency refers to both a single connection with multiple streams and multiple connections with
554+
/// one more streams, as the issues occurred on both. The failures aren't totally deterministic, so tests
555+
/// are repeated.
556+
@CartesianTest(name = "localChannel={0}, connections={1}, streams={2}, size={3}")
557+
void concurrentResponses(
558+
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
559+
@CartesianTest.Values(ints = {1, 8}) final int connections,
560+
@CartesianTest.Values(ints = {1,2,4}) final int streamsPerConnection,
561+
// 64kiB is the critical threshold, as it's the flow control window size
562+
@CartesianTest.Values(ints = {8, 65, 256}) final int responseSizeKib,
563+
// @RepeatedTest can't be combined with @CartesianTest, and this needs a few runs to ensure the concurrency
564+
// conditions are met
565+
@CartesianTest.Values(ints = {10}) final int repetitions) throws Exception {
566+
567+
// Use two threads to make sure that our connections are working concurrently
568+
final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(2);
569+
final DefaultEventLoopGroup localEventLoopGroup = new DefaultEventLoopGroup(2);
570+
571+
groupsToShutDown.add(nioEventLoopGroup);
572+
groupsToShutDown.add(localEventLoopGroup);
573+
574+
final List<Channel> clientConnections = new ArrayList<>();
575+
576+
try {
577+
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
578+
579+
final OmnibusH2Server server = startOmnibusServer(nioEventLoopGroup, localEventLoopGroup,
580+
Collections.emptyMap(),
581+
startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup, localChannel,
582+
DEFAULT_BACKEND_IDENTITY, _ -> {}, _ -> {}),
583+
Duration.ofMinutes(1));
584+
585+
for (int i = 0; i < connections; i++) {
586+
clientConnections.add(connectToOmnibus(server));
587+
}
588+
589+
record RequestAndExpected(CompletableFuture<byte[]> request, byte[] expected) {}
590+
591+
for (int i = 0; i <= repetitions; i++) {
592+
593+
final List<RequestAndExpected> responseFutures = new ArrayList<>();
594+
clientConnections.forEach(c -> {
595+
for (int stream = 0; stream < streamsPerConnection; stream++) {
596+
final byte streamId = (byte) (stream + 1);
597+
responseFutures.add(new RequestAndExpected(request(c, responseSize, streamId, _ -> {}),
598+
expectedBody(responseSize, streamId)));
599+
}
600+
});
601+
602+
responseFutures.forEach(r -> {
603+
assertDoesNotThrow(() -> r.request().get(5, TimeUnit.SECONDS));
604+
assertArrayEquals(r.expected(), r.request().resultNow());
605+
});
606+
}
607+
} finally {
608+
clientConnections.forEach(c -> c.close().syncUninterruptibly());
609+
}
610+
}
611+
612+
/// Opens a stream asking the default backend for a `responseSize`-byte response body
613+
/// @return a future that yields the response body
614+
private CompletableFuture<byte[]> request(final Channel h2Connection, final int responseSize, final byte contentByte, final Consumer<Http2StreamChannel> streamInit) {
615+
616+
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
617+
618+
final BodyCollectorHandler collector = new BodyCollectorHandler(responseFuture);
619+
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
620+
.handler(new ChannelInitializer<Http2StreamChannel>() {
621+
@Override
622+
protected void initChannel(final Http2StreamChannel ch) {
623+
streamInit.accept(ch);
624+
ch.pipeline().addLast(collector);
625+
}
626+
})
627+
.open()
628+
.syncUninterruptibly()
629+
.getNow();
630+
631+
final Http2Headers headers = new DefaultHttp2Headers()
632+
.method("POST")
633+
.path(FIXED_RESPONSE_PATH_PREFIX + responseSize + "/" + contentByte)
634+
.scheme("https")
635+
.authority("localhost");
636+
637+
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, true));
638+
return responseFuture;
639+
}
640+
641+
/// A deterministic body of a given size
642+
private static byte[] expectedBody(final int size, final byte contentByte) {
643+
final byte[] body = new byte[size];
644+
Arrays.fill(body, contentByte);
645+
return body;
646+
}
647+
472648
/// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()]
473649
///
474650
/// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target
475651
/// @param defaultBackend The target backend if no prefix routes match the request path
476652
/// @param timeout The omnibus idle timeout
477653
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend, final Duration timeout) throws Exception {
654+
return startOmnibusServer(nioEventLoopGroup, localEventLoopGroup, routes, defaultBackend, timeout);
655+
}
656+
657+
private OmnibusH2Server startOmnibusServer(
658+
final NioEventLoopGroup nioEventLoopGroup,
659+
final DefaultEventLoopGroup localEventLoopGroup,
660+
final Map<String, Channel> routes,
661+
final Channel defaultBackend,
662+
final Duration timeout) throws Exception {
478663
backendChannelsToShutDown.addAll(routes.values());
479664
backendChannelsToShutDown.add(defaultBackend);
480665

@@ -509,7 +694,12 @@ private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, fi
509694
/// @param h2ChannelInit a Consumer that will be called every time a new HTTP/2 connection is made to this server
510695
/// @param h2StreamInit a Consumer that will be called every time a new HTTP/2 stream is created on this server
511696
private Channel startBackendServer(final boolean localChannel, final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
512-
final EventLoopGroup eventLoopGroup = localChannel ? localEventLoopGroup : nioEventLoopGroup;
697+
return startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup,
698+
localChannel, identity, h2ChannelInit, h2StreamInit);
699+
}
700+
701+
private Channel startBackendServer(final EventLoopGroup eventLoopGroup, final boolean localChannel,
702+
final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
513703
return new ServerBootstrap()
514704
.group(eventLoopGroup, eventLoopGroup)
515705
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
@@ -587,10 +777,10 @@ private static SslContext sslContext() {
587777
}
588778

589779
private String sendRequestThroughOmnibus(final Channel h2Connection, final String path) {
590-
final CompletableFuture<String> responseFuture = new CompletableFuture<>();
780+
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
591781
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
592782
final Http2StreamChannel stream = streamBootstrap
593-
.handler(new ResponseCollectorHandler(responseFuture))
783+
.handler(new BodyCollectorHandler(responseFuture))
594784
.open()
595785
.syncUninterruptibly()
596786
.getNow();
@@ -603,7 +793,7 @@ private String sendRequestThroughOmnibus(final Channel h2Connection, final Strin
603793

604794
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, true));
605795

606-
return responseFuture.join();
796+
return responseFuture.thenApply(OmnibusH2ServerTest::stringFromUtfBytes).join();
607797
}
608798

609799
/// A backend that either echos the request body, returns an identity, or disconnects based on the request
@@ -634,6 +824,10 @@ public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
634824
.map(CharSequence::toString)
635825
.orElse("");
636826
writeResponse(ctx, Unpooled.copiedBuffer(xForwardedFor, StandardCharsets.UTF_8));
827+
} else if (path.startsWith(FIXED_RESPONSE_PATH_PREFIX)) {
828+
final int size = Integer.parseInt(path.substring(FIXED_RESPONSE_PATH_PREFIX.length(), path.lastIndexOf("/")));
829+
final byte contentByte = Byte.parseByte(path.substring(path.lastIndexOf("/") + 1));
830+
writeResponse(ctx, Unpooled.wrappedBuffer(expectedBody(size, contentByte)));
637831
} else if (headers.isEndStream()) {
638832
writeResponse(ctx, Unpooled.copiedBuffer(identity, StandardCharsets.UTF_8));
639833
}
@@ -653,21 +847,43 @@ private void writeResponse(final ChannelHandlerContext ctx, final ByteBuf body)
653847
}
654848
}
655849

656-
/// Completes the provided future with the first [Http2DataFrame] received
657-
private static class ResponseCollectorHandler extends ChannelInboundHandlerAdapter {
850+
private static String stringFromUtfBytes(final byte[] bytes) {
851+
return new String(bytes, StandardCharsets.UTF_8);
852+
}
853+
854+
/// Accumulates all [Http2DataFrame]s on a stream and completes once the stream ends
855+
private static class BodyCollectorHandler extends ChannelInboundHandlerAdapter {
658856

659-
private final CompletableFuture<String> responseFuture;
857+
private final CompletableFuture<byte[]> responseFuture;
858+
private final ByteArrayOutputStream accumulated = new ByteArrayOutputStream();
660859

661-
ResponseCollectorHandler(final CompletableFuture<String> responseFuture) {
860+
BodyCollectorHandler(final CompletableFuture<byte[]> responseFuture) {
662861
this.responseFuture = responseFuture;
663862
}
664863

665864
@Override
666865
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
667-
if (msg instanceof Http2DataFrame dataFrame) {
668-
responseFuture.complete(dataFrame.content().toString(StandardCharsets.UTF_8));
866+
try {
867+
if (msg instanceof Http2DataFrame dataFrame) {
868+
final ByteBuf content = dataFrame.content();
869+
final byte[] chunk = new byte[content.readableBytes()];
870+
content.getBytes(content.readerIndex(), chunk);
871+
accumulated.writeBytes(chunk);
872+
if (dataFrame.isEndStream()) {
873+
responseFuture.complete(accumulated.toByteArray());
874+
}
875+
}
876+
} finally {
877+
ReferenceCountUtil.release(msg);
878+
}
879+
}
880+
881+
@Override
882+
public void channelInactive(final ChannelHandlerContext ctx) {
883+
if (!responseFuture.isDone()) {
884+
responseFuture.completeExceptionally(
885+
new IllegalStateException("stream closed after " + accumulated.size() + " bytes"));
669886
}
670-
ReferenceCountUtil.release(msg);
671887
}
672888

673889
@Override

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.