From 9c5170d47cf41d9771d549324d20e438aa756982 Mon Sep 17 00:00:00 2001 From: Jon Chambers <63609320+jon-signal@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:24:58 -0400 Subject: [PATCH] Retire Redis message cache --- service/config/sample.yml | 5 - .../WhisperServerConfiguration.java | 10 - .../textsecuregcm/WhisperServerService.java | 18 +- .../MessageCacheConfiguration.java | 29 - .../dynamic/DynamicConfiguration.java | 8 - .../DynamicMessagePersisterConfiguration.java | 58 - .../controllers/KeepAliveController.java | 1 - .../push/MessageAvailabilityListener.java | 33 - .../push/RedisMessageAvailabilityManager.java | 358 ------ .../storage/ConcatenatingMessageStream.java | 10 +- .../storage/DynamoDbMessageStream.java | 65 + .../storage/MessagePersistenceException.java | 13 - .../storage/MessagePersister.java | 405 ------ .../textsecuregcm/storage/MessagesCache.java | 792 ------------ .../storage/MessagesCacheGetItemsScript.java | 53 - .../storage/MessagesCacheInsertScript.java | 75 -- ...edMultiRecipientPayloadAndViewsScript.java | 76 -- .../MessagesCacheReleaseNodeClaimScript.java | 32 - .../MessagesCacheRemoveByGuidScript.java | 51 - .../MessagesCacheRemoveQueueScript.java | 57 - ...eRemoveRecipientViewFromMrmDataScript.java | 45 - .../MessagesCacheUnlockQueueScript.java | 48 - .../storage/MessagesManager.java | 101 +- .../RedisDynamoDbMessagePublisher.java | 417 ------- .../storage/RedisDynamoDbMessageStream.java | 93 -- .../workers/CommandDependencies.java | 14 +- .../MessagePersisterServiceCommand.java | 123 -- .../main/proto/WebSocketConnectionEvent.proto | 10 +- service/src/main/resources/lua/get_items.lua | 22 - .../src/main/resources/lua/insert_item.lua | 23 - ...ert_shared_multirecipient_message_data.lua | 17 - .../main/resources/lua/release_node_claim.lua | 10 - .../resources/lua/remove_item_by_guid.lua | 32 - .../src/main/resources/lua/remove_queue.lua | 27 - .../remove_recipient_view_from_mrm_data.lua | 17 - .../src/main/resources/lua/unlock_queue.lua | 9 - .../dynamic/DynamicConfigurationTest.java | 52 +- .../MessageDispatcherIntegrationTest.java | 69 +- .../RedisMessageAvailabilityManagerTest.java | 370 ------ .../ConcatenatingMessageStreamTest.java | 12 +- ...st.java => DynamoDbMessageStreamTest.java} | 35 +- .../MessagePersisterIntegrationTest.java | 271 ----- .../storage/MessagePersisterTest.java | 585 --------- .../MessagesCacheGetItemsScriptTest.java | 77 -- .../MessagesCacheInsertScriptTest.java | 116 -- ...ltiRecipientPayloadAndViewsScriptTest.java | 149 --- .../MessagesCacheRemoveByGuidScriptTest.java | 57 - .../MessagesCacheRemoveQueueScriptTest.java | 54 - ...oveRecipientViewFromMrmDataScriptTest.java | 136 --- .../storage/MessagesCacheTest.java | 1083 ----------------- .../storage/MessagesManagerTest.java | 46 +- .../RedisDynamoDbMessagePublisherTest.java | 516 -------- .../WebSocketConnectionIntegrationTest.java | 119 +- ...xpiredFoundationDbMessagesCommandTest.java | 5 +- .../workers/NotifyIdleDevicesCommandTest.java | 1 - ...SecondaryDynamoDbTableDataCommandTest.java | 1 - ...dFoundationDbMessageQueuesCommandTest.java | 2 +- service/src/test/resources/config/test.yml | 5 - 58 files changed, 197 insertions(+), 6721 deletions(-) delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/configuration/MessageCacheConfiguration.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicMessagePersisterConfiguration.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/push/MessageAvailabilityListener.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/push/RedisMessageAvailabilityManager.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStream.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersistenceException.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCache.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheReleaseNodeClaimScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheUnlockQueueScript.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisher.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStream.java delete mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/workers/MessagePersisterServiceCommand.java delete mode 100644 service/src/main/resources/lua/get_items.lua delete mode 100644 service/src/main/resources/lua/insert_item.lua delete mode 100644 service/src/main/resources/lua/insert_shared_multirecipient_message_data.lua delete mode 100644 service/src/main/resources/lua/release_node_claim.lua delete mode 100644 service/src/main/resources/lua/remove_item_by_guid.lua delete mode 100644 service/src/main/resources/lua/remove_queue.lua delete mode 100644 service/src/main/resources/lua/remove_recipient_view_from_mrm_data.lua delete mode 100644 service/src/main/resources/lua/unlock_queue.lua delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/push/RedisMessageAvailabilityManagerTest.java rename service/src/test/java/org/whispersystems/textsecuregcm/storage/{RedisDynamoDbMessageStreamTest.java => DynamoDbMessageStreamTest.java} (61%) delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScriptTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScriptTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScriptTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScriptTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScriptTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheTest.java delete mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisherTest.java diff --git a/service/config/sample.yml b/service/config/sample.yml index a1082fb2d..5c82854d3 100644 --- a/service/config/sample.yml +++ b/service/config/sample.yml @@ -230,11 +230,6 @@ svrb: AAAAAAAAAAAAAAAAAAAA -----END CERTIFICATE----- -messageCache: # Redis server configuration for message store cache - persistDelayMinutes: 1 - cluster: - configurationUri: redis://redis.example.com:6379/ - attachments: maxAttachmentUploadSizeInBytes: 1024 maxMessageBackupUploadSizeInBytes: 1024 diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java index 840777921..1ac6919e5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerConfiguration.java @@ -47,7 +47,6 @@ import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConf import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration; import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration; import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration; -import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration; import org.whispersystems.textsecuregcm.configuration.PagedSingleUseKEMPreKeyStoreConfiguration; @@ -190,11 +189,6 @@ public class WhisperServerConfiguration extends Configuration { @JsonProperty private FaultTolerantRedisClusterFactory rateLimitersCluster; - @NotNull - @Valid - @JsonProperty - private MessageCacheConfiguration messageCache; - @Valid @NotNull @JsonProperty @@ -481,10 +475,6 @@ public class WhisperServerConfiguration extends Configuration { return storageService; } - public MessageCacheConfiguration getMessageCacheConfiguration() { - return messageCache; - } - public FaultTolerantRedisClusterFactory getPushSchedulerCluster() { return pushSchedulerCluster; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 515360ca1..9cb867483 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -241,7 +241,6 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager; import org.whispersystems.textsecuregcm.push.PushNotificationManager; import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; import org.whispersystems.textsecuregcm.push.ReceiptSender; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; @@ -269,7 +268,6 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.FoundationDbVersion; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.KeysManager; -import org.whispersystems.textsecuregcm.storage.MessagesCache; import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb; import org.whispersystems.textsecuregcm.storage.MessagesManager; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; @@ -339,7 +337,6 @@ import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesC import org.whispersystems.textsecuregcm.workers.CopyToS3Command; import org.whispersystems.textsecuregcm.workers.DeleteUserCommand; import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory; -import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand; import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand; import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand; import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand; @@ -401,7 +398,6 @@ public class WhisperServerService extends Application messageDeletionQueue = new LinkedBlockingQueue<>(); Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(), messageDeletionQueue); - ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor") + final ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor") .minThreads(2) .maxThreads(2) .allowCoreThreadTimeOut(true) @@ -638,9 +634,6 @@ public class WhisperServerService extends Application implements Managed { - - private final FaultTolerantRedisClusterClient clusterClient; - private final Executor listenerEventExecutor; - - // Note that this MUST be a single-threaded executor; its function is to process tasks that should usually be - // non-blocking, but can rarely block, and do so in the order in which those tasks were submitted. - private final Executor asyncOperationQueueingExecutor; - - @Nullable - private FaultTolerantPubSubClusterConnection pubSubConnection; - - private final Map listenersByAccountAndDeviceIdentifier; - - private final UUID serverId = UUID.randomUUID(); - - private final byte[] CLIENT_CONNECTED_EVENT_BYTES = ClientEvent.newBuilder() - .setClientConnected(ClientConnectedEvent.newBuilder() - .setServerId(UUIDUtil.toByteString(serverId)) - .build()) - .build() - .toByteArray(); - - private static final Counter PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER = - Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "publishClientConnectionEventError")); - - private static final Counter UNSUBSCRIBE_ERROR_COUNTER = - Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "unsubscribeError")); - - private static final Counter PUB_SUB_EVENT_WITHOUT_LISTENER_COUNTER = - Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "pubSubEventWithoutListener")); - - private static final Counter MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER = - Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "messageAvailableWithoutListener")); - - private static final String LISTENER_GAUGE_NAME = - MetricsUtil.name(RedisMessageAvailabilityManager.class, "listeners"); - - private static final Logger logger = LoggerFactory.getLogger(RedisMessageAvailabilityManager.class); - - @VisibleForTesting - record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) { - } - - public RedisMessageAvailabilityManager(final FaultTolerantRedisClusterClient clusterClient, - final Executor listenerEventExecutor, - final Executor asyncOperationQueueingExecutor) { - - this.clusterClient = clusterClient; - this.listenerEventExecutor = listenerEventExecutor; - this.asyncOperationQueueingExecutor = asyncOperationQueueingExecutor; - - this.listenersByAccountAndDeviceIdentifier = - Metrics.gaugeMapSize(LISTENER_GAUGE_NAME, Tags.empty(), new ConcurrentHashMap<>()); - } - - @Override - public synchronized void start() { - this.pubSubConnection = clusterClient.createBinaryPubSubConnection(); - this.pubSubConnection.usePubSubConnection(connection -> connection.addListener(this)); - - pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribe); - } - - @Override - public synchronized void stop() { - if (pubSubConnection != null) { - pubSubConnection.usePubSubConnection(connection -> { - connection.removeListener(this); - connection.close(); - }); - } - - pubSubConnection = null; - } - - /** - * Marks the given device as "present" for message delivery and registers a listener for new messages and conflicting - * connections. If the given device already has a presence registered with this manager, that presence is displaced - * immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageConsumer()} method is called. - * - * @param accountIdentifier the account identifier for the newly-connected device - * @param deviceId the ID of the newly-connected device within the given account - * @param listener the listener to notify when new messages or conflicting connections arrive for the newly-connected - * device - * - * @return a future that completes when the new device's presence has been registered; the future may fail if a - * pub/sub subscription could not be established, in which case callers should close the client's connection to the - * server - */ - public CompletionStage handleClientConnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) { - if (pubSubConnection == null) { - throw new IllegalStateException("WebSocket connection event manager not started"); - } - - final byte[] eventChannel = getClientEventChannel(accountIdentifier, deviceId); - final AtomicReference displacedListener = new AtomicReference<>(); - final AtomicReference> subscribeFuture = new AtomicReference<>(); - - // Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In - // particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says: - // - // > The entire method invocation is performed atomically. The supplied function is invoked exactly once per - // > invocation of this method. Some attempted update operations on this map by other threads may be blocked while - // > computation is in progress, so the computation should be short and simple. - // - // This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order - // as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued - // operation is asynchronous; we're not blocking on it in the scope of the `compute` operation. - listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId), - (key, existingListener) -> { - subscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection -> - connection.async().ssubscribe(eventChannel)), asyncOperationQueueingExecutor) - .thenCompose(Function.identity())); - - if (existingListener != null) { - displacedListener.set(existingListener); - } - - return listener; - }); - - if (displacedListener.get() != null) { - listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageConsumer()); - } - - return subscribeFuture.get() - .thenCompose(_ -> clusterClient.withBinaryCluster(connection -> connection.async() - .spublish(eventChannel, CLIENT_CONNECTED_EVENT_BYTES)) - .handle((_, throwable) -> { - if (throwable != null) { - PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER.increment(); - } - - return null; - })); - } - - /** - * Removes a "presence" and event listener for the given device if it is still the active listener. Callers should call this method when the client's - * underlying network connection has closed. - * - * @param accountIdentifier the identifier of the account for the disconnected device - * @param deviceId the ID of the disconnected device within the given account - * - * @return a future that completes when the presence and event listener have been removed - */ - public CompletionStage handleClientDisconnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) { - if (pubSubConnection == null) { - throw new IllegalStateException("WebSocket connection event manager not started"); - } - - final AtomicReference> unsubscribeFuture = new AtomicReference<>(CompletableFuture.completedFuture(null)); - - // Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In - // particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says: - // - // > The entire method invocation is performed atomically. The supplied function is invoked exactly once per - // > invocation of this method. Some attempted update operations on this map by other threads may be blocked while - // > computation is in progress, so the computation should be short and simple. - // - // This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order - // as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued - // operation is asynchronous; we're not blocking on it in the scope of the `compute` operation. - listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId), - (ignored, existingListener) -> { - if (listener != existingListener) { - // the listener was already replaced, ignore this event completely - return existingListener; - } - - unsubscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection -> - connection.async().sunsubscribe(getClientEventChannel(accountIdentifier, deviceId))) - .thenRun(Util.NOOP), asyncOperationQueueingExecutor) - .thenCompose(Function.identity())); - - return null; - }); - - return unsubscribeFuture.get().whenComplete((ignored, throwable) -> { - if (throwable != null) { - UNSUBSCRIBE_ERROR_COUNTER.increment(); - } - }); - } - - /** - * Tests whether a client with the given account/device is connected to this manager instance. - * - * @param accountUuid the account identifier for the client to check - * @param deviceId the ID of the device within the given account - * - * @return {@code true} if a client with the given account/device is connected to this manager instance or - * {@code false} if the client is not connected at all or is connected to a different manager instance - */ - public boolean isLocallyPresent(final UUID accountUuid, final byte deviceId) { - return listenersByAccountAndDeviceIdentifier.containsKey(new AccountAndDeviceIdentifier(accountUuid, deviceId)); - } - - @VisibleForTesting - void resubscribe(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) { - final boolean[] changedSlots = RedisClusterUtil.getChangedSlots(clusterTopologyChangedEvent); - - final Map> eventChannelsBySlot = new HashMap<>(); - - // Organize subscriptions by slot so we can issue a smaller number of larger resubscription commands - listenersByAccountAndDeviceIdentifier.keySet() - .stream() - .map(accountAndDeviceIdentifier -> getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId())) - .forEach(clientEventChannel -> { - final int slot = SlotHash.getSlot(clientEventChannel); - - if (changedSlots[slot]) { - eventChannelsBySlot.computeIfAbsent(slot, ignored -> new ArrayList<>()).add(clientEventChannel); - } - }); - - // Issue one resubscription command per affected slot - eventChannelsBySlot.forEach((slot, eventChannels) -> { - if (pubSubConnection != null) { - pubSubConnection.usePubSubConnection(connection -> - connection.sync().ssubscribe(eventChannels.toArray(byte[][]::new))); - } - }); - } - - /** - * Unsubscribes for notifications for the given account and device identifier if and only if no listener is registered - * for that account and device identifier. - * - * @param accountAndDeviceIdentifier the account and device identifier for which to stop receiving notifications - */ - void unsubscribeIfMissingListener(final AccountAndDeviceIdentifier accountAndDeviceIdentifier) { - listenersByAccountAndDeviceIdentifier.compute(accountAndDeviceIdentifier, (ignored, existingListener) -> { - if (existingListener == null && pubSubConnection != null) { - // Enqueue, but do not block on, an "unsubscribe" operation - asyncOperationQueueingExecutor.execute(() -> pubSubConnection.usePubSubConnection(connection -> - connection.async().sunsubscribe(getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(), - accountAndDeviceIdentifier.deviceId())))); - } - - // Make no change to the existing listener whether present or absent - return existingListener; - }); - } - - @Override - public void smessage(final RedisClusterNode node, final byte[] shardChannel, final byte[] message) { - final ClientEvent clientEvent; - - try { - clientEvent = ClientEvent.parseFrom(message); - } catch (final InvalidProtocolBufferException e) { - logger.error("Failed to parse pub/sub event protobuf", e); - return; - } - - final AccountAndDeviceIdentifier accountAndDeviceIdentifier = parseClientEventChannel(shardChannel); - - @Nullable final MessageAvailabilityListener listener = - listenersByAccountAndDeviceIdentifier.get(accountAndDeviceIdentifier); - - if (listener != null) { - switch (clientEvent.getEventCase()) { - case NEW_MESSAGE_AVAILABLE -> listener.handleNewMessageAvailable(); - - case CLIENT_CONNECTED -> { - // Only act on new connections to other event manager instances; we'll learn about displacements in THIS - // instance when we update the listener map in `handleClientConnected` - if (!this.serverId.equals(UUIDUtil.fromByteString(clientEvent.getClientConnected().getServerId()))) { - listenerEventExecutor.execute(listener::handleConflictingMessageConsumer); - } - } - - case MESSAGES_PERSISTED -> listenerEventExecutor.execute(listener::handleMessagesPersisted); - - default -> logger.warn("Unexpected client event type: {}", clientEvent.getClass()); - } - } else { - PUB_SUB_EVENT_WITHOUT_LISTENER_COUNTER.increment(); - - listenerEventExecutor.execute(() -> unsubscribeIfMissingListener(accountAndDeviceIdentifier)); - - if (clientEvent.getEventCase() == ClientEvent.EventCase.NEW_MESSAGE_AVAILABLE) { - MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER.increment(); - } - } - } - - public static byte[] getClientEventChannel(final UUID accountIdentifier, final byte deviceId) { - return ("client_presence::{" + accountIdentifier + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8); - } - - private static AccountAndDeviceIdentifier parseClientEventChannel(final byte[] eventChannelBytes) { - final String eventChannel = new String(eventChannelBytes, StandardCharsets.UTF_8); - final int uuidStart = "client_presence::{".length(); - - final UUID accountIdentifier = UUID.fromString(eventChannel.substring(uuidStart, uuidStart + 36)); - final byte deviceId = Byte.parseByte(eventChannel.substring(uuidStart + 38, eventChannel.length() - 1)); - - return new AccountAndDeviceIdentifier(accountIdentifier, deviceId); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStream.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStream.java index 428d75314..198ef879b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStream.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStream.java @@ -18,23 +18,23 @@ import java.util.concurrent.Flow; public class ConcatenatingMessageStream implements MessageStream { - private final RedisDynamoDbMessageStream redisDynamoDbMessageStream; + private final DynamoDbMessageStream dynamoDbMessageStream; private final FoundationDbMessageStream foundationDbMessageStream; private static final Counter CONFLICTING_CONSUMER_COUNTER = Metrics.counter(MetricsUtil.name(ConcatenatingMessageStream.class, "conflictingConsumer")); - public ConcatenatingMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream, + public ConcatenatingMessageStream(final DynamoDbMessageStream dynamoDbMessageStream, final FoundationDbMessageStream foundationDbMessageStream) { - this.redisDynamoDbMessageStream = redisDynamoDbMessageStream; + this.dynamoDbMessageStream = dynamoDbMessageStream; this.foundationDbMessageStream = foundationDbMessageStream; } @Override public Flow.Publisher getMessages() { return JdkFlowAdapter.publisherToFlowPublisher(Flux.concat( - JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages()), + JdkFlowAdapter.flowPublisherToFlux(dynamoDbMessageStream.getMessages()), JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())) .doOnError(throwable -> { if (ExceptionUtils.unwrap(throwable) instanceof ConflictingMessageConsumerException) { @@ -46,7 +46,7 @@ public class ConcatenatingMessageStream implements MessageStream { @Override public CompletableFuture acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) { return CompletableFuture.allOf( - redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp), + dynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp), messageGuid.version() == 8 ? foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp) : CompletableFuture.completedFuture(null)); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStream.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStream.java new file mode 100644 index 000000000..6a677fc6b --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStream.java @@ -0,0 +1,65 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; + +import io.micrometer.core.instrument.Metrics; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Flow; +import org.whispersystems.textsecuregcm.util.UUIDUtil; +import org.whispersystems.textsecuregcm.util.Util; +import reactor.adapter.JdkFlowAdapter; +import reactor.core.publisher.Flux; + +/// A [MessageStream] implementation that produces messages from a DynamoDB message store. +public class DynamoDbMessageStream implements MessageStream { + + private final MessagesDynamoDb messagesDynamoDb; + + private final UUID accountIdentifier; + private final Device device; + + private static final String MESSAGE_READ_COUNTER_NAME = + name(DynamoDbMessageStream.class, "messagesRead"); + + private static final String MESSAGE_ACKNOWLEDGED_COUNTER_NAME = + name(DynamoDbMessageStream.class, "messagesAcknowledged"); + + private static final String UUID_VERSION_TAG = "uuidVersion"; + + public DynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb, + final UUID accountIdentifier, + final Device device) { + + this.messagesDynamoDb = messagesDynamoDb; + + this.accountIdentifier = accountIdentifier; + this.device = device; + } + + @Override + public Flow.Publisher getMessages() { + return JdkFlowAdapter.publisherToFlowPublisher(Flux.from(messagesDynamoDb.load(accountIdentifier, device, null)) + .doOnNext(envelope -> { + final UUID messageGuid = UUIDUtil.fromByteString(envelope.getServerGuid()); + + Metrics.counter(MESSAGE_READ_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version())) + .increment(); + }) + .map(MessageStreamEntry.Envelope::new)); + } + + @Override + public CompletableFuture acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) { + Metrics.counter(MESSAGE_ACKNOWLEDGED_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version())) + .increment(); + + return messagesDynamoDb.deleteMessage(accountIdentifier, device, messageGuid, serverTimestamp) + .thenRun(Util.NOOP); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersistenceException.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersistenceException.java deleted file mode 100644 index 3e96a8fc4..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersistenceException.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright 2022 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -public class MessagePersistenceException extends Exception { - - public MessagePersistenceException(String message) { - super(message); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java deleted file mode 100644 index 7313509b5..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagePersister.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Copyright 2013-2021 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - -import com.google.common.annotations.VisibleForTesting; -import io.dropwizard.lifecycle.Managed; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Tags; -import io.micrometer.core.instrument.Timer; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; -import javax.annotation.Nullable; -import org.apache.commons.lang3.tuple.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.IdentityType; -import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import org.whispersystems.textsecuregcm.util.Util; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.util.function.Tuples; -import reactor.util.retry.Retry; -import reactor.util.retry.RetryBackoffSpec; -import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException; - -public class MessagePersister implements Managed { - - private final MessagesCache messagesCache; - private final MessagesManager messagesManager; - private final AccountsManager accountsManager; - private final DynamicConfigurationManager dynamicConfigurationManager; - private final Scheduler persistQueueScheduler; - private final Clock clock; - - private final Duration persistDelay; - private final int maxConcurrency; - private final int scanCount; - - private final RetryBackoffSpec retryBackoffSpec; - - private final String persisterId = UUID.randomUUID().toString(); - - private volatile boolean running; - - @Nullable - private Thread workerThread; - - private static final String INSPECTED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "inspectedQueue"); - - private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized"); - private static final String PERSISTED_MESSAGE_COUNTER_NAME = name(MessagePersister.class, "persistMessage"); - private static final String PERSISTED_BYTES_COUNTER_NAME = name(MessagePersister.class, "persistBytes"); - - private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue")); - private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage")); - private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes")); - - private static final Counter PERSIST_NODE_COUNTER = Metrics.counter(name(MessagePersister.class, "persistNodeCount")); - private static final LongTaskTimer PERSIST_NODE_TIMER = Metrics.more().longTaskTimer(name(MessagePersister.class, "persistNode")); - - private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize"); - - static final int QUEUE_BATCH_LIMIT = 100; - static final int MESSAGE_BATCH_LIMIT = 100; - - private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = - DistributionSummary.builder(name(MessagePersister.class, "queueCount")) - .register(Metrics.globalRegistry); - - private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis(); - - private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class); - - public MessagePersister(final MessagesCache messagesCache, - final MessagesManager messagesManager, - final AccountsManager accountsManager, - final DynamicConfigurationManager dynamicConfigurationManager, - final Scheduler persistQueueScheduler, - final Clock clock, - final Duration persistDelay, - final int maxConcurrency, - final int scanCount) { - - this(messagesCache, - messagesManager, - accountsManager, - dynamicConfigurationManager, - persistQueueScheduler, - clock, - persistDelay, - maxConcurrency, - scanCount, - Retry.backoff(3, Duration.ofSeconds(1))); - } - - @VisibleForTesting - MessagePersister(final MessagesCache messagesCache, - final MessagesManager messagesManager, - final AccountsManager accountsManager, - final DynamicConfigurationManager dynamicConfigurationManager, - final Scheduler persistQueueScheduler, - final Clock clock, - final Duration persistDelay, - final int maxConcurrency, - final int scanCount, - final RetryBackoffSpec retryBackoffSpec) { - - this.messagesCache = messagesCache; - this.messagesManager = messagesManager; - this.accountsManager = accountsManager; - this.dynamicConfigurationManager = dynamicConfigurationManager; - this.clock = clock; - this.persistDelay = persistDelay; - this.maxConcurrency = maxConcurrency; - this.scanCount = scanCount; - this.retryBackoffSpec = retryBackoffSpec; - this.persistQueueScheduler = persistQueueScheduler; - } - - @Override - public synchronized void start() { - running = true; - - workerThread = new Thread(() -> { - while (running) { - if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().isPersistenceEnabled()) { - try { - final int queuesPersisted = persistNextNode(); - QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted); - - if (queuesPersisted == 0) { - Util.sleep(100); - } - } catch (final Throwable t) { - logger.warn("Failed to persist queues", t); - Util.sleep(EXCEPTION_PAUSE_MILLIS); - } - } - - try { - // Persisters work through nodes quickly, and running in a hot loop taxes Redis nodes unnecessarily - Thread.sleep(dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getSleepBetweenNodes()); - } catch (final InterruptedException _) { - } - } - }, "MessagePersister"); - - workerThread.start(); - } - - @Override - public synchronized void stop() { - running = false; - - if (workerThread != null) { - try { - workerThread.join(); - } catch (final InterruptedException e) { - logger.warn("Interrupted while waiting for worker thread to complete current operation"); - } - - workerThread = null; - } - } - - @VisibleForTesting - int persistNextNode() { - final RedisClusterNode node; - { - final Duration nodeClaimTtl = - dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getNodeClaimTtl(); - - final Optional maybeNode = messagesCache.claimNextNodeToPersist(persisterId, nodeClaimTtl); - - if (maybeNode.isEmpty()) { - return 0; - } - - node = maybeNode.get(); - } - - try { - return persistNode(node); - } finally { - messagesCache.releaseNodeClaim(node, persisterId); - } - } - - int persistNode(final RedisClusterNode node) { - final LongTaskTimer.Sample sample = PERSIST_NODE_TIMER.start(); - - try { - final Tags tags = Tags.of("node", node.getUri().getHost()); - - return messagesCache.getQueues(node, scanCount) - .filter(_ -> dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration() - .isPersistenceEnabled()) - .flatMap(queueKey -> Mono.defer(() -> shouldPersistQueue(queueKey)) - .retryWhen(retryBackoffSpec) - .onErrorResume(e -> { - logger.warn("Failed to determine whether queue {} should be persisted", queueKey, e); - return Mono.empty(); - }) - .mapNotNull(shouldPersist -> shouldPersist ? queueKey : null) - .doOnTerminate(() -> Metrics.counter(INSPECTED_QUEUE_COUNTER_NAME, tags).increment()), maxConcurrency) - .distinct() - .flatMap(queueKey -> { - final UUID accountIdentifier = MessagesCache.getAccountUuidFromQueueName(queueKey); - final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queueKey); - - return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifier)) - .map(maybeAccount -> maybeAccount - .flatMap(account -> account.getDevice(deviceId)) - .map(device -> Tuples.of(maybeAccount.get(), device))) - .flatMap(Mono::justOrEmpty) - .retryWhen(retryBackoffSpec) - .onErrorResume(e -> { - logger.warn("Failed to fetch account/device for queue: {}", queueKey, e); - return Mono.empty(); - }); - }, maxConcurrency) - .flatMap(accountAndDevice -> { - final Account account = accountAndDevice.getT1(); - final Device device = accountAndDevice.getT2(); - - return persistQueue(account, device, tags) - .thenReturn(1) - .retryWhen(retryBackoffSpec - // Don't retry with backoff for persistence exceptions - .filter(e -> !(e instanceof MessagePersistenceException))) - .onErrorResume(e -> { - logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry", - account.getAccountIdentifier(), device.getId(), node.getUri().getHost(), e); - - return Mono.empty(); - }); - }, maxConcurrency) - .onErrorResume(e -> { - logger.warn("Unhandled error while persisting messages", e); - return Mono.empty(); - }) - .count() - .blockOptional() - .map(Math::toIntExact) - .orElse(0); - } finally { - sample.stop(); - PERSIST_NODE_COUNTER.increment(); - } - } - - @VisibleForTesting - Mono persistQueue(final Account account, final Device device, final Tags baseTags) { - final UUID accountUuid = account.getAccountIdentifier(); - final byte deviceId = device.getId(); - - final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device) - .map(platform -> platform.name().toLowerCase(Locale.ROOT)) - .orElse("unknown")); - - final Timer.Sample sample = Timer.start(); - final Tags tags = baseTags.and(platformTag); - - return Flux.usingWhen( - messagesCache.lockQueueForPersistence(accountUuid, deviceId) - .thenReturn(true), - _ -> Flux.from(messagesCache.getMessagesToPersist(accountUuid, deviceId)) - .buffer(MESSAGE_BATCH_LIMIT) - .flatMap(messages -> { - final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count(); - final int nonUrgentMessageCount = messages.size() - urgentMessageCount; - - Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount); - Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount); - Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags) - .increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum()); - - return Mono.fromRunnable(() -> messagesManager.persistMessages(accountUuid, device, messages)) - .subscribeOn(persistQueueScheduler) - .thenReturn(messages.size()); - }, 1) - .reduce(0, Integer::sum) - .onErrorResume(ItemCollectionSizeLimitExceededException.class, _ -> { - final boolean isPrimary = deviceId == Device.PRIMARY_ID; - Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment(); - // may throw, in which case we'll retry later by the usual mechanism - if (isPrimary) { - logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages", - account.getAccountIdentifier(), deviceId); - - return trimQueue(account, device) - .then(Mono.error(new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed"))); - } else { - logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId); - - return Mono.fromRunnable(() -> accountsManager.removeDevice(accountUuid, deviceId)) - .subscribeOn(persistQueueScheduler) - .then(Mono.empty()); - } - }) - .doOnSuccess(messagesPersisted -> { - if (messagesPersisted != null) { - DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME) - .tags(Tags.of(platformTag)) - .register(Metrics.globalRegistry) - .record(messagesPersisted); - } - }) - .doOnTerminate(() -> sample.stop(PERSIST_QUEUE_TIMER)), - _ -> messagesCache.unlockQueueForPersistence(accountUuid, deviceId)) - .then(); - } - - private Mono trimQueue(final Account account, final Device device) { - final UUID aci = account.getAccountIdentifier(); - final byte deviceId = device.getId(); - - final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration() - .getMessagePersisterConfiguration() - .getTrimOversizedQueueExtraRoomRatio(); - - final AtomicLong oldestMessage = new AtomicLong(0L); - final AtomicLong newestMessage = new AtomicLong(0L); - final AtomicLong bytesDeleted = new AtomicLong(0L); - - final AtomicLong cachedMessageBytes = new AtomicLong(0L); - final AtomicLong targetDeleteBytes = new AtomicLong(0L); - - return Mono.fromFuture(() -> messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId)) - .flatMap(estimatedPersistedQueueSize -> { - cachedMessageBytes.set(estimatedPersistedQueueSize); - targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio)); - - return Flux.from(messagesManager.getMessagesForDevice(aci, device)) - .concatMap(envelope -> { - if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) { - return Mono.just(Optional.empty()); - } - oldestMessage.compareAndSet(0L, envelope.getServerTimestamp()); - newestMessage.set(envelope.getServerTimestamp()); - return Mono.just(Optional.of(envelope)); - }) - .takeWhile(Optional::isPresent) - .flatMap(maybeEnvelope -> { - // We know this must be present because we `takeWhile` values are present - final MessageProtos.Envelope envelope = maybeEnvelope.orElseThrow(AssertionError::new); - TRIMMED_MESSAGE_COUNTER.increment(); - TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize()); - return Mono - .fromCompletionStage(() -> messagesManager - .delete(aci, device, UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp())) - .retryWhen(retryBackoffSpec) - .map(Optional::isPresent); - }) - .reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted - ? Pair.of(acc.getLeft() + 1, acc.getRight()) - : Pair.of(acc.getLeft(), acc.getRight() + 1)); - }) - .doOnSuccess(outcomes -> { - if (outcomes != null) { - logger.warn( - "Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.", - aci, deviceId, - Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()), - targetDeleteBytes, cachedMessageBytes, - outcomes.getLeft(), outcomes.getRight()); - } - }) - .then(); - } - - @VisibleForTesting - Mono shouldPersistQueue(final String queueKey) { - return messagesCache.getEarliestUndeliveredTimestamp( - MessagesCache.getAccountUuidFromQueueName(queueKey), - MessagesCache.getDeviceIdFromQueueName(queueKey)) - .map(oldestMessageTimestamp -> - Duration.between(Instant.ofEpochMilli(oldestMessageTimestamp), clock.instant()).compareTo(persistDelay) > 0) - .switchIfEmpty(Mono.just(false)); - } - - @VisibleForTesting - String getPersisterId() { - return persisterId; - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCache.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCache.java deleted file mode 100644 index d9e333bdd..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCache.java +++ /dev/null @@ -1,792 +0,0 @@ -/* - * Copyright 2013-2022 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - -import com.google.common.annotations.VisibleForTesting; -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import io.github.resilience4j.reactor.retry.RetryOperator; -import io.lettuce.core.Limit; -import io.lettuce.core.Range; -import io.lettuce.core.ScanArgs; -import io.lettuce.core.ScanStream; -import io.lettuce.core.ScoredValue; -import io.lettuce.core.SetArgs; -import io.lettuce.core.cluster.SlotHash; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Timer; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import org.reactivestreams.Publisher; -import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; -import org.signal.libsignal.protocol.ServiceId; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.metrics.MetricsUtil; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.util.ExceptionUtils; -import org.whispersystems.textsecuregcm.util.Pair; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import reactor.core.observability.micrometer.Micrometer; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -/** - * Manages short-term storage of messages in Redis. Messages are frequently delivered to their destination and deleted - * shortly after they reach the server, and this cache acts as a low-latency holding area for new messages, reducing - * load on higher-latency, longer-term storage systems. - *

- * The following structures are used: - *

- *
{@code queueKey}
- *
A sorted set of messages in a device’s queue. A message’s score is its queue-local message ID. See - * Redis.io: The - * Sorted Set data type for background on scores and this data structure.
- *
{@code queueMetadataKey}
- *
A hash containing message guids and their queue-local message ID. It also contains a {@code counter} key, which is - * incremented to supply the next message ID. This is used to remove a message by GUID from {@code queueKey} by its - * local messageId.
- *
{@code sharedMrmKey}
- *
A hash containing a single multi-recipient message pending delivery. It contains: - *
    - *
  • {@code data} - the serialized SealedSenderMultiRecipientMessage data
  • - *
  • fields with each recipient device's “view” into the payload ({@link SealedSenderMultiRecipientMessage#serializedRecipientView(SealedSenderMultiRecipientMessage.Recipient)}
  • - *
- * Note: this is shared among all of the message's recipients, and it may be located in any Redis shard. As each recipient’s - * message is delivered, its corresponding view is idempotently removed. When {@code data} is the only remaining - * field, the hash will be deleted. - *
- *
{@code queueLockKey}
- *
Used to indicate that a queue is being modified by the {@link MessagePersister} and that {@code get_items} should - * return an empty list.
- *
- *

- * At a high level, the process is: - *

    - *
  1. Insert: the queue metadata is queried for the next incremented message ID. The message data is inserted into - * the queue at that ID, and the message GUID is inserted in the queue metadata.
  2. - *
  3. Get: a batch of messages are retrieved from the queue, potentially with an after-message-ID offset.
  4. - *
  5. Remove: a set of messages are remove by GUID. For each GUID, the message ID is retrieved from the queue metadata, - * and then that single-value range is removed from the queue.
  6. - *
- * For multi-recipient messages (sometimes abbreviated “MRM”), there are similar operations on the common data during - * insert, get, and remove. MRM inserts must occur before individual queue inserts, while removal is considered - * best-effort, and uses key expiration as back-stop garbage collection. - *

- * For atomicity, many operations are implemented as Lua scripts that are executed on the Redis server using - * {@code EVAL}/{@code EVALSHA}. - * - * @see MessagesCacheInsertScript - * @see MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript - * @see MessagesCacheGetItemsScript - * @see MessagesCacheRemoveByGuidScript - * @see MessagesCacheRemoveRecipientViewFromMrmDataScript - * @see MessagesCacheRemoveQueueScript - */ -public class MessagesCache { - - private final FaultTolerantRedisClusterClient redisCluster; - private final Clock clock; - - private final Scheduler messageDeliveryScheduler; - private final ExecutorService messageDeletionExecutorService; - // messageDeletionExecutorService wrapped into a reactor Scheduler - private final Scheduler messageDeletionScheduler; - - private final MessagesCacheInsertScript insertScript; - private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript; - private final MessagesCacheRemoveByGuidScript removeByGuidScript; - private final MessagesCacheGetItemsScript getItemsScript; - private final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript; - private final MessagesCacheRemoveQueueScript removeQueueScript; - private final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript; - private final MessagesCacheUnlockQueueScript unlockQueueScript; - - private int nextNodeRotateDistance = 0; - - private final Timer insertTimer = Metrics.timer(name(MessagesCache.class, "insert")); - private final Timer insertSharedMrmPayloadTimer = Metrics.timer(name(MessagesCache.class, "insertSharedMrmPayload")); - private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid")); - private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView")); - private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear")); - private final Counter removeMessageCounter = Metrics.counter(name(MessagesCache.class, "remove")); - private final Counter staleEphemeralMessagesCounter = Metrics.counter( - name(MessagesCache.class, "staleEphemeralMessages")); - private final Counter staleMrmMessagesCounter = Metrics.counter(name(MessagesCache.class, "staleMrmMessages")); - private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved")); - private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError"); - private final String EPHEMERAL_TAG_NAME = "ephemeral"; - private final String MISSING_MRM_DATA_TAG_NAME = "missingMrmData"; - private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter( - name(MessagesCache.class, "skippedStaleEphemeralMrm")); - private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter( - name(MessagesCache.class, "sharedMrmKeyRemoved")); - - static final String RETRY_NAME = ResilienceUtil.name(MessagesCache.class); - - private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8); - - @VisibleForTesting - static final ByteString STALE_MRM_KEY = ByteString.copyFromUtf8("stale"); - - @VisibleForTesting - static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10); - - private static final String GET_FLUX_NAME = MetricsUtil.name(MessagesCache.class, "get"); - - @VisibleForTesting - static final int PAGE_SIZE = 100; - - private static final int REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY = 8; - - private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class); - - public MessagesCache(final FaultTolerantRedisClusterClient redisCluster, - final Scheduler messageDeliveryScheduler, - final ExecutorService messageDeletionExecutorService, - final ScheduledExecutorService retryExecutor, - final Clock clock) throws IOException { - - this( - redisCluster, - messageDeliveryScheduler, - messageDeletionExecutorService, - clock, - new MessagesCacheInsertScript(redisCluster, retryExecutor), - new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor), - new MessagesCacheGetItemsScript(redisCluster), - new MessagesCacheReleaseNodeClaimScript(redisCluster), - new MessagesCacheRemoveByGuidScript(redisCluster, retryExecutor), - new MessagesCacheRemoveQueueScript(redisCluster), - new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster), - new MessagesCacheUnlockQueueScript(redisCluster) - ); - } - - @VisibleForTesting - MessagesCache(final FaultTolerantRedisClusterClient redisCluster, - final Scheduler messageDeliveryScheduler, - final ExecutorService messageDeletionExecutorService, final Clock clock, - final MessagesCacheInsertScript insertScript, - final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript, - final MessagesCacheGetItemsScript getItemsScript, - final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript, - final MessagesCacheRemoveByGuidScript removeByGuidScript, - final MessagesCacheRemoveQueueScript removeQueueScript, - final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript, - final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException { - - this.redisCluster = redisCluster; - this.clock = clock; - - this.messageDeliveryScheduler = messageDeliveryScheduler; - this.messageDeletionExecutorService = messageDeletionExecutorService; - this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion"); - - this.insertScript = insertScript; - this.insertMrmScript = insertMrmScript; - this.removeByGuidScript = removeByGuidScript; - this.getItemsScript = getItemsScript; - this.releaseNodeClaimScript = releaseNodeClaimScript; - this.removeQueueScript = removeQueueScript; - this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript; - this.unlockQueueScript = unlockQueueScript; - } - - public CompletableFuture insert(final UUID messageGuid, - final UUID destinationAccountIdentifier, - final byte destinationDeviceId, - final MessageProtos.Envelope message) { - - final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(UUIDUtil.toByteString(messageGuid)).build(); - final Timer.Sample sample = Timer.start(); - - return insertScript.executeAsync(destinationAccountIdentifier, destinationDeviceId, messageWithGuid) - .toCompletableFuture() - .whenComplete((_, _) -> sample.stop(insertTimer)); - } - - public CompletableFuture insertSharedMultiRecipientMessagePayload( - final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage, - final Set resolvedRecipients) { - - final Timer.Sample sample = Timer.start(); - - final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID()); - - return insertMrmScript.executeAsync(sharedMrmKey, sealedSenderMultiRecipientMessage, resolvedRecipients) - .thenApply(_ -> sharedMrmKey) - .toCompletableFuture() - .whenComplete((_, _) -> sample.stop(insertSharedMrmPayloadTimer)); - } - - public CompletableFuture> remove(final UUID destinationUuid, final byte destinationDevice, - final UUID messageGuid) { - - return remove(destinationUuid, destinationDevice, List.of(messageGuid)) - .thenApply(removed -> removed.isEmpty() ? Optional.empty() : Optional.of(removed.getFirst())); - } - - public CompletableFuture> remove(final UUID destinationUuid, final byte destinationDevice, - final List messageGuids) { - - final Timer.Sample sample = Timer.start(); - - return removeByGuidScript.execute(destinationUuid, destinationDevice, messageGuids) - .thenApplyAsync(serialized -> { - - final List removedMessages = new ArrayList<>(serialized.size()); - final Map> serviceIdentifierToMrmKeys = new HashMap<>(); - - for (final byte[] bytes : serialized) { - try { - final MessageProtos.Envelope envelope = parseEnvelope(bytes); - removedMessages.add(RemovedMessage.fromEnvelope(envelope)); - if (envelope.hasSharedMrmKey()) { - serviceIdentifierToMrmKeys.computeIfAbsent( - ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()), _ -> new ArrayList<>()) - .add(envelope.getSharedMrmKey().toByteArray()); - } - } catch (final InvalidProtocolBufferException e) { - logger.warn("Failed to parse envelope", e); - } - } - - serviceIdentifierToMrmKeys.forEach( - (serviceId, keysToUpdate) -> removeRecipientViewFromMrmData(keysToUpdate, serviceId, destinationDevice)); - - return removedMessages; - }, messageDeletionExecutorService) - .toCompletableFuture() - .whenComplete((removedMessages, _) -> { - if (removedMessages != null) { - removeMessageCounter.increment(removedMessages.size()); - } - - sample.stop(removeByGuidTimer); - }); - - } - - public CompletableFuture hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) { - return redisCluster.withBinaryCluster(connection -> - connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) - .thenApply(cardinality -> cardinality > 0)) - .toCompletableFuture(); - } - - public Publisher get(final UUID destinationUuid, final byte destinationDeviceId) { - return get(destinationUuid, - destinationDeviceId, - clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY), - false); - } - - Publisher getMessagesToPersist(final UUID accountUuid, final byte destinationDeviceId) { - return Flux.from(get(accountUuid, - destinationDeviceId, - // Discard all ephemeral messages when persisting - Instant.ofEpochMilli(Long.MAX_VALUE), - true)); - } - - private Publisher get(final UUID destinationUuid, - final byte destinationDeviceId, - final Instant earliestAllowableEphemeralTimestamp, - final boolean bypassLock) { - - final long earliestAllowableEphemeralTimestampMillis = earliestAllowableEphemeralTimestamp.toEpochMilli(); - - final Flux allMessages = getAllMessages(destinationUuid, destinationDeviceId, - earliestAllowableEphemeralTimestampMillis, PAGE_SIZE, bypassLock) - .publish() - // We expect exactly three subscribers to this base flux: - // 1. the websocket that delivers messages to clients - // 2. an internal processes to discard stale ephemeral messages - // 3. an internal process to discard stale MRM messages - // The discard subscribers will subscribe immediately, but we don’t want to do any work if the - // websocket never subscribes. - .autoConnect(3); - - final Flux messagesToPublish = allMessages - .filter(Predicate.not(envelope -> - isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis) || isStaleMrmMessage(envelope))); - - final Flux staleEphemeralMessages = allMessages - .filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis)); - discardStaleMessages(destinationUuid, destinationDeviceId, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral"); - - final Flux staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage) - // clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data - .map(envelope -> envelope.toBuilder().clearSharedMrmKey().build()); - discardStaleMessages(destinationUuid, destinationDeviceId, staleMrmMessages, staleMrmMessagesCounter, "mrm"); - - return messagesToPublish.name(GET_FLUX_NAME) - .tap(Micrometer.metrics(Metrics.globalRegistry)); - } - - /// Returns the server-issued timestamp of the earliest message in the queue for the given account/device, regardless - /// of the type of message. Note that this method may return a timestamp for a message that would ultimately be - /// discarded were a caller to actually fetch messages (i.e. an expired ephemeral message). - /// - /// @param destinationUuid the account identifier for the queue for which to get a timestamp - /// @param destinationDeviceId the device identifier for the queue for which to get a timestamp - /// - /// @return a `Mono` that publishes the timestamp (in milliseconds since the epoch) of the earliest message in the - /// given queue or yields no value if the queue is empty or does not exist - public Mono getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDeviceId) { - return redisCluster.withBinaryCluster(connection -> - connection.reactive().zrange(getMessageQueueKey(destinationUuid, destinationDeviceId), 0, 0)) - .next() - .flatMap(serializedEnvelope -> { - try { - return Mono.just(parseEnvelope(serializedEnvelope).getServerTimestamp()); - } catch (final InvalidProtocolBufferException e) { - return Mono.error(e); - } - }); - } - - private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message, - long earliestAllowableTimestamp) { - return message.getEphemeral() && message.getClientTimestamp() < earliestAllowableTimestamp; - } - - /** - * Checks whether the given message is a stale MRM message - * - * @see #getMessageWithSharedMrmData(MessageProtos.Envelope, byte) - */ - private static boolean isStaleMrmMessage(final MessageProtos.Envelope message) { - return message.hasSharedMrmKey() && STALE_MRM_KEY.equals(message.getSharedMrmKey()); - } - - private void discardStaleMessages(final UUID destinationUuid, final byte destinationDevice, - Flux staleMessages, final Counter counter, final String context) { - staleMessages - .map(e -> UUIDUtil.fromByteString(e.getServerGuid())) - .buffer(PAGE_SIZE) - .subscribeOn(messageDeletionScheduler) - .subscribe(messageGuids -> - remove(destinationUuid, destinationDevice, messageGuids) - .thenAccept(removedMessages -> counter.increment(removedMessages.size())), - e -> { - if (!ExceptionUtils.isBreakerOpen(e)) { - logger.warn("Could not remove stale {} messages from cache", context, e); - } - }); - } - - @VisibleForTesting - Flux getAllMessages(final UUID destinationUuid, - final byte destinationDevice, - final long earliestAllowableEphemeralTimestamp, - final int pageSize, - final boolean bypassLock) { - - // fetch messages by page - return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize, bypassLock) - .expand(queueItemsAndLastMessageId -> { - // expand() is breadth-first, so each page will be published in order - if (queueItemsAndLastMessageId.first().isEmpty()) { - return Mono.empty(); - } - - return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize, bypassLock); - }) - .limitRate(1) - // we want to ensure we don’t accidentally block the Lettuce/netty i/o executors - .publishOn(messageDeliveryScheduler) - .map(Pair::first) - .concatMap(queueItems -> { - - final List> envelopes = new ArrayList<>(queueItems.size() / 2); - - for (int i = 0; i < queueItems.size() - 1; i += 2) { - try { - final MessageProtos.Envelope message = parseEnvelope(queueItems.get(i)); - - final Mono messageMono; - if (message.hasSharedMrmKey()) { - - if (isStaleEphemeralMessage(message, earliestAllowableEphemeralTimestamp)) { - // skip fetching content for message that will be discarded - messageMono = Mono.just(message.toBuilder().clearSharedMrmKey().build()); - skippedStaleEphemeralMrmCounter.increment(); - } else { - messageMono = getMessageWithSharedMrmData(message, destinationDevice); - } - - } else { - messageMono = Mono.just(message); - } - - envelopes.add(messageMono); - - } catch (InvalidProtocolBufferException e) { - logger.warn("Failed to parse envelope", e); - } - } - - return Flux.mergeSequential(envelopes); - }); - } - - /** - * Returns the given message with its shared MRM data. There are three possible cases: - *

    - *
  1. The reconstructed message for delivery with {@code content} set and {@code sharedMrmKey} cleared
  2. - *
  3. The input with {@code sharedMrmKey} set to a static value, indicating that the shared MRM data is no longer available, and the message should be - * discarded from the queue
  4. - *
  5. An empty {@code Mono}, if an unexpected error occurred
  6. - *
- */ - private Mono getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage, - final byte destinationDevice) { - - assert mrmMessage.hasSharedMrmKey(); - - final byte[] key = mrmMessage.getSharedMrmKey().toByteArray(); - final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey( - // the message might be addressed to the account's PNI, so use the service ID from the envelope - ServiceIdentifier.fromByteString(mrmMessage.getDestinationServiceId()), destinationDevice); - - return Mono.from(redisCluster.withBinaryCluster( - conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey) - .collectList() - .publishOn(messageDeliveryScheduler))) - .transformDeferred(RetryOperator.of(ResilienceUtil.getGeneralRedisRetry(RETRY_NAME))) - .handle((mrmDataAndView, sink) -> { - try { - assert mrmDataAndView.size() == 2; - - if (mrmDataAndView.getFirst().isEmpty()) { - // shared data is missing - //noinspection ReactiveStreamsThrowInOperator - throw new MrmDataMissingException(MrmDataMissingException.Type.SHARED); - } - - if (mrmDataAndView.getLast().isEmpty()) { - // recipient's view is missing - //noinspection ReactiveStreamsThrowInOperator - throw new MrmDataMissingException(MrmDataMissingException.Type.RECIPIENT_VIEW); - } - - final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient( - mrmDataAndView.getFirst().getValue(), - mrmDataAndView.getLast().getValue()); - - sink.next(mrmMessage.toBuilder() - .clearSharedMrmKey() - .setContent(ByteString.copyFrom(content)) - .build()); - - mrmContentRetrievedCounter.increment(); - } catch (Exception e) { - sink.error(e); - } - }) - .onErrorResume(throwable -> { - - final List tags = new ArrayList<>(); - tags.add(Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral()))); - - final Mono result; - if (throwable instanceof MrmDataMissingException mdme) { - tags.add(Tag.of(MISSING_MRM_DATA_TAG_NAME, mdme.getType().name())); - // MRM data may be missing if either of the two non-transactional writes (delete from queue, update shared - // MRM data) fails after it has been delivered. We return it so that it may be discarded from the queue. - result = Mono.just(mrmMessage.toBuilder().setSharedMrmKey(STALE_MRM_KEY).build()); - } else { - if (!ExceptionUtils.isBreakerOpen(throwable)) { - logger.warn("Failed to retrieve shared mrm data", throwable); - } - // For unexpected errors, return empty. The message will remain in the queue and be retried in the future. - result = Mono.empty(); - } - - Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME, tags).increment(); - - return result; - }) - .share(); - } - - /** - * Makes a best-effort attempt at asynchronously updating (and removing when empty) the MRM data structure - */ - void removeRecipientViewFromMrmData(final List sharedMrmKeys, final ServiceIdentifier serviceIdentifier, - final byte deviceId) { - - if (sharedMrmKeys.isEmpty()) { - return; - } - - final Timer.Sample sample = Timer.start(); - Flux.fromIterable(sharedMrmKeys) - .collectMultimap(SlotHash::getSlot) - .flatMapMany(slotsAndKeys -> Flux.fromIterable(slotsAndKeys.values())) - .flatMap( - keys -> removeRecipientViewFromMrmDataScript.execute(keys, serviceIdentifier, deviceId), - REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY) - .doOnNext(sharedMrmDataKeyRemovedCounter::increment) - .onErrorResume(e -> { - if (!ExceptionUtils.isBreakerOpen(e)) { - logger.warn("Error removing recipient view", e); - } - return Mono.just(0L); - }) - .then() - .doOnTerminate(() -> sample.stop(removeRecipientViewTimer)) - .subscribe(); - } - - private Mono, Long>> getNextMessagePage(final UUID destinationUuid, - final byte destinationDevice, - final long messageId, - final int pageSize, - final boolean bypassLock) { - - return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId, bypassLock) - .map(queueItems -> { - logger.trace("Processing page: {}", messageId); - - if (queueItems.isEmpty()) { - return new Pair<>(Collections.emptyList(), null); - } - - if (queueItems.size() % 2 != 0) { - logger.error("\"Get messages\" operation returned a list with a non-even number of elements."); - return new Pair<>(Collections.emptyList(), null); - } - - final long lastMessageId = Long.parseLong( - new String(queueItems.getLast(), StandardCharsets.UTF_8)); - - return new Pair<>(queueItems, lastMessageId); - }); - } - - /** - * Estimate the size of the cached queue if it were to be persisted - * @param accountUuid The account identifier - * @param destinationDevice The destination device id - * @return A future that completes with the approximate size of stored messages that need to be persisted - */ - CompletableFuture estimatePersistedQueueSizeBytes(final UUID accountUuid, final byte destinationDevice) { - final Function, Mono>>> getNextPage = (Optional start) -> - Mono.fromCompletionStage(() -> redisCluster.withBinaryCluster(connection -> - connection.async().zrangebyscoreWithScores( - getMessageQueueKey(accountUuid, destinationDevice), - Range.from( - start.map(Range.Boundary::excluding).orElse(Range.Boundary.unbounded()), - Range.Boundary.unbounded()), - Limit.from(PAGE_SIZE)))); - final Flux allSerializedMessages = getNextPage.apply(Optional.empty()) - .expand(scoredValues -> { - if (scoredValues.isEmpty()) { - return Mono.empty(); - } - long lastTimestamp = (long) scoredValues.getLast().getScore(); - return getNextPage.apply(Optional.of(lastTimestamp)); - }) - .concatMap(scoredValues -> Flux.fromStream(scoredValues.stream().map(ScoredValue::getValue))); - - return parseAndFetchMrms(allSerializedMessages, destinationDevice) - .filter(Predicate.not(envelope -> envelope.getEphemeral() || isStaleMrmMessage(envelope))) - .reduce(0L, (acc, envelope) -> acc + envelope.getSerializedSize()) - .toFuture(); - } - - private Flux parseAndFetchMrms(final Flux serializedMessages, final byte destinationDevice) { - return serializedMessages - .mapNotNull(message -> { - try { - return parseEnvelope(message); - } catch (InvalidProtocolBufferException e) { - logger.warn("Failed to parse envelope", e); - return null; - } - }) - .concatMap(message -> { - final Mono messageMono; - if (message.hasSharedMrmKey()) { - messageMono = getMessageWithSharedMrmData(message, destinationDevice); - } else { - messageMono = Mono.just(message); - } - - return messageMono; - }); - } - - public CompletableFuture clear(final UUID destinationUuid) { - return CompletableFuture.allOf( - Device.ALL_POSSIBLE_DEVICE_IDS.stream() - .map(deviceId -> clear(destinationUuid, deviceId)) - .toList() - .toArray(CompletableFuture[]::new)); - } - - public CompletableFuture clear(final UUID destinationUuid, final byte deviceId) { - final Timer.Sample sample = Timer.start(); - - return removeQueueScript.execute(destinationUuid, deviceId, Collections.emptyList()) - .publishOn(messageDeletionScheduler) - .expand(messagesToProcess -> { - if (messagesToProcess.isEmpty()) { - return Mono.empty(); - } - - final Map> serviceIdentifierToMrmKeys = new HashMap<>(); - final List processedMessages = new ArrayList<>(messagesToProcess.size()); - for (byte[] serialized : messagesToProcess) { - try { - final MessageProtos.Envelope message = parseEnvelope(serialized); - - processedMessages.add(UUIDUtil.fromByteString(message.getServerGuid()).toString()); - - if (message.hasSharedMrmKey()) { - serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.fromByteString(message.getDestinationServiceId()), - _ -> new ArrayList<>()) - .add(message.getSharedMrmKey().toByteArray()); - } - } catch (final InvalidProtocolBufferException e) { - logger.warn("Failed to parse envelope", e); - } - } - - serviceIdentifierToMrmKeys.forEach((serviceId, keysToUpdate) -> - removeRecipientViewFromMrmData(keysToUpdate, serviceId, deviceId)); - - return removeQueueScript.execute(destinationUuid, deviceId, processedMessages); - }) - .then() - .toFuture() - .thenRun(() -> sample.stop(clearQueueTimer)); - } - - Optional claimNextNodeToPersist(final String persisterId, final Duration ttl) { - final List primaryNodes = redisCluster.withCluster(connection -> connection.getPartitions().stream() - .filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM)) - .collect(Collectors.toCollection(ArrayList::new))); - - Collections.rotate(primaryNodes, Math.abs(nextNodeRotateDistance++) % primaryNodes.size()); - - return primaryNodes.stream() - .filter(node -> claimNode(node, persisterId, ttl)) - .findFirst(); - } - - @VisibleForTesting - boolean claimNode(final RedisClusterNode node, final String persisterId, final Duration claimTtl) { - return redisCluster.withCluster(connection -> - "OK".equals(connection.sync().set(getPersisterNodeClaimKey(node), persisterId, SetArgs.Builder.nx().ex(claimTtl)))); - } - - void releaseNodeClaim(final RedisClusterNode node, final String persisterId) { - releaseNodeClaimScript.execute(node, persisterId); - } - - @VisibleForTesting - static String getPersisterNodeClaimKey(final RedisClusterNode node) { - return "persister_node_claim::" + node.getNodeId(); - } - - Flux getQueues(final RedisClusterNode node, final int scanCount) { - return redisCluster.withCluster(connection -> - ScanStream.scan(connection.getConnection(node.getNodeId()).reactive(), - ScanArgs.Builder.matches("user_queue::*").limit(scanCount))); - } - - Mono lockQueueForPersistence(final UUID accountUuid, final byte deviceId) { - return redisCluster.withBinaryCluster( - connection -> connection.reactive().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE)) - .then(); - } - - Mono unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) { - return unlockQueueScript.execute(accountUuid, deviceId); - } - - static byte[] getMessageQueueKey(final UUID accountUuid, final byte deviceId) { - return ("user_queue::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8); - } - - static byte[] getMessageQueueMetadataKey(final UUID accountUuid, final byte deviceId) { - return ("user_queue_metadata::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8); - } - - static byte[] getSharedMrmKey(final UUID mrmGuid) { - return ("mrm::{" + mrmGuid.toString() + "}").getBytes(StandardCharsets.UTF_8); - } - - static byte[] getPersistInProgressKey(final UUID accountUuid, final byte deviceId) { - return ("user_queue_persisting::{" + accountUuid + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8); - } - - static byte[] getSharedMrmViewKey(final ServiceId serviceId, final byte deviceId) { - return getSharedMrmViewKey(serviceId.toServiceIdFixedWidthBinary(), deviceId); - } - - static byte[] getSharedMrmViewKey(final ServiceIdentifier serviceIdentifier, final byte deviceId) { - return getSharedMrmViewKey(serviceIdentifier.toFixedWidthByteArray(), deviceId); - } - - private static byte[] getSharedMrmViewKey(final byte[] fixedWithServiceId, final byte deviceId) { - assert fixedWithServiceId.length == 17; - - final ByteBuffer keyBb = ByteBuffer.allocate(18); - keyBb.put(fixedWithServiceId); - keyBb.put(deviceId); - assert !keyBb.hasRemaining(); - return keyBb.array(); - } - - static UUID getAccountUuidFromQueueName(final String queueName) { - final int startOfHashTag = queueName.indexOf('{'); - - return UUID.fromString(queueName.substring(startOfHashTag + 1, queueName.indexOf("::", startOfHashTag))); - } - - static byte getDeviceIdFromQueueName(final String queueName) { - return Byte.parseByte(queueName.substring(queueName.lastIndexOf("::") + 2, queueName.lastIndexOf('}'))); - } - - private MessageProtos.Envelope parseEnvelope(final byte[] envelopeBytes) - throws InvalidProtocolBufferException { - - return MessageProtos.Envelope.parseFrom(envelopeBytes); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScript.java deleted file mode 100644 index f10d45263..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScript.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.github.resilience4j.reactor.retry.RetryOperator; -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.UUID; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; -import reactor.core.publisher.Mono; - -/** - * Retrieves a list of messages and their corresponding queue-local IDs for the device. To support streaming processing, - * the last queue-local message ID from a previous call may be used as the {@code afterMessageId}. - */ -class MessagesCacheGetItemsScript { - - private final ClusterLuaScript getItemsScript; - - MessagesCacheGetItemsScript(FaultTolerantRedisClusterClient redisCluster) throws IOException { - this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.OBJECT); - } - - Mono> execute(final UUID destinationUuid, - final byte destinationDevice, - final int limit, - final long afterMessageId, - final boolean bypassLock) { - - final List keys = List.of( - MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey - MessagesCache.getPersistInProgressKey(destinationUuid, destinationDevice) // queueLockKey - ); - final List args = List.of( - String.valueOf(limit).getBytes(StandardCharsets.UTF_8), // limit - String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8), // afterMessageId - String.valueOf(bypassLock).getBytes(StandardCharsets.UTF_8) // bypassLock - ); - //noinspection unchecked - return getItemsScript.executeBinaryReactive(keys, args) - .transformDeferred(RetryOperator.of(ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME))) - .map(result -> (List) result) - .next(); - } - -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScript.java deleted file mode 100644 index 3496597d3..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScript.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.ScheduledExecutorService; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.push.ClientEvent; -import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; -import org.whispersystems.textsecuregcm.util.UUIDUtil; - -/** - * Inserts an envelope into the message queue for a destination device and publishes a "new message available" event. - */ -class MessagesCacheInsertScript { - - private final ClusterLuaScript insertScript; - private final ScheduledExecutorService retryExecutor; - - private static final byte[] NEW_MESSAGE_EVENT_BYTES = ClientEvent.newBuilder() - .setNewMessageAvailable(NewMessageAvailableEvent.getDefaultInstance()) - .build() - .toByteArray(); - - MessagesCacheInsertScript(FaultTolerantRedisClusterClient redisCluster, - final ScheduledExecutorService retryExecutor) throws IOException { - - this.insertScript = ClusterLuaScript.fromResource(redisCluster, "lua/insert_item.lua", ScriptOutputType.BOOLEAN); - this.retryExecutor = retryExecutor; - } - - /** - * Inserts a message into the given device's message queue and publishes a "new message available" event. - * - * @param destinationUuid the account identifier for the receiving account - * @param destinationDevice the ID of the receiving device within the given account - * @param envelope the message to insert - * @return {@code true} if the destination device had a registered "presence"/event subscriber or {@code false} - * otherwise - */ - CompletionStage executeAsync(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) { - assert envelope.hasServerGuid(); - assert envelope.hasServerTimestamp(); - - final List keys = List.of( - MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey - MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey - RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey - ); - - final List args = new ArrayList<>(Arrays.asList( - envelope.toByteArray(), // message - UUIDUtil.fromByteString(envelope.getServerGuid()).toString().getBytes(StandardCharsets.UTF_8), // guid - NEW_MESSAGE_EVENT_BYTES // eventPayload - )); - - return ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME) - .executeCompletionStage(retryExecutor, () -> insertScript.executeBinaryAsync(keys, args)) - .thenApply(result -> (boolean) result); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.java deleted file mode 100644 index a56755ce3..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.ScheduledExecutorService; -import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; -import org.whispersystems.textsecuregcm.util.Util; - -/** - * Inserts the shared multi-recipient message payload into the cache. The list of recipients and views will be set as - * fields in the hash. - * - * @see SealedSenderMultiRecipientMessage#serializedRecipientView(SealedSenderMultiRecipientMessage.Recipient) - */ -class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript { - - private final ClusterLuaScript script; - private final ScheduledExecutorService retryExecutor; - - static final String ERROR_KEY_EXISTS = "ERR key exists"; - - MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(FaultTolerantRedisClusterClient redisCluster, - final ScheduledExecutorService retryExecutor) throws IOException { - - this.script = ClusterLuaScript.fromResource(redisCluster, "lua/insert_shared_multirecipient_message_data.lua", - ScriptOutputType.INTEGER); - - this.retryExecutor = retryExecutor; - } - - CompletionStage executeAsync(final byte[] sharedMrmKey, - final SealedSenderMultiRecipientMessage message, - final Set resolvedRecipients) { - - final List keys = List.of( - sharedMrmKey // sharedMrmKey - ); - - final int deviceCount = message.getRecipients().values().stream() - .filter(resolvedRecipients::contains) - .mapToInt(recipient -> recipient.getDevices().length) - .sum(); - - // Pre-allocate capacity for the most fields we expect -- the shared data field plus one for each device - final List args = new ArrayList<>(1 + deviceCount); - args.add(message.serialized()); - - message.getRecipients().forEach((serviceId, recipient) -> { - if (!resolvedRecipients.contains(recipient)) { - return; - } - - for (final byte deviceId : recipient.getDevices()) { - args.add(MessagesCache.getSharedMrmViewKey(serviceId, deviceId)); - args.add(message.serializedRecipientView(recipient)); - } - }); - - return ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME) - .executeCompletionStage(retryExecutor, () -> script.executeBinaryAsync(keys, args)) - .thenRun(Util.NOOP); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheReleaseNodeClaimScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheReleaseNodeClaimScript.java deleted file mode 100644 index 7e44b39a0..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheReleaseNodeClaimScript.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2026 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import java.io.IOException; -import java.util.List; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; - -class MessagesCacheReleaseNodeClaimScript { - - private final ClusterLuaScript releaseNodeClaimScript; - - MessagesCacheReleaseNodeClaimScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException { - this.releaseNodeClaimScript = - ClusterLuaScript.fromResource(redisCluster, "lua/release_node_claim.lua", ScriptOutputType.STATUS); - } - - void execute(final RedisClusterNode node, final String persisterId) { - final List keys = List.of(MessagesCache.getPersisterNodeClaimKey(node)); - final List arguments = List.of(persisterId); - - ResilienceUtil.getGeneralRedisRetry(getClass().getSimpleName()) - .executeRunnable(() -> releaseNodeClaimScript.execute(keys, arguments)); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScript.java deleted file mode 100644 index 6a2d7ef2c..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScript.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.ScheduledExecutorService; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.util.ResilienceUtil; - -/** - * Removes a list of message GUIDs from the queue of a destination device. - */ -class MessagesCacheRemoveByGuidScript { - - private final ClusterLuaScript removeByGuidScript; - private final ScheduledExecutorService retryExecutor; - - MessagesCacheRemoveByGuidScript(final FaultTolerantRedisClusterClient redisCluster, - final ScheduledExecutorService retryExecutor) throws IOException { - - this.removeByGuidScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_item_by_guid.lua", - ScriptOutputType.OBJECT); - this.retryExecutor = retryExecutor; - } - - CompletionStage> execute(final UUID destinationUuid, final byte destinationDevice, - final List messageGuids) { - - final List keys = List.of( - MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey - MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey - ); - final List args = messageGuids.stream().map(guid -> guid.toString().getBytes(StandardCharsets.UTF_8)) - .toList(); - - //noinspection unchecked - return ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME) - .executeCompletionStage(retryExecutor, () -> removeByGuidScript.executeBinaryAsync(keys, args)) - .thenApply(result -> (List) result); - } - -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScript.java deleted file mode 100644 index 7ff616c4b..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScript.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import reactor.core.publisher.Mono; - -/** - * Removes a device's queue from the cache. For a non-empty queue, this script must be executed multiple times. - *
    - *
  1. The first call will return a list of messages to check for {@code sharedMrmKeys}. If a {@code sharedMrmKey} is present, {@link MessagesCacheRemoveRecipientViewFromMrmDataScript} must be called.
  2. - *
  3. Once theses messages have been processed, this script should be called again, confirming that the messages have been processed.
  4. - *
  5. This should be repeated until the script returns an empty list, as the script only returns a page ({@value PAGE_SIZE}) of messages at a time.
  6. - *
- */ -class MessagesCacheRemoveQueueScript { - - private static final int PAGE_SIZE = 100; - - private final ClusterLuaScript removeQueueScript; - - MessagesCacheRemoveQueueScript(FaultTolerantRedisClusterClient redisCluster) throws IOException { - this.removeQueueScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_queue.lua", - ScriptOutputType.MULTI); - } - - Mono> execute(final UUID destinationUuid, final byte destinationDevice, - final List processedMessageGuids) { - - final List keys = List.of( - MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey - MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey - ); - - final List args = new ArrayList<>(); - - args.addFirst(String.valueOf(PAGE_SIZE).getBytes(StandardCharsets.UTF_8)); // limit - args.addAll(processedMessageGuids.stream().map(guid -> guid.getBytes(StandardCharsets.UTF_8)) - .toList()); // processedMessageGuids - - //noinspection unchecked - return removeQueueScript.executeBinaryReactive(keys, args) - .map(result -> (List) result) - .next(); - } - -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScript.java deleted file mode 100644 index e3d2ccc64..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScript.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import reactor.core.publisher.Mono; - -/** - * Removes the given destination device from the given {@code sharedMrmKeys}. If there are no devices remaining in the - * hash as a result, the shared payload is deleted. - *

- * NOTE: Callers are responsible for ensuring that all keys are in the same slot. - */ -class MessagesCacheRemoveRecipientViewFromMrmDataScript { - - private final ClusterLuaScript removeRecipientViewFromMrmDataScript; - - MessagesCacheRemoveRecipientViewFromMrmDataScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException { - this.removeRecipientViewFromMrmDataScript = ClusterLuaScript.fromResource(redisCluster, - "lua/remove_recipient_view_from_mrm_data.lua", ScriptOutputType.INTEGER); - } - - Mono execute(final Collection keysCollection, final ServiceIdentifier serviceIdentifier, - final byte deviceId) { - - final List keys = keysCollection instanceof List - ? (List) keysCollection - : new ArrayList<>(keysCollection); - - return removeRecipientViewFromMrmDataScript.executeBinaryReactive(keys, - List.of(MessagesCache.getSharedMrmViewKey(serviceIdentifier, deviceId))) - .map(o -> (long) o) - .next(); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheUnlockQueueScript.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheUnlockQueueScript.java deleted file mode 100644 index 342fd13a6..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesCacheUnlockQueueScript.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import io.lettuce.core.ScriptOutputType; -import java.io.IOException; -import java.time.Duration; -import java.util.List; -import java.util.UUID; -import org.whispersystems.textsecuregcm.push.ClientEvent; -import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import reactor.core.publisher.Mono; -import reactor.util.retry.Retry; - -/** - * Unlocks a message queue for persistence/message retrieval. - */ -class MessagesCacheUnlockQueueScript { - - private final ClusterLuaScript unlockQueueScript; - - private final List MESSAGES_PERSISTED_EVENT_ARGS = List.of(ClientEvent.newBuilder() - .setMessagesPersisted(MessagesPersistedEvent.getDefaultInstance()) - .build() - .toByteArray()); // eventPayload - - MessagesCacheUnlockQueueScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException { - this.unlockQueueScript = - ClusterLuaScript.fromResource(redisCluster, "lua/unlock_queue.lua", ScriptOutputType.STATUS); - } - - Mono execute(final UUID accountIdentifier, final byte deviceId) { - final List keys = List.of( - MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey - RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey - ); - - return unlockQueueScript.executeBinaryReactive(keys, MESSAGES_PERSISTED_EVENT_ARGS) - .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) - .then(); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java index 9a068184e..e46667150 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java @@ -4,12 +4,8 @@ */ package org.whispersystems.textsecuregcm.storage; -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - import com.apple.foundationdb.FDBException; import com.google.protobuf.ByteString; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Metrics; import java.time.Clock; import java.time.Instant; import java.util.Arrays; @@ -19,61 +15,39 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.reactivestreams.Publisher; import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.util.ExceptionUtils; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import reactor.core.observability.micrometer.Micrometer; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class MessagesManager { - final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = name(MessagesManager.class, "getMessagesForDevice"); - private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class); - private static final Counter PERSIST_MESSAGE_COUNTER = Metrics.counter( - name(MessagesManager.class, "persistMessage")); - - private static final Counter PERSIST_MESSAGE_BYTES_COUNTER = Metrics.counter( - name(MessagesManager.class, "persistMessageBytes")); - private final MessagesDynamoDb messagesDynamoDb; - private final MessagesCache messagesCache; private final FoundationDbMessageStore foundationDbMessageStore; - private final RedisMessageAvailabilityManager redisMessageAvailabilityManager; private final ReportMessageManager reportMessageManager; private final ExecutorService messageDeletionExecutor; private final Clock clock; public MessagesManager( final MessagesDynamoDb messagesDynamoDb, - final MessagesCache messagesCache, final FoundationDbMessageStore foundationDbMessageStore, - final RedisMessageAvailabilityManager redisMessageAvailabilityManager, final ReportMessageManager reportMessageManager, final ExecutorService messageDeletionExecutor, final Clock clock) { this.messagesDynamoDb = messagesDynamoDb; - this.messagesCache = messagesCache; this.foundationDbMessageStore = foundationDbMessageStore; - this.redisMessageAvailabilityManager = redisMessageAvailabilityManager; this.reportMessageManager = reportMessageManager; this.messageDeletionExecutor = messageDeletionExecutor; this.clock = clock; @@ -85,9 +59,7 @@ public class MessagesManager { * @param accountIdentifier the account identifier for the destination queue * @param messagesByDeviceId a map of device IDs to messages * - * @return a map of device IDs to a device's presence state (i.e. if the device has an active event listener) - * - * @see RedisMessageAvailabilityManager + * @return a map of device IDs to a device's presence state */ public Map insert(final UUID accountIdentifier, final Map messagesByDeviceId) { return insertAsync(accountIdentifier, messagesByDeviceId).join(); @@ -139,10 +111,7 @@ public class MessagesManager { * connections to a Signal server or {@code false} otherwise * @param isUrgent {@code true} if the given message is urgent or {@code false} otherwise * - * @return a map of accounts to maps of device IDs to a device's presence state (i.e. if the device has an active - * event listener) - * - * @see RedisMessageAvailabilityManager + * @return a map of accounts to maps of device IDs to a device's presence state */ public CompletableFuture>> insertMultiRecipientMessage( final SealedSenderMultiRecipientMessage multiRecipientMessage, @@ -199,7 +168,6 @@ public class MessagesManager { public CompletableFuture mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) { @SuppressWarnings("unchecked") final CompletableFuture[] mayHaveMessagesFutures = new CompletableFuture[] { foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()), - messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId()), messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice) }; @@ -214,22 +182,13 @@ public class MessagesManager { public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) { return new ConcatenatingMessageStream( - new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, - destinationUuid, destinationDevice, true), + new DynamoDbMessageStream(messagesDynamoDb, destinationUuid, destinationDevice), foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()) ); } - Publisher getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) { - return Flux.concat( - messagesDynamoDb.load(destinationUuid, destinationDevice, null), - messagesCache.get(destinationUuid, destinationDevice.getId())) - .name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME) - .tap(Micrometer.metrics(Metrics.globalRegistry)); - } - public CompletableFuture clear(final UUID destinationUuid) { - messageDeletionExecutor.execute(() -> { + return CompletableFuture.runAsync(() -> { try { foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid)); } catch (final Exception e) { @@ -237,13 +196,11 @@ public class MessagesManager { logger.warn("Failed to clear messages for {}", destinationUuid, e); } } - }); - - return messagesCache.clear(destinationUuid); + }, messageDeletionExecutor); } public CompletableFuture clear(final UUID destinationUuid, final byte deviceId) { - messageDeletionExecutor.execute(() -> { + return CompletableFuture.runAsync(() -> { try { foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId); } catch (final Exception e) { @@ -251,56 +208,12 @@ public class MessagesManager { logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e); } } - }); - - return messagesCache.clear(destinationUuid, deviceId); - } - - public CompletableFuture> delete(final UUID destinationUuid, - final Device destinationDevice, - final UUID guid, - final long serverTimestamp) { - - return messagesCache.remove(destinationUuid, destinationDevice.getId(), guid) - .thenComposeAsync(removed -> removed - .map(_ -> CompletableFuture.completedFuture(removed)) - .orElseGet(() -> messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid, serverTimestamp) - .thenApply(maybeEnvelope -> maybeEnvelope.map(RemovedMessage::fromEnvelope)) - ), messageDeletionExecutor); - } - - /** - * @return the number of messages successfully removed from the cache. - */ - public int persistMessages( - final UUID destinationUuid, - final Device destinationDevice, - final List messages) { - - messagesDynamoDb.store(messages, destinationUuid, destinationDevice); - - final List messageGuids = messages.stream().map(message -> UUIDUtil.fromByteString(message.getServerGuid())) - .collect(Collectors.toList()); - int messagesRemovedFromCache = 0; - try { - messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids) - .get(30, TimeUnit.SECONDS).size(); - PERSIST_MESSAGE_COUNTER.increment(messages.size()); - PERSIST_MESSAGE_BYTES_COUNTER.increment(messages.stream() - .mapToInt(Envelope::getSerializedSize) - .sum()); - - } catch (InterruptedException | ExecutionException | TimeoutException e) { - logger.warn("Failed to remove messages from cache", e); - } - return messagesRemovedFromCache; + }, messageDeletionExecutor); } public CompletableFuture> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, Device destinationDevice) { // If there's any message in the persisted layer, return the oldest return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp) - // If not, return the oldest message in the cache - .switchIfEmpty(Mono.defer(() -> messagesCache.getEarliestUndeliveredTimestamp(destinationUuid, destinationDevice.getId()))) // And if there are none there, then check FoundationDB .switchIfEmpty(Mono.fromFuture(() -> foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())) .mapNotNull(maybeTimestamp -> maybeTimestamp.map(Instant::toEpochMilli).orElse(null))) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisher.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisher.java deleted file mode 100644 index 143a0a5b2..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisher.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - -import io.micrometer.core.instrument.Metrics; -import java.util.UUID; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.Flow; -import javax.annotation.Nullable; -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscription; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import reactor.core.observability.micrometer.Micrometer; -import reactor.core.publisher.BaseSubscriber; -import reactor.core.publisher.Flux; - -/// A Redis/DynamoDB message publisher produces an optionally-terminating stream of messages for a specific device. It -/// listens for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its -/// subscriber when available. -/// -/// This publisher supports only a single subscriber. It assumes that subscribers acknowledge (delete) messages as they -/// read the messages, and may emit duplicate messages if subscribers do not acknowledge messages before requesting more -/// messages. -class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow.Publisher { - - private final MessagesDynamoDb messagesDynamoDb; - private final MessagesCache messagesCache; - private final RedisMessageAvailabilityManager redisMessageAvailabilityManager; - - private final UUID accountIdentifier; - private final Device device; - - private final boolean terminateOnQueueEmpty; - - // Indicates which data source(s) we think might contain messages for the destination device. Messages initially land - // in Redis, but are eventually "persisted" to DynamoDB. This state changes in response to signals this publisher - // receives as a MessageAvailabilityListener. As an initial state, we assume that we have messages in both DynamoDB - // and Redis. - private StoredMessageState storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE; - - // Indicates whether we've sent an "initial queue drain complete" signal to subscribers. This state will transition - // from "not ready" to "pending" as soon as the initial message source subscription completes, and then from "pending" - // to "send" when the signal has been sent. This state will never roll backwards. - private QueueEmptySignalState queueEmptySignalState = QueueEmptySignalState.NOT_READY; - - // The total requested demand from the subscriber across the whole lifetime of this publisher - private long requestedDemand = 0; - - // The total number of signals (new messages or "queue empty" signals) published during the lifetime of this - // publisher. Must not exceed `requestedDemand`. - private long publishedEntries = 0; - - // The total number of published signals that have been acknowledged by the subscriber; to avoid re-reading messages, - // we should never start a new message source subscriber until `acknowledgedEntries` is equal to `publishedEntries` - private long acknowledgedEntries = 0; - - // Although technically nullable, operation of this publisher really begins once we get a subscriber. This publisher - // supports only a single subscriber. - @Nullable private Flow.Subscriber subscriber; - - // If terminated (i.e. by an error or by downstream cancellation), this publisher will stop emitting signals. Once - // terminated, a publisher cannot be un-terminated. - private boolean terminated = false; - - // A message source subscriber subscribes to messages from upstream data sources (i.e. DynamoDB and Redis), and this - // publisher relays signals the message source subscriber to the downstream subscriber. The message source subscriber - // may be null if we're not actively fetching messages from an upstream source and changes every time an upstream - // publisher completes. - @Nullable private MessageSourceSubscriber messageSourceSubscriber; - - private static final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = - name(RedisDynamoDbMessagePublisher.class, "getMessagesForDevice"); - - private enum StoredMessageState { - // Indicates that stored messages are available in at least DynamoDB and possibly also Redis - PERSISTED_NEW_MESSAGES_AVAILABLE, - - // Indicates that messages are available in Redis, but have not yet been persisted to DynamoDB - CACHED_NEW_MESSAGES_AVAILABLE, - - // Indicates that no new messages are available in either Redis or DynamoDB - EMPTY - } - - private enum QueueEmptySignalState { - // Indicates that we are not yet ready to send the "initial queue drain complete" signal regardless of outstanding - // demand - NOT_READY, - - // Indicates that we are ready to send the "queue empty" signal as soon as demand is available - PENDING, - - // Indicates that we have sent the "queue empty" signal and must never send it again - SENT - } - - /// A message source subscriber subscribes to upstream message source publishers and relays signals to the downstream - /// subscriber via the parent `RedisDynamoDbMessagePublisher`. - private static class MessageSourceSubscriber extends BaseSubscriber { - - private final RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher; - - private MessageSourceSubscriber(RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher) { - this.redisDynamoDbMessagePublisher = redisDynamoDbMessagePublisher; - } - - @Override - protected void hookOnSubscribe(final Subscription subscription) { - redisDynamoDbMessagePublisher.handleMessageSourceSubscribed(subscription); - } - - @Override - protected void hookOnNext(final MessageProtos.Envelope message) { - redisDynamoDbMessagePublisher.handleNextMessage(message); - } - - @Override - protected void hookOnComplete() { - redisDynamoDbMessagePublisher.handleMessageSourceComplete(); - } - - @Override - protected void hookOnError(final Throwable throwable) { - redisDynamoDbMessagePublisher.handleMessageSourceError(throwable); - } - } - - RedisDynamoDbMessagePublisher(final MessagesDynamoDb messagesDynamoDb, - final MessagesCache messagesCache, - final RedisMessageAvailabilityManager redisMessageAvailabilityManager, - final UUID accountIdentifier, - final Device device, - final boolean terminateOnQueueEmpty) { - - this.messagesDynamoDb = messagesDynamoDb; - this.messagesCache = messagesCache; - this.redisMessageAvailabilityManager = redisMessageAvailabilityManager; - this.accountIdentifier = accountIdentifier; - this.device = device; - this.terminateOnQueueEmpty = terminateOnQueueEmpty; - } - - @Override - public synchronized void subscribe(final Flow.Subscriber subscriber) { - if (this.subscriber != null) { - subscriber.onError(new IllegalStateException("Redis/DynamoDB message publisher only allows one subscriber")); - return; - } - - this.subscriber = subscriber; - - @Nullable final CompletionStage clientConnectedFuture; - - if (!terminateOnQueueEmpty) { - // If we're trying to follow a live stream of messages, then listen for signals indicating that new messages are - // available in Redis, that messages have been persisted from Redis to DynamoDB, or that there's a conflicting - // message reader connected somewhere else - clientConnectedFuture = redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this); - } else { - clientConnectedFuture = null; - } - - subscriber.onSubscribe(new Flow.Subscription() { - @Override - public void request(final long n) { - addDemand(n); - } - - @Override - public void cancel() { - terminate(); - } - }); - - // Defer the client connected handling until after onSubscribe() is called. Otherwise, onError() might be called - // first, which violates the Reactive Streams spec. - if (clientConnectedFuture != null) { - clientConnectedFuture.whenComplete((_, throwable) -> { - if (throwable != null) { - handleMessageSourceError(throwable); - } - }); - } - } - - @Override - public synchronized void handleNewMessageAvailable() { - // We only need to take action if we think there aren't already messages to pass downstream. Any other stored - // message state implies that we're either actively sending messages downstream or we're waiting for demand from the - // downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when - // we receive a request for more messages or when the current upstream publisher completes. - if (storedMessageState == StoredMessageState.EMPTY) { - storedMessageState = StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE; - maybeGenerateMessageSource(); - } - } - - @Override - public synchronized void handleMessagesPersisted() { - // We only need to take action if we think there aren't already messages in DynamoDB. If we're already aware of - // messages in DynamoDB, then we're either actively sending messages downstream or we're waiting for demand from the - // downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when - // we receive a request for more messages or when the current upstream publisher completes. - if (storedMessageState != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE) { - storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE; - maybeGenerateMessageSource(); - } - } - - @Override - public synchronized void handleConflictingMessageConsumer() { - // We don't register as a listener for conflicting consumer signals until we have a subscriber - assert subscriber != null; - - if (!terminated) { - terminate(); - subscriber.onError(new ConflictingMessageConsumerException()); - } - } - - synchronized void handleMessageAcknowledged() { - acknowledgedEntries += 1; - - if (!terminated) { - // As a temporary migration measure, we may receive additional acknowledgements after the stream has terminated - // (i.e. we're mirroring deletions from FoundationDB) - assert acknowledgedEntries <= publishedEntries; - - maybeGenerateMessageSource(); - } - } - - private synchronized boolean maybeSendQueueEmptySignal() { - // Regardless of any other state, don't do anything if terminated - if (terminated) { - return false; - } - - // Don't send a "queue empty" signal if we're supposed to terminate when the queue is empty - if (terminateOnQueueEmpty) { - return false; - } - - // The machinery that produces messages won't activate until we have a subscriber - assert subscriber != null; - - if (queueEmptySignalState == QueueEmptySignalState.PENDING && publishedEntries < requestedDemand) { - queueEmptySignalState = QueueEmptySignalState.SENT; - publishedEntries += 1; - - // Subscribers don't explicitly acknowledge "queue empty" signals, and we can consider them automatically - // acknowledged - acknowledgedEntries += 1; - - subscriber.onNext(new MessageStreamEntry.QueueEmpty()); - - assert publishedEntries <= requestedDemand; - assert acknowledgedEntries <= publishedEntries; - - return true; - } - - return false; - } - - private synchronized void maybeGenerateMessageSource() { - if (terminated) { - // Regardless of any other state, don't do anything if terminated - return; - } - - if (messageSourceSubscriber != null) { - // We're still working through a previous message source; wait until it completes before starting a new one. - return; - } - - if (acknowledgedEntries < publishedEntries) { - // To avoid double-reading messages from data stores that don't support cursors, don't get a new message source - // unless all previously-published signals have been acknowledged (when messages are acknowledged, we'll come back - // to this point with a higher value for `acknowledgedEntries` via `handleMessageAcknowledged`) - return; - } - - if (terminateOnQueueEmpty && queueEmptySignalState == QueueEmptySignalState.PENDING) { - // If we've acknowledged everything we've published and we're ready to send a "queue empty" signal, we can use the - // "ready to send a 'queue empty' signal" state as our cue to terminate the subscription - assert subscriber != null; - - subscriber.onComplete(); - terminate(); - - return; - } - - if (storedMessageState == StoredMessageState.EMPTY) { - // We don't think there are any messages in either message source; don't do anything until the situation changes - // (when new messages arrive, we'll come back to this point with a non-empty stored message state) - return; - } - - if (publishedEntries == requestedDemand) { - // Even if there are messages available, there's no demand for them yet (when there's new demand, we'll come back - // to this point with a higher value for `requestedDemand` via `addDemand`) - return; - } - - // We maybe be able to skip reading from DynamoDB entirely if we think messages are only stored in Redis - final Publisher dynamoPublisher = - storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE - ? messagesDynamoDb.load(accountIdentifier, device, null) - : Flux.empty(); - - final Publisher redisPublisher = messagesCache.get(accountIdentifier, device.getId()); - - final Flux messageSource = Flux.concat(dynamoPublisher, redisPublisher) - .name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME) - .tap(Micrometer.metrics(Metrics.globalRegistry)); - - messageSourceSubscriber = new MessageSourceSubscriber(this); - messageSource.subscribe(messageSourceSubscriber); - - // If nothing else happens before the DynamoDB/Redis publisher completes, then we'll have emptied all stored - // messages; new signals about persisted messages or newly-arrived messages will change this state - storedMessageState = StoredMessageState.EMPTY; - } - - private synchronized void handleMessageSourceSubscribed(final Subscription subscription) { - if (!terminated) { - // If we already have some unmet demand, pass that on to the upstream publisher immediately on subscribing - if (requestedDemand > publishedEntries) { - subscription.request(requestedDemand - publishedEntries); - } - } - } - - private synchronized void handleNextMessage(final MessageProtos.Envelope message) { - // The machinery that produces messages won't activate until we have a subscriber - assert subscriber != null; - - if (!terminated) { - // We only pass along unfulfilled demand to the message source subscriber, so if the message source subscriber - // emits a new signal, it should fit within the unfulfilled demand from the downstream subscriber - assert publishedEntries < requestedDemand; - - publishedEntries += 1; - subscriber.onNext(new MessageStreamEntry.Envelope(message)); - } - } - - private synchronized void handleMessageSourceComplete() { - // The machinery that produces messages won't activate until we have a subscriber - assert subscriber != null; - - messageSourceSubscriber = null; - - if (queueEmptySignalState == QueueEmptySignalState.NOT_READY) { - queueEmptySignalState = QueueEmptySignalState.PENDING; - maybeSendQueueEmptySignal(); - } - - // New messages may have arrived already; fetch them if possible - maybeGenerateMessageSource(); - } - - private synchronized void handleMessageSourceError(final Throwable throwable) { - // The machinery that produces messages won't activate until we have a subscriber - assert subscriber != null; - - if (!terminated) { - terminate(); - subscriber.onError(throwable); - } - } - - private synchronized void addDemand(final long demand) { - if (demand <= 0) { - throw new IllegalArgumentException("Demand must be positive"); - } - - requestedDemand += demand; - - final boolean sentQueueEmptySignal = maybeSendQueueEmptySignal(); - - // This is a little tricky; if we already have a subscriber, we only want to request NEW demand, not the total - // outstanding demand. On top of that, we may have consumed some demand by sending a "queue empty" message. - final long newDemand = demand - (sentQueueEmptySignal ? 1 : 0); - - if (newDemand > 0) { - if (messageSourceSubscriber != null) { - messageSourceSubscriber.request(newDemand); - } else { - maybeGenerateMessageSource(); - } - } - } - - private synchronized void terminate() { - if (!terminated) { - terminated = true; - - if (messageSourceSubscriber != null) { - messageSourceSubscriber.dispose(); - messageSourceSubscriber = null; - } - - // Stop receiving signals about new messages/conflicting consumers - redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId(), this); - } - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStream.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStream.java deleted file mode 100644 index ee179bd51..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStream.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Flow; -import com.google.common.annotations.VisibleForTesting; -import io.micrometer.core.instrument.Metrics; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import org.whispersystems.textsecuregcm.util.Util; -import reactor.adapter.JdkFlowAdapter; - -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - -/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store. -public class RedisDynamoDbMessageStream implements MessageStream { - - private final MessagesDynamoDb messagesDynamoDb; - private final MessagesCache messagesCache; - - private final UUID accountIdentifier; - private final Device device; - - private final RedisDynamoDbMessagePublisher messagePublisher; - - private static final String MESSAGE_READ_COUNTER_NAME = - name(RedisDynamoDbMessageStream.class, "messagesRead"); - - private static final String MESSAGE_ACKNOWLEDGED_COUNTER_NAME = - name(RedisDynamoDbMessageStream.class, "messagesAcknowledged"); - - private static final String UUID_VERSION_TAG = "uuidVersion"; - - public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb, - final MessagesCache messagesCache, - final RedisMessageAvailabilityManager redisMessageAvailabilityManager, - final UUID accountIdentifier, - final Device device, - final boolean terminateOnQueueEmpty) { - - this(messagesDynamoDb, messagesCache, accountIdentifier, device, new RedisDynamoDbMessagePublisher(messagesDynamoDb, - messagesCache, - redisMessageAvailabilityManager, - accountIdentifier, - device, - terminateOnQueueEmpty)); - } - - @VisibleForTesting - RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb, - final MessagesCache messagesCache, - final UUID accountIdentifier, - final Device device, - final RedisDynamoDbMessagePublisher messagePublisher) { - - this.messagesDynamoDb = messagesDynamoDb; - this.messagesCache = messagesCache; - this.accountIdentifier = accountIdentifier; - this.device = device; - this.messagePublisher = messagePublisher; - } - - @Override - public Flow.Publisher getMessages() { - return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(messagePublisher) - .doOnNext(messageStreamEntry -> { - if (messageStreamEntry instanceof MessageStreamEntry.Envelope(org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope message)) { - final UUID messageGuid = UUIDUtil.fromByteString(message.getServerGuid()); - - Metrics.counter(MESSAGE_READ_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version())) - .increment(); - } - })); - } - - @Override - public CompletableFuture acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) { - Metrics.counter(MESSAGE_ACKNOWLEDGED_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version())) - .increment(); - - return messagesCache.remove(accountIdentifier, device.getId(), messageGuid) - .thenCompose(removed -> removed.map(_ -> CompletableFuture.completedFuture(null)) - .orElseGet(() -> - messagesDynamoDb.deleteMessage(accountIdentifier, device, messageGuid, serverTimestamp) - .thenRun(Util.NOOP))) - .whenComplete((_, _) -> messagePublisher.handleMessageAcknowledged()); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index aba78714c..0dc263aa4 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -53,7 +53,6 @@ import org.whispersystems.textsecuregcm.push.APNSender; import org.whispersystems.textsecuregcm.push.FcmSender; import org.whispersystems.textsecuregcm.push.PushNotificationManager; import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient; import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient; @@ -68,7 +67,6 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbRecoveryManager; import org.whispersystems.textsecuregcm.storage.FoundationDbVersion; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.KeysManager; -import org.whispersystems.textsecuregcm.storage.MessagesCache; import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb; import org.whispersystems.textsecuregcm.storage.MessagesManager; import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore; @@ -110,7 +108,6 @@ public record CommandDependencies( AccountsManager accountsManager, ProfilesManager profilesManager, ReportMessageManager reportMessageManager, - MessagesCache messagesCache, MessagesManager messagesManager, KeysManager keysManager, PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager, @@ -330,8 +327,6 @@ public record CommandDependencies( configuration.getDynamoDbTables().getMessages().getTableName(), configuration.getDynamoDbTables().getMessages().getExpiration(), messageDeletionExecutor); - FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration() - .getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder); FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters", redisClientResourcesBuilder); SecureValueRecoveryClient secureValueRecovery2Client = new SecureValueRecoveryClient( @@ -350,8 +345,6 @@ public record CommandDependencies( storageServiceExecutor, retryExecutor, configuration.getSecureStorageServiceConfiguration()); DisconnectionRequestManager disconnectionRequestManager = new DisconnectionRequestManager(pubsubClient, disconnectionRequestListenerExecutor, retryExecutor); - MessagesCache messagesCache = new MessagesCache(messagesCluster, - messageDeliveryScheduler, messageDeletionExecutor, retryExecutor, Clock.systemUTC()); final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch, configuration.getFoundationDbMessagesConfiguration().activeEpoch(), new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(), @@ -367,11 +360,8 @@ public record CommandDependencies( configuration.getReportMessageConfiguration().getReportTtl()); ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster, configuration.getReportMessageConfiguration().getCounterTtl()); - RedisMessageAvailabilityManager redisMessageAvailabilityManager = - new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor); final MessagesManager messagesManager = - new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, - reportMessageManager, messageDeletionExecutor, Clock.systemUTC()); + new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, messageDeletionExecutor, Clock.systemUTC()); AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient, configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName()); PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager = @@ -465,14 +455,12 @@ public record CommandDependencies( environment.lifecycle().manage(apnSender); environment.lifecycle().manage(disconnectionRequestManager); - environment.lifecycle().manage(redisMessageAvailabilityManager); environment.lifecycle().manage(new ManagedAwsCrt()); return new CommandDependencies( accountsManager, profilesManager, reportMessageManager, - messagesCache, messagesManager, keys, phoneNumberRecoveryPasswordsManager, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/MessagePersisterServiceCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/MessagePersisterServiceCommand.java deleted file mode 100644 index 1771cdc7f..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/MessagePersisterServiceCommand.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2023 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.workers; - -import io.dropwizard.core.Application; -import io.dropwizard.core.cli.ServerCommand; -import io.dropwizard.core.server.DefaultServerFactory; -import io.dropwizard.core.setup.Environment; -import io.dropwizard.jetty.HttpsConnectorFactory; -import java.time.Clock; -import java.time.Duration; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import net.sourceforge.argparse4j.inf.Namespace; -import net.sourceforge.argparse4j.inf.Subparser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.WhisperServerConfiguration; -import org.whispersystems.textsecuregcm.metrics.MetricsUtil; -import org.whispersystems.textsecuregcm.storage.MessagePersister; -import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler; -import reactor.core.publisher.Hooks; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; -import javax.annotation.Nullable; - -public class MessagePersisterServiceCommand extends ServerCommand { - - @Nullable - private ExecutorService persistQueueExecutorService; - - @Nullable - private Scheduler persistQueueScheduler; - - private static final String MAX_CONCURRENCY = "maxConcurrency"; - private static final String SCAN_COUNT = "scanCount"; - - private static final Logger logger = LoggerFactory.getLogger(MessagePersisterServiceCommand.class); - - public MessagePersisterServiceCommand() { - super(new Application<>() { - @Override - public void run(WhisperServerConfiguration configuration, Environment environment) { - - } - }, "message-persister-service", - "Starts a persistent service to persist undelivered messages from Redis to Dynamo DB"); - } - - @Override - public void configure(final Subparser subparser) { - super.configure(subparser); - - // This is a deliberate misnomer for consistency with other service commands that expect a worker count - subparser.addArgument("--workers") - .type(Integer.class) - .dest(MAX_CONCURRENCY) - .required(true) - .help("The maximum number of concurrent Redis/DynamoDB operations"); - - subparser.addArgument("--scan-count") - .type(Integer.class) - .dest(SCAN_COUNT) - .required(false) - .setDefault(1024) - .help("The COUNT argument for the Redis SCAN operation that finds message queues"); - } - - @Override - protected void run(Environment environment, Namespace namespace, WhisperServerConfiguration configuration) - throws Exception { - - UncaughtExceptionHandler.register(); - Hooks.onErrorDropped(e -> logger.warn("Dropped message persistence error", e)); - - final CommandDependencies deps = CommandDependencies.build("message-persister-service", environment, configuration); - MetricsUtil.configureRegistries(configuration, environment, deps.dynamicConfigurationManager()); - - if (configuration.getServerFactory() instanceof DefaultServerFactory defaultServerFactory) { - defaultServerFactory.getApplicationConnectors() - .forEach(connectorFactory -> { - if (connectorFactory instanceof HttpsConnectorFactory h) { - h.setKeyStorePassword(configuration.getTlsKeyStoreConfiguration().password().value()); - } - }); - } - - persistQueueExecutorService = Executors.newVirtualThreadPerTaskExecutor(); - persistQueueScheduler = Schedulers.fromExecutorService(persistQueueExecutorService, "persistQueue"); - - final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(), - deps.messagesManager(), - deps.accountsManager(), - deps.dynamicConfigurationManager(), - persistQueueScheduler, - Clock.systemUTC(), - Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()), - namespace.getInt(MAX_CONCURRENCY), - namespace.getInt(SCAN_COUNT)); - - environment.lifecycle().manage(messagePersister); - - super.run(environment, namespace, configuration); - } - - @Override - protected void cleanup() { - super.cleanup(); - - Hooks.resetOnErrorDropped(); - - if (persistQueueScheduler != null) { - persistQueueScheduler.dispose(); - } - - if (persistQueueExecutorService != null) { - persistQueueExecutorService.shutdown(); - } - } -} diff --git a/service/src/main/proto/WebSocketConnectionEvent.proto b/service/src/main/proto/WebSocketConnectionEvent.proto index 7d37cea5b..b95a4f86b 100644 --- a/service/src/main/proto/WebSocketConnectionEvent.proto +++ b/service/src/main/proto/WebSocketConnectionEvent.proto @@ -10,11 +10,10 @@ option java_package = "org.whispersystems.textsecuregcm.push"; option java_multiple_files = true; message ClientEvent { - reserved 3; + reserved 3, 4; oneof event { NewMessageAvailableEvent new_message_available = 1; ClientConnectedEvent client_connected = 2; - MessagesPersistedEvent messages_persisted = 4; } } @@ -30,10 +29,3 @@ message NewMessageAvailableEvent { message ClientConnectedEvent { bytes server_id = 1; } - -/** - * Indicates that messages for the client have been persisted from short-term - * storage to long-term storage. - */ -message MessagesPersistedEvent { -} diff --git a/service/src/main/resources/lua/get_items.lua b/service/src/main/resources/lua/get_items.lua deleted file mode 100644 index 65fa73f3e..000000000 --- a/service/src/main/resources/lua/get_items.lua +++ /dev/null @@ -1,22 +0,0 @@ --- gets messages from a device's queue, up to a given limit --- returns a list of all envelopes and their queue-local IDs - -local queueKey = KEYS[1] -- sorted set of all Envelopes for a device, scored by queue-local ID -local queueLockKey = KEYS[2] -- a key whose presence indicates that the queue is being persisted and must not be read -local limit = ARGV[1] -- [number] the maximum number of messages to return -local afterMessageId = ARGV[2] -- [number] a queue-local ID to exclusively start after, to support pagination. Use -1 to start at the beginning -local bypassLock = ARGV[3] -- [string] whether to bypass the persistence lock (i.e. when fetching messages for persistence) - -if bypassLock ~= "true" then - local locked = redis.call("GET", queueLockKey) - - if locked then - return {} - end -end - -if afterMessageId == "null" or afterMessageId == nil then - return redis.error_reply("ERR afterMessageId is required") -end - -return redis.call("ZRANGE", queueKey, "("..afterMessageId, "+inf", "BYSCORE", "LIMIT", 0, limit, "WITHSCORES") diff --git a/service/src/main/resources/lua/insert_item.lua b/service/src/main/resources/lua/insert_item.lua deleted file mode 100644 index 2d7ccd7a9..000000000 --- a/service/src/main/resources/lua/insert_item.lua +++ /dev/null @@ -1,23 +0,0 @@ --- inserts a message into a device's queue, and updates relevant associated data --- returns a number, the queue-local message ID (useful for testing) - -local queueKey = KEYS[1] -- sorted set of Envelopes for a device, by queue-local ID -local queueMetadataKey = KEYS[2] -- hash of message GUID to queue-local IDs -local eventChannelKey = KEYS[3] -- pub/sub channel for message availability events -local message = ARGV[1] -- [bytes] the Envelope to insert -local guid = ARGV[2] -- [string] the message GUID -local eventPayload = ARGV[3] -- [bytes] a protobuf payload for a "message available" pub/sub event - -if redis.call("HEXISTS", queueMetadataKey, guid) == 1 then - return tonumber(redis.call("HGET", queueMetadataKey, guid)) -end - -local messageId = redis.call("HINCRBY", queueMetadataKey, "counter", 1) - -redis.call("ZADD", queueKey, "NX", messageId, message) - -redis.call("HSET", queueMetadataKey, guid, messageId) -redis.call("EXPIRE", queueKey, 3974400) -- 46 days -redis.call("EXPIRE", queueMetadataKey, 3974400) -- 46 days - -return redis.call("SPUBLISH", eventChannelKey, eventPayload) > 0 diff --git a/service/src/main/resources/lua/insert_shared_multirecipient_message_data.lua b/service/src/main/resources/lua/insert_shared_multirecipient_message_data.lua deleted file mode 100644 index 3fb92c770..000000000 --- a/service/src/main/resources/lua/insert_shared_multirecipient_message_data.lua +++ /dev/null @@ -1,17 +0,0 @@ --- inserts shared multi-recipient message data - -local sharedMrmKey = KEYS[1] -- [string] the key containing the shared MRM data -local mrmData = ARGV[1] -- [bytes] the serialized multi-recipient message data --- the remainder of ARGV is list of recipient keys and view data - -if 1 == redis.call("EXISTS", sharedMrmKey) then - return redis.error_reply("ERR key exists") -end - -redis.call("HSET", sharedMrmKey, "data", mrmData); -redis.call("EXPIRE", sharedMrmKey, 43200) -- 12 hours - --- unpack() fails with "too many results" at very large table sizes, so we loop -for i = 2, #ARGV, 2 do - redis.call("HSET", sharedMrmKey, ARGV[i], ARGV[i + 1]) -end diff --git a/service/src/main/resources/lua/release_node_claim.lua b/service/src/main/resources/lua/release_node_claim.lua deleted file mode 100644 index e50c1552a..000000000 --- a/service/src/main/resources/lua/release_node_claim.lua +++ /dev/null @@ -1,10 +0,0 @@ --- Releases a message persister's claim to a Redis node when a persist-to-DynamoDB run has finished - -local nodeClaimKey = KEYS[1] -- simple string key whose presence indicates a claim on a node -local persisterId = ARGV[1] -- a string identifying the persister that claimed the node - -local claimedByInstanceId = redis.call("GET", nodeClaimKey) - -if persisterId == claimedByInstanceId then - redis.call("DEL", nodeClaimKey) -end diff --git a/service/src/main/resources/lua/remove_item_by_guid.lua b/service/src/main/resources/lua/remove_item_by_guid.lua deleted file mode 100644 index 239289ab0..000000000 --- a/service/src/main/resources/lua/remove_item_by_guid.lua +++ /dev/null @@ -1,32 +0,0 @@ --- removes a list of messages by ID from the cluster, returning the deleted messages --- returns a list of removed envelopes --- Note: content may be absent for MRM messages, and for these messages, the caller must update the sharedMrmKey --- to remove the recipient's reference - -local queueKey = KEYS[1] -- sorted set of Envelopes for a device, by queue-local ID -local queueMetadataKey = KEYS[2] -- hash of message GUID to queue-local IDs -local messageGuids = ARGV -- [list[string]] message GUIDs - -local removedMessages = {} - -for _, guid in ipairs(messageGuids) do - local messageId = redis.call("HGET", queueMetadataKey, guid) - - if messageId then - local envelope = redis.call("ZRANGE", queueKey, messageId, messageId, "BYSCORE", "LIMIT", 0, 1) - - redis.call("ZREMRANGEBYSCORE", queueKey, messageId, messageId) - redis.call("HDEL", queueMetadataKey, guid) - - if envelope and next(envelope) then - table.insert(removedMessages, envelope[1]) - end - end -end - -if (redis.call("ZCARD", queueKey) == 0) then - redis.call("DEL", queueKey) - redis.call("DEL", queueMetadataKey) -end - -return removedMessages diff --git a/service/src/main/resources/lua/remove_queue.lua b/service/src/main/resources/lua/remove_queue.lua deleted file mode 100644 index 68c58047c..000000000 --- a/service/src/main/resources/lua/remove_queue.lua +++ /dev/null @@ -1,27 +0,0 @@ --- incrementally removes a given device's queue and associated data --- returns: a page of messages and scores. --- The messages must be checked for mrmKeys to update. After updating MRM keys, this script must be called again --- with processedMessageGuids. If the returned table is empty, then --- the queue has been fully deleted. - -local queueKey = KEYS[1] -- sorted set of Envelopes for a device, by queue-local ID -local queueMetadataKey = KEYS[2] -- hash of message GUID to queue-local IDs -local limit = ARGV[1] -- the maximum number of messages to return -local processedMessageGuids = { unpack(ARGV, 2) } - -for _, guid in ipairs(processedMessageGuids) do - local messageId = redis.call("HGET", queueMetadataKey, guid) - if messageId then - redis.call("ZREMRANGEBYSCORE", queueKey, messageId, messageId) - redis.call("HDEL", queueMetadataKey, guid) - end -end - -local messages = redis.call("ZRANGE", queueKey, 0, limit-1) - -if #messages == 0 then - redis.call("DEL", queueKey) - redis.call("DEL", queueMetadataKey) -end - -return messages diff --git a/service/src/main/resources/lua/remove_recipient_view_from_mrm_data.lua b/service/src/main/resources/lua/remove_recipient_view_from_mrm_data.lua deleted file mode 100644 index bf91f82a1..000000000 --- a/service/src/main/resources/lua/remove_recipient_view_from_mrm_data.lua +++ /dev/null @@ -1,17 +0,0 @@ --- Removes the given recipient view from the shared MRM data. If the only field remaining after the removal is the --- `data` field, then the key will be deleted - -local sharedMrmKeys = KEYS -- KEYS: list of all keys in a single slot to update -local recipientViewToRemove = ARGV[1] -- the recipient view to remove from the hash - -local keysDeleted = 0 - -for _, sharedMrmKey in ipairs(sharedMrmKeys) do - redis.call("HDEL", sharedMrmKey, recipientViewToRemove) - if redis.call("HLEN", sharedMrmKey) == 1 then - redis.call("DEL", sharedMrmKey) - keysDeleted = keysDeleted + 1 - end -end - -return keysDeleted diff --git a/service/src/main/resources/lua/unlock_queue.lua b/service/src/main/resources/lua/unlock_queue.lua deleted file mode 100644 index 1d1f7243a..000000000 --- a/service/src/main/resources/lua/unlock_queue.lua +++ /dev/null @@ -1,9 +0,0 @@ --- Unlocks a message queue when a persist-to-DynamoDB run has finished and publishes an event notifying listeners that --- messages have been persisted - -local persistInProgressKey = KEYS[1] -- simple string key whose presence indicates a lock -local eventChannelKey = KEYS[2] -- the channel on which to publish the "messages persisted" event -local eventPayload = ARGV[1] -- [bytes] a protobuf payload for a "message persisted" pub/sub event - -redis.call("DEL", persistInProgressKey) -redis.call("SPUBLISH", eventChannelKey, eventPayload) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfigurationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfigurationTest.java index bdab13184..d92ab874c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfigurationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/configuration/dynamic/DynamicConfigurationTest.java @@ -11,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.fasterxml.jackson.core.JsonProcessingException; import com.vdurmont.semver4j.Semver; import java.time.Duration; import java.util.Collections; @@ -35,7 +34,7 @@ class DynamicConfigurationTest { """; @Test - void testParseExperimentConfig() throws JsonProcessingException { + void testParseExperimentConfig() { { final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true"); final DynamicConfiguration emptyConfig = @@ -125,7 +124,7 @@ class DynamicConfigurationTest { } @Test - void testParseE164Experiments() throws JsonProcessingException { + void testParseE164Experiments() { { final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true"); final DynamicConfiguration emptyConfig = @@ -207,7 +206,7 @@ class DynamicConfigurationTest { } @Test - void testParseRemoteDeprecationConfig() throws JsonProcessingException { + void testParseRemoteDeprecationConfig() { { final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true"); final DynamicConfiguration emptyConfig = @@ -246,7 +245,7 @@ class DynamicConfigurationTest { } @Test - void testParsePaymentsConfiguration() throws JsonProcessingException { + void testParsePaymentsConfiguration() { { final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true"); final DynamicConfiguration emptyConfig = @@ -271,7 +270,7 @@ class DynamicConfigurationTest { } @Test - void testParseCaptchaConfiguration() throws JsonProcessingException { + void testParseCaptchaConfiguration() { { final String emptyConfigYaml = "test: true"; @@ -319,7 +318,7 @@ class DynamicConfigurationTest { } @Test - void testParseLimits() throws JsonProcessingException { + void testParseLimits() { final String limitsConfig = REQUIRED_CONFIG.concat(""" limits: rateLimitReset: @@ -334,43 +333,4 @@ class DynamicConfigurationTest { assertThat(resetRateLimiterConfig.bucketSize()).isEqualTo(17); assertThat(resetRateLimiterConfig.permitRegenerationDuration()).isEqualTo(Duration.ofNanos(4_000)); } - - @Test - void testMessagePersister() throws JsonProcessingException { - { - final String emptyConfigYaml = REQUIRED_CONFIG.concat("test: true"); - final DynamicConfiguration emptyConfig = - DynamicConfigurationManager.parseConfiguration(emptyConfigYaml, DynamicConfiguration.class).orElseThrow(); - - assertTrue(emptyConfig.getMessagePersisterConfiguration().isPersistenceEnabled()); - } - - { - final String messagePersisterEnabledYaml = REQUIRED_CONFIG.concat(""" - messagePersister: - persistenceEnabled: true - dedicatedProcessEnabled: true - """); - - final DynamicConfiguration config = - DynamicConfigurationManager.parseConfiguration(messagePersisterEnabledYaml, DynamicConfiguration.class) - .orElseThrow(); - - assertTrue(config.getMessagePersisterConfiguration().isPersistenceEnabled()); - } - - { - final String messagePersisterDisabledYaml = REQUIRED_CONFIG.concat(""" - messagePersister: - persistenceEnabled: false - """); - - final DynamicConfiguration config = - DynamicConfigurationManager.parseConfiguration(messagePersisterDisabledYaml, DynamicConfiguration.class) - .orElseThrow(); - - assertFalse(config.getMessagePersisterConfiguration().isPersistenceEnabled()); - } - } - } 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 e183785c3..c27c4013d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java @@ -5,7 +5,6 @@ package org.whispersystems.textsecuregcm.grpc; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -34,7 +33,6 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; 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; @@ -51,8 +49,6 @@ 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.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; import org.whispersystems.textsecuregcm.storage.Device; @@ -60,7 +56,6 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.DynamoDbExtension; import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension; -import org.whispersystems.textsecuregcm.storage.MessagesCache; import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb; import org.whispersystems.textsecuregcm.storage.MessagesManager; import org.whispersystems.textsecuregcm.storage.ReportMessageManager; @@ -79,9 +74,6 @@ class MessageDispatcherIntegrationTest { @RegisterExtension static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.MESSAGES); - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - @RegisterExtension static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1); @@ -91,8 +83,6 @@ class MessageDispatcherIntegrationTest { private FoundationDbMessageStore foundationDbMessageStore; private MessagesDynamoDb messagesDynamoDb; - private MessagesCache messagesCache; - private RedisMessageAvailabilityManager redisMessageAvailabilityManager; private Account account; private Device device; private MessageDispatcher messageDispatcher; @@ -114,13 +104,9 @@ class MessageDispatcherIntegrationTest { when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration()); - messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC()); messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7), sharedExecutorService); - redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - sharedExecutorService, sharedExecutorService); account = mock(Account.class); device = mock(Device.class); @@ -142,11 +128,9 @@ class MessageDispatcherIntegrationTest { when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(device.getId()).thenReturn(Device.PRIMARY_ID); - redisMessageAvailabilityManager.start(); - messageDispatcher = new MessageDispatcher( mock(ReceiptSender.class), - new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, + new MessagesManager(messagesDynamoDb, foundationDbMessageStore, mock(ReportMessageManager.class), sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), @@ -156,11 +140,6 @@ class MessageDispatcherIntegrationTest { mock(ClientReleaseManager.class)); } - @AfterEach - void tearDown() { - redisMessageAvailabilityManager.stop(); - } - @AfterAll static void afterAll() throws InterruptedException { sharedExecutorService.shutdown(); @@ -181,13 +160,12 @@ class MessageDispatcherIntegrationTest { @ParameterizedTest @CsvSource({ - "207, 173, 77", - "323, 0, 0", - "0, 221, 0", - "0, 0, 87" + "207, 77", + "323, 0", + "0, 87" }) - void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount, final int foundationDbMessageCount) { - final List expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, foundationDbMessageCount); + void testProcessStoredMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) { + final List expectedMessages = fillRandomMessages(dynamoDbMessageCount, foundationDbMessageCount); final Sinks.Many acks = Sinks.many().unicast().onBackpressureBuffer(); final List receivedMessages = messageDispatcher .getMessages(true, null, account, device, acks.asFlux()) @@ -201,11 +179,10 @@ class MessageDispatcherIntegrationTest { @Test void testProcessStoredMessagesMultipleSegments() { - final int persistedMessageCount = 77; - final int cachedMessageCount = 104; + final int dynamoDbMessageCount = 77; - final List expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, 0); - final AtomicInteger remainingMessages = new AtomicInteger(persistedMessageCount + cachedMessageCount); + final List expectedMessages = fillRandomMessages(dynamoDbMessageCount, 0); + final AtomicInteger remainingMessages = new AtomicInteger(dynamoDbMessageCount); final int additionalMessageCount = 67; final Sinks.Many acks = Sinks.many().unicast().onBackpressureBuffer(); @@ -217,10 +194,10 @@ class MessageDispatcherIntegrationTest { acks.tryEmitNext(UUIDUtil.fromByteString(envelope.getServerGuid())); if (remainingMessages.addAndGet(-1) == 60) { sharedExecutorService - .submit(() -> expectedMessages.addAll(fillRandomMessages(0, 0, additionalMessageCount))); + .submit(() -> expectedMessages.addAll(fillRandomMessages( 0, additionalMessageCount))); } }) - .take(persistedMessageCount + cachedMessageCount + additionalMessageCount) + .take(dynamoDbMessageCount + additionalMessageCount) .collectList() .block(Duration.ofSeconds(15)); assertEquals(expectedMessages.size(), receivedMessages.size()); @@ -229,17 +206,14 @@ class MessageDispatcherIntegrationTest { @Test void testProcessStoredMessagesClientClosed() { - final int persistedMessageCount = 207; - final int cachedMessageCount = 173; + final int dynamoDbMessageCount = 207; final Set receivedMessages = Collections.newSetFromMap(new ConcurrentHashMap<>()); - final List expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, 0); + final List expectedMessages = fillRandomMessages(dynamoDbMessageCount, 0); final TestPublisher acks = TestPublisher.create(); final Exception thrown = assertThrows(Exception.class, () -> messageDispatcher .getMessages(true, null, account, device, acks.flux()) .doOnNext(response -> { - assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(), device.getId()), - "Client should not be present until initial queue is cleared"); receivedMessages.add(response.getEnvelope()); acks.error(new IOException("test exception")); }) @@ -248,26 +222,19 @@ class MessageDispatcherIntegrationTest { assertInstanceOf(IOException.class, thrown.getCause()); assertTrue(expectedMessages.containsAll(receivedMessages)); - assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(), device.getId())); } - private List fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount, final int foundationDbMessageCount) { + private List fillRandomMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) { - final List expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount); - for (int i = 0; i < persistedMessageCount; i++) { + final List expectedMessages = new ArrayList<>(dynamoDbMessageCount + foundationDbMessageCount); + + for (int i = 0; i < dynamoDbMessageCount; i++) { final Envelope envelope = generateRandomMessage(UUID.randomUUID()); expectedMessages.add(envelope); } + messagesDynamoDb.store(expectedMessages, account.getAccountIdentifier(), device); - for (int i = 0; i < cachedMessageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final Envelope envelope = generateRandomMessage(messageGuid); - - messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); - expectedMessages.add(envelope); - } - for (int i = 0; i < foundationDbMessageCount; i++) { final Envelope envelope = generateRandomMessage(UUID.randomUUID()) .toBuilder() diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/push/RedisMessageAvailabilityManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/push/RedisMessageAvailabilityManagerTest.java deleted file mode 100644 index 3955c80d0..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/push/RedisMessageAvailabilityManagerTest.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.push; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -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.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.lettuce.core.RedisException; -import io.lettuce.core.cluster.SlotHash; -import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands; -import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import io.lettuce.core.cluster.pubsub.api.async.RedisClusterPubSubAsyncCommands; -import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.stream.IntStream; -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; -import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.storage.Device; -import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture; -import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper; - -@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) -class RedisMessageAvailabilityManagerTest { - - private RedisMessageAvailabilityManager localEventManager; - private RedisMessageAvailabilityManager remoteEventManager; - - private static ExecutorService webSocketConnectionEventExecutor; - private static ExecutorService asyncOperationQueueingExecutor; - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - private static class MessageAvailabilityAdapter implements MessageAvailabilityListener { - - @Override - public void handleNewMessageAvailable() { - } - - @Override - public void handleMessagesPersisted() { - } - - @Override - public void handleConflictingMessageConsumer() { - } - } - - @BeforeAll - static void setUpBeforeAll() { - webSocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor(); - asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor(); - } - - @BeforeEach - void setUp() { - localEventManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - webSocketConnectionEventExecutor, - asyncOperationQueueingExecutor); - - remoteEventManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - webSocketConnectionEventExecutor, - asyncOperationQueueingExecutor); - - localEventManager.start(); - remoteEventManager.start(); - } - - @AfterEach - void tearDown() { - localEventManager.stop(); - remoteEventManager.stop(); - } - - @AfterAll - static void tearDownAfterAll() { - webSocketConnectionEventExecutor.shutdown(); - asyncOperationQueueingExecutor.shutdown(); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void handleClientConnected(final boolean displaceRemotely) throws InterruptedException { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false); - - final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false); - - final AtomicReference firstListener = new AtomicReference<>(); - firstListener.set(new MessageAvailabilityAdapter() { - @Override - public void handleConflictingMessageConsumer() { - synchronized (firstListenerDisplaced) { - localEventManager.handleClientDisconnected(accountIdentifier, deviceId, firstListener.get()); - firstListenerDisplaced.set(true); - firstListenerDisplaced.notifyAll(); - } - } - }); - - localEventManager.handleClientConnected(accountIdentifier, deviceId, firstListener.get()).toCompletableFuture().join(); - - assertFalse(firstListenerDisplaced.get()); - assertFalse(secondListenerDisplaced.get()); - - final RedisMessageAvailabilityManager displacingManager = - displaceRemotely ? remoteEventManager : localEventManager; - - displacingManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() { - @Override - public void handleConflictingMessageConsumer() { - secondListenerDisplaced.set(true); - } - }).toCompletableFuture().join(); - - synchronized (firstListenerDisplaced) { - while (!firstListenerDisplaced.get()) { - firstListenerDisplaced.wait(); - } - } - - assertTrue(firstListenerDisplaced.get()); - assertFalse(secondListenerDisplaced.get()); - assertTrue(displacingManager.isLocallyPresent(accountIdentifier, deviceId)); - } - - @Test - void isLocallyPresent() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - assertFalse(localEventManager.isLocallyPresent(accountIdentifier, deviceId)); - assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId)); - - final MessageAvailabilityAdapter localListener = new MessageAvailabilityAdapter(); - localEventManager.handleClientConnected(accountIdentifier, deviceId, localListener) - .toCompletableFuture() - .join(); - - assertTrue(localEventManager.isLocallyPresent(accountIdentifier, deviceId)); - assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId)); - - localEventManager.handleClientDisconnected(accountIdentifier, deviceId, localListener) - .toCompletableFuture() - .join(); - - assertFalse(localEventManager.isLocallyPresent(accountIdentifier, deviceId)); - assertFalse(remoteEventManager.isLocallyPresent(accountIdentifier, deviceId)); - } - - @Test - void resubscribe() { - @SuppressWarnings("unchecked") final RedisClusterPubSubCommands pubSubCommands = - mock(RedisClusterPubSubCommands.class); - - @SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands pubSubAsyncCommands = - mock(RedisClusterPubSubAsyncCommands.class); - - when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null)); - - final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder() - .binaryPubSubCommands(pubSubCommands) - .binaryPubSubAsyncCommands(pubSubAsyncCommands) - .binaryAsyncCommands(buildBinaryAsyncCommands()) - .build(); - - final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager( - clusterClient, - Runnable::run, - Runnable::run); - - eventManager.start(); - - final UUID firstAccountIdentifier = UUID.randomUUID(); - final byte firstDeviceId = Device.PRIMARY_ID; - final int firstSlot = SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId)); - - final UUID secondAccountIdentifier; - final byte secondDeviceId = firstDeviceId + 1; - - // Make sure that the two subscriptions wind up in different slots - { - UUID candidateIdentifier; - - do { - candidateIdentifier = UUID.randomUUID(); - } while (SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(candidateIdentifier, secondDeviceId)) == firstSlot); - - secondAccountIdentifier = candidateIdentifier; - } - - eventManager.handleClientConnected(firstAccountIdentifier, firstDeviceId, new MessageAvailabilityAdapter()).toCompletableFuture().join(); - eventManager.handleClientConnected(secondAccountIdentifier, secondDeviceId, new MessageAvailabilityAdapter()).toCompletableFuture().join(); - - final int secondSlot = SlotHash.getSlot(RedisMessageAvailabilityManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId)); - - final String firstNodeId = UUID.randomUUID().toString(); - - final RedisClusterNode firstBeforeNode = mock(RedisClusterNode.class); - when(firstBeforeNode.getNodeId()).thenReturn(firstNodeId); - when(firstBeforeNode.getSlots()).thenReturn(IntStream.range(0, SlotHash.SLOT_COUNT).boxed().toList()); - - final RedisClusterNode firstAfterNode = mock(RedisClusterNode.class); - when(firstAfterNode.getNodeId()).thenReturn(firstNodeId); - when(firstAfterNode.getSlots()).thenReturn(IntStream.range(0, SlotHash.SLOT_COUNT) - .filter(slot -> slot != secondSlot) - .boxed() - .toList()); - - final RedisClusterNode secondAfterNode = mock(RedisClusterNode.class); - when(secondAfterNode.getNodeId()).thenReturn(UUID.randomUUID().toString()); - when(secondAfterNode.getSlots()).thenReturn(List.of(secondSlot)); - - eventManager.resubscribe(new ClusterTopologyChangedEvent( - List.of(firstBeforeNode), - List.of(firstAfterNode, secondAfterNode))); - - verify(pubSubCommands).ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId)); - verify(pubSubCommands, never()).ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId)); - } - - @Test - void unsubscribeIfMissingListener() { - @SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands pubSubAsyncCommands = - mock(RedisClusterPubSubAsyncCommands.class); - - when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null)); - - final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder() - .binaryPubSubAsyncCommands(pubSubAsyncCommands) - .binaryAsyncCommands(buildBinaryAsyncCommands()) - .build(); - - final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager( - clusterClient, - Runnable::run, - Runnable::run); - - eventManager.start(); - - final UUID listenerAccountIdentifier = UUID.randomUUID(); - final byte listenerDeviceId = Device.PRIMARY_ID; - - final UUID noListenerAccountIdentifier = UUID.randomUUID(); - final byte noListenerDeviceId = listenerDeviceId + 1; - - eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new MessageAvailabilityAdapter()) - .toCompletableFuture() - .join(); - - eventManager.unsubscribeIfMissingListener( - new RedisMessageAvailabilityManager.AccountAndDeviceIdentifier(listenerAccountIdentifier, listenerDeviceId)); - - eventManager.unsubscribeIfMissingListener( - new RedisMessageAvailabilityManager.AccountAndDeviceIdentifier(noListenerAccountIdentifier, noListenerDeviceId)); - - verify(pubSubAsyncCommands, never()) - .sunsubscribe(RedisMessageAvailabilityManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId)); - - verify(pubSubAsyncCommands) - .sunsubscribe(RedisMessageAvailabilityManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId)); - } - - @Test - void handleClientConnectedSubscribeFailure() { - @SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands pubSubAsyncCommands = - mock(RedisClusterPubSubAsyncCommands.class); - - final RedisException exception = new RedisException("Currently not connected. Commands are rejected."); - when(pubSubAsyncCommands.ssubscribe(any())) - .thenReturn(MockRedisFuture.failedFuture(exception)); - - final RedisAdvancedClusterAsyncCommands binaryAsyncCommands = buildBinaryAsyncCommands(); - - final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder() - .binaryPubSubAsyncCommands(pubSubAsyncCommands) - .binaryAsyncCommands(binaryAsyncCommands) - .build(); - - final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager( - clusterClient, - Runnable::run, - Runnable::run); - - eventManager.start(); - - final CompletionException completionException = assertThrows(CompletionException.class, () -> - eventManager.handleClientConnected(UUID.randomUUID(), Device.PRIMARY_ID, new MessageAvailabilityAdapter()) - .toCompletableFuture() - .join()); - - assertEquals(exception, completionException.getCause()); - - // We shouldn't announce a client connection if we couldn't subscribe to events for that client - verify(binaryAsyncCommands, never()).spublish(any(), any()); - } - - @Test - void handleClientConnectedPublishFailure() { - @SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands pubSubAsyncCommands = - mock(RedisClusterPubSubAsyncCommands.class); - - when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null)); - - @SuppressWarnings("unchecked") final RedisAdvancedClusterAsyncCommands binaryAsyncCommands = - mock(RedisAdvancedClusterAsyncCommands.class); - - when(binaryAsyncCommands.spublish(any(), any())) - .thenReturn(MockRedisFuture.failedFuture(new RedisException("Currently not connected. Commands are rejected."))); - - final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder() - .binaryPubSubAsyncCommands(pubSubAsyncCommands) - .binaryAsyncCommands(binaryAsyncCommands) - .build(); - - final RedisMessageAvailabilityManager eventManager = new RedisMessageAvailabilityManager( - clusterClient, - Runnable::run, - Runnable::run); - - eventManager.start(); - - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - assertDoesNotThrow(() -> eventManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter()) - .toCompletableFuture() - .join()); - - assertTrue(eventManager.isLocallyPresent(accountIdentifier, deviceId)); - } - - private static RedisAdvancedClusterAsyncCommands buildBinaryAsyncCommands() { - @SuppressWarnings("unchecked") final RedisAdvancedClusterAsyncCommands binaryAsyncCommands = - mock(RedisAdvancedClusterAsyncCommands.class); - - when(binaryAsyncCommands.spublish(any(), any())).thenReturn(MockRedisFuture.completedFuture(0L)); - - return binaryAsyncCommands; - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStreamTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStreamTest.java index 0a040d865..492990637 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStreamTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/ConcatenatingMessageStreamTest.java @@ -25,17 +25,17 @@ import reactor.test.StepVerifier; class ConcatenatingMessageStreamTest { - private RedisDynamoDbMessageStream redisDynamoDbMessageStream; + private DynamoDbMessageStream dynamoDbMessageStream; private FoundationDbMessageStream foundationDbMessageStream; private ConcatenatingMessageStream concatenatingMessageStream; @BeforeEach void setUp() { - redisDynamoDbMessageStream = mock(RedisDynamoDbMessageStream.class); + dynamoDbMessageStream = mock(DynamoDbMessageStream.class); foundationDbMessageStream = mock(FoundationDbMessageStream.class); - concatenatingMessageStream = new ConcatenatingMessageStream(redisDynamoDbMessageStream, foundationDbMessageStream); + concatenatingMessageStream = new ConcatenatingMessageStream(dynamoDbMessageStream, foundationDbMessageStream); } @Test @@ -47,7 +47,7 @@ class ConcatenatingMessageStreamTest { .toList(); for (int i = 0; i < messageCount; i++) { - when(redisDynamoDbMessageStream.getMessages()) + when(dynamoDbMessageStream.getMessages()) .thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(messageStreamEntries.subList(0, i)))); when(foundationDbMessageStream.getMessages()) @@ -66,13 +66,13 @@ class ConcatenatingMessageStreamTest { final long serverTimestamp = System.currentTimeMillis(); concatenatingMessageStream.acknowledgeMessage(v4Uuid, serverTimestamp).join(); - verify(redisDynamoDbMessageStream).acknowledgeMessage(v4Uuid, serverTimestamp); + verify(dynamoDbMessageStream).acknowledgeMessage(v4Uuid, serverTimestamp); verify(foundationDbMessageStream, never()).acknowledgeMessage(eq(v4Uuid), anyLong()); final UUID v8Uuid = MessageGuidUtil.generateRandomV8UUID(); concatenatingMessageStream.acknowledgeMessage(v8Uuid, serverTimestamp).join(); - verify(redisDynamoDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp); + verify(dynamoDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp); verify(foundationDbMessageStream).acknowledgeMessage(v8Uuid, serverTimestamp); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStreamTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStreamTest.java similarity index 61% rename from service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStreamTest.java rename to service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStreamTest.java index 44e710d50..2255dce58 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessageStreamTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbMessageStreamTest.java @@ -6,10 +6,8 @@ package org.whispersystems.textsecuregcm.storage; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyByte; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -22,12 +20,10 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.util.UUIDUtil; -class RedisDynamoDbMessageStreamTest { +class DynamoDbMessageStreamTest { private MessagesDynamoDb messagesDynamoDb; - private MessagesCache messagesCache; - - private RedisDynamoDbMessageStream redisDynamoDbMessageStream; + private DynamoDbMessageStream dynamoDbMessageStream; private Device device; @@ -37,22 +33,16 @@ class RedisDynamoDbMessageStreamTest { @BeforeEach void setUp() { messagesDynamoDb = mock(MessagesDynamoDb.class); - messagesCache = mock(MessagesCache.class); device = mock(Device.class); when(device.getId()).thenReturn(DEVICE_ID); - redisDynamoDbMessageStream = new RedisDynamoDbMessageStream(messagesDynamoDb, - messagesCache, + dynamoDbMessageStream = new DynamoDbMessageStream(messagesDynamoDb, ACCOUNT_IDENTIFIER, - device, - mock(RedisDynamoDbMessagePublisher.class)); + device); when(messagesDynamoDb.deleteMessage(any(), any(), any(), anyLong())) .thenReturn(CompletableFuture.completedFuture(Optional.empty())); - - when(messagesCache.remove(any(), anyByte(), any(UUID.class))) - .thenReturn(CompletableFuture.completedFuture(Optional.empty())); } @Test @@ -64,26 +54,11 @@ class RedisDynamoDbMessageStreamTest { when(messagesDynamoDb.deleteMessage(ACCOUNT_IDENTIFIER, device, messageGuid, serverTimestamp)) .thenReturn(CompletableFuture.completedFuture(Optional.of(message))); - redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp).join(); + dynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp).join(); - verify(messagesCache).remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid); verify(messagesDynamoDb).deleteMessage(ACCOUNT_IDENTIFIER, device, messageGuid, serverTimestamp); } - @Test - void acknowledgeMessageRedis() { - final MessageProtos.Envelope message = generateMessage(); - final UUID messageGuid = UUIDUtil.fromByteString(message.getServerGuid()); - - when(messagesCache.remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(RemovedMessage.fromEnvelope(message)))); - - redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, message.getServerTimestamp()).join(); - - verify(messagesCache).remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid); - verify(messagesDynamoDb, never()).deleteMessage(any(), any(), any(), anyLong()); - } - private static MessageProtos.Envelope generateMessage() { return MessageProtos.Envelope.newBuilder() .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java deleted file mode 100644 index e908b1b06..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterIntegrationTest.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Copyright 2013-2021 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import io.micrometer.core.instrument.Tags; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; -import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagePersisterConfiguration; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; -import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; -import org.whispersystems.textsecuregcm.tests.util.DevicesHelper; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.ScanRequest; - -class MessagePersisterIntegrationTest { - - @RegisterExtension - static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.MESSAGES); - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - private Scheduler messageDeliveryScheduler; - private Scheduler persistQueueScheduler; - private ExecutorService messageDeletionExecutorService; - private ExecutorService websocketConnectionEventExecutor; - private ExecutorService asyncOperationQueueingExecutor; - private MessagesCache messagesCache; - private RedisMessageAvailabilityManager redisMessageAvailabilityManager; - private MessagePersister messagePersister; - private Account account; - - private static final Duration PERSIST_DELAY = Duration.ofMinutes(10); - - @BeforeEach - void setUp() throws Exception { - REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> connection.sync().flushall()); - - @SuppressWarnings("unchecked") final DynamicConfigurationManager dynamicConfigurationManager = - mock(DynamicConfigurationManager.class); - - final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class); - - when(dynamicConfiguration.getMessagePersisterConfiguration()) - .thenReturn(new DynamicMessagePersisterConfiguration(true, 1.5, Duration.ofMinutes(5), Duration.ZERO)); - - when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration); - - messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery"); - persistQueueScheduler = Schedulers.newBoundedElastic(10, 10_000, "persistQueue"); - messageDeletionExecutorService = Executors.newSingleThreadExecutor(); - final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(), - DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(14), - messageDeletionExecutorService); - final AccountsManager accountsManager = mock(AccountsManager.class); - - messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, messageDeletionExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC()); - - final MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, - messagesCache, - mock(FoundationDbMessageStore.class), - mock(RedisMessageAvailabilityManager.class), - mock(ReportMessageManager.class), - messageDeletionExecutorService, - Clock.systemUTC()); - - websocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor(); - asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor(); - redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - websocketConnectionEventExecutor, - asyncOperationQueueingExecutor); - - redisMessageAvailabilityManager.start(); - - messagePersister = new MessagePersister(messagesCache, - messagesManager, - accountsManager, - dynamicConfigurationManager, - persistQueueScheduler, - Clock.systemUTC(), - PERSIST_DELAY, - 1, - 1024); - - account = mock(Account.class); - - final UUID accountUuid = UUID.randomUUID(); - - when(account.getNumber()).thenReturn(Optional.of("+18005551234")); - when(account.getAccountIdentifier()).thenReturn(accountUuid); - when(accountsManager.getByAccountIdentifier(accountUuid)).thenReturn(Optional.of(account)); - when(accountsManager.getByAccountIdentifierAsync(accountUuid)).thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(DevicesHelper.createDevice(Device.PRIMARY_ID))); - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - @AfterEach - void tearDown() throws Exception { - messageDeletionExecutorService.shutdown(); - messageDeletionExecutorService.awaitTermination(15, TimeUnit.SECONDS); - - websocketConnectionEventExecutor.shutdown(); - websocketConnectionEventExecutor.awaitTermination(15, TimeUnit.SECONDS); - - asyncOperationQueueingExecutor.shutdown(); - asyncOperationQueueingExecutor.awaitTermination(15, TimeUnit.SECONDS); - - messageDeliveryScheduler.dispose(); - persistQueueScheduler.dispose(); - - redisMessageAvailabilityManager.stop(); - } - - @Test - void testPersistMessages() throws InterruptedException { - - final int messageCount = 377; - final List expectedMessages = new ArrayList<>(messageCount); - final Instant now = Instant.now(); - - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final long timestamp = now.minus(PERSIST_DELAY.multipliedBy(2)).toEpochMilli() + i; - - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, timestamp, false); - - messagesCache.insert(messageGuid, account.getAccountIdentifier(), Device.PRIMARY_ID, message).join(); - expectedMessages.add(message); - } - - final CountDownLatch messagesPersistedLatch = new CountDownLatch(1); - - redisMessageAvailabilityManager.handleClientConnected(account.getAccountIdentifier(), Device.PRIMARY_ID, - new MessageAvailabilityListener() { - @Override - public void handleNewMessageAvailable() { - } - - @Override - public void handleMessagesPersisted() { - messagesPersistedLatch.countDown(); - } - - @Override - public void handleConflictingMessageConsumer() { - } - }) - .toCompletableFuture() - .join(); - - messagePersister.start(); - - assertTrue(messagesPersistedLatch.await(15, TimeUnit.SECONDS)); - - messagePersister.stop(); - - final DynamoDbClient dynamoDB = DYNAMO_DB_EXTENSION.getDynamoDbClient(); - - final List persistedMessages = - dynamoDB.scan(ScanRequest.builder().tableName(Tables.MESSAGES.tableName()).build()).items().stream() - .map(item -> { - try { - return MessagesDynamoDb.convertItemToEnvelope(item); - } catch (InvalidProtocolBufferException e) { - fail("Could not parse stored message", e); - return null; - } - }) - .toList(); - - assertEquals(expectedMessages, persistedMessages); - } - - @Test - void testPersistFirstPageDiscarded() { - final int discardableMessages = MessagePersister.MESSAGE_BATCH_LIMIT * 2; - final int persistableMessages = MessagePersister.MESSAGE_BATCH_LIMIT + 1; - - final Instant now = Instant.now(); - - for (int i = 0; i < discardableMessages; i++) { - final UUID messageGuid = UUID.randomUUID(); - final long timestamp = now.minus(PERSIST_DELAY.multipliedBy(2)).toEpochMilli() + i; - - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, timestamp, true); - - messagesCache.insert(messageGuid, account.getAccountIdentifier(), Device.PRIMARY_ID, message).join(); - } - - final List expectedMessages = new ArrayList<>(persistableMessages); - - for (int i = 0; i < persistableMessages; i++) { - final UUID messageGuid = UUID.randomUUID(); - final long timestamp = now.minus(PERSIST_DELAY.multipliedBy(2)).toEpochMilli() + i; - - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, timestamp, false); - - messagesCache.insert(messageGuid, account.getAccountIdentifier(), Device.PRIMARY_ID, message).join(); - expectedMessages.add(message); - } - - messagePersister.persistQueue(account, account.getDevice(Device.PRIMARY_ID).orElseThrow(), Tags.empty()).block(); - - final DynamoDbClient dynamoDB = DYNAMO_DB_EXTENSION.getDynamoDbClient(); - - final List persistedMessages = - dynamoDB.scan(ScanRequest.builder().tableName(Tables.MESSAGES.tableName()).build()).items().stream() - .map(item -> { - try { - return MessagesDynamoDb.convertItemToEnvelope(item); - } catch (InvalidProtocolBufferException e) { - fail("Could not parse stored message", e); - return null; - } - }) - .toList(); - - assertEquals(expectedMessages, persistedMessages); - assertFalse(messagesCache.hasMessagesAsync(account.getAccountIdentifier(), Device.PRIMARY_ID).join()); - } - - private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, final long serverTimestamp, final boolean ephemeral) { - return MessageProtos.Envelope.newBuilder() - .setClientTimestamp(serverTimestamp * 2) // client timestamp may not be accurate - .setServerTimestamp(serverTimestamp) - .setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256))) - .setType(MessageProtos.Envelope.Type.CIPHERTEXT) - .setServerGuid(UUIDUtil.toByteString(messageGuid)) - .setDestinationServiceId(new AciServiceIdentifier(UUID.randomUUID()).toCompactByteString()) - .setEphemeral(ephemeral) - .build(); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java deleted file mode 100644 index 7d9ab2bc0..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagePersisterTest.java +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Copyright 2013-2020 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyByte; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.whispersystems.textsecuregcm.util.MockUtils.exactly; - -import com.google.protobuf.ByteString; -import io.lettuce.core.RedisException; -import io.lettuce.core.cluster.SlotHash; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import io.micrometer.core.instrument.Tags; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.stream.Stream; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.mockito.ArgumentCaptor; -import org.mockito.stubbing.Answer; -import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; -import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagePersisterConfiguration; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.tests.util.DevicesHelper; -import org.whispersystems.textsecuregcm.util.TestClock; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; -import reactor.util.retry.Retry; -import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException; - -@Timeout(value = 15, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) -class MessagePersisterTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - private ExecutorService sharedExecutorService; - private ScheduledExecutorService resubscribeRetryExecutorService; - private Scheduler messageDeliveryScheduler; - private Scheduler persistQueueScheduler; - private MessagesCache messagesCache; - private MessagesDynamoDb messagesDynamoDb; - private MessagePersister messagePersister; - private AccountsManager accountsManager; - private MessagesManager messagesManager; - private DynamicConfiguration dynamicConfiguration; - - private Account destinationAccount; - - private Answer persistMessagesAnswer; - - private static final TestClock CLOCK = TestClock.pinned(Instant.now()); - - private static final UUID DESTINATION_ACCOUNT_UUID = UUID.randomUUID(); - private static final String DESTINATION_ACCOUNT_NUMBER = "+18005551234"; - private static final byte DESTINATION_DEVICE_ID = 7; - private static final Device DESTINATION_DEVICE = DevicesHelper.createDevice(DESTINATION_DEVICE_ID); - - private static final Duration PERSIST_DELAY = Duration.ofMinutes(5); - - private static final double EXTRA_ROOM_RATIO = 2.0; - - @BeforeEach - void setUp() throws Exception { - - messagesManager = mock(MessagesManager.class); - @SuppressWarnings("unchecked") final DynamicConfigurationManager dynamicConfigurationManager = - mock(DynamicConfigurationManager.class); - - messagesDynamoDb = mock(MessagesDynamoDb.class); - accountsManager = mock(AccountsManager.class); - destinationAccount = mock(Account.class); - - when(accountsManager.getByAccountIdentifier(DESTINATION_ACCOUNT_UUID)).thenReturn(Optional.of(destinationAccount)); - when(accountsManager.getByAccountIdentifierAsync(DESTINATION_ACCOUNT_UUID)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(destinationAccount))); - when(accountsManager.removeDevice(any(), anyByte())) - .thenAnswer(invocation -> accountsManager.getByAccountIdentifier(invocation.getArgument(0)).orElseThrow()); - - when(destinationAccount.getAccountIdentifier()).thenReturn(DESTINATION_ACCOUNT_UUID); - when(destinationAccount.getNumber()).thenReturn(Optional.of(DESTINATION_ACCOUNT_NUMBER)); - when(destinationAccount.getDevice(DESTINATION_DEVICE_ID)).thenReturn(Optional.of(DESTINATION_DEVICE)); - - dynamicConfiguration = mock(DynamicConfiguration.class); - when(dynamicConfiguration.getMessagePersisterConfiguration()) - .thenReturn(new DynamicMessagePersisterConfiguration(true, EXTRA_ROOM_RATIO, Duration.ofHours(1), Duration.ZERO)); - when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration); - - sharedExecutorService = Executors.newSingleThreadExecutor(); - resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor(); - messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery"); - persistQueueScheduler = Schedulers.newBoundedElastic(10, 10_000, "persistQueue"); - messagesCache = spy(new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), CLOCK)); - messagePersister = new MessagePersister(messagesCache, - messagesManager, - accountsManager, - dynamicConfigurationManager, - persistQueueScheduler, - CLOCK, - PERSIST_DELAY, - 1, - 1024, - Retry.backoff(1, Duration.ZERO)); - - when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null)); - - persistMessagesAnswer = invocation -> { - final UUID destinationUuid = invocation.getArgument(0); - final Device destinationDevice = invocation.getArgument(1); - final List messages = invocation.getArgument(2); - - messagesDynamoDb.store(messages, destinationUuid, destinationDevice); - - for (final MessageProtos.Envelope message : messages) { - messagesCache.remove(destinationUuid, destinationDevice.getId(), UUIDUtil.fromByteString(message.getServerGuid())).get(); - } - - return messages.size(); - }; - - when(messagesManager.persistMessages(any(UUID.class), any(), any())).thenAnswer(persistMessagesAnswer); - } - - @AfterEach - void tearDown() throws Exception { - sharedExecutorService.shutdown(); - //noinspection ResultOfMethodCallIgnored - sharedExecutorService.awaitTermination(1, TimeUnit.SECONDS); - - messageDeliveryScheduler.dispose(); - persistQueueScheduler.dispose(); - - resubscribeRetryExecutorService.shutdown(); - //noinspection ResultOfMethodCallIgnored - resubscribeRetryExecutorService.awaitTermination(1, TimeUnit.SECONDS); - } - - @Test - void persistQueue() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - messagePersister.persistQueue(destinationAccount, destinationAccount.getDevice(DESTINATION_DEVICE_ID).orElseThrow(), Tags.empty()) - .block(); - - @SuppressWarnings("unchecked") final ArgumentCaptor> messagesCaptor = - ArgumentCaptor.forClass(List.class); - - verify(messagesDynamoDb, atLeastOnce()) - .store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE)); - - assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum()); - } - - @Test - void persistNextNodeNoQueues() { - assertEquals(0, messagePersister.persistNextNode()); - - verify(accountsManager, never()).getByAccountIdentifier(any(UUID.class)); - } - - @Test - void persistNodeSingleQueue() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - assertEquals(1, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - @SuppressWarnings("unchecked") final ArgumentCaptor> messagesCaptor = - ArgumentCaptor.forClass(List.class); - - verify(messagesDynamoDb, atLeastOnce()) - .store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE)); - - assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum()); - } - - @Test - void persistNodeSingleQueueTooSoon() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, CLOCK.instant()); - - assertEquals(0, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - verify(messagesDynamoDb, never()).store(any(), any(), any()); - } - - @Test - void testPersistNextQueuesMultiplePages() { - final int queueCount = (MessagePersister.QUEUE_BATCH_LIMIT * 3) + 7; - final int messagesPerQueue = 10; - - for (int i = 0; i < queueCount; i++) { - final UUID accountUuid = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final Account account = mock(Account.class); - - when(accountsManager.getByAccountIdentifierAsync(accountUuid)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - - when(account.getAccountIdentifier()).thenReturn(accountUuid); - when(account.getAccountIdentifier()).thenReturn(accountUuid); - when(account.getDevice(anyByte())).thenAnswer(invocation -> Optional.of(DevicesHelper.createDevice(invocation.getArgument(0)))); - - insertMessages(accountUuid, deviceId, messagesPerQueue, CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - } - - final Set persistedNodes = new HashSet<>(); - boolean addedNode; - int queuesPersisted = 0; - - do { - final RedisClusterNode node = - messagesCache.claimNextNodeToPersist(messagePersister.getPersisterId(), Duration.ofHours(1)).orElseThrow(); - - queuesPersisted += messagePersister.persistNode(node); - - messagesCache.releaseNodeClaim(node, messagePersister.getPersisterId()); - addedNode = persistedNodes.add(node); - } while (addedNode); - - assertEquals(queueCount, queuesPersisted); - - @SuppressWarnings("unchecked") final ArgumentCaptor> messagesCaptor = - ArgumentCaptor.forClass(List.class); - - verify(messagesDynamoDb, atLeastOnce()).store(messagesCaptor.capture(), any(UUID.class), any()); - assertEquals(queueCount * messagesPerQueue, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum()); - } - - @Test - void testPersistNodePersistenceDisabled() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - when(dynamicConfiguration.getMessagePersisterConfiguration()) - .thenReturn(new DynamicMessagePersisterConfiguration(false, EXTRA_ROOM_RATIO, Duration.ofHours(1), Duration.ZERO)); - - assertEquals(0, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - verify(messagesDynamoDb, never()).store(any(), any(), any()); - } - - @Test - void testPersistNodeShouldPersistException() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - doReturn(Mono.error(new RedisException("Badness 10,000"))) - .when(messagesCache).getEarliestUndeliveredTimestamp(any(), anyByte()); - - assertEquals(0, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - verify(messagesDynamoDb, never()).store(any(), any(), any()); - } - - @Test - void testPersistNodeShouldPersistExceptionRetry() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - doReturn(Mono.error(new RedisException("Badness 10,000"))) - .doReturn(Mono.fromSupplier(() -> CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1)).toEpochMilli())) - .when(messagesCache).getEarliestUndeliveredTimestamp(any(), anyByte()); - - assertEquals(1, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - @SuppressWarnings("unchecked") final ArgumentCaptor> messagesCaptor = - ArgumentCaptor.forClass(List.class); - - verify(messagesDynamoDb, atLeastOnce()) - .store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE)); - - assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum()); - } - - @Test - void persistNodeAccountNotFound() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - when(accountsManager.getByAccountIdentifierAsync(any())) - .thenReturn(CompletableFuture.completedFuture(Optional.empty())); - - assertEquals(0, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - verify(messagesDynamoDb, never()).store(any(), any(), any()); - } - - @Test - void persistNodeFetchAccountException() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - when(accountsManager.getByAccountIdentifierAsync(any())) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException("Badness 10,000"))); - - assertEquals(0, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - verify(messagesDynamoDb, never()).store(any(), any(), any()); - } - - @Test - void persistNodeFetchAccountExceptionRetry() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - when(accountsManager.getByAccountIdentifierAsync(DESTINATION_ACCOUNT_UUID)) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException("Badness 10,000"))) - .thenReturn(CompletableFuture.completedFuture(Optional.of(destinationAccount))); - - assertEquals(1, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - @SuppressWarnings("unchecked") final ArgumentCaptor> messagesCaptor = - ArgumentCaptor.forClass(List.class); - - verify(messagesDynamoDb, atLeastOnce()) - .store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE)); - - assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum()); - } - - @Test - void persistNodePersistQueueException() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - when(messagesManager.persistMessages(any(), any(), any())) - .thenThrow(new RuntimeException("Badness 10,000")); - - assertEquals(0, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - verify(messagesDynamoDb, never()).store(any(), any(), any()); - } - - @Test - void persistNodePersistQueueExceptionRetry() { - final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, - CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - when(messagesManager.persistMessages(any(), any(), any())) - .thenThrow(new RuntimeException("Badness 10,000")) - .thenAnswer(persistMessagesAnswer); - - assertEquals(1, messagePersister.persistNode( - getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)))); - - @SuppressWarnings("unchecked") final ArgumentCaptor> messagesCaptor = - ArgumentCaptor.forClass(List.class); - - verify(messagesDynamoDb, atLeastOnce()) - .store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE)); - - assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum()); - } - - @Test - void testUnlinkOnFullQueue() { - final int messageCount = 1; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - final Device primary = mock(Device.class); - when(primary.getId()).thenReturn((byte) 1); - when(primary.isPrimary()).thenReturn(true); - when(primary.getFetchesMessages()).thenReturn(true); - - final Device activeA = mock(Device.class); - when(activeA.getId()).thenReturn((byte) 2); - when(activeA.getFetchesMessages()).thenReturn(true); - - final Device inactiveB = mock(Device.class); - final byte inactiveId = 3; - when(inactiveB.getId()).thenReturn(inactiveId); - - final Device inactiveC = mock(Device.class); - when(inactiveC.getId()).thenReturn((byte) 4); - - final Device activeD = mock(Device.class); - when(activeD.getId()).thenReturn((byte) 5); - when(activeD.getFetchesMessages()).thenReturn(true); - - final Device destination = mock(Device.class); - when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID); - - when(destinationAccount.getDevices()) - .thenReturn(List.of(primary, activeA, inactiveB, inactiveC, activeD, destination)); - - when(messagesManager.persistMessages(any(), any(), any())) - .thenThrow(ItemCollectionSizeLimitExceededException.builder().build()); - - assertTimeoutPreemptively(Duration.ofSeconds(1), () -> - messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty()).block()); - - verify(accountsManager, exactly()).removeDevice(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID); - } - - @Test - void testTrimOnFullPrimaryQueue() { - final List cachedMessages = Stream.generate(() -> generateMessage( - DESTINATION_ACCOUNT_UUID, UUID.randomUUID(), CLOCK.instant().getEpochSecond(), ThreadLocalRandom.current().nextInt(100))) - .limit(10) - .toList(); - final long cacheSize = cachedMessages.stream().mapToLong(MessageProtos.Envelope::getSerializedSize).sum(); - for (final MessageProtos.Envelope envelope : cachedMessages) { - messagesCache.insert(UUIDUtil.fromByteString(envelope.getServerGuid()), DESTINATION_ACCOUNT_UUID, Device.PRIMARY_ID, envelope).join(); - } - - final long expectedClearedBytes = (long) (cacheSize * EXTRA_ROOM_RATIO); - - final int persistedMessageCount = 100; - final List persistedMessages = new ArrayList<>(persistedMessageCount); - final List expectedClearedGuids = new ArrayList<>(); - long total = 0L; - for (int i = 0; i < 100; i++) { - final UUID guid = UUID.randomUUID(); - final MessageProtos.Envelope envelope = generateMessage(DESTINATION_ACCOUNT_UUID, guid, CLOCK.instant().getEpochSecond(), 13); - persistedMessages.add(envelope); - if (total < expectedClearedBytes) { - total += envelope.getSerializedSize(); - expectedClearedGuids.add(guid); - } - } - - final Device primary = mock(Device.class); - when(primary.getId()).thenReturn((byte) 1); - when(primary.isPrimary()).thenReturn(true); - when(primary.getFetchesMessages()).thenReturn(true); - when(destinationAccount.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(primary)); - - when(messagesManager.persistMessages(any(UUID.class), any(), anyList())) - .thenThrow(ItemCollectionSizeLimitExceededException.builder().build()); - when(messagesManager.getMessagesForDevice(DESTINATION_ACCOUNT_UUID, primary)) - .thenReturn(Flux.concat( - Flux.fromIterable(persistedMessages), - Flux.fromIterable(cachedMessages))); - when(messagesManager.delete(any(), any(), any(), anyLong())) - .thenReturn(CompletableFuture.completedFuture(Optional.empty())); - - StepVerifier.create(messagePersister.persistQueue(destinationAccount, primary, Tags.empty())) - .expectError(MessagePersistenceException.class) - .verify(); - - verify(messagesManager, times(expectedClearedGuids.size())) - .delete(eq(DESTINATION_ACCOUNT_UUID), eq(primary), argThat(expectedClearedGuids::contains), anyLong()); - verify(messagesManager, never()) - .delete(any(), any(), argThat(guid -> !expectedClearedGuids.contains(guid)), anyLong()); - } - - @Test - void testFailedUnlinkOnFullQueueThrowsForRetry() { - final int messageCount = 1; - - insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1))); - - final Device primary = mock(Device.class); - when(primary.getId()).thenReturn((byte) 1); - when(primary.isPrimary()).thenReturn(true); - when(primary.getFetchesMessages()).thenReturn(true); - - final Device activeA = mock(Device.class); - when(activeA.getId()).thenReturn((byte) 2); - when(activeA.getFetchesMessages()).thenReturn(true); - - final Device inactiveB = mock(Device.class); - final byte inactiveId = 3; - when(inactiveB.getId()).thenReturn(inactiveId); - - final Device inactiveC = mock(Device.class); - when(inactiveC.getId()).thenReturn((byte) 4); - - final Device activeD = mock(Device.class); - when(activeD.getId()).thenReturn((byte) 5); - when(activeD.getFetchesMessages()).thenReturn(true); - - final Device destination = mock(Device.class); - when(destination.getId()).thenReturn(DESTINATION_DEVICE_ID); - - when(destinationAccount.getDevices()).thenReturn(List.of(primary, activeA, inactiveB, inactiveC, activeD, destination)); - - when(messagesManager.persistMessages(any(UUID.class), any(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build()); - when(accountsManager.removeDevice(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID)).thenThrow(new RuntimeException()); - - assertThrows(RuntimeException.class, () -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty()).block()); - } - - private static RedisClusterNode getNodeWithKey(final byte[] key) { - return REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> - connection.getPartitions().stream().filter(node -> node.hasSlot(SlotHash.getSlot(key))).findFirst()) - .orElseThrow(); - } - - private void insertMessages(final UUID accountUuid, final byte deviceId, final int messageCount, - final Instant firstMessageTimestamp) { - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope envelope = generateMessage( - accountUuid, messageGuid, firstMessageTimestamp.toEpochMilli() + i, 256); - messagesCache.insert(messageGuid, accountUuid, deviceId, envelope).join(); - } - } - - private MessageProtos.Envelope generateMessage(UUID accountUuid, UUID messageGuid, long messageTimestamp, int contentSize) { - return MessageProtos.Envelope.newBuilder() - .setDestinationServiceId(new AciServiceIdentifier(accountUuid).toCompactByteString()) - .setClientTimestamp(messageTimestamp) - .setServerTimestamp(messageTimestamp) - .setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(contentSize))) - .setType(MessageProtos.Envelope.Type.CIPHERTEXT) - .setServerGuid(UUIDUtil.toByteString(messageGuid)) - .build(); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScriptTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScriptTest.java deleted file mode 100644 index 0133ddd6f..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheGetItemsScriptTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; - -import io.lettuce.core.RedisCommandExecutionException; -import io.lettuce.core.ScriptOutputType; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ScheduledExecutorService; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.redis.ClusterLuaScript; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.UUIDUtil; - -class MessagesCacheGetItemsScriptTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - @Test - void testCacheGetItemsScript() throws Exception { - final MessagesCacheInsertScript insertScript = new MessagesCacheInsertScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), - mock(ScheduledExecutorService.class)); - - final UUID destinationUuid = UUID.randomUUID(); - final byte deviceId = 1; - final UUID serverGuid = UUID.randomUUID(); - final MessageProtos.Envelope envelope1 = MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(serverGuid)) - .build(); - - insertScript.executeAsync(destinationUuid, deviceId, envelope1).toCompletableFuture().join(); - - final MessagesCacheGetItemsScript getItemsScript = new MessagesCacheGetItemsScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster()); - - final List messageAndScores = getItemsScript.execute(destinationUuid, deviceId, 1, -1, false) - .block(Duration.ofSeconds(1)); - - assertNotNull(messageAndScores); - assertEquals(2, messageAndScores.size()); - final MessageProtos.Envelope resultEnvelope = MessageProtos.Envelope.parseFrom(messageAndScores.getFirst()); - - assertEquals(serverGuid, UUIDUtil.fromByteString(resultEnvelope.getServerGuid())); - } - - @Test - void testCacheGetItemsInvalidParameter() throws Exception { - final ClusterLuaScript getItemsScript = ClusterLuaScript.fromResource(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - "lua/get_items.lua", ScriptOutputType.OBJECT); - - final byte[] fakeKey = new byte[]{1}; - - final Exception e = assertThrows(RedisCommandExecutionException.class, - () -> getItemsScript.executeBinaryReactive(List.of(fakeKey, fakeKey), - List.of("1".getBytes(StandardCharsets.UTF_8))) - .next() - .block(Duration.ofSeconds(1))); - - assertEquals("ERR afterMessageId is required", e.getMessage()); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScriptTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScriptTest.java deleted file mode 100644 index 0c4d3dd8a..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertScriptTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ScheduledExecutorService; -import com.google.protobuf.InvalidProtocolBufferException; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.UUIDUtil; - -class MessagesCacheInsertScriptTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - @Test - void testCacheInsertScript() throws Exception { - final MessagesCacheInsertScript insertScript = - new MessagesCacheInsertScript(REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final UUID destinationUuid = UUID.randomUUID(); - final byte deviceId = 1; - final MessageProtos.Envelope envelope1 = MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) - .build(); - - insertScript.executeAsync(destinationUuid, deviceId, envelope1).toCompletableFuture().join(); - - assertEquals(List.of(envelope1), getStoredMessages(destinationUuid, deviceId)); - - final MessageProtos.Envelope envelope2 = MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) - .build(); - - insertScript.executeAsync(destinationUuid, deviceId, envelope2).toCompletableFuture().join(); - - assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId)); - - insertScript.executeAsync(destinationUuid, deviceId, envelope1).toCompletableFuture().join(); - - assertEquals(List.of(envelope1, envelope2), - getStoredMessages(destinationUuid, deviceId), - "Messages with same GUID should be deduplicated"); - } - - private List getStoredMessages(final UUID destinationUuid, final byte deviceId) throws IOException { - final MessagesCacheGetItemsScript getItemsScript = - new MessagesCacheGetItemsScript(REDIS_CLUSTER_EXTENSION.getRedisCluster()); - - final List queueItems = getItemsScript.execute(destinationUuid, deviceId, 1024, 0, false) - .blockOptional() - .orElseGet(Collections::emptyList); - - final List messages = new ArrayList<>(queueItems.size() / 2); - - for (int i = 0; i < queueItems.size(); i += 2) { - try { - messages.add(MessageProtos.Envelope.parseFrom(queueItems.get(i))); - } catch (final InvalidProtocolBufferException e) { - throw new UncheckedIOException(e); - } - } - - return messages; - } - - @Test - void returnPresence() throws IOException { - final UUID destinationUuid = UUID.randomUUID(); - final byte deviceId = 1; - - final MessagesCacheInsertScript insertScript = - new MessagesCacheInsertScript(REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - assertFalse(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) - .build()) - .toCompletableFuture() - .join()); - - final FaultTolerantPubSubClusterConnection pubSubClusterConnection = - REDIS_CLUSTER_EXTENSION.getRedisCluster().createBinaryPubSubConnection(); - - pubSubClusterConnection.usePubSubConnection(connection -> - connection.sync().ssubscribe(RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, deviceId))); - - assertTrue(insertScript.executeAsync(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) - .build()) - .toCompletableFuture() - .join()); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest.java deleted file mode 100644 index be600ee23..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -import io.lettuce.core.RedisException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ScheduledExecutorService; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.Pair; - -class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - @ParameterizedTest - @MethodSource - void testInsert(final int count, final Map> destinations) throws Exception { - - final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final SealedSenderMultiRecipientMessage multiRecipientMessage = - MessagesCacheTest.generateRandomMrmMessage(destinations); - - final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID()); - insertMrmScript.executeAsync(sharedMrmKey, multiRecipientMessage, new HashSet<>(multiRecipientMessage.getRecipients().values())) - .toCompletableFuture().join(); - - final int totalDevices = destinations.values().stream().mapToInt(List::size).sum(); - final long hashFieldCount = REDIS_CLUSTER_EXTENSION.getRedisCluster() - .withBinaryCluster(conn -> conn.sync().hlen(sharedMrmKey)); - // + 1 because of "data" field - assertEquals(1 + totalDevices, hashFieldCount); - } - - public static List testInsert() { - final Map> singleAccount = Map.of( - new AciServiceIdentifier(UUID.randomUUID()), List.of((byte) 1, (byte) 2)); - - final List testCases = new ArrayList<>(); - testCases.add(Arguments.of(1, singleAccount)); - - for (int j = 1000; j <= 30000; j += 1000) { - - final Map> deviceLists = new HashMap<>(); - final Map> manyAccounts = IntStream.range(0, j) - .mapToObj(i -> { - final int deviceCount = 1 + i % 5; - final List devices = deviceLists.computeIfAbsent(deviceCount, count -> IntStream.rangeClosed(1, count) - .mapToObj(v -> (byte) v) - .toList()); - - return new Pair<>(new AciServiceIdentifier(UUID.randomUUID()), devices); - }) - .collect(Collectors.toMap(Pair::first, Pair::second)); - - testCases.add(Arguments.of(j, manyAccounts)); - } - - return testCases; - } - - @Test - void testInsertUnresolvedRecipient() throws IOException { - final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final AciServiceIdentifier resolvedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - final AciServiceIdentifier unresolvedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - - final Map> destinations = Map.of( - resolvedServiceIdentifier, List.of(Device.PRIMARY_ID), - unresolvedServiceIdentifier, List.of(Device.PRIMARY_ID)); - - final SealedSenderMultiRecipientMessage multiRecipientMessage = - MessagesCacheTest.generateRandomMrmMessage(destinations); - - final Set resolvedRecipients = - multiRecipientMessage.getRecipients().entrySet().stream() - .filter(entry -> entry.getKey().getRawUUID().equals(resolvedServiceIdentifier.uuid())) - .map(Map.Entry::getValue) - .collect(Collectors.toSet()); - - final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID()); - insertMrmScript.executeAsync(sharedMrmKey, multiRecipientMessage, resolvedRecipients) - .toCompletableFuture().join(); - - final long hashFieldCount = REDIS_CLUSTER_EXTENSION.getRedisCluster() - .withBinaryCluster(conn -> conn.sync().hlen(sharedMrmKey)); - - // We expect a single device for the single resolved destination and then the data field - assertEquals(2, hashFieldCount); - } - - @Test - void testInsertDuplicateKey() throws Exception { - final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final SealedSenderMultiRecipientMessage multiRecipientMessage = - MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), Device.PRIMARY_ID); - - final Set resolvedRecipients = - new HashSet<>(multiRecipientMessage.getRecipients().values()); - - final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID()); - insertMrmScript.executeAsync(sharedMrmKey, multiRecipientMessage, resolvedRecipients) - .toCompletableFuture() - .join(); - - final CompletionException completionException = assertThrows(CompletionException.class, - () -> insertMrmScript.executeAsync(sharedMrmKey, - MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), - Device.PRIMARY_ID), resolvedRecipients).toCompletableFuture().join()); - - assertInstanceOf(RedisException.class, completionException.getCause()); - assertTrue(completionException.getCause().getMessage() - .contains(MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.ERROR_KEY_EXISTS)); - } - -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScriptTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScriptTest.java deleted file mode 100644 index 0b48777f1..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveByGuidScriptTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.UUIDUtil; - -class MessagesCacheRemoveByGuidScriptTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - @Test - void testCacheRemoveByGuid() throws Exception { - final MessagesCacheInsertScript insertScript = new MessagesCacheInsertScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), - mock(ScheduledExecutorService.class)); - - final UUID destinationUuid = UUID.randomUUID(); - final byte deviceId = 1; - final UUID serverGuid = UUID.randomUUID(); - final MessageProtos.Envelope envelope1 = MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(serverGuid)) - .build(); - - insertScript.executeAsync(destinationUuid, deviceId, envelope1).toCompletableFuture().join(); - - final MessagesCacheRemoveByGuidScript removeByGuidScript = new MessagesCacheRemoveByGuidScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final List removedMessages = - removeByGuidScript.execute(destinationUuid, deviceId, List.of(serverGuid)) - .toCompletableFuture() - .get(1, TimeUnit.SECONDS); - - assertEquals(1, removedMessages.size()); - - final MessageProtos.Envelope resultMessage = MessageProtos.Envelope.parseFrom(removedMessages.getFirst()); - - assertEquals(serverGuid, UUIDUtil.fromByteString(resultMessage.getServerGuid())); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScriptTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScriptTest.java deleted file mode 100644 index 73329f0a6..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveQueueScriptTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; - -import java.time.Duration; -import java.time.Instant; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ScheduledExecutorService; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.UUIDUtil; - -class MessagesCacheRemoveQueueScriptTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - - @Test - void testCacheRemoveQueueScript() throws Exception { - final MessagesCacheInsertScript insertScript = new MessagesCacheInsertScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), - mock(ScheduledExecutorService.class)); - - final UUID destinationUuid = UUID.randomUUID(); - final byte deviceId = 1; - final MessageProtos.Envelope envelope1 = MessageProtos.Envelope.newBuilder() - .setServerTimestamp(Instant.now().getEpochSecond()) - .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) - .build(); - - insertScript.executeAsync(destinationUuid, deviceId, envelope1).toCompletableFuture().join(); - - final MessagesCacheRemoveQueueScript removeScript = new MessagesCacheRemoveQueueScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster()); - - final List messagesToCheckForMrmKeys = removeScript.execute(destinationUuid, deviceId, - Collections.emptyList()) - .block(Duration.ofSeconds(1)); - - assertEquals(1, messagesToCheckForMrmKeys.size()); - - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScriptTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScriptTest.java deleted file mode 100644 index 252319cb3..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheRemoveRecipientViewFromMrmDataScriptTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2024 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; - -import io.lettuce.core.cluster.SlotHash; -import java.time.Duration; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.ScheduledExecutorService; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.Pair; -import reactor.core.publisher.Flux; -import reactor.util.function.Tuples; - -class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - @ParameterizedTest - @MethodSource - void testUpdateSingleKey(final Map> destinations) throws Exception { - - final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final SealedSenderMultiRecipientMessage multiRecipientMessage = - MessagesCacheTest.generateRandomMrmMessage(destinations); - - final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID()); - insertMrmScript.executeAsync(sharedMrmKey, multiRecipientMessage, new HashSet<>(multiRecipientMessage.getRecipients().values())) - .toCompletableFuture() - .join(); - - final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript = new MessagesCacheRemoveRecipientViewFromMrmDataScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster()); - - final long keysRemoved = Objects.requireNonNull(Flux.fromIterable(destinations.entrySet()) - .flatMap(e -> Flux.fromStream(e.getValue().stream().map(deviceId -> Tuples.of(e.getKey(), deviceId)))) - .flatMap(serviceIdentifierByteTuple -> removeRecipientViewFromMrmDataScript.execute(List.of(sharedMrmKey), - serviceIdentifierByteTuple.getT1(), serviceIdentifierByteTuple.getT2())) - .reduce(Long::sum) - .block(Duration.ofSeconds(35))); - - assertEquals(1, keysRemoved); - - final long keyExists = REDIS_CLUSTER_EXTENSION.getRedisCluster() - .withBinaryCluster(conn -> conn.sync().exists(sharedMrmKey)); - assertEquals(0, keyExists); - } - - public static List>> testUpdateSingleKey() { - final Map> singleAccount = Map.of( - new AciServiceIdentifier(UUID.randomUUID()), List.of((byte) 1, (byte) 2)); - - final List>> testCases = new ArrayList<>(); - testCases.add(singleAccount); - - // Generate a more, from smallish to very large - for (int j = 1000; j <= 81000; j *= 3) { - - final Map> deviceLists = new HashMap<>(); - final Map> manyAccounts = IntStream.range(0, j) - .mapToObj(i -> { - final int deviceCount = 1 + i % 5; - final List devices = deviceLists.computeIfAbsent(deviceCount, count -> IntStream.rangeClosed(1, count) - .mapToObj(v -> (byte) v) - .toList()); - - return new Pair<>(new AciServiceIdentifier(UUID.randomUUID()), devices); - }) - .collect(Collectors.toMap(Pair::first, Pair::second)); - - testCases.add(manyAccounts); - } - - return testCases; - } - - @ParameterizedTest - @ValueSource(ints = {1, 10, 100, 1000, 10000}) - void testUpdateManyKeys(int keyCount) throws Exception { - - final List sharedMrmKeys = new ArrayList<>(keyCount); - final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID()); - final byte deviceId = 1; - - for (int i = 0; i < keyCount; i++) { - - final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster(), mock(ScheduledExecutorService.class)); - - final SealedSenderMultiRecipientMessage multiRecipientMessage = - MessagesCacheTest.generateRandomMrmMessage(serviceIdentifier, deviceId); - - final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID()); - insertMrmScript.executeAsync(sharedMrmKey, - multiRecipientMessage, new HashSet<>(multiRecipientMessage.getRecipients().values())).toCompletableFuture().join(); - - sharedMrmKeys.add(sharedMrmKey); - } - - final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript = new MessagesCacheRemoveRecipientViewFromMrmDataScript( - REDIS_CLUSTER_EXTENSION.getRedisCluster()); - - final long keysRemoved = Objects.requireNonNull(Flux.fromIterable(sharedMrmKeys) - .collectMultimap(SlotHash::getSlot) - .flatMapMany(slotsAndKeys -> Flux.fromIterable(slotsAndKeys.values())) - .flatMap(keys -> removeRecipientViewFromMrmDataScript.execute(keys, serviceIdentifier, deviceId)) - .reduce(Long::sum) - .block(Duration.ofSeconds(5))); - - assertEquals(sharedMrmKeys.size(), keysRemoved); - } - -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheTest.java deleted file mode 100644 index f3affefdb..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesCacheTest.java +++ /dev/null @@ -1,1083 +0,0 @@ -/* - * Copyright 2013 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.atMost; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import io.lettuce.core.RedisCommandTimeoutException; -import io.lettuce.core.RedisFuture; -import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands; -import io.lettuce.core.cluster.api.reactive.RedisAdvancedClusterReactiveCommands; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import io.lettuce.core.protocol.AsyncCommand; -import io.lettuce.core.protocol.RedisCommand; -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneId; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.reactivestreams.Publisher; -import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; -import reactor.test.publisher.TestPublisher; - -class MessagesCacheTest { - - private final Random random = new Random(); - private long serialTimestamp = 0; - - @Nested - class WithRealCluster { - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - private ExecutorService sharedExecutorService; - private ScheduledExecutorService resubscribeRetryExecutorService; - private Scheduler messageDeliveryScheduler; - private MessagesCache messagesCache; - - private static final UUID DESTINATION_UUID = UUID.randomUUID(); - private static final byte DESTINATION_DEVICE_ID = 7; - - private static final Duration NODE_CLAIM_TTL = Duration.ofHours(1); - - @BeforeEach - void setUp() throws Exception { - sharedExecutorService = Executors.newSingleThreadExecutor(); - resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor(); - messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery"); - messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC()); - } - - @AfterEach - void tearDown() throws Exception { - sharedExecutorService.shutdown(); - sharedExecutorService.awaitTermination(1, TimeUnit.SECONDS); - - messageDeliveryScheduler.dispose(); - resubscribeRetryExecutorService.shutdown(); - resubscribeRetryExecutorService.awaitTermination(1, TimeUnit.SECONDS); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testInsert(final boolean sealedSender) { - final UUID messageGuid = UUID.randomUUID(); - assertDoesNotThrow(() -> messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, - generateRandomMessage(messageGuid, sealedSender))).join(); - } - - @Test - void testDoubleInsertGuid() { - final UUID duplicateGuid = UUID.randomUUID(); - final MessageProtos.Envelope duplicateMessage = generateRandomMessage(duplicateGuid, false); - - messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage).join(); - messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage).join(); - - assertEquals(1, messagesCache.getAllMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID, 0, 10, false) - .count() - .blockOptional() - .orElse(0L)); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testRemoveByUUID(final boolean sealedSender) throws Exception { - final UUID messageGuid = UUID.randomUUID(); - - assertEquals(Optional.empty(), - messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageGuid).get(5, TimeUnit.SECONDS)); - - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender); - - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - final Optional maybeRemovedMessage = messagesCache.remove(DESTINATION_UUID, - DESTINATION_DEVICE_ID, messageGuid).get(5, TimeUnit.SECONDS); - - assertEquals(Optional.of(RemovedMessage.fromEnvelope(message)), maybeRemovedMessage); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testRemoveBatchByUUID(final boolean sealedSender) throws Exception { - final int messageCount = 10; - - final List messagesToRemove = new ArrayList<>(messageCount); - final List messagesToPreserve = new ArrayList<>(messageCount); - - for (int i = 0; i < 10; i++) { - messagesToRemove.add(generateRandomMessage(UUID.randomUUID(), sealedSender)); - messagesToPreserve.add(generateRandomMessage(UUID.randomUUID(), sealedSender)); - } - - assertEquals(Collections.emptyList(), messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, - messagesToRemove.stream().map(message -> UUIDUtil.fromByteString(message.getServerGuid())) - .collect(Collectors.toList())).get(5, TimeUnit.SECONDS)); - - for (final MessageProtos.Envelope message : messagesToRemove) { - messagesCache.insert(UUIDUtil.fromByteString(message.getServerGuid()), DESTINATION_UUID, DESTINATION_DEVICE_ID, - message).join(); - } - - for (final MessageProtos.Envelope message : messagesToPreserve) { - messagesCache.insert(UUIDUtil.fromByteString(message.getServerGuid()), DESTINATION_UUID, DESTINATION_DEVICE_ID, - message).join(); - } - - final List removedMessages = messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, - messagesToRemove.stream().map(message -> UUIDUtil.fromByteString(message.getServerGuid())) - .collect(Collectors.toList())).get(5, TimeUnit.SECONDS); - - assertEquals(messagesToRemove.stream().map(RemovedMessage::fromEnvelope).toList(), removedMessages); - assertEquals(messagesToPreserve, get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount)); - } - - @Test - void testHasMessagesAsync() { - assertFalse(messagesCache.hasMessagesAsync(DESTINATION_UUID, DESTINATION_DEVICE_ID).join()); - - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true); - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - - assertTrue(messagesCache.hasMessagesAsync(DESTINATION_UUID, DESTINATION_DEVICE_ID).join()); - } - - @Test - void getOldestTimestamp() { - final int messageCount = 100; - - final List expectedMessages = new ArrayList<>(messageCount); - - long expectedOldestTimestamp = serialTimestamp; - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, i % 2 == 0); - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - assertEquals(expectedOldestTimestamp, - messagesCache.getEarliestUndeliveredTimestamp(DESTINATION_UUID, DESTINATION_DEVICE_ID).block()); - expectedMessages.add(message); - } - - for (final MessageProtos.Envelope message : expectedMessages) { - assertEquals(expectedOldestTimestamp, - messagesCache.getEarliestUndeliveredTimestamp(DESTINATION_UUID, DESTINATION_DEVICE_ID).block()); - messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, UUIDUtil.fromByteString(message.getServerGuid())).join(); - expectedOldestTimestamp += 1; - } - assertNull(messagesCache.getEarliestUndeliveredTimestamp(DESTINATION_UUID, DESTINATION_DEVICE_ID).block()); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testGetMessages(final boolean sealedSender) throws Exception { - final int messageCount = 100; - - final List expectedMessages = new ArrayList<>(messageCount); - - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender); - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - expectedMessages.add(message); - } - - assertEquals(expectedMessages, get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount)); - - messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, - expectedMessages.stream() - .map(MessageProtos.Envelope::getServerGuid) - .map(UUIDUtil::fromByteString) - .collect(Collectors.toList())); - - final UUID message1Guid = UUID.randomUUID(); - final MessageProtos.Envelope message1 = generateRandomMessage(message1Guid, sealedSender); - messagesCache.insert(message1Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message1).join(); - final List get1 = get(DESTINATION_UUID, DESTINATION_DEVICE_ID, - 1); - assertEquals(List.of(message1), get1); - - messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, message1Guid).get(5, TimeUnit.SECONDS); - - final UUID message2Guid = UUID.randomUUID(); - final MessageProtos.Envelope message2 = generateRandomMessage(message2Guid, sealedSender); - - messagesCache.insert(message2Guid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message2).join(); - - assertEquals(List.of(message2), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, 1)); - } - - @Test - void testGetMessagesFirstPageDiscarded() { - final int discardableMessages = MessagesCache.PAGE_SIZE * 2; - final int deliverableMessages = MessagesCache.PAGE_SIZE + 1; - - final Instant now = Instant.now(); - final ServiceIdentifier destinationServiceIdentifier = new AciServiceIdentifier(DESTINATION_UUID); - - for (int i = 0; i < discardableMessages; i++) { - final UUID messageGuid = UUID.randomUUID(); - final long timestamp = now.minus(MessagesCache.MAX_EPHEMERAL_MESSAGE_DELAY.multipliedBy(2)).toEpochMilli() + i; - - final MessageProtos.Envelope message = - generateRandomMessage(messageGuid, destinationServiceIdentifier, true, true, timestamp); - - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - } - - final List expectedMessages = new ArrayList<>(deliverableMessages); - - for (int i = 0; i < deliverableMessages; i++) { - final UUID messageGuid = UUID.randomUUID(); - final long timestamp = now.plusMillis(i).toEpochMilli(); - - final MessageProtos.Envelope message = - generateRandomMessage(messageGuid, destinationServiceIdentifier, true, false, timestamp); - - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - expectedMessages.add(message); - } - - assertEquals(expectedMessages, get(DESTINATION_UUID, DESTINATION_DEVICE_ID, deliverableMessages + discardableMessages)); - } - - @Test - void testGetMessagesLockedForPersistence() { - final int messageCount = 100; - - final List expectedMessages = new ArrayList<>(messageCount); - - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true); - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - expectedMessages.add(message); - } - - messagesCache.lockQueueForPersistence(DESTINATION_UUID, DESTINATION_DEVICE_ID).block(); - - assertTrue(get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount).isEmpty()); - - messagesCache.unlockQueueForPersistence(DESTINATION_UUID, DESTINATION_DEVICE_ID).block(); - - assertEquals(expectedMessages, get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount)); - } - - @Test - void testGetMessagesToPersistLockedForPersistence() { - final int messageCount = 100; - - final List expectedMessages = new ArrayList<>(messageCount); - - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true); - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - expectedMessages.add(message); - } - - messagesCache.lockQueueForPersistence(DESTINATION_UUID, DESTINATION_DEVICE_ID).block(); - - try { - assertEquals(expectedMessages, - Flux.from(messagesCache.getMessagesToPersist(DESTINATION_UUID, DESTINATION_DEVICE_ID)) - .collectList() - .blockOptional() - .orElseThrow()); - } finally { - messagesCache.unlockQueueForPersistence(DESTINATION_UUID, DESTINATION_DEVICE_ID).block(); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testGetMessagesPublisher(final boolean expectStale) throws Exception { - final int messageCount = 214; - - final List expectedMessages = new ArrayList<>(messageCount); - - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, true); - messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, message).join(); - - expectedMessages.add(message); - } - - final UUID ephemeralMessageGuid = UUID.randomUUID(); - final MessageProtos.Envelope ephemeralMessage = generateRandomMessage(ephemeralMessageGuid, true) - .toBuilder().setEphemeral(true).build(); - messagesCache.insert(ephemeralMessageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, ephemeralMessage).join(); - - final Clock cacheClock; - if (expectStale) { - cacheClock = Clock.fixed(Instant.ofEpochMilli(serialTimestamp + 1), - ZoneId.of("Etc/UTC")); - } else { - cacheClock = Clock.fixed( - Instant.ofEpochMilli(serialTimestamp + 1).plus(MessagesCache.MAX_EPHEMERAL_MESSAGE_DELAY), - ZoneId.of("Etc/UTC")); - } - - final MessagesCache messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), cacheClock); - - final List actualMessages = Flux.from( - messagesCache.get(DESTINATION_UUID, DESTINATION_DEVICE_ID)) - .collectList() - .block(Duration.ofSeconds(5)); - - if (expectStale) { - final List expectedAllMessages = new ArrayList<>() {{ - addAll(expectedMessages); - add(ephemeralMessage); - }}; - - assertEquals(expectedAllMessages, actualMessages); - - } else { - assertEquals(expectedMessages, actualMessages); - - // delete all of these messages and call `getAll()`, to confirm that ephemeral messages have been discarded - CompletableFuture.allOf(actualMessages.stream() - .map(message -> messagesCache.remove(DESTINATION_UUID, DESTINATION_DEVICE_ID, - UUIDUtil.fromByteString(message.getServerGuid()))) - .toArray(CompletableFuture[]::new)) - .get(5, TimeUnit.SECONDS); - - final List messages = messagesCache.getAllMessages(DESTINATION_UUID, - DESTINATION_DEVICE_ID, 0, 10, false) - .collectList() - .toFuture().get(5, TimeUnit.SECONDS); - - assertTrue(messages.isEmpty()); - } - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testClearQueueForDevice(final boolean sealedSender) { - final int messageCount = 1000; - - for (final byte deviceId : new byte[]{DESTINATION_DEVICE_ID, DESTINATION_DEVICE_ID + 1}) { - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender); - - messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message).join(); - } - } - - messagesCache.clear(DESTINATION_UUID, DESTINATION_DEVICE_ID).join(); - - assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount)); - assertEquals(messageCount, get(DESTINATION_UUID, (byte) (DESTINATION_DEVICE_ID + 1), messageCount).size()); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testClearQueueForAccount(final boolean sealedSender) { - final int messageCount = 1000; - - for (final byte deviceId : new byte[]{DESTINATION_DEVICE_ID, DESTINATION_DEVICE_ID + 1}) { - for (int i = 0; i < messageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, sealedSender); - - messagesCache.insert(messageGuid, DESTINATION_UUID, deviceId, message).join(); - } - } - - messagesCache.clear(DESTINATION_UUID).join(); - - assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount)); - assertEquals(Collections.emptyList(), get(DESTINATION_UUID, (byte) (DESTINATION_DEVICE_ID + 1), messageCount)); - } - - @Test - void testGetAccountFromQueueName() { - assertEquals(DESTINATION_UUID, - MessagesCache.getAccountUuidFromQueueName( - new String(MessagesCache.getMessageQueueKey(DESTINATION_UUID, DESTINATION_DEVICE_ID), - StandardCharsets.UTF_8))); - } - - @Test - void testGetDeviceIdFromQueueName() { - assertEquals(DESTINATION_DEVICE_ID, - MessagesCache.getDeviceIdFromQueueName( - new String(MessagesCache.getMessageQueueKey(DESTINATION_UUID, DESTINATION_DEVICE_ID), - StandardCharsets.UTF_8))); - } - - @Test - void claimNextNodeToPersist() { - final int partitionCount = - REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> connection.getPartitions().size()); - - final String persisterId = UUID.randomUUID().toString(); - - for (int i = 0; i < partitionCount; i++) { - assertTrue(messagesCache.claimNextNodeToPersist(persisterId, NODE_CLAIM_TTL).isPresent()); - } - - assertTrue(messagesCache.claimNextNodeToPersist(persisterId, NODE_CLAIM_TTL).isEmpty(), - "Should not be able to claim a node when all nodes are already claimed"); - } - - @Test - void claimNextNodeToPersistRotation() { - final int partitionCount = - REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> connection.getPartitions().size()); - - final String persisterId = UUID.randomUUID().toString(); - - final Set claimedNodes = new HashSet<>(); - - for (int i = 0; i < partitionCount; i++) { - final Optional maybeNode = messagesCache.claimNextNodeToPersist(persisterId, NODE_CLAIM_TTL); - assertTrue(maybeNode.isPresent()); - - claimedNodes.add(maybeNode.get()); - messagesCache.releaseNodeClaim(maybeNode.get(), persisterId); - } - - assertEquals(partitionCount, claimedNodes.size(), - "Persisters should cycle through all available partitions when claims are uncontested"); - } - - @Test - void claimNode() { - final RedisClusterNode node = - REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> - connection.getPartitions().stream().findFirst().orElseThrow()); - - final String persisterId = UUID.randomUUID().toString(); - - assertTrue(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL)); - assertFalse(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL), "Should not be able to claim a node twice"); - - messagesCache.releaseNodeClaim(node, persisterId); - assertTrue(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL), "Should be able to claim node after releasing claim"); - } - - @Test - void releaseNodeClaim() { - final RedisClusterNode node = - REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> - connection.getPartitions().stream().findFirst().orElseThrow()); - - final String persisterId = UUID.randomUUID().toString(); - final String competingPersisterId = UUID.randomUUID().toString(); - - messagesCache.claimNode(node, competingPersisterId, NODE_CLAIM_TTL); - - assertFalse(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL), - "Should not be able to claim a node claimed by another persister"); - - messagesCache.releaseNodeClaim(node, persisterId); - assertFalse(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL), - "Should not be able to release/claim a node claimed by another persister"); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testMultiRecipientMessage(final boolean sharedMrmKeyPresent) { - - final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID()); - final byte deviceId = 1; - - final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId); - - final byte[] sharedMrmDataKey; - if (sharedMrmKeyPresent) { - sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm, new HashSet<>(mrm.getRecipients().values())).join(); - } else { - sharedMrmDataKey = "{1}".getBytes(StandardCharsets.UTF_8); - } - - final UUID guid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(guid, destinationServiceId, true) - .toBuilder() - // clear some things added by the helper - .clearServerGuid() - .setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey)) - .clearContent() - .build(); - messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message).join(); - - assertEquals(sharedMrmKeyPresent ? 1 : 0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster() - .withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey))); - - final List messages = get(destinationServiceId.uuid(), deviceId, 1); - - if (!sharedMrmKeyPresent) { - assertTrue(messages.isEmpty()); - - // the discard is purely async, so we just wait for it - assertTimeoutPreemptively(Duration.ofSeconds(1), () -> { - boolean exists; - do { - exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster() - .withBinaryCluster(conn -> - conn.sync().exists(MessagesCache.getMessageQueueKey(destinationServiceId.uuid(), deviceId))); - } while (exists); - }, "Stale MRM message should be deleted asynchronously"); - - } else { - assertEquals(1, messages.size()); - - assertEquals(guid, UUIDUtil.fromByteString(messages.getFirst().getServerGuid())); - assertFalse(messages.getFirst().hasSharedMrmKey()); - final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients() - .get(destinationServiceId.toLibsignal()); - assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray()); - - final Optional removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid) - .join(); - - assertTrue(removedMessage.isPresent()); - assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString())); - } - - assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty()); - - // updating the shared MRM data is purely async, so we just wait for it - assertTimeoutPreemptively(Duration.ofSeconds(1), () -> { - boolean exists; - do { - exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster() - .withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)); - } while (exists); - }, "Shared MRM data should be deleted asynchronously"); - } - - @Test - void testEstimatePersistedQueueSize() { - final UUID destinationUuid = UUID.randomUUID(); - final ServiceIdentifier serviceId = new AciServiceIdentifier(destinationUuid); - final byte deviceId = 1; - - // Should count all non-ephemeral, non-stale message bytes - long expectedQueueSize = 0L; - for (int i = 0; i < 400; i++) { - final MessageProtos.Envelope messageToInsert = switch (i % 4) { - // An MRM message - case 0 -> { - - // First generate a random MRM message - final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(serviceId, deviceId); - final SealedSenderMultiRecipientMessage.Recipient recepient = mrm.getRecipients() - .get(serviceId.toLibsignal()); - - // Calculate the size of a message that has the shared content in it - final MessageProtos.Envelope message = generateRandomMessage(UUID.randomUUID(), serviceId, true) - .toBuilder() - .setContent(ByteString.copyFrom(mrm.messageForRecipient(recepient))) - .build(); - expectedQueueSize += message.getSerializedSize(); - byte[] sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm, new HashSet<>(mrm.getRecipients().values())).join(); - - // Insert the MRM message without the content - yield message - .toBuilder() - .clearContent() - .setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey)) - .build(); - } - - // A stale MRM message - case 1 -> - generateRandomMessage(UUID.randomUUID(), serviceId, true) - .toBuilder() - // clear some things added by the helper - .clearContent() - .setSharedMrmKey(MessagesCache.STALE_MRM_KEY) - .build(); - - // An ephemeral message - case 2 -> generateRandomMessage(UUID.randomUUID(), serviceId, true).toBuilder().setEphemeral(true).build(); - - // A standardard message - case 3 -> { - final MessageProtos.Envelope message = generateRandomMessage(UUID.randomUUID(), serviceId, true); - expectedQueueSize += message.getSerializedSize(); - yield message; - } - - default -> throw new IllegalStateException(); - }; - messagesCache.insert(UUIDUtil.fromByteString(messageToInsert.getServerGuid()), destinationUuid, deviceId, messageToInsert).join(); - } - long actualQueueSize = messagesCache.estimatePersistedQueueSizeBytes(destinationUuid, deviceId).join(); - assertEquals(expectedQueueSize, actualQueueSize); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) { - - final UUID destinationUuid = UUID.randomUUID(); - final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(destinationUuid); - final byte deviceId = 1; - - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope message = generateRandomMessage(messageGuid, - new AciServiceIdentifier(destinationUuid), true); - - messagesCache.insert(messageGuid, destinationUuid, deviceId, message).join(); - - final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId); - - final byte[] sharedMrmDataKey; - if (sharedMrmKeyPresent) { - sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm, new HashSet<>(mrm.getRecipients().values())).join(); - } else { - sharedMrmDataKey = new byte[]{1}; - } - - final UUID mrmMessageGuid = UUID.randomUUID(); - final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, destinationServiceId, true) - .toBuilder() - // clear some things added by the helper - .clearContent() - .setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey)) - .build(); - messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage).join(); - - final List messages = - Flux.from(messagesCache.getMessagesToPersist(destinationUuid, deviceId)) - .collectList() - .blockOptional() - .orElseThrow(); - - if (!sharedMrmKeyPresent) { - assertEquals(1, messages.size()); - } else { - assertEquals(2, messages.size()); - - assertEquals(mrmMessage.toBuilder() - .clearSharedMrmKey() - .setContent(ByteString.copyFrom( - mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal())))) - .build(), - messages.getLast()); - } - - assertEquals(message.toBuilder() - .setServerGuid(UUIDUtil.toByteString(messageGuid)) - .build(), - messages.getFirst()); - } - - private List get(final UUID destinationUuid, final byte destinationDeviceId, - final int messageCount) { - return Flux.from(messagesCache.get(destinationUuid, destinationDeviceId)) - .take(messageCount, true) - .collectList() - .block(); - } - } - - @Nested - class WithMockCluster { - - private MessagesCache messagesCache; - private RedisAdvancedClusterReactiveCommands reactiveCommands; - private RedisAdvancedClusterAsyncCommands asyncCommands; - private Scheduler messageDeliveryScheduler; - - @SuppressWarnings("unchecked") - @BeforeEach - void setup() throws Exception { - reactiveCommands = mock(RedisAdvancedClusterReactiveCommands.class); - asyncCommands = mock(RedisAdvancedClusterAsyncCommands.class); - final FaultTolerantRedisClusterClient mockCluster = RedisClusterHelper.builder() - .binaryReactiveCommands(reactiveCommands) - .binaryAsyncCommands(asyncCommands) - .build(); - - messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery"); - - messagesCache = new MessagesCache(mockCluster, messageDeliveryScheduler, - Executors.newSingleThreadExecutor(), mock(ScheduledExecutorService.class), Clock.systemUTC()); - } - - @AfterEach - void teardown() { - StepVerifier.resetDefaultTimeout(); - messageDeliveryScheduler.dispose(); - } - - @Test - @Disabled("flaky test") - void testGetAllMessagesLimitsAndBackpressure() { - // this test makes sure that we don’t fetch and buffer all messages from the cache when the publisher - // is subscribed. Rather, we should be fetching in pages to satisfy downstream requests, so that memory usage - // is limited to few pages of messages - - // we use a combination of Flux.just() and TestPublishers to control when data is “fetched” and emitted from the - // cache. The initial Flux.just()s are pages that are readily available, on demand. By design, there are more of - // these pages than the initial prefetch. The publishers allow us to create extra demand but defer producing - // values to satisfy the demand until later on. - - final TestPublisher page4Publisher = TestPublisher.create(); - final TestPublisher page56Publisher = TestPublisher.create(); - final TestPublisher emptyFinalPagePublisher = TestPublisher.create(); - - final Deque> pages = new ArrayDeque<>(); - pages.add(generatePage()); - pages.add(generatePage()); - pages.add(generatePage()); - pages.add(generatePage()); - // make sure that stale ephemeral messages are also produced by calls to getAllMessages() - pages.add(generateStaleEphemeralPage()); - pages.add(generatePage()); - - when(reactiveCommands.evalsha(any(), any(), any(), any())) - .thenReturn(Flux.just(pages.pop())) - .thenReturn(Flux.just(pages.pop())) - .thenReturn(Flux.just(pages.pop())) - .thenReturn(Flux.from(page4Publisher)) - .thenReturn(Flux.from(page56Publisher)) - .thenReturn(Flux.from(emptyFinalPagePublisher)) - .thenReturn(Flux.empty()); - - final Flux allMessages = messagesCache.getAllMessages(UUID.randomUUID(), Device.PRIMARY_ID, 0, 10, false); - - // Why initialValue = 3? - // 1. messagesCache.getAllMessages() above produces the first call - // 2. when we subscribe, the prefetch of 1 results in `expand()`, which produces a second call - // 3. there is an implicit “low tide mark” of 1, meaning there will be an extra call to replenish when there is - // 1 value remaining - final AtomicInteger expectedReactiveCommandInvocations = new AtomicInteger(3); - - StepVerifier.setDefaultTimeout(Duration.ofSeconds(5)); - - final int page = 100; - final int halfPage = page / 2; - - // in order to fully control demand and separate the prefetch mechanics, initially subscribe with a request of 0 - StepVerifier.create(allMessages, 0) - .expectSubscription() - .then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.get())).evalsha(any(), any(), - any(), any())) - .thenRequest(halfPage) // page 0.5 requested - .expectNextCount(halfPage) // page 0.5 produced - // page 0.5 produced, 1.5 remain, so no additional interactions with the cache cluster - .then(() -> verify(reactiveCommands, atMost(expectedReactiveCommandInvocations.get())).evalsha(any(), - any(), any(), any())) - .then(page4Publisher::assertWasNotRequested) - .thenRequest(page) // page 1.5 requested - .expectNextCount(page) // page 1.5 produced - - // we now have produced 1.5 pages, have 0.5 buffered, and two more have been prefetched. - // after producing more than a full page, we’ll need to replenish from the cache. - // future requests will depend on sink emitters. - // also NB: times() checks cumulative calls, hence addAndGet - .then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.addAndGet(1))).evalsha(any(), - any(), any(), any())) - .then(page4Publisher::assertWasSubscribed) - .thenRequest(page + halfPage) // page 3 requested - .expectNextCount(page + halfPage) // page 1.5–3 produced - - .thenRequest(halfPage) // page 3.5 requested - .then(page56Publisher::assertWasNotRequested) - .then(() -> page4Publisher.emit(pages.pop())) - .expectNextCount(halfPage) // page 3.5 produced - .then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.addAndGet(1))).evalsha(any(), - any(), any(), any())) - .then(page56Publisher::assertWasSubscribed) - - .thenRequest(page) // page 4.5 requested - .expectNextCount(halfPage) // page 4 produced - - .thenRequest(page * 4) // request more demand than we will ultimately satisfy - - .then(() -> page56Publisher.next(pages.pop()).next(pages.pop()).complete()) - .expectNextCount(page + page) // page 5 and 6 produced - .then(emptyFinalPagePublisher::complete) - // confirm that cache calls increased by 2: one for page 5-and-6 (we got a two-fer in next(pop()).next(pop()), - // and one for the final, empty page - .then(() -> verify(reactiveCommands, times(expectedReactiveCommandInvocations.addAndGet(2))).evalsha(any(), - any(), any(), - any())) - .expectComplete() - .log() - .verify(); - - // make sure that we consumed all the pages, especially in case of refactoring - assertTrue(pages.isEmpty()); - } - - @Test - void testGetDiscardsEphemeralMessages() { - final Deque> pages = new ArrayDeque<>(); - pages.add(generatePage()); - pages.add(generatePage()); - pages.add(generateStaleEphemeralPage()); - - when(reactiveCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) - .thenReturn(Flux.just(pages.pop())) - .thenReturn(Flux.just(pages.pop())) - .thenReturn(Flux.just(pages.pop())) - .thenReturn(Flux.empty()); - - final AsyncCommand removeSuccess = new AsyncCommand<>(mock(RedisCommand.class)); - removeSuccess.complete(); - - when(asyncCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) - .thenReturn((RedisFuture) removeSuccess); - - final Publisher allMessages = messagesCache.get(UUID.randomUUID(), Device.PRIMARY_ID); - - StepVerifier.setDefaultTimeout(Duration.ofSeconds(5)); - - // async commands are used for remove(), and nothing should happen until we are subscribed - verify(asyncCommands, never()).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); - // the reactive commands will be called once, to prep the first page fetch (but no remote request would actually be sent) - verify(reactiveCommands, times(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); - - StepVerifier.create(allMessages) - .expectSubscription() - .expectNextCount(200) - .expectComplete() - .log() - .verify(); - - assertTrue(pages.isEmpty()); - verify(asyncCommands, atLeast(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); - } - - @Test - void testGetRetries() { - final List page = generatePage(); - - final AtomicBoolean emittedError = new AtomicBoolean(false); - final AtomicBoolean emittedPage = new AtomicBoolean(false); - - when(reactiveCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) - .thenReturn(Flux.defer(() -> { - if (emittedError.compareAndSet(false, true)) { - return Flux.error(new RedisCommandTimeoutException("Timeout")); - } else if (emittedPage.compareAndSet(false, true)) { - return Flux.just(page); - } - - return Flux.empty(); - })); - - final AsyncCommand removeSuccess = new AsyncCommand<>(mock(RedisCommand.class)); - removeSuccess.complete(); - - when(asyncCommands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) - .thenReturn((RedisFuture) removeSuccess); - - final Publisher allMessages = messagesCache.get(UUID.randomUUID(), Device.PRIMARY_ID); - - StepVerifier.setDefaultTimeout(Duration.ofSeconds(5)); - - // async commands are used for remove(), and nothing should happen until we are subscribed - verify(asyncCommands, never()).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); - // the reactive commands will be called once, to prep the first page fetch (but no remote request would actually be sent) - verify(reactiveCommands, times(1)).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); - - StepVerifier.create(allMessages) - .expectSubscription() - .expectNextCount(page.size() / 2) - .expectComplete() - .log() - .verify(); - } - - private List generatePage() { - final List messagesAndIds = new ArrayList<>(); - - for (int i = 0; i < 100; i++) { - final MessageProtos.Envelope envelope = generateRandomMessage(UUID.randomUUID(), true); - messagesAndIds.add(envelope.toByteArray()); - messagesAndIds.add(String.valueOf(serialTimestamp).getBytes()); - } - - return messagesAndIds; - } - - private List generateStaleEphemeralPage() { - final List messagesAndIds = new ArrayList<>(); - - for (int i = 0; i < 100; i++) { - final MessageProtos.Envelope envelope = generateRandomMessage(UUID.randomUUID(), true) - .toBuilder().setEphemeral(true).build(); - messagesAndIds.add(envelope.toByteArray()); - messagesAndIds.add(String.valueOf(serialTimestamp).getBytes()); - } - - return messagesAndIds; - } - } - - private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, final boolean sealedSender) { - return generateRandomMessage(messageGuid, new AciServiceIdentifier(UUID.randomUUID()), sealedSender, false, - serialTimestamp++); - } - - private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, - final ServiceIdentifier destinationServiceId, - final boolean sealedSender) { - - return generateRandomMessage(messageGuid, destinationServiceId, sealedSender, false, serialTimestamp++); - } - - private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, - final ServiceIdentifier destinationServiceId, - final boolean sealedSender, - final boolean ephemeral, - final long timestamp) { - final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder() - .setClientTimestamp(timestamp) - .setServerTimestamp(timestamp) - .setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256))) - .setType(MessageProtos.Envelope.Type.CIPHERTEXT) - .setServerGuid(UUIDUtil.toByteString(messageGuid)) - .setDestinationServiceId(destinationServiceId.toCompactByteString()) - .setEphemeral(ephemeral); - - if (!sealedSender) { - envelopeBuilder.setSourceDevice(random.nextInt(Device.MAXIMUM_DEVICE_ID) + 1) - .setSourceServiceId(new AciServiceIdentifier(UUID.randomUUID()).toCompactByteString()); - } - - return envelopeBuilder.build(); - } - - static SealedSenderMultiRecipientMessage generateRandomMrmMessage( - Map> destinations) { - - try { - final ByteBuffer prefix = ByteBuffer.allocate(7); - prefix.put((byte) 0x23); // version - writeVarint(prefix, destinations.size()); // recipient count - prefix.flip(); - - List recipients = new ArrayList<>(destinations.size()); - - for (Map.Entry> serviceIdentifierAndDeviceIds : destinations.entrySet()) { - - final ServiceIdentifier destination = serviceIdentifierAndDeviceIds.getKey(); - final List deviceIds = serviceIdentifierAndDeviceIds.getValue(); - - assert deviceIds.size() < 255; - - final ByteBuffer recipient = ByteBuffer.allocate(17 + 3 * deviceIds.size() + 48); - - recipient.put(destination.toFixedWidthByteArray()); - for (int i = 0; i < deviceIds.size(); i++) { - final int hasMore = i == deviceIds.size() - 1 ? 0x0000 : 0x8000; - recipient.put(new byte[]{deviceIds.get(i)}); // device ID - recipient.putShort((short) ((100 + deviceIds.get(i)) | hasMore)); // registration ID - } - - final byte[] keyMaterial = new byte[48]; - ThreadLocalRandom.current().nextBytes(keyMaterial); - recipient.put(keyMaterial); - - recipients.add(recipient); - } - - final byte[] commonPayload = new byte[64]; - ThreadLocalRandom.current().nextBytes(commonPayload); - - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(prefix.array(), 0, prefix.limit()); - for (ByteBuffer recipient : recipients) { - baos.write(recipient.array()); - } - baos.write(commonPayload); - - return SealedSenderMultiRecipientMessage.parse(baos.toByteArray()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - static SealedSenderMultiRecipientMessage generateRandomMrmMessage(ServiceIdentifier destination, - byte... deviceIds) { - - final Map> destinations = new HashMap<>(); - destinations.put(destination, Arrays.asList(ArrayUtils.toObject(deviceIds))); - return generateRandomMrmMessage(destinations); - } - - private static void writeVarint(ByteBuffer bb, long n) { - while (n >= 0x80) { - bb.put((byte) (n & 0x7F | 0x80)); - n = n >> 7; - } - bb.put((byte) (n & 0x7F)); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java index e18a7ffa8..da23013de 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java @@ -9,8 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyByte; -import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -47,7 +45,6 @@ import org.testcontainers.shaded.org.checkerframework.checker.nullness.qual.Null import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper; import org.whispersystems.textsecuregcm.tests.util.TestRecipient; @@ -57,7 +54,6 @@ import reactor.core.publisher.Mono; class MessagesManagerTest { private MessagesDynamoDb messagesDynamoDb; - private MessagesCache messagesCache; private FoundationDbMessageStore foundationDbMessageStore; private ReportMessageManager reportMessageManager; @@ -68,16 +64,11 @@ class MessagesManagerTest { @BeforeEach void setUp() { messagesDynamoDb = mock(MessagesDynamoDb.class); - messagesCache = mock(MessagesCache.class); foundationDbMessageStore = mock(FoundationDbMessageStore.class); reportMessageManager = mock(ReportMessageManager.class); - when(messagesCache.insert(any(), any(), anyByte(), any())).thenReturn(CompletableFuture.completedFuture(true)); - messagesManager = new MessagesManager(messagesDynamoDb, - messagesCache, foundationDbMessageStore, - mock(RedisMessageAvailabilityManager.class), reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK); @@ -118,7 +109,6 @@ class MessagesManagerTest { verifyNoMoreInteractions(reportMessageManager); verify(foundationDbMessageStore, times(2)).insert(any(), any()); - verify(messagesCache, never()).insert(any(), any(), anyByte(), any()); } @Test @@ -140,11 +130,6 @@ class MessagesManagerTest { assertInstanceOf(RuntimeException.class, completionException.getCause()); verify(foundationDbMessageStore).insert(any(), any()); - verify(messagesCache, never()) - .insert(argThat(messageGuid -> messageGuid.version() == 4), - eq(destinationUuid), - eq(Device.PRIMARY_ID), - any()); } private static UUID generateRandomV8UUID() { @@ -218,9 +203,6 @@ class MessagesManagerTest { final byte[] sharedMrmKey = "shared-mrm-key".getBytes(StandardCharsets.UTF_8); - when(messagesCache.insertSharedMultiRecipientMessagePayload(eq(multiRecipientMessage), any())) - .thenReturn(CompletableFuture.completedFuture(sharedMrmKey)); - final long clientTimestamp = System.currentTimeMillis(); final boolean isStory = ThreadLocalRandom.current().nextBoolean(); final boolean isEphemeral = ThreadLocalRandom.current().nextBoolean(); @@ -241,8 +223,6 @@ class MessagesManagerTest { assertEquals(expectedPresenceByAccountAndDeviceId, messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp, isStory, isEphemeral, isUrgent).join()); - verify(messagesCache, never()).insert(any(), any(), anyByte(), any()); - final Envelope prototypeExpectedFoundationDbMessage = prototypeExpectedMessage.toBuilder().clearSharedMrmKey().build(); verify(foundationDbMessageStore).insert(singleDeviceAccountAciServiceIdentifier, @@ -273,48 +253,38 @@ class MessagesManagerTest { } @CartesianTest - void mayHaveMessages(@CartesianTest.Values(booleans = {true, false}) final boolean hasCachedMessages, - @CartesianTest.Values(booleans = {true, false}) final boolean hasPersistedMessages, + void mayHaveMessages(@CartesianTest.Values(booleans = {true, false}) final boolean hasPersistedMessages, @CartesianTest.Values(booleans = {true, false}) final boolean hasFoundationDbMessages) { final UUID accountIdentifier = UUID.randomUUID(); final Device device = mock(Device.class); when(device.getId()).thenReturn(Device.PRIMARY_ID); - when(messagesCache.hasMessagesAsync(accountIdentifier, Device.PRIMARY_ID)) - .thenReturn(CompletableFuture.completedFuture(hasCachedMessages)); - when(messagesDynamoDb.mayHaveMessages(accountIdentifier, device)) .thenReturn(CompletableFuture.completedFuture(hasPersistedMessages)); when(foundationDbMessageStore.hasMessages(new AciServiceIdentifier(accountIdentifier), Device.PRIMARY_ID)) .thenReturn(CompletableFuture.completedFuture(hasFoundationDbMessages)); - assertEquals(hasCachedMessages || hasPersistedMessages || hasFoundationDbMessages, + assertEquals(hasPersistedMessages || hasFoundationDbMessages, messagesManager.mayHaveMessages(accountIdentifier, device).join()); } @ParameterizedTest @CsvSource({ - ",,,", - "1,,,1", - ",1,,1", - "2,1,,1", - "1,2,,2", - "1,2,3,2", - ",,3,3" + ",,", + "1,,1", + "2,,2", + "2,3,2", + ",3,3" }) - public void oldestMessageTimestamp(@Nullable final Long oldestCached, - @Nullable final Long oldestPersisted, + public void oldestMessageTimestamp(@Nullable final Long oldestPersisted, @Nullable final Long oldestInFoundationDb, @Nullable final Long expected) { final UUID accountIdentifier = UUID.randomUUID(); final Device device = mock(Device.class); when(device.getId()).thenReturn(Device.PRIMARY_ID); - when(messagesCache.getEarliestUndeliveredTimestamp(accountIdentifier, Device.PRIMARY_ID)) - .thenReturn(oldestCached == null ? Mono.empty() : Mono.just(oldestCached)); - when(messagesDynamoDb.load(accountIdentifier, device, 1)) .thenReturn(oldestPersisted == null ? Mono.empty() diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisherTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisherTest.java deleted file mode 100644 index 6a1b33631..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/RedisDynamoDbMessagePublisherTest.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * Copyright 2025 Signal Messenger, LLC - * SPDX-License-Identifier: AGPL-3.0-only - */ - -package org.whispersystems.textsecuregcm.storage; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.protobuf.ByteString; -import java.io.IOException; -import java.time.Clock; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicLong; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; -import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager; -import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; -import org.whispersystems.textsecuregcm.util.UUIDUtil; -import reactor.adapter.JdkFlowAdapter; -import reactor.core.Disposable; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; - -@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) -class RedisDynamoDbMessagePublisherTest { - - private MessagesDynamoDb messagesDynamoDb; - private MessagesCache messagesCache; - private RedisMessageAvailabilityManager redisMessageAvailabilityManager; - - private static ExecutorService sharedExecutorService; - private static Scheduler messageDeliveryScheduler; - - private Device destinationDevice; - - @RegisterExtension - static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.MESSAGES); - - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - - private static final AtomicLong SERIAL_TIMESTAMP = new AtomicLong(0); - - private static final ServiceIdentifier DESTINATION_SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID()); - - @BeforeAll - static void setUpBeforeAll() { - sharedExecutorService = Executors.newVirtualThreadPerTaskExecutor(); - messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery"); - } - - @BeforeEach - void setUp() throws IOException { - messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(), - DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), - DynamoDbExtensionSchema.Tables.MESSAGES.tableName(), - Duration.ofDays(14), - sharedExecutorService); - - messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC()); - - redisMessageAvailabilityManager = mock(RedisMessageAvailabilityManager.class); - - destinationDevice = mock(Device.class); - when(destinationDevice.getId()).thenReturn(Device.PRIMARY_ID); - when(destinationDevice.getCreated()).thenReturn(System.currentTimeMillis()); - } - - @AfterAll - static void tearDownAfterAll() { - sharedExecutorService.shutdown(); - messageDeliveryScheduler.dispose(); - } - - @Test - void subscribeDispose() { - final byte deviceId = Device.PRIMARY_ID; - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(deviceId); - when(device.getCreated()).thenReturn(System.currentTimeMillis()); - - { - final UUID accountIdentifier = UUID.randomUUID(); - - final RedisDynamoDbMessagePublisher _ = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device, false); - - verify(redisMessageAvailabilityManager, never()).handleClientConnected(eq(accountIdentifier), eq(deviceId), any()); - verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId), any()); - } - - { - final UUID accountIdentifier = UUID.randomUUID(); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device, false); - - JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe(); - - verify(redisMessageAvailabilityManager).handleClientConnected(eq(accountIdentifier), eq(deviceId), any()); - verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId), any()); - } - - { - final UUID accountIdentifier = UUID.randomUUID(); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device, false); - - final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe(); - disposable.dispose(); - - verify(redisMessageAvailabilityManager).handleClientConnected(eq(accountIdentifier), eq(deviceId), any()); - verify(redisMessageAvailabilityManager).handleClientDisconnected(eq(accountIdentifier), eq(deviceId), any()); - } - } - - @Test - void publishMessages() { - final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage()); - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)) - .expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage)) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - - @Test - void publishMessagesTerminateOnEmpty() { - final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage()); - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, true); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)) - .expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage)) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNoEvent(Duration.ofMillis(100)) - .then(() -> { - // Acknowledge the DynamoDB message and the Redis message - messagePublisher.handleMessageAcknowledged(); - messagePublisher.handleMessageAcknowledged(); - }) - .expectComplete() - .verify(); - } - - @Test - void publishMessagesTerminateNoMessages() { - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, true); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)) - .expectComplete() - .verify(); - } - - @Test - void publishMessagesDynamoDbOnly() { - final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage()); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)) - .expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - - @Test - void publishMessagesRedisOnly() { - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - - @Test - void publishMessagesTailNewRedisMessages() { - final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage()); - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - final MessageProtos.Envelope newArrivalRedisMessage = generateRandomMessage(); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1); - - Thread.ofVirtual().start(() -> { - try { - queueEmptyCountDownLatch.await(); - } catch (final InterruptedException e) { - throw new RuntimeException(e); - } - - deleteRedisMessage(redisMessage); - messagePublisher.handleMessageAcknowledged(); - - deleteDynamoDbMessage(dynamoDbMessage); - messagePublisher.handleMessageAcknowledged(); - - insertRedisMessage(newArrivalRedisMessage); - messagePublisher.handleNewMessageAvailable(); - }); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher) - .doOnNext(entry -> { - if (entry instanceof MessageStreamEntry.QueueEmpty) { - queueEmptyCountDownLatch.countDown(); - } - })) - .expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage)) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .expectNext(new MessageStreamEntry.Envelope(newArrivalRedisMessage)) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - - @Test - void publishMessagesTailNewPersistedMessages() { - final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage()); - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - final MessageProtos.Envelope persistedMessage = generateRandomMessage(); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1); - - Thread.ofVirtual().start(() -> { - try { - queueEmptyCountDownLatch.await(); - } catch (final InterruptedException e) { - throw new RuntimeException(e); - } - - deleteRedisMessage(redisMessage); - messagePublisher.handleMessageAcknowledged(); - - deleteDynamoDbMessage(dynamoDbMessage); - messagePublisher.handleMessageAcknowledged(); - - insertDynamoDbMessage(persistedMessage); - messagePublisher.handleMessagesPersisted(); - }); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher) - .doOnNext(entry -> { - if (entry instanceof MessageStreamEntry.QueueEmpty) { - queueEmptyCountDownLatch.countDown(); - } - })) - .expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage)) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .expectNext(new MessageStreamEntry.Envelope(persistedMessage)) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - - @Test - void publishMessagesWaitForAcknowledgement() { - final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage()); - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - final MessageProtos.Envelope persistedMessage = generateRandomMessage(); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1); - - final Thread persister = Thread.ofVirtual().start(() -> { - try { - queueEmptyCountDownLatch.await(); - } catch (final InterruptedException e) { - throw new RuntimeException(e); - } - - insertDynamoDbMessage(persistedMessage); - messagePublisher.handleMessagesPersisted(); - }); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher) - .doOnNext(entry -> { - if (entry instanceof MessageStreamEntry.QueueEmpty) { - queueEmptyCountDownLatch.countDown(); - } - })) - .expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage)) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .then(() -> { - try { - persister.join(); - } catch (final InterruptedException e) { - throw new RuntimeException(e); - } - }) - // Extra time to catch unexpected events after persisting completes - .expectNoEvent(Duration.ofMillis(500)) - .thenCancel() - .verify(); - } - - @Test - void publishMessagesConsumerConflict() { - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - final CountDownLatch countDownLatch = new CountDownLatch(1); - - Thread.ofVirtual().start(() -> { - try { - countDownLatch.await(); - } catch (final InterruptedException e) { - throw new RuntimeException(e); - } - - messagePublisher.handleConflictingMessageConsumer(); - }); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher) - .doOnSubscribe(_ -> countDownLatch.countDown())) - .expectError(ConflictingMessageConsumerException.class) - .verify(); - - verify(redisMessageAvailabilityManager, timeout(1_000)).handleClientConnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), messagePublisher); - verify(redisMessageAvailabilityManager, timeout(1_000)).handleClientDisconnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), messagePublisher); - } - - @Test - void publishMessagesClientConnectedFailure() { - final CompletableFuture clientConnectedFuture = new CompletableFuture<>(); - - final RuntimeException exception = new RuntimeException("OH NO"); - clientConnectedFuture.completeExceptionally(exception); - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - when(redisMessageAvailabilityManager.handleClientConnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), messagePublisher)) - .thenReturn(clientConnectedFuture); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)) - .expectErrorMatches(exception::equals) - .verify(); - - verify(redisMessageAvailabilityManager).handleClientDisconnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), messagePublisher); - } - - @ParameterizedTest - @CsvSource({ - "207, 173", - "323, 0", - "0, 221", - }) - void publishMessagesMultipleRequests(final int persistedMessageCount, final int cachedMessageCount) { - final List expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount); - - for (int i = 0; i < persistedMessageCount; i++) { - expectedMessages.add(insertDynamoDbMessage(generateRandomMessage())); - } - - for (int i = 0; i < cachedMessageCount; i++) { - expectedMessages.add(insertRedisMessage(generateRandomMessage())); - } - - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - final List publishedMessages = new ArrayList<>(expectedMessages.size()); - - final CompletableFuture queueEmptyFuture = new CompletableFuture<>(); - - final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher) - .limitRate(20) - .doOnNext(entry -> { - if (entry instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) { - publishedMessages.add(message); - } else if (entry instanceof MessageStreamEntry.QueueEmpty) { - queueEmptyFuture.complete(null); - } - }) - .subscribe(); - - queueEmptyFuture.thenRun(disposable::dispose).join(); - - assertEquals(expectedMessages, publishedMessages); - } - - @Test - void publishQueueEmptySignalDeferred() { - final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage()); - - { - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, - DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 1) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - - { - final RedisDynamoDbMessagePublisher messagePublisher = - new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, - DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice, false); - - StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 2) - .expectNext(new MessageStreamEntry.Envelope(redisMessage)) - .expectNext(new MessageStreamEntry.QueueEmpty()) - .expectNoEvent(Duration.ofMillis(100)) - .thenCancel() - .verify(); - } - } - - private MessageProtos.Envelope insertRedisMessage(final MessageProtos.Envelope message) { - messagesCache.insert(UUIDUtil.fromByteString(message.getServerGuid()), - DESTINATION_SERVICE_IDENTIFIER.uuid(), - destinationDevice.getId(), - message) - .join(); - - return message; - } - - private void deleteRedisMessage(final MessageProtos.Envelope message) { - messagesCache.remove(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), UUIDUtil.fromByteString(message.getServerGuid())).join(); - } - - private MessageProtos.Envelope insertDynamoDbMessage(final MessageProtos.Envelope message) { - messagesDynamoDb.store(List.of(message), DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice); - - return message; - } - - private void deleteDynamoDbMessage(final MessageProtos.Envelope message) { - messagesDynamoDb.deleteMessage(DESTINATION_SERVICE_IDENTIFIER.uuid(), - destinationDevice, - UUIDUtil.fromByteString(message.getServerGuid()), - message.getServerTimestamp()) - .join(); - } - - private static MessageProtos.Envelope generateRandomMessage() { - - final long timestamp = SERIAL_TIMESTAMP.incrementAndGet(); - - final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder() - .setClientTimestamp(timestamp) - .setServerTimestamp(timestamp) - .setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256))) - .setType(MessageProtos.Envelope.Type.CIPHERTEXT) - .setServerGuid(UUIDUtil.toByteString(UUID.randomUUID())) - .setDestinationServiceId(DESTINATION_SERVICE_IDENTIFIER.toCompactByteString()); - - return envelopeBuilder.build(); - } -} 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 17e132a4f..43005584c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java @@ -61,7 +61,6 @@ 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.push.RedisMessageAvailabilityManager; import org.whispersystems.textsecuregcm.redis.RedisClusterExtension; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; @@ -70,7 +69,6 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.DynamoDbExtension; import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables; import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension; -import org.whispersystems.textsecuregcm.storage.MessagesCache; import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb; import org.whispersystems.textsecuregcm.storage.MessagesManager; import org.whispersystems.textsecuregcm.storage.ReportMessageManager; @@ -89,9 +87,6 @@ class WebSocketConnectionIntegrationTest { @RegisterExtension static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.MESSAGES); - @RegisterExtension - static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build(); - @RegisterExtension static final FoundationDbClusterExtension FOUNDATION_DB_EXTENSION; @@ -105,8 +100,6 @@ class WebSocketConnectionIntegrationTest { private ExecutorService sharedExecutorService; private FoundationDbMessageStore foundationDbMessageStore; private MessagesDynamoDb messagesDynamoDb; - private MessagesCache messagesCache; - private RedisMessageAvailabilityManager redisMessageAvailabilityManager; private ReportMessageManager reportMessageManager; private Account account; private Device device; @@ -133,12 +126,9 @@ class WebSocketConnectionIntegrationTest { when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration()); - messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC()); messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(), DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7), sharedExecutorService); - redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, sharedExecutorService); reportMessageManager = mock(ReportMessageManager.class); account = mock(Account.class); device = mock(Device.class); @@ -162,14 +152,10 @@ class WebSocketConnectionIntegrationTest { when(account.getNumber()).thenReturn(Optional.of("+18005551234")); when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID()); when(device.getId()).thenReturn(Device.PRIMARY_ID); - - redisMessageAvailabilityManager.start(); } @AfterEach void tearDown() throws Exception { - redisMessageAvailabilityManager.stop(); - sharedExecutorService.shutdown(); final Mono schedulerShutdownMono = messageDeliveryScheduler.disposeGracefully(); @@ -194,10 +180,10 @@ class WebSocketConnectionIntegrationTest { "323, 0", "0, 221", }) - void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) { + void testProcessStoredMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) { final WebSocketConnection webSocketConnection = new WebSocketConnection( mock(ReceiptSender.class), - new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC()), + new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class), @@ -209,14 +195,14 @@ class WebSocketConnectionIntegrationTest { mock(ExperimentEnrollmentManager.class) ); - final List expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount); + final List expectedMessages = new ArrayList<>(dynamoDbMessageCount + foundationDbMessageCount); assertTimeoutPreemptively(Duration.ofSeconds(15), () -> { { - final List persistedMessages = new ArrayList<>(persistedMessageCount); + final List persistedMessages = new ArrayList<>(dynamoDbMessageCount); - for (int i = 0; i < persistedMessageCount; i++) { + for (int i = 0; i < dynamoDbMessageCount; i++) { final MessageProtos.Envelope envelope = generateRandomMessage(UUID.randomUUID()); persistedMessages.add(envelope); @@ -226,12 +212,23 @@ class WebSocketConnectionIntegrationTest { messagesDynamoDb.store(persistedMessages, account.getAccountIdentifier(), device); } - for (int i = 0; i < cachedMessageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); + for (int i = 0; i < foundationDbMessageCount; i++) { + final Envelope envelope = generateRandomMessage(UUID.randomUUID()) + .toBuilder() + .clearServerGuid() + .build(); - messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); - expectedMessages.add(envelope); + final UUID messageGuid = foundationDbMessageStore.insert(new AciServiceIdentifier(account.getAccountIdentifier()), + Map.of(device.getId(), envelope)) + .join() + .get(device.getId()) + .messageGuid() + .orElseThrow(); + + expectedMessages.add(envelope + .toBuilder() + .setServerGuid(UUIDUtil.toByteString(messageGuid)) + .build()); } final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class); @@ -248,7 +245,7 @@ class WebSocketConnectionIntegrationTest { verify(webSocketClient, timeout(10_000)) .sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty())); - verify(webSocketClient, times(persistedMessageCount + cachedMessageCount)) + verify(webSocketClient, times(dynamoDbMessageCount + foundationDbMessageCount)) .sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), messageBodyCaptor.capture()); final List sentMessages = new ArrayList<>(); @@ -271,7 +268,7 @@ class WebSocketConnectionIntegrationTest { void testProcessStoredMessagesMultipleSegments() { final WebSocketConnection webSocketConnection = new WebSocketConnection( mock(ReceiptSender.class), - new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC()), + new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class), @@ -283,17 +280,17 @@ class WebSocketConnectionIntegrationTest { mock(ExperimentEnrollmentManager.class) ); - final int persistedMessageCount = 77; - final int cachedMessageCount = 104; + final int dynamoDbMessageCount = 77; + final int initialFoundationDbMessageCount = 104; - final List expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount); + final List expectedMessages = new ArrayList<>(dynamoDbMessageCount + initialFoundationDbMessageCount); assertTimeoutPreemptively(Duration.ofSeconds(15), () -> { { - final List persistedMessages = new ArrayList<>(persistedMessageCount); + final List persistedMessages = new ArrayList<>(dynamoDbMessageCount); - for (int i = 0; i < persistedMessageCount; i++) { + for (int i = 0; i < dynamoDbMessageCount; i++) { final MessageProtos.Envelope envelope = generateRandomMessage(UUID.randomUUID()); persistedMessages.add(envelope); @@ -303,17 +300,28 @@ class WebSocketConnectionIntegrationTest { messagesDynamoDb.store(persistedMessages, account.getAccountIdentifier(), device); } - for (int i = 0; i < cachedMessageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); + for (int i = 0; i < initialFoundationDbMessageCount; i++) { + final Envelope envelope = generateRandomMessage(UUID.randomUUID()) + .toBuilder() + .clearServerGuid() + .build(); - messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); - expectedMessages.add(envelope); + final UUID messageGuid = foundationDbMessageStore.insert(new AciServiceIdentifier(account.getAccountIdentifier()), + Map.of(device.getId(), envelope)) + .join() + .get(device.getId()) + .messageGuid() + .orElseThrow(); + + expectedMessages.add(envelope + .toBuilder() + .setServerGuid(UUIDUtil.toByteString(messageGuid)) + .build()); } final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class); - final AtomicInteger remainingMessages = new AtomicInteger(persistedMessageCount + cachedMessageCount); + final AtomicInteger remainingMessages = new AtomicInteger(dynamoDbMessageCount + initialFoundationDbMessageCount); final int additionalMessageCount = 67; when(successResponse.getStatus()).thenReturn(200); @@ -353,7 +361,7 @@ class WebSocketConnectionIntegrationTest { verify(webSocketClient, timeout(10_000)) .sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty())); - verify(webSocketClient, timeout(10_000).times(persistedMessageCount + cachedMessageCount + additionalMessageCount)) + verify(webSocketClient, timeout(10_000).times(dynamoDbMessageCount + initialFoundationDbMessageCount + additionalMessageCount)) .sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), messageBodyCaptor.capture()); final List sentMessages = new ArrayList<>(); @@ -376,7 +384,7 @@ class WebSocketConnectionIntegrationTest { void testProcessStoredMessagesClientClosed() { final WebSocketConnection webSocketConnection = new WebSocketConnection( mock(ReceiptSender.class), - new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC()), + new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class), @@ -388,17 +396,17 @@ class WebSocketConnectionIntegrationTest { mock(ExperimentEnrollmentManager.class) ); - final int persistedMessageCount = 207; - final int cachedMessageCount = 173; + final int dynamoDBMessageCount = 207; + final int foundationDbMessageCount = 173; - final List expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount); + final List expectedMessages = new ArrayList<>(dynamoDBMessageCount + foundationDbMessageCount); assertTimeoutPreemptively(Duration.ofSeconds(15), () -> { { - final List persistedMessages = new ArrayList<>(persistedMessageCount); + final List persistedMessages = new ArrayList<>(dynamoDBMessageCount); - for (int i = 0; i < persistedMessageCount; i++) { + for (int i = 0; i < dynamoDBMessageCount; i++) { final MessageProtos.Envelope envelope = generateRandomMessage(UUID.randomUUID()); persistedMessages.add(envelope); expectedMessages.add(envelope); @@ -407,12 +415,23 @@ class WebSocketConnectionIntegrationTest { messagesDynamoDb.store(persistedMessages, account.getAccountIdentifier(), device); } - for (int i = 0; i < cachedMessageCount; i++) { - final UUID messageGuid = UUID.randomUUID(); - final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid); - messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join(); + for (int i = 0; i < foundationDbMessageCount; i++) { + final Envelope envelope = generateRandomMessage(UUID.randomUUID()) + .toBuilder() + .clearServerGuid() + .build(); - expectedMessages.add(envelope); + final UUID messageGuid = foundationDbMessageStore.insert(new AciServiceIdentifier(account.getAccountIdentifier()), + Map.of(device.getId(), envelope)) + .join() + .get(device.getId()) + .messageGuid() + .orElseThrow(); + + expectedMessages.add(envelope + .toBuilder() + .setServerGuid(UUIDUtil.toByteString(messageGuid)) + .build()); } when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any())) @@ -423,7 +442,7 @@ class WebSocketConnectionIntegrationTest { //noinspection unchecked final ArgumentCaptor> messageBodyCaptor = ArgumentCaptor.forClass(Optional.class); - verify(webSocketClient, atMost(persistedMessageCount + cachedMessageCount)).sendRequest(eq("PUT"), + verify(webSocketClient, atMost(dynamoDBMessageCount + foundationDbMessageCount)).sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), messageBodyCaptor.capture()); verify(webSocketClient, never()).sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty())); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java index fcc44d84f..30dab0ba8 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java @@ -30,7 +30,7 @@ import reactor.core.publisher.Flux; class ClearExpiredFoundationDbMessagesCommandTest { - private MessagesManager messagesManager = mock(MessagesManager.class); + private final MessagesManager messagesManager = mock(MessagesManager.class); private static class TestClearExpiredFoundationDbMessagesCommand extends ClearExpiredFoundationDbMessagesCommand { @@ -44,8 +44,7 @@ class ClearExpiredFoundationDbMessagesCommandTest { super(clock); - this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, - null, null); + this.commandDependencies = new CommandDependencies(null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); this.dryRun = dryRun; } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java index 3501f7cdf..fa21d4c0d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java @@ -47,7 +47,6 @@ class NotifyIdleDevicesCommandTest { null, null, null, - null, messagesManager, null, null, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java index 5535ed386..0d230edcf 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java @@ -52,7 +52,6 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest { null, null, null, - null, dynamoDbRecoveryManager, null, null, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java index 821a3a0b2..0f73893d8 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java @@ -39,7 +39,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest { final boolean dryRun) { super(); - this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); + this.commandDependencies = new CommandDependencies(null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); this.dryRun = dryRun; } diff --git a/service/src/test/resources/config/test.yml b/service/src/test/resources/config/test.yml index 31915b19d..1deb417bd 100644 --- a/service/src/test/resources/config/test.yml +++ b/service/src/test/resources/config/test.yml @@ -238,11 +238,6 @@ svrb: 9Kxq0DY7RCEpdHMCKcOL -----END CERTIFICATE----- -messageCache: # Redis server configuration for message store cache - persistDelayMinutes: 1 - cluster: - type: local - attachments: maxAttachmentUploadSizeInBytes: 1024 maxMessageBackupUploadSizeInBytes: 1024