mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:06:50 +00:00
Use a virtual thread executor for gRPC service callbacks
This commit is contained in:
1 parent
3f7012dba4
commit
eaa5b96079
4 files changed
+290
-3
No files matched your search
@@ -170,6 +170,7 @@ import org.whispersystems.textsecuregcm.grpc.CredentialsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.DevicesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.DonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorConformanceInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ConcurrentCallLimitingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
|
||||
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
|
||||
@@ -1101,6 +1102,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
|
||||
|
||||
final ConcurrentCallLimitingInterceptor concurrentCallLimitingInterceptor =
|
||||
new ConcurrentCallLimitingInterceptor(config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor());
|
||||
|
||||
final ExternalRequestFilter grpcExternalRequestFilter = new ExternalRequestFilter(
|
||||
config.getExternalRequestFilterConfiguration().permittedInternalRanges(),
|
||||
config.getExternalRequestFilterConfiguration().grpcMethods());
|
||||
@@ -1157,7 +1161,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
requestAttributesInterceptor,
|
||||
requireAuthenticationInterceptor))
|
||||
requireAuthenticationInterceptor,
|
||||
concurrentCallLimitingInterceptor))
|
||||
.toList();
|
||||
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
|
||||
@@ -1185,7 +1190,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
requestAttributesInterceptor,
|
||||
prohibitAuthenticationInterceptor))
|
||||
prohibitAuthenticationInterceptor,
|
||||
concurrentCallLimitingInterceptor))
|
||||
.toList();
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
@@ -1195,7 +1201,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.forAddress(grpcLocalAddress)
|
||||
.channelType(LocalServerChannel.class)
|
||||
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup());
|
||||
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment));
|
||||
authenticatedServices.forEach(serverBuilder::addService);
|
||||
unauthenticatedServices.forEach(serverBuilder::addService);
|
||||
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.grpc.ForwardingServerCallListener;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
/// Limits the number of concurrent gRPC calls. Returns `io.grpc.Status.UNAVAILABLE` if the limit is exceeded. This
|
||||
/// interceptor is meant to be used alongside a virtual thread executor. Unfortunately, we can't re-use
|
||||
/// [org.whispersystems.textsecuregcm.util.BoundedVirtualThreadFactory] directly because the gRPC stack does not
|
||||
/// gracefully handle [java.util.concurrent.RejectedExecutionException]s (see
|
||||
/// [issue](https://github.com/grpc/grpc-java/issues/636))
|
||||
public class ConcurrentCallLimitingInterceptor implements ServerInterceptor {
|
||||
|
||||
private final int maxConcurrentCalls;
|
||||
|
||||
private final AtomicInteger concurrentCalls = new AtomicInteger(0);
|
||||
private final Counter rejectedCallCounter;
|
||||
|
||||
public ConcurrentCallLimitingInterceptor(final int maxConcurrentCalls) {
|
||||
this.maxConcurrentCalls = maxConcurrentCalls;
|
||||
|
||||
Metrics.gauge(MetricsUtil.name(ConcurrentCallLimitingInterceptor.class, "active"),
|
||||
concurrentCalls, AtomicInteger::doubleValue);
|
||||
this.rejectedCallCounter =
|
||||
Metrics.counter(MetricsUtil.name(ConcurrentCallLimitingInterceptor.class, "rejected"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
|
||||
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
|
||||
|
||||
if (concurrentCalls.incrementAndGet() > maxConcurrentCalls) {
|
||||
concurrentCalls.decrementAndGet();
|
||||
rejectedCallCounter.increment();
|
||||
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.unavailable());
|
||||
}
|
||||
|
||||
try {
|
||||
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(next.startCall(call, headers)) {
|
||||
@Override
|
||||
public void onComplete() {
|
||||
concurrentCalls.decrementAndGet();
|
||||
super.onComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
concurrentCalls.decrementAndGet();
|
||||
super.onCancel();
|
||||
}
|
||||
};
|
||||
} catch (final Exception e) {
|
||||
concurrentCalls.decrementAndGet();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int getActiveCalls() {
|
||||
return concurrentCalls.get();
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
/**
|
||||
* Build Executor Services managed by dropwizard, supplementing executors provided by
|
||||
@@ -32,6 +33,21 @@ public class ManagedExecutors {
|
||||
|
||||
final BoundedVirtualThreadFactory threadFactory =
|
||||
new BoundedVirtualThreadFactory(threadNamePrefix, maxConcurrentThreads);
|
||||
return newVirtualThreadPerTaskExecutor(threadNamePrefix, threadFactory, environment);
|
||||
}
|
||||
|
||||
public static ExecutorService newVirtualThreadPerTaskExecutor(
|
||||
final String threadNamePrefix,
|
||||
final Environment environment) {
|
||||
|
||||
final ThreadFactory threadFactory = Thread.ofVirtual().name(threadNamePrefix + "-", 0).factory();
|
||||
return newVirtualThreadPerTaskExecutor(threadNamePrefix, threadFactory, environment);
|
||||
}
|
||||
|
||||
private static ExecutorService newVirtualThreadPerTaskExecutor(
|
||||
final String threadNamePrefix,
|
||||
final ThreadFactory threadFactory,
|
||||
final Environment environment) {
|
||||
final ExecutorService virtualThreadExecutor = Executors.newThreadPerTaskExecutor(threadFactory);
|
||||
environment.lifecycle()
|
||||
.manage(new ExecutorServiceManager(virtualThreadExecutor, SHUTDOWN_DURATION, threadNamePrefix));
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* 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.Fail.fail;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Context;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
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;
|
||||
|
||||
class ConcurrentCallLimitingInterceptorTest {
|
||||
|
||||
private static final String SERVER_NAME = "ConcurrentCallLimitingInterceptorTest";
|
||||
private Server server;
|
||||
private ManagedChannel channel;
|
||||
|
||||
private static final int MAX_CONCURRENT_CALLS = 10;
|
||||
private final CountDownLatch handlerStarted = new CountDownLatch(MAX_CONCURRENT_CALLS);
|
||||
private final CountDownLatch handlerReleased = new CountDownLatch(1);
|
||||
|
||||
private final class BlockingEchoService extends EchoServiceGrpc.EchoServiceImplBase {
|
||||
|
||||
@Override
|
||||
public void echo(final EchoRequest request, final StreamObserver<EchoResponse> responseObserver) {
|
||||
handlerStarted.countDown();
|
||||
try {
|
||||
handlerReleased.await();
|
||||
} catch (final InterruptedException e) {
|
||||
fail(e);
|
||||
}
|
||||
responseObserver.onNext(EchoResponse.newBuilder().setPayload(request.getPayload()).build());
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
handlerReleased.countDown();
|
||||
server.shutdownNow();
|
||||
channel.shutdownNow();
|
||||
server.awaitTermination(1, TimeUnit.SECONDS);
|
||||
channel.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxConcurrentCallsReached() throws Exception {
|
||||
final ConcurrentCallLimitingInterceptor interceptor = new ConcurrentCallLimitingInterceptor(MAX_CONCURRENT_CALLS);
|
||||
server = InProcessServerBuilder.forName(SERVER_NAME)
|
||||
.addService(new BlockingEchoService())
|
||||
.intercept(interceptor)
|
||||
.build()
|
||||
.start();
|
||||
channel = InProcessChannelBuilder.forName(SERVER_NAME).build();
|
||||
final ByteString payload = ByteString.copyFromUtf8("payload");
|
||||
|
||||
final EchoRequest request = EchoRequest.newBuilder().setPayload(payload).build();
|
||||
|
||||
// Initiate MAX_CONCURRENT_CALLS (non-blocking) calls that will wait until we signal them to finish
|
||||
final List<CompletableFuture<EchoResponse>> responses = IntStream.range(0, MAX_CONCURRENT_CALLS)
|
||||
.mapToObj(_ -> {
|
||||
final CompletableFuture<EchoResponse> responseFuture = new CompletableFuture<>();
|
||||
EchoServiceGrpc.newStub(channel).echo(request, new StreamObserver<>() {
|
||||
@Override
|
||||
public void onNext(final EchoResponse value) {
|
||||
responseFuture.complete(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final Throwable t) {
|
||||
responseFuture.completeExceptionally(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCompleted() {
|
||||
}
|
||||
});
|
||||
return responseFuture;
|
||||
})
|
||||
.toList();
|
||||
|
||||
assertThat(handlerStarted.await(1, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(interceptor.getActiveCalls()).isEqualTo(MAX_CONCURRENT_CALLS);
|
||||
|
||||
// Finally, issue a blocking call that should fail because all slots are occupied
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub blockingStub =
|
||||
EchoServiceGrpc.newBlockingStub(channel).withDeadlineAfter(1, TimeUnit.SECONDS);
|
||||
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE, () -> blockingStub.echo(request));
|
||||
|
||||
handlerReleased.countDown();
|
||||
// Verify that the other requests completed normally
|
||||
CompletableFuture.allOf(responses.toArray(new CompletableFuture[responses.size()])).get(1, TimeUnit.SECONDS);
|
||||
responses.forEach(response -> assertThat(response.join().getPayload()).isEqualTo(payload));
|
||||
}
|
||||
|
||||
@Test
|
||||
void releasesSlotWhenHandlerThrows() throws Exception {
|
||||
final ConcurrentCallLimitingInterceptor interceptor = new ConcurrentCallLimitingInterceptor(1);
|
||||
|
||||
server = InProcessServerBuilder.forName(SERVER_NAME)
|
||||
.addService(new EchoServiceGrpc.EchoServiceImplBase() {
|
||||
@Override
|
||||
public void echo(final EchoRequest request, final StreamObserver<EchoResponse> responseObserver) {
|
||||
throw new RuntimeException("handler failed!");
|
||||
}
|
||||
})
|
||||
.intercept(interceptor)
|
||||
.build()
|
||||
.start();
|
||||
channel = InProcessChannelBuilder.forName(SERVER_NAME).build();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub blockingStub = EchoServiceGrpc.newBlockingStub(channel);
|
||||
GrpcTestUtils.assertStatusException(Status.UNKNOWN, () -> blockingStub.echo(EchoRequest.newBuilder().build()));
|
||||
|
||||
// the gRPC response can arrive before onComplete() because it is called asynchronously, so poll until there are no active calls.
|
||||
final Instant deadline = Clock.systemUTC().instant().plusSeconds(1);
|
||||
while (interceptor.getActiveCalls() > 0 && Clock.systemUTC().instant().isBefore(deadline)) {
|
||||
Thread.sleep(Duration.ofMillis(10));
|
||||
}
|
||||
assertThat(interceptor.getActiveCalls()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void releasesSlotWhenCallCancelled() throws Exception {
|
||||
final ConcurrentCallLimitingInterceptor interceptor = new ConcurrentCallLimitingInterceptor(1);
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
|
||||
server = InProcessServerBuilder.forName(SERVER_NAME)
|
||||
.addService(new EchoServiceGrpc.EchoServiceImplBase() {
|
||||
@Override
|
||||
public void echo(final EchoRequest request, final StreamObserver<EchoResponse> responseObserver) {
|
||||
// Never complete the response; the call stays in-flight until the client cancels.
|
||||
latch.countDown();
|
||||
}
|
||||
})
|
||||
.intercept(interceptor)
|
||||
.build()
|
||||
.start();
|
||||
channel = InProcessChannelBuilder.forName(SERVER_NAME).build();
|
||||
|
||||
//noinspection resource
|
||||
final Context.CancellableContext cancellableContext = Context.current().withCancellation();
|
||||
cancellableContext.run(() -> EchoServiceGrpc.newStub(channel).echo(EchoRequest.newBuilder().build(),
|
||||
new StreamObserver<>() {
|
||||
@Override
|
||||
public void onNext(final EchoResponse value) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final Throwable t) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCompleted() {
|
||||
}
|
||||
}));
|
||||
|
||||
assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(interceptor.getActiveCalls()).isEqualTo(1);
|
||||
|
||||
assertThat(cancellableContext.cancel(new RuntimeException("client cancelled"))).isTrue();
|
||||
|
||||
// the gRPC response can arrive before onComplete() because it is called asynchronously, so poll until there are no active calls.
|
||||
final Instant deadline = Clock.systemUTC().instant().plusSeconds(1);
|
||||
while (interceptor.getActiveCalls() > 0 && Clock.systemUTC().instant().isBefore(deadline)) {
|
||||
Thread.sleep(Duration.ofMillis(10));
|
||||
}
|
||||
assertThat(interceptor.getActiveCalls()).isZero();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user