mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:16:50 +00:00
Retire Redis message cache
This commit is contained in:
1 parent
4c940f2a39
commit
9c5170d47c
58 files changed
+197
-6721
No files matched your search
@@ -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
|
||||
|
||||
-10
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new SetUserDiscoverabilityCommand());
|
||||
bootstrap.addCommand(new UnlinkDeviceCommand());
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredSandboxAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new SandboxAccountPoolCommand());
|
||||
@@ -565,7 +561,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BlockingQueue<Runnable> 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<WhisperServerConfiguration
|
||||
|
||||
FaultTolerantRedisClusterClient cacheCluster = config.getCacheClusterConfiguration()
|
||||
.build("main_cache", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -797,8 +790,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
@@ -813,10 +804,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Clock.systemUTC());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
|
||||
final MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, foundationDbMessageStore,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
|
||||
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
|
||||
@@ -945,7 +934,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
environment.lifecycle().manage(redisMessageAvailabilityManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class MessageCacheConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private FaultTolerantRedisClusterFactory cluster;
|
||||
|
||||
@JsonProperty
|
||||
private int persistDelayMinutes = 10;
|
||||
|
||||
public FaultTolerantRedisClusterFactory getRedisClusterConfiguration() {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public int getPersistDelayMinutes() {
|
||||
return persistDelayMinutes;
|
||||
}
|
||||
}
|
||||
-8
@@ -41,10 +41,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicCaptchaConfiguration captcha = new DynamicCaptchaConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
@@ -115,10 +111,6 @@ public class DynamicConfiguration {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
|
||||
public DynamicMessageDeliveryConfiguration getMessageDeliveryConfiguration() {
|
||||
return messageDelivery;
|
||||
}
|
||||
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean persistenceEnabled = true;
|
||||
|
||||
/**
|
||||
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
|
||||
*/
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofMinutes(5);
|
||||
|
||||
@JsonProperty
|
||||
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl,
|
||||
final Duration sleepBetweenNodes) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
this.sleepBetweenNodes = sleepBetweenNodes;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
return persistenceEnabled;
|
||||
}
|
||||
|
||||
public double getTrimOversizedQueueExtraRoomRatio() {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
|
||||
public Duration getSleepBetweenNodes() {
|
||||
return sleepBetweenNodes;
|
||||
}
|
||||
}
|
||||
-1
@@ -25,5 +25,4 @@ public class KeepAliveController {
|
||||
public Response getProvisioningKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A message availability listener handles message availability and presence events related to a client's open message
|
||||
* stream. Handler methods are run on dedicated threads and may safely perform blocking operations.
|
||||
*
|
||||
* @see RedisMessageAvailabilityManager#handleClientConnected(UUID, byte, MessageAvailabilityListener)
|
||||
*/
|
||||
public interface MessageAvailabilityListener {
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available in the connected client's message queue.
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersisted();
|
||||
|
||||
/**
|
||||
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
|
||||
* underlying network connection.
|
||||
*/
|
||||
void handleConflictingMessageConsumer();
|
||||
}
|
||||
-358
@@ -1,358 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* The Redis message availability manager distributes events related to client presence and message availability to
|
||||
* registered listeners. In the current Signal server implementation, clients generally interact with the service by
|
||||
* opening a dual-purpose WebSocket. The WebSocket serves as both a delivery mechanism for messages and as a channel
|
||||
* for the client to issue API requests to the server. Clients are considered "present" if they have an open WebSocket
|
||||
* connection and are therefore likely to receive messages as soon as they're delivered to the server. Redis message
|
||||
* availability managers ensure that clients have at most one active message delivery channel at a time on a
|
||||
* best-effort basis.
|
||||
*
|
||||
* @implNote The Redis message availability manager uses the Redis 7 sharded pub/sub system to distribute events. This
|
||||
* system makes a best effort to ensure that a given client has only a single open connection across the fleet of
|
||||
* servers, but cannot guarantee at-most-one behavior.
|
||||
*
|
||||
* @see MessageAvailabilityListener
|
||||
* @see org.whispersystems.textsecuregcm.storage.MessagesManager#insert(UUID, Map)
|
||||
*/
|
||||
public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<byte[], byte[]> 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<byte[], byte[]> pubSubConnection;
|
||||
|
||||
private final Map<AccountAndDeviceIdentifier, MessageAvailabilityListener> 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<Void> 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<MessageAvailabilityListener> displacedListener = new AtomicReference<>();
|
||||
final AtomicReference<CompletionStage<Void>> 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<Void> handleClientDisconnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("WebSocket connection event manager not started");
|
||||
}
|
||||
|
||||
final AtomicReference<CompletionStage<Void>> 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<Integer, List<byte[]>> 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);
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -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<MessageStreamEntry> 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<Void> 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));
|
||||
|
||||
+65
@@ -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<MessageStreamEntry> 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<Void> 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);
|
||||
}
|
||||
}
|
||||
-13
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<DynamicConfiguration> 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<DynamicConfiguration> 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<DynamicConfiguration> 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<RedisClusterNode> 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<Void> 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<Void> 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.<MessageProtos.Envelope>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<Boolean> 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;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
* <p>
|
||||
* The following structures are used:
|
||||
* <dl>
|
||||
* <dt>{@code queueKey}</code></dt>
|
||||
* <dd>A sorted set of messages in a device’s queue. A message’s score is its queue-local message ID. See
|
||||
* <a href="https://redis.io/docs/latest/develop/use/patterns/twitter-clone/#the-sorted-set-data-type">Redis.io: The
|
||||
* Sorted Set data type</a> for background on scores and this data structure.</dd>
|
||||
* <dt>{@code queueMetadataKey}</dt>
|
||||
* <dd>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.</dd>
|
||||
* <dt>{@code sharedMrmKey}</dt>
|
||||
* <dd>A hash containing a single multi-recipient message pending delivery. It contains:
|
||||
* <ul>
|
||||
* <li>{@code data} - the serialized SealedSenderMultiRecipientMessage data</li>
|
||||
* <li>fields with each recipient device's “view” into the payload ({@link SealedSenderMultiRecipientMessage#serializedRecipientView(SealedSenderMultiRecipientMessage.Recipient)}</li>
|
||||
* </ul>
|
||||
* 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.
|
||||
* </dd>
|
||||
* <dt>{@code queueLockKey}</dt>
|
||||
* <dd>Used to indicate that a queue is being modified by the {@link MessagePersister} and that {@code get_items} should
|
||||
* return an empty list.</dd>
|
||||
* </dl>
|
||||
* <p>
|
||||
* At a high level, the process is:
|
||||
* <ol>
|
||||
* <li>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.</li>
|
||||
* <li>Get: a batch of messages are retrieved from the queue, potentially with an after-message-ID offset.</li>
|
||||
* <li>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.</li>
|
||||
* </ol>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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<Boolean> 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<byte[]> insertSharedMultiRecipientMessagePayload(
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage,
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> 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<Optional<RemovedMessage>> 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<List<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<UUID> messageGuids) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return removeByGuidScript.execute(destinationUuid, destinationDevice, messageGuids)
|
||||
.thenApplyAsync(serialized -> {
|
||||
|
||||
final List<RemovedMessage> removedMessages = new ArrayList<>(serialized.size());
|
||||
final Map<ServiceIdentifier, List<byte[]>> 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<Boolean> hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice))
|
||||
.thenApply(cardinality -> cardinality > 0))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return get(destinationUuid,
|
||||
destinationDeviceId,
|
||||
clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY),
|
||||
false);
|
||||
}
|
||||
|
||||
Publisher<MessageProtos.Envelope> 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<MessageProtos.Envelope> get(final UUID destinationUuid,
|
||||
final byte destinationDeviceId,
|
||||
final Instant earliestAllowableEphemeralTimestamp,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final long earliestAllowableEphemeralTimestampMillis = earliestAllowableEphemeralTimestamp.toEpochMilli();
|
||||
|
||||
final Flux<MessageProtos.Envelope> 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<MessageProtos.Envelope> messagesToPublish = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis) || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis));
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> 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<Long> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> 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<Mono<MessageProtos.Envelope>> 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<MessageProtos.Envelope> 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:
|
||||
* <ol>
|
||||
* <li>The reconstructed message for delivery with {@code content} set and {@code sharedMrmKey} cleared</li>
|
||||
* <li>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</li>
|
||||
* <li>An empty {@code Mono}, if an unexpected error occurred</li>
|
||||
* </ol>
|
||||
*/
|
||||
private Mono<MessageProtos.Envelope> 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)))
|
||||
.<MessageProtos.Envelope>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<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral())));
|
||||
|
||||
final Mono<MessageProtos.Envelope> 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<byte[]> 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<Pair<List<byte[]>, 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<Long> estimatePersistedQueueSizeBytes(final UUID accountUuid, final byte destinationDevice) {
|
||||
final Function<Optional<Long>, Mono<List<ScoredValue<byte[]>>>> getNextPage = (Optional<Long> 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<byte[]> 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<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> 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<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
}
|
||||
|
||||
return messageMono;
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
return CompletableFuture.allOf(
|
||||
Device.ALL_POSSIBLE_DEVICE_IDS.stream()
|
||||
.map(deviceId -> clear(destinationUuid, deviceId))
|
||||
.toList()
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> 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<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
final List<String> 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<RedisClusterNode> claimNextNodeToPersist(final String persisterId, final Duration ttl) {
|
||||
final List<RedisClusterNode> 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<String> 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<Void> lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.reactive().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE))
|
||||
.then();
|
||||
}
|
||||
|
||||
Mono<Void> 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);
|
||||
}
|
||||
}
|
||||
-53
@@ -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<List<byte[]>> execute(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final int limit,
|
||||
final long afterMessageId,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getPersistInProgressKey(destinationUuid, destinationDevice) // queueLockKey
|
||||
);
|
||||
final List<byte[]> 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<byte[]>) result)
|
||||
.next();
|
||||
}
|
||||
|
||||
}
|
||||
-75
@@ -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<Boolean> executeAsync(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
|
||||
assert envelope.hasServerGuid();
|
||||
assert envelope.hasServerTimestamp();
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
);
|
||||
|
||||
final List<byte[]> 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);
|
||||
}
|
||||
}
|
||||
-76
@@ -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<Void> executeAsync(final byte[] sharedMrmKey,
|
||||
final SealedSenderMultiRecipientMessage message,
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> resolvedRecipients) {
|
||||
|
||||
final List<byte[]> 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<byte[]> 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);
|
||||
}
|
||||
}
|
||||
-32
@@ -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<String> keys = List.of(MessagesCache.getPersisterNodeClaimKey(node));
|
||||
final List<String> arguments = List.of(persisterId);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(getClass().getSimpleName())
|
||||
.executeRunnable(() -> releaseNodeClaimScript.execute(keys, arguments));
|
||||
}
|
||||
}
|
||||
-51
@@ -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<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<UUID> messageGuids) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
final List<byte[]> 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<byte[]>) result);
|
||||
}
|
||||
|
||||
}
|
||||
-57
@@ -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.
|
||||
* <ol>
|
||||
* <li>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.</li>
|
||||
* <li>Once theses messages have been processed, this script should be called again, confirming that the messages have been processed.</li>
|
||||
* <li>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.</li>
|
||||
* </ol>
|
||||
*/
|
||||
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<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<String> processedMessageGuids) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
|
||||
final List<byte[]> 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<byte[]>) result)
|
||||
.next();
|
||||
}
|
||||
|
||||
}
|
||||
-45
@@ -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.
|
||||
* <p>
|
||||
* 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<Long> execute(final Collection<byte[]> keysCollection, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
final List<byte[]> keys = keysCollection instanceof List<byte[]>
|
||||
? (List<byte[]>) keysCollection
|
||||
: new ArrayList<>(keysCollection);
|
||||
|
||||
return removeRecipientViewFromMrmDataScript.executeBinaryReactive(keys,
|
||||
List.of(MessagesCache.getSharedMrmViewKey(serviceIdentifier, deviceId)))
|
||||
.map(o -> (long) o)
|
||||
.next();
|
||||
}
|
||||
}
|
||||
-48
@@ -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<byte[]> 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<Void> execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
final List<byte[]> 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();
|
||||
}
|
||||
}
|
||||
+7
-94
@@ -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<Byte, Boolean> insert(final UUID accountIdentifier, final Map<Byte, Envelope> 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<Map<Account, Map<Byte, Boolean>>> insertMultiRecipientMessage(
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
@@ -199,7 +168,6 @@ public class MessagesManager {
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@SuppressWarnings("unchecked") final CompletableFuture<Boolean>[] 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<Envelope> 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<Void> 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<Void> 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<Optional<RemovedMessage>> 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<Envelope> messages) {
|
||||
|
||||
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
|
||||
|
||||
final List<UUID> 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<Optional<Instant>> 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)))
|
||||
|
||||
-417
@@ -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<MessageStreamEntry> {
|
||||
|
||||
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<? super MessageStreamEntry> 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<MessageProtos.Envelope> {
|
||||
|
||||
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<? super MessageStreamEntry> subscriber) {
|
||||
if (this.subscriber != null) {
|
||||
subscriber.onError(new IllegalStateException("Redis/DynamoDB message publisher only allows one subscriber"));
|
||||
return;
|
||||
}
|
||||
|
||||
this.subscriber = subscriber;
|
||||
|
||||
@Nullable final CompletionStage<Void> 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<MessageProtos.Envelope> dynamoPublisher =
|
||||
storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
? messagesDynamoDb.load(accountIdentifier, device, null)
|
||||
: Flux.empty();
|
||||
|
||||
final Publisher<MessageProtos.Envelope> redisPublisher = messagesCache.get(accountIdentifier, device.getId());
|
||||
|
||||
final Flux<MessageProtos.Envelope> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
-93
@@ -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<MessageStreamEntry> 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<Void> 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.<Void>completedFuture(null))
|
||||
.orElseGet(() ->
|
||||
messagesDynamoDb.deleteMessage(accountIdentifier, device, messageGuid, serverTimestamp)
|
||||
.thenRun(Util.NOOP)))
|
||||
.whenComplete((_, _) -> messagePublisher.handleMessageAcknowledged());
|
||||
}
|
||||
}
|
||||
+1
-13
@@ -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,
|
||||
|
||||
-123
@@ -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<WhisperServerConfiguration> {
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
}
|
||||
@@ -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")
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
+6
-46
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+18
-51
@@ -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<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, foundationDbMessageCount);
|
||||
void testProcessStoredMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) {
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(dynamoDbMessageCount, foundationDbMessageCount);
|
||||
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final List<Envelope> 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<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, 0);
|
||||
final AtomicInteger remainingMessages = new AtomicInteger(persistedMessageCount + cachedMessageCount);
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(dynamoDbMessageCount, 0);
|
||||
final AtomicInteger remainingMessages = new AtomicInteger(dynamoDbMessageCount);
|
||||
final int additionalMessageCount = 67;
|
||||
|
||||
final Sinks.Many<UUID> 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<Envelope> receivedMessages = Collections.newSetFromMap(new ConcurrentHashMap<>());
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, 0);
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(dynamoDbMessageCount, 0);
|
||||
final TestPublisher<UUID> 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<Envelope> fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount, final int foundationDbMessageCount) {
|
||||
private List<Envelope> fillRandomMessages(final int dynamoDbMessageCount, final int foundationDbMessageCount) {
|
||||
|
||||
final List<Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
for (int i = 0; i < persistedMessageCount; i++) {
|
||||
final List<Envelope> 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()
|
||||
|
||||
-370
@@ -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<MessageAvailabilityAdapter> 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<byte[], byte[]> pubSubCommands =
|
||||
mock(RedisClusterPubSubCommands.class);
|
||||
|
||||
@SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands<byte[], byte[]> 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<byte[], byte[]> 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<byte[], byte[]> 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<byte[], byte[]> 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<byte[], byte[]> pubSubAsyncCommands =
|
||||
mock(RedisClusterPubSubAsyncCommands.class);
|
||||
|
||||
when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
|
||||
@SuppressWarnings("unchecked") final RedisAdvancedClusterAsyncCommands<byte[], byte[]> 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<byte[], byte[]> buildBinaryAsyncCommands() {
|
||||
@SuppressWarnings("unchecked") final RedisAdvancedClusterAsyncCommands<byte[], byte[]> binaryAsyncCommands =
|
||||
mock(RedisAdvancedClusterAsyncCommands.class);
|
||||
|
||||
when(binaryAsyncCommands.spublish(any(), any())).thenReturn(MockRedisFuture.completedFuture(0L));
|
||||
|
||||
return binaryAsyncCommands;
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -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);
|
||||
}
|
||||
}
|
||||
+5
-30
@@ -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()))
|
||||
-271
@@ -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<DynamicConfiguration> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> 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();
|
||||
}
|
||||
}
|
||||
-585
@@ -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<Integer> 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<DynamicConfiguration> 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<MessageProtos.Envelope> 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<List<MessageProtos.Envelope>> 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<List<MessageProtos.Envelope>> 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<RedisClusterNode> 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<List<MessageProtos.Envelope>> 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<List<MessageProtos.Envelope>> 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<List<MessageProtos.Envelope>> 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<List<MessageProtos.Envelope>> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> persistedMessages = new ArrayList<>(persistedMessageCount);
|
||||
final List<UUID> 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();
|
||||
}
|
||||
}
|
||||
-77
@@ -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<byte[]> 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());
|
||||
}
|
||||
}
|
||||
-116
@@ -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<MessageProtos.Envelope> getStoredMessages(final UUID destinationUuid, final byte deviceId) throws IOException {
|
||||
final MessagesCacheGetItemsScript getItemsScript =
|
||||
new MessagesCacheGetItemsScript(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final List<byte[]> queueItems = getItemsScript.execute(destinationUuid, deviceId, 1024, 0, false)
|
||||
.blockOptional()
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
final List<MessageProtos.Envelope> 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<byte[], byte[]> 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());
|
||||
}
|
||||
}
|
||||
-149
@@ -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<ServiceIdentifier, List<Byte>> 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<Arguments> testInsert() {
|
||||
final Map<ServiceIdentifier, List<Byte>> singleAccount = Map.of(
|
||||
new AciServiceIdentifier(UUID.randomUUID()), List.of((byte) 1, (byte) 2));
|
||||
|
||||
final List<Arguments> testCases = new ArrayList<>();
|
||||
testCases.add(Arguments.of(1, singleAccount));
|
||||
|
||||
for (int j = 1000; j <= 30000; j += 1000) {
|
||||
|
||||
final Map<Integer, List<Byte>> deviceLists = new HashMap<>();
|
||||
final Map<ServiceIdentifier, List<Byte>> manyAccounts = IntStream.range(0, j)
|
||||
.mapToObj(i -> {
|
||||
final int deviceCount = 1 + i % 5;
|
||||
final List<Byte> 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<ServiceIdentifier, List<Byte>> destinations = Map.of(
|
||||
resolvedServiceIdentifier, List.of(Device.PRIMARY_ID),
|
||||
unresolvedServiceIdentifier, List.of(Device.PRIMARY_ID));
|
||||
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage =
|
||||
MessagesCacheTest.generateRandomMrmMessage(destinations);
|
||||
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> 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<SealedSenderMultiRecipientMessage.Recipient> 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));
|
||||
}
|
||||
|
||||
}
|
||||
-57
@@ -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<byte[]> 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()));
|
||||
}
|
||||
}
|
||||
-54
@@ -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<byte[]> messagesToCheckForMrmKeys = removeScript.execute(destinationUuid, deviceId,
|
||||
Collections.emptyList())
|
||||
.block(Duration.ofSeconds(1));
|
||||
|
||||
assertEquals(1, messagesToCheckForMrmKeys.size());
|
||||
|
||||
}
|
||||
}
|
||||
-136
@@ -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<ServiceIdentifier, List<Byte>> 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<Map<ServiceIdentifier, List<Byte>>> testUpdateSingleKey() {
|
||||
final Map<ServiceIdentifier, List<Byte>> singleAccount = Map.of(
|
||||
new AciServiceIdentifier(UUID.randomUUID()), List.of((byte) 1, (byte) 2));
|
||||
|
||||
final List<Map<ServiceIdentifier, List<Byte>>> testCases = new ArrayList<>();
|
||||
testCases.add(singleAccount);
|
||||
|
||||
// Generate a more, from smallish to very large
|
||||
for (int j = 1000; j <= 81000; j *= 3) {
|
||||
|
||||
final Map<Integer, List<Byte>> deviceLists = new HashMap<>();
|
||||
final Map<ServiceIdentifier, List<Byte>> manyAccounts = IntStream.range(0, j)
|
||||
.mapToObj(i -> {
|
||||
final int deviceCount = 1 + i % 5;
|
||||
final List<Byte> 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<byte[]> 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);
|
||||
}
|
||||
|
||||
}
|
||||
-1083
File diff suppressed because it is too large.
Load diff
+8
-38
@@ -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()
|
||||
|
||||
-516
@@ -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<Void> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> publishedMessages = new ArrayList<>(expectedMessages.size());
|
||||
|
||||
final CompletableFuture<Void> 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();
|
||||
}
|
||||
}
|
||||
+69
-50
@@ -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<Void> 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<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(dynamoDbMessageCount + foundationDbMessageCount);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), () -> {
|
||||
|
||||
{
|
||||
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(persistedMessageCount);
|
||||
final List<MessageProtos.Envelope> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(dynamoDbMessageCount + initialFoundationDbMessageCount);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), () -> {
|
||||
|
||||
{
|
||||
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(persistedMessageCount);
|
||||
final List<MessageProtos.Envelope> 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<MessageProtos.Envelope> 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<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(dynamoDBMessageCount + foundationDbMessageCount);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), () -> {
|
||||
|
||||
{
|
||||
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(persistedMessageCount);
|
||||
final List<MessageProtos.Envelope> 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<Optional<byte[]>> 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()));
|
||||
|
||||
+2
-3
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -47,7 +47,6 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
messagesManager,
|
||||
null,
|
||||
null,
|
||||
|
||||
-1
@@ -52,7 +52,6 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
dynamoDbRecoveryManager,
|
||||
null,
|
||||
null,
|
||||
|
||||
+1
-1
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user