Throttle requests when a client has a suspected delivery loop

This commit is contained in:
Jon Chambers authored and GitHub committed 2026-11-18 15:49:11 -05:00
1 parent 5de899da4b
commit 9dfbb454d1
9 files changed
+116 -32

No files matched your search

@@ -8,10 +8,10 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.GetMessagesStreamClosed;
@@ -48,7 +48,8 @@ public class MessageDispatcher {
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
@VisibleForTesting
static final int MAX_UNACKED_MESSAGES = 256;
static final int DEFAULT_MAX_UNACKED_MESSAGES = 256;
@VisibleForTesting
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
@@ -133,10 +134,21 @@ public class MessageDispatcher {
pushNotificationManager.handleMessagesRetrieved(account, device, userAgentString);
final Flux<GetMessagesResponse> messages = JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
final AtomicInteger maxUnacknowledgedMessages = new AtomicInteger(DEFAULT_MAX_UNACKED_MESSAGES);
final Flux<GetMessagesResponse> messages = Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(account.getAccountIdentifier(), device.getId()))
.flatMapMany(hasSuspectedDeliveryLoop -> {
if (hasSuspectedDeliveryLoop) {
maxUnacknowledgedMessages.set(1);
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.GRPC_CHANNEL, userAgent, clientReleaseManager);
}
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(maxUnacknowledgedMessages.get());
})
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
@@ -156,7 +168,7 @@ public class MessageDispatcher {
pendingAcknowledgementTracker.markEndOfQueue();
yield Mono.empty();
}
}, MAX_UNACKED_MESSAGES)
}, maxUnacknowledgedMessages.get())
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
return CONFLICTING_STREAM_EXCEPTION;
@@ -165,7 +177,7 @@ public class MessageDispatcher {
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
// after that a permit is emitted every time we receive an ack.
final Sinks.Many<Boolean> ackPermits = Sinks.many().unicast().onBackpressureBuffer();
final Flux<Boolean> permits = Flux.range(0, MAX_UNACKED_MESSAGES)
final Flux<Boolean> permits = Flux.range(0, maxUnacknowledgedMessages.get())
.map(_ -> true)
.concatWith(ackPermits.asFlux());
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
@@ -185,7 +197,7 @@ public class MessageDispatcher {
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
// Just have to emit some value that indicates we can release a permit
.thenReturn(true);
}, MAX_UNACKED_MESSAGES)
}, maxUnacknowledgedMessages.get())
.doOnNext(_ -> ackPermits.tryEmitNext(true))
.ignoreElements()
.cast(GetMessagesResponse.class);
@@ -51,6 +51,8 @@ public final class MessageMetrics {
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
private static final String SUSPECTED_DELIVERY_LOOP_COUNTER_NAME = name(MessageMetrics.class, "suspectedDeliveryLoop");
private final MeterRegistry metricRegistry;
private final Counter sendMessageCounter;
private final Counter bytesSentCounter;
@@ -145,4 +147,16 @@ public final class MessageMetrics {
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
.register(metricRegistry));
}
public static void recordSuspectedDeliveryLoop(final String channel,
@Nullable final UserAgent userAgent,
final ClientReleaseManager clientReleaseManager) {
final Tags tags = UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
.map(Tags::of)
.orElseGet(Tags::empty)
.and(UserAgentTagUtil.getPlatformTag(userAgent));
Metrics.counter(SUSPECTED_DELIVERY_LOOP_COUNTER_NAME, tags).increment();
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
import com.apple.foundationdb.FDBException;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.Instant;
@@ -40,6 +41,9 @@ public class MessagesManager {
private final ExecutorService messageDeletionExecutor;
private final Clock clock;
@VisibleForTesting
static final long DELIVERY_LOOP_READ_THRESHOLD = 10;
public MessagesManager(
final MessagesDynamoDb messagesDynamoDb,
final FoundationDbMessageStore foundationDbMessageStore,
@@ -223,6 +227,19 @@ public class MessagesManager {
.toFuture();
}
/// Checks whether the given device is in a suspected "delivery loop" where it is repeatedly requesting but not
/// acknowledging messages.
///
/// @param accountIdentifier the identifier of the account to check for a delivery loop
/// @param deviceId the ID of the device to check for a delivery loop
///
/// @return a future that yields `true` if the identified device is suspected of being stuck in a message delivery
/// loop or `false` otherwise
public CompletableFuture<Boolean> hasSuspectedDeliveryLoop(final UUID accountIdentifier, final byte deviceId) {
return foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(new AciServiceIdentifier(accountIdentifier), deviceId)
.thenApply(readsSinceLastAcknowledgedMessage -> readsSinceLastAcknowledgedMessage >= DELIVERY_LOOP_READ_THRESHOLD);
}
/// Record versionstamps for the current time in the FoundationDB database(s).
public void recordFoundationDbVersionstamps() {
foundationDbMessageStore.recordVersionstamps();
@@ -807,8 +807,7 @@ public class FoundationDbMessageStore {
///
/// @return the number of times a subscriber has started reading messages from the identified message queue since the
/// last time any message in the queue was acknowledged
@VisibleForTesting
CompletableFuture<Long> getReadsSinceLastAcknowledgedMessage(final AciServiceIdentifier aci, final byte deviceId) {
public CompletableFuture<Long> getReadsSinceLastAcknowledgedMessage(final AciServiceIdentifier aci, final byte deviceId) {
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
transaction.get(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId)), FaultTolerantDatabase.Context.TEST)))
@@ -19,6 +19,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
@@ -141,10 +142,21 @@ public class WebSocketConnection {
final Timer.Sample queueDrainStart = Timer.start();
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
final AtomicInteger maxConcurrency = new AtomicInteger(MESSAGE_SENDER_MAX_CONCURRENCY);
messageSubscription.set(Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(authenticatedAccount.getAccountIdentifier(), authenticatedDevice.getId()))
.flatMapMany(hasSuspectedDeliveryLoop -> {
if (hasSuspectedDeliveryLoop) {
maxConcurrency.set(1);
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, clientReleaseManager);
}
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(maxConcurrency.get());
})
// We want to handle conflicting connections as soon as possible, and so do this before we start processing
// messages in the `flatMapSequential` stage below. If we didn't do this first, then we'd wait for clients to
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
@@ -156,7 +168,7 @@ public class WebSocketConnection {
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope envelope -> Mono.fromFuture(() -> sendMessage(envelope.message())).thenReturn(entry);
case MessageStreamEntry.QueueEmpty _ -> Mono.just(entry);
}, MESSAGE_SENDER_MAX_CONCURRENCY)
}, maxConcurrency.get())
.subscribeOn(messageDeliveryScheduler)
.subscribe(
entry -> {
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -94,6 +95,9 @@ class MessageDispatcherTest {
when(device.getId()).thenReturn(DEVICE_ID);
when(device.isPrimary()).thenReturn(true);
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
.thenReturn(CompletableFuture.completedFuture(false));
dispatcher = new MessageDispatcher(
receiptSender,
messagesManager,
@@ -140,7 +144,7 @@ class MessageDispatcherTest {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
final List<UUID> guids = messages.stream().map(Envelope::getServerGuid).map(UUIDUtil::fromByteString).toList();
@@ -158,18 +162,18 @@ class MessageDispatcherTest {
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
StepVerifier.create(responses)
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
// Sending an ack should allow another message to come back
.then(() -> acks.next(guids.get(0)))
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES))
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES))
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(0), timestamps.get(0)))
.expectNoEvent(Duration.ofMillis(1))
// Send another one
.then(() -> acks.next(guids.get(1)))
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES + 1))
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 1))
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(1), timestamps.get(1)))
.expectNoEvent(Duration.ofMillis(1))
@@ -187,7 +191,7 @@ class MessageDispatcherTest {
void maxOutstandingAllowsGaps() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final int totalMessages = MessageDispatcher.MAX_UNACKED_MESSAGES * 2;
final int totalMessages = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES * 2;
final List<Envelope> messages = IntStream
.range(0, totalMessages)
@@ -208,22 +212,22 @@ class MessageDispatcherTest {
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
StepVerifier.create(responses)
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> {
for (int i = 0; i < MessageDispatcher.MAX_UNACKED_MESSAGES; i++) {
for (int i = 0; i < MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i++) {
if (i != 2) {
acks.next(ackRequests.get(i));
}
}
})
.expectNext(expectedMessages.subList(MessageDispatcher.MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
.expectNext(expectedMessages.subList(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> acks.next(ackRequests.get(2)))
.expectNext(expectedMessages.get(totalMessages - 1))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> {
for (int i = MessageDispatcher.MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
for (int i = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
acks.next(ackRequests.get(i));
}
})
@@ -236,7 +240,7 @@ class MessageDispatcherTest {
void duplicateAckIgnored() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
@@ -249,7 +253,7 @@ class MessageDispatcherTest {
StepVerifier
.create(dispatcher.getMessages(true, TEST_UA, account, device, acks.flux()))
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
.expectNoEvent(Duration.ofMillis(1))
// Ack a message, we should then get a new message
@@ -312,7 +316,7 @@ class MessageDispatcherTest {
void conflictingConsumerWhileWaitingForAcks() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<MessageStreamEntry.Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.map(MessageStreamEntry.Envelope::new)
.toList();
@@ -323,7 +327,7 @@ class MessageDispatcherTest {
StepVerifier
.create(dispatcher.getMessages(true, TEST_UA, account, device, Flux.never()))
.then(() -> messages.forEach(source::next))
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
.expectNoEvent(Duration.ofMillis(1))
// The error should make it to us immediately even though there are max-unacked messages outstanding
.then(() -> source.error(new ConflictingMessageConsumerException()))
@@ -34,8 +34,10 @@ import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
@@ -297,4 +299,25 @@ class MessagesManagerTest {
messagesManager.getEarliestUndeliveredTimestampForDevice(accountIdentifier, device).join();
assertEquals(Optional.ofNullable(expected).map(Instant::ofEpochMilli), earliest);
}
@ParameterizedTest
@MethodSource
void hasSuspectedDeliveryLoop(final long readsSinceLastAcknowledgedMessage, final boolean expectSuspectedLoop) {
final AciServiceIdentifier aciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = Device.PRIMARY_ID;
when(foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aciServiceIdentifier, deviceId))
.thenReturn(CompletableFuture.completedFuture(readsSinceLastAcknowledgedMessage));
assertEquals(expectSuspectedLoop,
messagesManager.hasSuspectedDeliveryLoop(aciServiceIdentifier.uuid(), deviceId).join());
}
private static List<Arguments> hasSuspectedDeliveryLoop() {
return List.of(
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD - 1, false),
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD, true),
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD + 1, true)
);
}
}
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -50,7 +51,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -102,6 +102,7 @@ class AuthenticatedConnectListenerIntegrationTest {
void setUp() throws Exception {
reset(messagesManager, disconnectionRequestManager, accountsManager, account, device);
when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false));
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(false));
when(account.getNumber()).thenReturn(Optional.of(E164));
when(account.getAccountIdentifier()).thenReturn(ACCOUNT_UUID);
when(account.getDevice(DEVICE_ID)).thenReturn(Optional.of(device));
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.websocket;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
@@ -43,9 +44,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InOrder;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
@@ -98,6 +97,9 @@ class WebSocketConnectionTest {
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
clientReleaseManager = mock(ClientReleaseManager.class);
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
.thenReturn(CompletableFuture.completedFuture(false));
ON_ERROR_DROPPED_COUNTER.set(0);
}