From 7af5bd4d2e1c47f0241750ca6acd70258c2cac07 Mon Sep 17 00:00:00 2001 From: Chris Eager Date: Fri, 30 Oct 2026 15:03:43 -0400 Subject: [PATCH] Add GrpcCompressionInterceptor --- .../textsecuregcm/WhisperServerService.java | 8 +- .../dynamic/DynamicConfiguration.java | 8 + .../DynamicGrpcCompressionConfiguration.java | 35 ++++ .../grpc/GrpcCompressionInterceptor.java | 43 +++++ .../grpc/MetricServerInterceptor.java | 10 +- .../grpc/MetricServerStreamTracer.java | 55 ++++++ .../grpc/GrpcCompressionInterceptorTest.java | 173 ++++++++++++++++++ .../grpc/MetricServerInterceptorTest.java | 8 +- .../grpc/MetricServerStreamTracerTest.java | 149 +++++++++++++++ 9 files changed, 475 insertions(+), 14 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicGrpcCompressionConfiguration.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptor.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracer.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptorTest.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracerTest.java diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index f8b678e2c..f7858ce3c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -177,6 +177,7 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor; import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions; import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil; import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor; +import org.whispersystems.textsecuregcm.grpc.GrpcCompressionInterceptor; import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService; import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService; import org.whispersystems.textsecuregcm.grpc.KeysGrpcService; @@ -185,6 +186,7 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher; import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService; import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService; import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor; +import org.whispersystems.textsecuregcm.grpc.MetricServerStreamTracer; import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService; import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService; import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService; @@ -1102,6 +1104,7 @@ public class WhisperServerService extends Application compressedServices, + Set compressedMethods) { + + public DynamicGrpcCompressionConfiguration { + if (compressedServices == null) { + compressedServices = Collections.emptySet(); + } + if (compressedMethods == null) { + compressedMethods = Collections.emptySet(); + } + } + + public DynamicGrpcCompressionConfiguration() { + // By default, no gRPC responses are compressed + this(Collections.emptySet(), Collections.emptySet()); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptor.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptor.java new file mode 100644 index 000000000..b7f4d7e5c --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptor.java @@ -0,0 +1,43 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.grpc; + +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration; +import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; + +/// Requests gzip compression of responses for configured gRPC methods. Compression is only applied if the client +/// advertises gzip in its `grpc-accept-encoding` header; otherwise gRPC falls back to sending uncompressed responses. +public class GrpcCompressionInterceptor implements ServerInterceptor { + + private static final String GZIP = "gzip"; + + private final DynamicConfigurationManager dynamicConfigurationManager; + + public GrpcCompressionInterceptor( + final DynamicConfigurationManager dynamicConfigurationManager) { + this.dynamicConfigurationManager = dynamicConfigurationManager; + } + + @Override + public ServerCall.Listener interceptCall(final ServerCall serverCall, + final Metadata metadata, final ServerCallHandler next) { + final DynamicGrpcCompressionConfiguration compressionConfiguration = + this.dynamicConfigurationManager.getConfiguration().getGrpcCompression(); + final MethodDescriptor methodDescriptor = serverCall.getMethodDescriptor(); + if (compressionConfiguration.compressedServices().contains(methodDescriptor.getServiceName()) || + compressionConfiguration.compressedMethods().contains(methodDescriptor.getFullMethodName())) { + // This does not necessarily enable compression. The implementation will handle negotiation with the client + // and may fall back to no compression. + serverCall.setCompression(GZIP); + } + return next.startCall(serverCall, metadata); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptor.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptor.java index 82375001c..2105ee9cc 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptor.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptor.java @@ -59,6 +59,7 @@ public class MetricServerInterceptor implements ServerInterceptor { static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes"); @VisibleForTesting static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage"); + /// Response bytes as written to the wire (i.e. after compression), as reported by [MetricServerStreamTracer] @VisibleForTesting static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes"); @VisibleForTesting @@ -113,15 +114,16 @@ public class MetricServerInterceptor implements ServerInterceptor { private class MetricServerCall extends ForwardingServerCall.SimpleForwardingServerCall { private final Counter responseMessageCounter; - private final Counter responseBytesCounter; private final Tags tags; private @Nullable String reason = null; MetricServerCall(final ServerCall delegate, final Tags tags) { super(delegate); this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags); - this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags); this.tags = tags; + + MetricServerStreamTracer.current().ifPresent(tracer -> + tracer.setResponseBytesCounter(meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags))); } @Override @@ -143,10 +145,6 @@ public class MetricServerInterceptor implements ServerInterceptor { public void sendMessage(final RespT responseMessage) { this.responseMessageCounter.increment(); - if (responseMessage instanceof GeneratedMessage generatedMessage) { - this.responseBytesCounter.increment(generatedMessage.getSerializedSize()); - } - // Extract the annotated reason (if any) from the message final String messageReason = MetricServerCall.reason(responseMessage); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracer.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracer.java new file mode 100644 index 000000000..5b79de2da --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracer.java @@ -0,0 +1,55 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.grpc; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.ServerStreamTracer; +import io.micrometer.core.instrument.Counter; +import java.util.Optional; +import javax.annotation.Nullable; + +/// Records on-the-wire (i.e. possibly compressed) sizes of response messages. +/// +/// Stream tracers are created before the method being called has been resolved. The tracer makes itself available +/// via the call's [Context], and [MetricServerInterceptor] (which only runs for registered methods) supplies the +/// counter to increment; without it, nothing is recorded. +public class MetricServerStreamTracer extends ServerStreamTracer { + + private static final Context.Key CONTEXT_KEY = Context.key("metricServerStreamTracer"); + + @Nullable + private volatile Counter responseBytesCounter; + + public static class Factory extends ServerStreamTracer.Factory { + + @Override + public ServerStreamTracer newServerStreamTracer(final String fullMethodName, final Metadata headers) { + return new MetricServerStreamTracer(); + } + } + + /// @return the tracer for the current call, if a [Factory] is installed on the server + static Optional current() { + return Optional.ofNullable(CONTEXT_KEY.get()); + } + + void setResponseBytesCounter(final Counter responseBytesCounter) { + this.responseBytesCounter = responseBytesCounter; + } + + @Override + public Context filterContext(final Context context) { + return context.withValue(CONTEXT_KEY, this); + } + + @Override + public void outboundWireSize(final long bytes) { + final Counter counter = responseBytesCounter; + if (counter != null) { + counter.increment(bytes); + } + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptorTest.java new file mode 100644 index 000000000..e5192dfc1 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/GrpcCompressionInterceptorTest.java @@ -0,0 +1,173 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.Codec; +import io.grpc.DecompressorRegistry; +import io.grpc.ForwardingClientCall; +import io.grpc.ForwardingClientCallListener; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import java.io.IOException; +import java.util.Collections; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.signal.chat.rpc.EchoRequest; +import org.signal.chat.rpc.EchoResponse; +import org.signal.chat.rpc.EchoServiceGrpc; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration; +import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager; + +class GrpcCompressionInterceptorTest { + + private static final String SERVER_NAME = GrpcCompressionInterceptor.class.getSimpleName(); + + private static final Metadata.Key GRPC_ENCODING_KEY = + Metadata.Key.of("grpc-encoding", Metadata.ASCII_STRING_MARSHALLER); + + private static final EchoRequest REQUEST = EchoRequest.newBuilder() + .setPayload(ByteString.copyFromUtf8("compressible ".repeat(100))) + .build(); + + private Server server; + private ManagedChannel channel; + private final ResponseHeaderCapturingInterceptor responseHeaderCapturingInterceptor = + new ResponseHeaderCapturingInterceptor(); + + @AfterEach + void tearDown() throws Exception { + server.shutdownNow(); + channel.shutdownNow(); + server.awaitTermination(1, TimeUnit.SECONDS); + channel.awaitTermination(1, TimeUnit.SECONDS); + } + + @Test + void noCompressionByDefault() throws Exception { + final EchoServiceGrpc.EchoServiceBlockingStub client = + setup(Collections.emptySet(), Collections.emptySet(), DecompressorRegistry.getDefaultInstance()); + + assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity"); + } + + @Test + void compressByMethod() throws Exception { + final EchoServiceGrpc.EchoServiceBlockingStub client = + setup(Collections.emptySet(), Set.of("org.signal.chat.rpc.EchoService/echo"), + DecompressorRegistry.getDefaultInstance()); + + final EchoResponse echo = client.echo(REQUEST); + assertThat(echo.getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip"); + + final EchoResponse echo2 = client.echo2(REQUEST); + assertThat(echo2.getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity"); + } + + @Test + void compressByService() throws Exception { + final EchoServiceGrpc.EchoServiceBlockingStub client = + setup(Set.of("org.signal.chat.rpc.EchoService"), Collections.emptySet(), + DecompressorRegistry.getDefaultInstance()); + + final EchoResponse echo = client.echo(REQUEST); + assertThat(echo.getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip"); + + final EchoResponse echo2 = client.echo2(REQUEST); + assertThat(echo2.getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip"); + } + + @Test + void compressByServiceWrongService() throws Exception { + final EchoServiceGrpc.EchoServiceBlockingStub client = + setup(Set.of("org.signal.chat.rpc.NotEchoService"), Collections.emptySet(), + DecompressorRegistry.getDefaultInstance()); + + assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity"); + } + + @Test + void clientDoesNotAcceptGzip() throws Exception { + final EchoServiceGrpc.EchoServiceBlockingStub client = + setup(Set.of("org.signal.chat.rpc.EchoService"), Collections.emptySet(), + DecompressorRegistry.emptyInstance().with(Codec.Identity.NONE, true)); + + assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload()); + assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity"); + } + + private EchoServiceGrpc.EchoServiceBlockingStub setup( + final Set compressedServices, + final Set compressedMethods, + final DecompressorRegistry clientDecompressorRegistry) throws IOException { + + final DynamicConfiguration configuration = mock(DynamicConfiguration.class); + when(configuration.getGrpcCompression()) + .thenReturn(new DynamicGrpcCompressionConfiguration(compressedServices, compressedMethods)); + + server = InProcessServerBuilder.forName(SERVER_NAME) + .directExecutor() + .addService(new EchoServiceImpl()) + .intercept(new GrpcCompressionInterceptor(new FakeDynamicConfigurationManager<>(configuration))) + .build() + .start(); + + channel = InProcessChannelBuilder.forName(SERVER_NAME) + .directExecutor() + .decompressorRegistry(clientDecompressorRegistry) + .intercept(responseHeaderCapturingInterceptor) + .build(); + + return EchoServiceGrpc.newBlockingStub(channel); + } + + private static class ResponseHeaderCapturingInterceptor implements ClientInterceptor { + + @Nullable + private volatile String responseEncoding; + + @Override + public ClientCall interceptCall(final MethodDescriptor method, + final CallOptions callOptions, final Channel next) { + + return new ForwardingClientCall.SimpleForwardingClientCall<>(next.newCall(method, callOptions)) { + @Override + public void start(final Listener responseListener, final Metadata headers) { + responseEncoding = null; + + super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<>(responseListener) { + @Override + public void onHeaders(final Metadata responseHeaders) { + responseEncoding = responseHeaders.get(GRPC_ENCODING_KEY); + super.onHeaders(responseHeaders); + } + }, headers); + } + }; + } + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptorTest.java index d79dcbd69..9c75bcc83 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerInterceptorTest.java @@ -103,7 +103,7 @@ public class MetricServerInterceptorTest { void unary() { final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel); final EchoRequest request = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build(); - final EchoResponse response = client.echo(request); + client.echo(request); final Tags commonTags = Tags.of( "platform", "android", @@ -119,9 +119,6 @@ public class MetricServerInterceptorTest { final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME); assertThat(responseCount.count()).isCloseTo(1.0, offset(0.01)); - final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME); - assertThat(responseByteCount.count()).isCloseTo(response.getSerializedSize(), offset(0.01)); - final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME); assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01)); @@ -170,9 +167,6 @@ public class MetricServerInterceptorTest { final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME); assertThat(responseCount.count()).isCloseTo(responses.size(), offset(0.01)); - final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME); - assertThat(responseByteCount.count()).isCloseTo(responses.stream().mapToInt(EchoResponse::getSerializedSize).sum(), offset(0.01)); - final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME); assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01)); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracerTest.java new file mode 100644 index 000000000..9d3bccdef --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MetricServerStreamTracerTest.java @@ -0,0 +1,149 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.common.net.InetAddresses; +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.NettyServerBuilder; +import io.grpc.stub.BlockingClientCall; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Tag; +import io.micrometer.core.instrument.Tags; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.signal.chat.rpc.EchoRequest; +import org.signal.chat.rpc.EchoResponse; +import org.signal.chat.rpc.EchoServiceGrpc; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration; +import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; +import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager; + +class MetricServerStreamTracerTest { + + private static final String USER_AGENT = "Signal-Android/12.53.7 (Android 14.1; libsignal)"; + + private static final EchoRequest REQUEST = EchoRequest.newBuilder() + .setPayload(ByteString.copyFromUtf8("compressible ".repeat(100))) + .build(); + + private Server server; + private ManagedChannel channel; + private SimpleMeterRegistry simpleMeterRegistry; + + @BeforeEach + void setUp() throws Exception { + simpleMeterRegistry = new SimpleMeterRegistry(); + + final MockRequestAttributesInterceptor mockRequestAttributesInterceptor = new MockRequestAttributesInterceptor(); + mockRequestAttributesInterceptor.setRequestAttributes( + new RequestAttributes(InetAddresses.forString("127.0.0.1"), USER_AGENT, null)); + + // Only compress echo + final DynamicConfiguration configuration = mock(DynamicConfiguration.class); + when(configuration.getGrpcCompression()) + .thenReturn(new DynamicGrpcCompressionConfiguration(Set.of(), Set.of("org.signal.chat.rpc.EchoService/echo"))); + + // By default, the in-process transport doesn't report message sizes to stream tracers at all, and it never + // compresses messages; use a real transport instead + server = NettyServerBuilder.forPort(0) + .directExecutor() + .addService(new EchoServiceImpl()) + .addStreamTracerFactory(new MetricServerStreamTracer.Factory()) + .intercept(new GrpcCompressionInterceptor(new FakeDynamicConfigurationManager<>(configuration))) + .intercept(new MetricServerInterceptor(simpleMeterRegistry, mock(ClientReleaseManager.class))) + .intercept(mockRequestAttributesInterceptor) + .build() + .start(); + + channel = NettyChannelBuilder.forAddress("localhost", server.getPort()) + .directExecutor() + .usePlaintext() + .build(); + } + + @AfterEach + void tearDown() throws Exception { + server.shutdownNow(); + channel.shutdownNow(); + server.awaitTermination(1, TimeUnit.SECONDS); + channel.awaitTermination(1, TimeUnit.SECONDS); + } + + @Test + void uncompressed() { + final EchoResponse response = EchoServiceGrpc.newBlockingStub(channel).echo2(REQUEST); + + final Counter wireBytes = find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echo2"); + assertThat(wireBytes.count()).isCloseTo(response.getSerializedSize(), offset(0.01)); + } + + @Test + void streaming() throws Exception { + final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel); + final BlockingClientCall echoStream = client.echoStream(); + + final List requests = IntStream.range(0, 2) + .mapToObj(i -> EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8(String.valueOf(i))).build()) + .toList(); + + final List responses = new ArrayList<>(requests.size()); + + for (final EchoRequest request : requests) { + echoStream.write(request); + responses.add(echoStream.read()); + } + + echoStream.halfClose(); + + // Wait for the close to finish; metrics are reported after close + channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); + + final int expectedBytes = responses.stream().mapToInt(EchoResponse::getSerializedSize).sum(); + + assertThat(find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echoStream").count()) + .isCloseTo(expectedBytes, offset(0.01)); + } + + @Test + void compressed() { + final EchoResponse response = EchoServiceGrpc.newBlockingStub(channel).echo(REQUEST); + + final Counter wireBytes = find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echo"); + + assertThat(wireBytes.count()).isPositive().isLessThan(response.getSerializedSize()); + + // we expect >90% compression + assertThat(wireBytes.count() / response.getSerializedSize()).isLessThan(0.1); + + final Tags expectedTags = Tags.of( + "platform", "android", + "grpcService", "org.signal.chat.rpc.EchoService", + "method", "echo"); + + for (final Tag tag : expectedTags) { + assertThat(wireBytes.getId().getTag(tag.getKey())).isEqualTo(tag.getValue()); + } + } + + private Counter find(final String name, final String method) { + return simpleMeterRegistry.find(name).tag("method", method).counter(); + } +}