From fbb42763d910a77f679f31bce595bd486e8e4842 Mon Sep 17 00:00:00 2001 From: Ravi Khadiwala Date: Mon, 26 Oct 2026 13:35:12 -0500 Subject: [PATCH] Re-establish presence after finding it null --- .../FoundationDbMessagePublisher.java | 44 +++++++++---- .../MessageDispatcherIntegrationTest.java | 43 ++++++++++++- .../WebSocketConnectionIntegrationTest.java | 62 ++++++++++++++++++- 3 files changed, 136 insertions(+), 13 deletions(-) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java index ad8f4edee..84b40aa1a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java @@ -316,7 +316,22 @@ class FoundationDbMessagePublisher { // This is an unbounded publisher and we've established presence, so we should check for conflicts checkPresenceFuture = transaction.get(presenceKey) .thenAccept(presenceValue -> { + if (presenceValue == null) { + // We wrote a presence key earlier, but now it is gone. Two possibilities: + // 1. The queue was cleared by an account/device delete. We should eventually get a disconnection + // request so we should stay present until then. + // 2. Someone else connected, wrote their own presence key, and then disconnected (nulling the key), + // without us ever noticing an update to messagesAvailableWatchKey. Though we briefly did + // conflict, we're not conflicting any more so we can continue. + // In either case, we can try to re-establish our presence (unless we've already been disposed) + if (!isTerminated()) { + setPresence(transaction); + } + return; + } + if (isPresenceContested(presenceValue)) { + // Someone else established presence over us throw new CompletionException(new ConflictingMessageConsumerException()); } }); @@ -413,7 +428,7 @@ class FoundationDbMessagePublisher { private synchronized void setWatch(final Transaction transaction) { assert messagesAvailableWatchKey != null; - if (state == State.TERMINATED || state == State.ERROR) { + if (isTerminated()) { // If we're already in a terminal state, we don't want to set a watch that would leak return; } @@ -490,16 +505,20 @@ class FoundationDbMessagePublisher { } private synchronized CompletableFuture renewPresence() { - if (state == State.TERMINATED || state == State.ERROR) { + if (isTerminated()) { return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated")); } return database.runAsync(transaction -> { - transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId)); + setPresence(transaction); return CompletableFuture.completedFuture(null); }, FaultTolerantDatabase.Context.SET_PRESENCE); } + private void setPresence(final Transaction transaction) { + transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId)); + } + @VisibleForTesting synchronized void clearPresence() { if (renewPresenceFuture != null) { @@ -507,7 +526,10 @@ class FoundationDbMessagePublisher { renewPresenceFuture.whenComplete((_, _) -> database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> { - if (!isPresenceContested(presenceValue)) { + if (presenceValue == null || !isPresenceContested(presenceValue)) { + // Note: we still try to set the value to null even if it is already null. This way we would still + // cause a FoundationDB transaction conflict with a concurrent presence renewal that was updating + // from null to something else. transaction.clear(presenceKey); } }), FaultTolerantDatabase.Context.CLEAR_PRESENCE) @@ -519,19 +541,19 @@ class FoundationDbMessagePublisher { } } + /// @return true if a publisher other than us has claimed presence private boolean isPresenceContested(final byte[] presenceValue) { - if (presenceValue == null) { - // Some other process has cleared our presence key, so we must assume a conflict somewhere - return true; - } - return streamId != FoundationDbMessageStore.getPresenceStreamId(presenceValue) || !Arrays.equals(FoundationDbMessageStore.getPresenceServerId(presenceValue), FoundationDbMessageStore.getServerId()); } + private synchronized boolean isTerminated() { + return state == State.TERMINATED || state == State.ERROR; + } + @VisibleForTesting synchronized void terminateWithError(final Throwable throwable) { - if (state != State.TERMINATED && state != State.ERROR && !emitter.isCancelled()) { + if (!isTerminated() && !emitter.isCancelled()) { setState(State.ERROR, Event.INTERNAL_TRIGGER); emitter.error(throwable); } @@ -540,7 +562,7 @@ class FoundationDbMessagePublisher { private synchronized void onDispose() { // Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point // in evaluating the state machine when there's no live subscription. - if (state != State.TERMINATED && state != State.ERROR) { + if (!isTerminated()) { setState(State.TERMINATED, Event.INTERNAL_TRIGGER); } cancelWatch(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java index 67f4e0e42..5ee17945e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java @@ -12,6 +12,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import io.grpc.Status; import java.io.IOException; import java.security.SecureRandom; import java.time.Clock; @@ -36,6 +37,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -52,6 +54,7 @@ import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.push.PushNotificationManager; import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; import org.whispersystems.textsecuregcm.push.ReceiptSender; +import org.whispersystems.textsecuregcm.redis.RedisServerExtension; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; import org.whispersystems.textsecuregcm.storage.Device; @@ -69,6 +72,7 @@ import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; @Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) @@ -80,6 +84,9 @@ class MessageDispatcherIntegrationTest { @RegisterExtension static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1); + @RegisterExtension + static final RedisServerExtension REDIS_EXTENSION = RedisServerExtension.builder().build(); + private static ExecutorService sharedExecutorService; private static ScheduledExecutorService sharedScheduledExecutorService; private static Scheduler messageDeliveryScheduler; @@ -89,6 +96,7 @@ class MessageDispatcherIntegrationTest { private Account account; private Device device; private MessageDispatcher messageDispatcher; + private DisconnectionRequestManager disconnectionRequestManager; private long serialTimestamp = System.currentTimeMillis(); @@ -131,6 +139,11 @@ class MessageDispatcherIntegrationTest { when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(device.getId()).thenReturn(Device.PRIMARY_ID); + disconnectionRequestManager = new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(), + Runnable::run, + mock(ScheduledExecutorService.class)); + disconnectionRequestManager.start(); + messageDispatcher = new MessageDispatcher( mock(ReceiptSender.class), new MessagesManager(messagesDynamoDb, foundationDbMessageStore, @@ -139,10 +152,15 @@ class MessageDispatcherIntegrationTest { new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class), - mock(DisconnectionRequestManager.class), + disconnectionRequestManager, mock(ClientReleaseManager.class)); } + @AfterEach + void tearDown() { + disconnectionRequestManager.stop(); + } + @AfterAll static void afterAll() throws InterruptedException { sharedExecutorService.shutdown(); @@ -229,6 +247,29 @@ class MessageDispatcherIntegrationTest { assertTrue(expectedMessages.containsAll(receivedMessages)); } + @Test + void testAccountDeletedWhileConnected() { + final AciServiceIdentifier aci = new AciServiceIdentifier(account.getAccountIdentifier()); + final Envelope envelope = generateRandomMessage(UUID.randomUUID()).toBuilder().clearServerGuid().build(); + final Sinks.Many acks = Sinks.many().unicast().onBackpressureBuffer(); + + StepVerifier.create(messageDispatcher.getMessages(true, null, account, device, acks.asFlux())) + .expectNextMatches(GetMessagesResponse::hasQueueEmpty) + // Clearing deletes the watch key, which wakes our stream only if the key exists. Make sure we have written a + // watch key by sending a message while we're present to make the interaction with clear more interesting. + .then(() -> foundationDbMessageStore.insert(aci, Map.of(device.getId(), envelope)).join()) + .expectNextMatches(GetMessagesResponse::hasEnvelope) + // Emulate an account delete + .then(() -> foundationDbMessageStore.clearAll(aci)) + // Increase the chance that the stream observes the effects of the clear before the disconnection + .thenAwait(Duration.ofMillis(1)) + .then(() -> disconnectionRequestManager.requestDisconnection(aci.uuid(), List.of(device.getId())) + .toCompletableFuture().join()) + .expectErrorSatisfies(throwable -> + assertEquals(Status.Code.UNAUTHENTICATED, Status.fromThrowable(throwable).getCode())) + .verify(Duration.ofSeconds(5)); + } + private List fillRandomMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) { final List expectedMessages = new ArrayList<>(dynamoDbMessageCount + foundationDbMessageCount); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java index a4543d821..e5f928a2e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java @@ -11,6 +11,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; @@ -52,6 +53,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentCaptor; +import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration; import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration; import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; @@ -63,7 +65,7 @@ import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.push.PushNotificationManager; import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; import org.whispersystems.textsecuregcm.push.ReceiptSender; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; +import org.whispersystems.textsecuregcm.redis.RedisServerExtension; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; import org.whispersystems.textsecuregcm.storage.Device; @@ -99,6 +101,9 @@ class WebSocketConnectionIntegrationTest { FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1, new CircuitBreakerConfiguration(), bulkheadConfiguration); } + @RegisterExtension + static final RedisServerExtension REDIS_EXTENSION = RedisServerExtension.builder().build(); + private ExecutorService sharedExecutorService; private FoundationDbMessageStore foundationDbMessageStore; private MessagesDynamoDb messagesDynamoDb; @@ -108,6 +113,7 @@ class WebSocketConnectionIntegrationTest { private WebSocketClient webSocketClient; private Scheduler messageDeliveryScheduler; private ClientReleaseManager clientReleaseManager; + private DisconnectionRequestManager disconnectionRequestManager; private long serialTimestamp = System.currentTimeMillis(); @@ -154,10 +160,16 @@ class WebSocketConnectionIntegrationTest { when(account.getNumber()).thenReturn(Optional.of("+18005551234")); when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(device.getId()).thenReturn(Device.PRIMARY_ID); + + disconnectionRequestManager = new DisconnectionRequestManager(REDIS_EXTENSION.getRedisClient(), + Runnable::run, + mock(ScheduledExecutorService.class)); + disconnectionRequestManager.start(); } @AfterEach void tearDown() throws Exception { + disconnectionRequestManager.stop(); sharedExecutorService.shutdown(); final Mono schedulerShutdownMono = messageDeliveryScheduler.disposeGracefully(); @@ -468,6 +480,54 @@ class WebSocketConnectionIntegrationTest { }); } + @Test + void testAccountDeletedWhileConnected() { + final MessagesManager messagesManager = + new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()); + + disconnectionRequestManager.addListener(account.getAccountIdentifier(), device.getId(), + new WebSocketDisconnectionRequestListener(new MessageMetrics(), webSocketClient, false)); + + final WebSocketConnection webSocketConnection = new WebSocketConnection( + mock(ReceiptSender.class), + messagesManager, + new MessageMetrics(), + mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), + account, + device, + webSocketClient, + messageDeliveryScheduler, + clientReleaseManager, + mock(ExperimentEnrollmentManager.class)); + + final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class); + when(successResponse.getStatus()).thenReturn(200); + when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any())) + .thenReturn(CompletableFuture.completedFuture(successResponse)); + + webSocketConnection.start(); + + verify(webSocketClient, timeout(Duration.ofSeconds(5).toMillis())) + .sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty())); + + // Clearing deletes the watch key, which wakes our stream only if the key exists. Make sure we have written a watch + // key by sending a message while we're present to make the interaction with clear more interesting. + foundationDbMessageStore.insert(new AciServiceIdentifier(account.getAccountIdentifier()), + Map.of(device.getId(), generateRandomMessage(UUID.randomUUID()).toBuilder().clearServerGuid().build())) + .join(); + verify(webSocketClient, timeout(Duration.ofSeconds(5).toMillis())) + .sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any()); + + // Emulates an account delete + messagesManager.clear(account.getAccountIdentifier()).join(); + disconnectionRequestManager.requestDisconnection(account.getAccountIdentifier(), List.of(device.getId())) + .toCompletableFuture().join(); + + verify(webSocketClient, timeout(Duration.ofSeconds(5).toMillis())).close(eq(4401), anyString()); + verify(webSocketClient, never()).close(eq(4409), anyString()); + } + private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid) { final long timestamp = serialTimestamp++;