Add GrpcCompressionInterceptor

This commit is contained in:
Chris Eager authored and ravi-signal committed 2026-11-04 14:22:39 -06:00
1 parent f8e22ae674
commit 7af5bd4d2e
9 files changed
+475 -14

No files matched your search

@@ -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<WhisperServerConfiguration
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
final GrpcAllowListInterceptor grpcAllowListInterceptor = new GrpcAllowListInterceptor(dynamicConfigurationManager);
final GrpcCompressionInterceptor grpcCompressionInterceptor = new GrpcCompressionInterceptor(dynamicConfigurationManager);
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
@@ -1158,6 +1161,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
validatingInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcCompressionInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
@@ -1190,6 +1194,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
validatingInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcCompressionInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
@@ -1211,7 +1216,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.channelType(LocalServerChannel.class)
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment));
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment))
.addStreamTracerFactory(new MetricServerStreamTracer.Factory());
authenticatedServices.forEach(serverBuilder::addService);
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
@@ -77,6 +77,10 @@ public class DynamicConfiguration {
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@JsonProperty
@Valid
private DynamicGrpcCompressionConfiguration grpcCompression = new DynamicGrpcCompressionConfiguration();
@JsonProperty
@Valid
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
@@ -151,6 +155,10 @@ public class DynamicConfiguration {
return grpcAllowList;
}
public DynamicGrpcCompressionConfiguration getGrpcCompression() {
return grpcCompression;
}
public DynamicOmnibusConfiguration getOmnibus() {
return omnibus;
}
@@ -0,0 +1,35 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.Collections;
import java.util.Set;
/// Configure which gRPC methods may compress their responses
///
/// @param compressedServices A list of fully qualified service names for which all RPC responses should be compressed.
/// For example, `kt_query.KeyTransparencyQueryService` would compress responses for all RPCs
/// on that service.
/// @param compressedMethods A list of fully qualified method names of RPCs whose responses should be compressed. For
/// example, `kt_query.KeyTransparencyQueryService/Search` would compress responses for the
/// `Search` RPC method
public record DynamicGrpcCompressionConfiguration(
Set<String> compressedServices,
Set<String> 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());
}
}
@@ -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<DynamicConfiguration> dynamicConfigurationManager;
public GrpcCompressionInterceptor(
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
final DynamicGrpcCompressionConfiguration compressionConfiguration =
this.dynamicConfigurationManager.getConfiguration().getGrpcCompression();
final MethodDescriptor<ReqT, RespT> 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);
}
}
@@ -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<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private final Counter responseMessageCounter;
private final Counter responseBytesCounter;
private final Tags tags;
private @Nullable String reason = null;
MetricServerCall(final ServerCall<ReqT, RespT> 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);
@@ -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<MetricServerStreamTracer> 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<MetricServerStreamTracer> 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);
}
}
}
@@ -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<String> 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<String> compressedServices,
final Set<String> 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 <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method,
final CallOptions callOptions, final Channel next) {
return new ForwardingClientCall.SimpleForwardingClientCall<>(next.newCall(method, callOptions)) {
@Override
public void start(final Listener<RespT> 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);
}
};
}
}
}
@@ -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));
@@ -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<EchoRequest, EchoResponse> echoStream = client.echoStream();
final List<EchoRequest> requests = IntStream.range(0, 2)
.mapToObj(i -> EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8(String.valueOf(i))).build())
.toList();
final List<EchoResponse> 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();
}
}