mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 10:46:47 +00:00
Use a SCAN-based strategy for message persisters
This commit is contained in:
1 parent
a142916fef
commit
50fe6194a5
11 files changed
+621
-303
No files matched your search
+12
-1
@@ -7,6 +7,7 @@ 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 {
|
||||
|
||||
@@ -19,12 +20,19 @@ public class DynamicMessagePersisterConfiguration {
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofHours(1);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled, final double trimOversizedQueueExtraRoomRatio) {
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
@@ -35,4 +43,7 @@ public class DynamicMessagePersisterConfiguration {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
}
|
||||
+176
-87
@@ -9,19 +9,24 @@ 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.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executor;
|
||||
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;
|
||||
@@ -32,7 +37,11 @@ import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
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 {
|
||||
@@ -41,31 +50,41 @@ public class MessagePersister implements Managed {
|
||||
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 RetryBackoffSpec retryBackoffSpec;
|
||||
|
||||
private final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
private final Thread[] workerThreads;
|
||||
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 GET_QUEUES_TIMER = Metrics.timer(name(MessagePersister.class, "getQueues"));
|
||||
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
|
||||
private static final Counter PERSIST_QUEUE_EXCEPTION_METER =
|
||||
Metrics.counter(name(MessagePersister.class, "persistQueueException"));
|
||||
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 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 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();
|
||||
|
||||
@@ -77,117 +96,172 @@ public class MessagePersister implements Managed {
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int dedicatedProcessWorkerThreadCount) {
|
||||
final int maxConcurrency) {
|
||||
|
||||
this(messagesCache,
|
||||
messagesManager,
|
||||
accountsManager,
|
||||
dynamicConfigurationManager,
|
||||
persistQueueScheduler,
|
||||
clock,
|
||||
persistDelay,
|
||||
maxConcurrency,
|
||||
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 RetryBackoffSpec retryBackoffSpec) {
|
||||
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.clock = clock;
|
||||
this.persistDelay = persistDelay;
|
||||
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
|
||||
|
||||
for (int i = 0; i < workerThreads.length; i++) {
|
||||
workerThreads[i] = new Thread(() -> {
|
||||
while (running) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextQueues(Instant.now());
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
}
|
||||
}, "MessagePersisterWorker-" + i);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Duration getPersistDelay() {
|
||||
return persistDelay;
|
||||
this.maxConcurrency = maxConcurrency;
|
||||
this.retryBackoffSpec = retryBackoffSpec;
|
||||
this.persistQueueScheduler = persistQueueScheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
public synchronized void start() {
|
||||
running = true;
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
workerThread.start();
|
||||
}
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
}
|
||||
}, "MessagePersister");
|
||||
|
||||
workerThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
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 persistNextQueues(final Instant currentTime) {
|
||||
final int slot = messagesCache.getNextSlotToPersist();
|
||||
final String shard = messagesCache.shardForSlot(slot);
|
||||
int persistNextNode() {
|
||||
final RedisClusterNode node;
|
||||
{
|
||||
final Duration nodeClaimTtl =
|
||||
dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getNodeClaimTtl();
|
||||
|
||||
List<String> queuesToPersist;
|
||||
int queuesPersisted = 0;
|
||||
final Optional<RedisClusterNode> maybeNode = messagesCache.claimNextNodeToPersist(persisterId, nodeClaimTtl);
|
||||
|
||||
do {
|
||||
queuesToPersist = GET_QUEUES_TIMER.record(
|
||||
() -> messagesCache.getQueuesToPersist(slot, currentTime.minus(persistDelay), QUEUE_BATCH_LIMIT));
|
||||
|
||||
for (final String queue : queuesToPersist) {
|
||||
final UUID accountUuid = MessagesCache.getAccountUuidFromQueueName(queue);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queue);
|
||||
|
||||
final Optional<Account> maybeAccount = accountsManager.getByAccountIdentifier(accountUuid);
|
||||
if (maybeAccount.isEmpty()) {
|
||||
logger.error("No account record found for account {}", accountUuid);
|
||||
continue;
|
||||
}
|
||||
final Optional<Device> maybeDevice = maybeAccount.flatMap(account -> account.getDevice(deviceId));
|
||||
if (maybeDevice.isEmpty()) {
|
||||
logger.error("Account {} does not have a device with id {}", accountUuid, deviceId);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
persistQueue(maybeAccount.get(), maybeDevice.get(), shard);
|
||||
} catch (final Exception e) {
|
||||
PERSIST_QUEUE_EXCEPTION_METER.increment();
|
||||
logger.warn("Failed to persist queue {}::{} (slot {}, shard {}); will schedule for retry",
|
||||
accountUuid, deviceId, slot, shard, e);
|
||||
|
||||
messagesCache.addQueueToPersist(accountUuid, deviceId);
|
||||
|
||||
if (!(e instanceof MessagePersistenceException)) {
|
||||
// Pause after unexpected exceptions
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
}
|
||||
if (maybeNode.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
queuesPersisted += queuesToPersist.size();
|
||||
} while (queuesToPersist.size() >= QUEUE_BATCH_LIMIT);
|
||||
node = maybeNode.get();
|
||||
}
|
||||
|
||||
return queuesPersisted;
|
||||
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)
|
||||
.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 Mono.fromCallable(() -> {
|
||||
persistQueue(account, device, tags);
|
||||
return 1;
|
||||
})
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.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.getIdentifier(IdentityType.ACI), device.getId(), node.getUri().getHost(), e);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.count()
|
||||
.blockOptional()
|
||||
.map(Math::toIntExact)
|
||||
.orElse(0);
|
||||
} finally {
|
||||
sample.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void persistQueue(final Account account, final Device device, final String shard) throws MessagePersistenceException {
|
||||
void persistQueue(final Account account, final Device device, final Tags baseTags) throws MessagePersistenceException {
|
||||
final UUID accountUuid = account.getUuid();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
@@ -211,7 +285,7 @@ public class MessagePersister implements Managed {
|
||||
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
|
||||
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
|
||||
|
||||
final Tags tags = Tags.of(platformTag, Tag.of("shard", shard));
|
||||
final Tags tags = baseTags.and(platformTag);
|
||||
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
|
||||
@@ -237,7 +311,7 @@ public class MessagePersister implements Managed {
|
||||
.tags(Tags.of(platformTag))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messageCount);
|
||||
} catch (ItemCollectionSizeLimitExceededException e) {
|
||||
} catch (final ItemCollectionSizeLimitExceededException e) {
|
||||
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
|
||||
@@ -297,7 +371,7 @@ public class MessagePersister implements Managed {
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUID.fromString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(Retry.backoff(5, Duration.ofSeconds(1)))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
|
||||
@@ -313,4 +387,19 @@ public class MessagePersister implements Managed {
|
||||
targetDeleteBytes, cachedMessageBytes,
|
||||
outcomes.getLeft(), outcomes.getRight());
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,12 @@ 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.ZAddArgs;
|
||||
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;
|
||||
@@ -25,7 +28,6 @@ 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;
|
||||
@@ -38,6 +40,7 @@ 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;
|
||||
@@ -48,9 +51,9 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -127,15 +130,16 @@ public class MessagesCache {
|
||||
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
|
||||
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
|
||||
private final MessagesCacheGetItemsScript getItemsScript;
|
||||
private final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript;
|
||||
private final MessagesCacheRemoveQueueScript removeQueueScript;
|
||||
private final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript;
|
||||
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 getMessagesTimer = Metrics.timer(name(MessagesCache.class, "get"));
|
||||
private final Timer getQueuesToPersistTimer = Metrics.timer(name(MessagesCache.class, "getQueuesToPersist"));
|
||||
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"));
|
||||
@@ -187,9 +191,9 @@ public class MessagesCache {
|
||||
new MessagesCacheInsertScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheGetItemsScript(redisCluster),
|
||||
new MessagesCacheReleaseNodeClaimScript(redisCluster),
|
||||
new MessagesCacheRemoveByGuidScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheRemoveQueueScript(redisCluster),
|
||||
new MessagesCacheGetQueuesToPersistScript(redisCluster),
|
||||
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster),
|
||||
new MessagesCacheUnlockQueueScript(redisCluster)
|
||||
);
|
||||
@@ -202,9 +206,10 @@ public class MessagesCache {
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript,
|
||||
final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript,
|
||||
final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript,
|
||||
final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException {
|
||||
|
||||
@@ -220,8 +225,8 @@ public class MessagesCache {
|
||||
this.insertMrmScript = insertMrmScript;
|
||||
this.removeByGuidScript = removeByGuidScript;
|
||||
this.getItemsScript = getItemsScript;
|
||||
this.releaseNodeClaimScript = releaseNodeClaimScript;
|
||||
this.removeQueueScript = removeQueueScript;
|
||||
this.getQueuesToPersistScript = getQueuesToPersistScript;
|
||||
this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript;
|
||||
this.unlockQueueScript = unlockQueueScript;
|
||||
}
|
||||
@@ -680,28 +685,37 @@ public class MessagesCache {
|
||||
.thenRun(() -> sample.stop(clearQueueTimer));
|
||||
}
|
||||
|
||||
public String shardForSlot(int slot) {
|
||||
try {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.getPartitions().getPartitionBySlot(slot).getUri().getHost());
|
||||
} catch (final Throwable _) {
|
||||
return "unknown";
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
int getNextSlotToPersist() {
|
||||
return (int) (redisCluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY))
|
||||
% SlotHash.SLOT_COUNT);
|
||||
@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))));
|
||||
}
|
||||
|
||||
List<String> getQueuesToPersist(final int slot, final Instant maxTime, final int limit) {
|
||||
return getQueuesToPersistTimer.record(() -> getQueuesToPersistScript.execute(slot, maxTime, limit));
|
||||
void releaseNodeClaim(final RedisClusterNode node, final String persisterId) {
|
||||
releaseNodeClaimScript.execute(node, persisterId);
|
||||
}
|
||||
|
||||
void addQueueToPersist(final UUID accountUuid, final byte deviceId) {
|
||||
redisCluster.useBinaryCluster(connection -> connection.sync()
|
||||
.zadd(getQueueIndexKey(accountUuid, deviceId), ZAddArgs.Builder.nx(), System.currentTimeMillis(),
|
||||
getMessageQueueKey(accountUuid, deviceId)));
|
||||
@VisibleForTesting
|
||||
static String getPersisterNodeClaimKey(final RedisClusterNode node) {
|
||||
return "persister_node_claim::" + node.getNodeId();
|
||||
}
|
||||
|
||||
Flux<String> getQueues(final RedisClusterNode node) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
ScanStream.scan(connection.getConnection(node.getNodeId()).reactive(),
|
||||
ScanArgs.Builder.matches("user_queue::*")));
|
||||
}
|
||||
|
||||
void lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
|
||||
-43
@@ -1,43 +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.time.Instant;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Returns a list of queues that may be persisted. They will be sorted from oldest to more recent, limited by the
|
||||
* {@code maxTime} argument.
|
||||
*
|
||||
* @see MessagePersister
|
||||
*/
|
||||
class MessagesCacheGetQueuesToPersistScript {
|
||||
|
||||
private final ClusterLuaScript getQueuesToPersistScript;
|
||||
|
||||
MessagesCacheGetQueuesToPersistScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_queues_to_persist.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
List<String> execute(final int slot, final Instant maxTime, final int limit) {
|
||||
final List<String> keys = List.of(
|
||||
new String(MessagesCache.getQueueIndexKey(slot), StandardCharsets.UTF_8) // queueTotalIndexKey
|
||||
);
|
||||
final List<String> args = List.of(
|
||||
String.valueOf(maxTime.toEpochMilli()), // maxTime
|
||||
String.valueOf(limit) // limit
|
||||
);
|
||||
|
||||
//noinspection unchecked
|
||||
return (List<String>) getQueuesToPersistScript.execute(keys, args);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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));
|
||||
}
|
||||
}
|
||||
+21
-11
@@ -10,17 +10,21 @@ 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.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.scheduler.Schedulers;
|
||||
|
||||
public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerConfiguration> {
|
||||
|
||||
private static final String WORKER_COUNT = "workers";
|
||||
private static final String MAX_CONCURRENCY = "maxConcurrency";
|
||||
|
||||
public MessagePersisterServiceCommand() {
|
||||
super(new Application<>() {
|
||||
@@ -35,11 +39,13 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
@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(WORKER_COUNT)
|
||||
.dest(MAX_CONCURRENCY)
|
||||
.required(true)
|
||||
.help("The number of worker threads");
|
||||
.help("The maximum number of concurrent Redis/DynamoDB operations");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -60,16 +66,20 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
});
|
||||
}
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(),
|
||||
deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
try (final ExecutorService persistQueueExecutorService = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(),
|
||||
deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
Schedulers.fromExecutorService(persistQueueExecutorService, "persistQueue"),
|
||||
Clock.systemUTC(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(MAX_CONCURRENCY));
|
||||
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
|
||||
super.run(environment, namespace, configuration);
|
||||
super.run(environment, namespace, configuration);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
-- returns a list of queues that meet persistence criteria
|
||||
|
||||
local queueTotalIndexKey = KEYS[1] -- sorted set of all queues in the shard, by timestamp of oldest message
|
||||
local maxTime = ARGV[1] -- [number] the most recent queue timestamp that may be fetched
|
||||
local limit = ARGV[2] -- [number] the maximum number of queues to fetch
|
||||
|
||||
local results = redis.call("ZRANGE", queueTotalIndexKey, 0, maxTime, "BYSCORE", "LIMIT", 0, limit)
|
||||
|
||||
if results and next(results) then
|
||||
redis.call("ZREM", queueTotalIndexKey, unpack(results))
|
||||
end
|
||||
|
||||
return results
|
||||
@@ -0,0 +1,10 @@
|
||||
-- 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
|
||||
+13
-2
@@ -21,6 +21,7 @@ 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.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -53,6 +54,7 @@ class MessagePersisterIntegrationTest {
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private Scheduler persistQueueScheduler;
|
||||
private ExecutorService messageDeletionExecutorService;
|
||||
private ExecutorService websocketConnectionEventExecutor;
|
||||
private ExecutorService asyncOperationQueueingExecutor;
|
||||
@@ -77,6 +79,7 @@ class MessagePersisterIntegrationTest {
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
persistQueueScheduler = Schedulers.newBoundedElastic(10, 10_000, "persistQueue");
|
||||
messageDeletionExecutorService = Executors.newSingleThreadExecutor();
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
@@ -97,8 +100,14 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
redisMessageAvailabilityManager.start();
|
||||
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
messagePersister = new MessagePersister(messagesCache,
|
||||
messagesManager,
|
||||
accountsManager,
|
||||
dynamicConfigurationManager,
|
||||
persistQueueScheduler,
|
||||
Clock.systemUTC(),
|
||||
PERSIST_DELAY,
|
||||
1);
|
||||
|
||||
account = mock(Account.class);
|
||||
|
||||
@@ -107,6 +116,7 @@ class MessagePersisterIntegrationTest {
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getUuid()).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)));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
@@ -125,6 +135,7 @@ class MessagePersisterIntegrationTest {
|
||||
asyncOperationQueueingExecutor.awaitTermination(15, TimeUnit.SECONDS);
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
persistQueueScheduler.dispose();
|
||||
|
||||
redisMessageAvailabilityManager.stop();
|
||||
}
|
||||
|
||||
+249
-107
@@ -15,23 +15,27 @@ 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.doAnswer;
|
||||
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 java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
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;
|
||||
@@ -55,9 +59,12 @@ import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.util.retry.Retry;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
|
||||
|
||||
@Timeout(value = 15, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@@ -69,13 +76,20 @@ class MessagePersisterTest {
|
||||
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;
|
||||
@@ -97,6 +111,8 @@ class MessagePersisterTest {
|
||||
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 -> invocation.getArgument(0));
|
||||
|
||||
@@ -105,22 +121,30 @@ class MessagePersisterTest {
|
||||
when(destinationAccount.getNumber()).thenReturn(DESTINATION_ACCOUNT_NUMBER);
|
||||
when(destinationAccount.getDevice(DESTINATION_DEVICE_ID)).thenReturn(Optional.of(DESTINATION_DEVICE));
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getMessagePersisterConfiguration())
|
||||
.thenReturn(new DynamicMessagePersisterConfiguration(true, EXTRA_ROOM_RATIO));
|
||||
.thenReturn(new DynamicMessagePersisterConfiguration(true, EXTRA_ROOM_RATIO, Duration.ofHours(1)));
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC(), mock(ExperimentEnrollmentManager.class));
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
persistQueueScheduler = Schedulers.newBoundedElastic(10, 10_000, "persistQueue");
|
||||
messagesCache = spy(new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), CLOCK, mock(ExperimentEnrollmentManager.class)));
|
||||
messagePersister = new MessagePersister(messagesCache,
|
||||
messagesManager,
|
||||
accountsManager,
|
||||
dynamicConfigurationManager,
|
||||
persistQueueScheduler,
|
||||
CLOCK,
|
||||
PERSIST_DELAY,
|
||||
1,
|
||||
Retry.backoff(1, Duration.ZERO));
|
||||
|
||||
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), any())).thenAnswer(invocation -> {
|
||||
persistMessagesAnswer = invocation -> {
|
||||
final UUID destinationUuid = invocation.getArgument(0);
|
||||
final Device destinationDevice = invocation.getArgument(1);
|
||||
final List<MessageProtos.Envelope> messages = invocation.getArgument(2);
|
||||
@@ -132,7 +156,9 @@ class MessagePersisterTest {
|
||||
}
|
||||
|
||||
return messages.size();
|
||||
});
|
||||
};
|
||||
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), any())).thenAnswer(persistMessagesAnswer);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -142,79 +168,87 @@ class MessagePersisterTest {
|
||||
sharedExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
persistQueueScheduler.dispose();
|
||||
|
||||
resubscribeRetryExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
resubscribeRetryExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPersistNextQueuesNoQueues() {
|
||||
messagePersister.persistNextQueues(Instant.now());
|
||||
void persistNextNodeNoQueues() {
|
||||
assertEquals(0, messagePersister.persistNextNode());
|
||||
|
||||
verify(accountsManager, never()).getByAccountIdentifier(any(UUID.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPersistNextQueuesSingleQueue() {
|
||||
final String queueName = new String(
|
||||
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
|
||||
void persistNodeSingleQueue() {
|
||||
final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount,
|
||||
CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1)));
|
||||
|
||||
messagePersister.persistNextQueues(now.plus(messagePersister.getPersistDelay()));
|
||||
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));
|
||||
verify(messagesDynamoDb, atLeastOnce())
|
||||
.store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE));
|
||||
|
||||
assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPersistNextQueuesSingleQueueTooSoon() {
|
||||
final String queueName = new String(
|
||||
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
|
||||
void persistNodeSingleQueueTooSoon() {
|
||||
final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, CLOCK.instant());
|
||||
|
||||
messagePersister.persistNextQueues(now);
|
||||
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 slot = 7;
|
||||
final int queueCount = (MessagePersister.QUEUE_BATCH_LIMIT * 3) + 7;
|
||||
final int messagesPerQueue = 10;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
for (int i = 0; i < queueCount; i++) {
|
||||
final String queueName = generateRandomQueueNameForSlot(slot);
|
||||
final UUID accountUuid = MessagesCache.getAccountUuidFromQueueName(queueName);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queueName);
|
||||
final String accountNumber = "+1800555%04d".formatted(i);
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(accountUuid)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByAccountIdentifierAsync(accountUuid))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
|
||||
when(account.getUuid()).thenReturn(accountUuid);
|
||||
when(account.getNumber()).thenReturn(accountNumber);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountUuid);
|
||||
when(account.getDevice(anyByte())).thenAnswer(invocation -> Optional.of(DevicesHelper.createDevice(invocation.getArgument(0))));
|
||||
|
||||
insertMessages(accountUuid, deviceId, messagesPerQueue, now);
|
||||
insertMessages(accountUuid, deviceId, messagesPerQueue, CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1)));
|
||||
}
|
||||
|
||||
setNextSlotToPersist(slot);
|
||||
final Set<RedisClusterNode> persistedNodes = new HashSet<>();
|
||||
boolean addedNode;
|
||||
int queuesPersisted = 0;
|
||||
|
||||
messagePersister.persistNextQueues(now.plus(messagePersister.getPersistDelay()));
|
||||
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);
|
||||
@@ -224,53 +258,192 @@ class MessagePersisterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPersistQueueRetry() {
|
||||
final String queueName = new String(
|
||||
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
|
||||
void testPersistNodePersistenceDisabled() {
|
||||
final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount,
|
||||
CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1)));
|
||||
|
||||
doAnswer((Answer<Void>) _ -> {
|
||||
throw new RuntimeException("OH NO.");
|
||||
}).when(messagesDynamoDb).store(any(), eq(DESTINATION_ACCOUNT_UUID), eq(DESTINATION_DEVICE));
|
||||
when(dynamicConfiguration.getMessagePersisterConfiguration())
|
||||
.thenReturn(new DynamicMessagePersisterConfiguration(false, EXTRA_ROOM_RATIO, Duration.ofHours(1)));
|
||||
|
||||
messagePersister.persistNextQueues(now.plus(messagePersister.getPersistDelay()));
|
||||
assertEquals(0, messagePersister.persistNode(
|
||||
getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID))));
|
||||
|
||||
assertEquals(List.of(queueName),
|
||||
messagesCache.getQueuesToPersist(SlotHash.getSlot(queueName),
|
||||
Instant.now().plus(messagePersister.getPersistDelay()), 1));
|
||||
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 persistNodePersistQueueMessagePersistenceException() {
|
||||
final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7;
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount,
|
||||
CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1)));
|
||||
|
||||
// Provoke a MessagePersistenceException
|
||||
when(messagesManager.persistMessages(any(), any(), any())).thenReturn(0);
|
||||
|
||||
assertEquals(0, messagePersister.persistNode(
|
||||
getNodeWithKey(MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID))));
|
||||
|
||||
// We use this as a proxy for attempts to persist messages; for a MessagePersistenceException, we should NOT retry,
|
||||
// and this should happen exactly once
|
||||
verify(messagesCache).lockQueueForPersistence(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID);
|
||||
verify(messagesDynamoDb, never()).store(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPersistQueueRetryLoop() {
|
||||
final String queueName = new String(
|
||||
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
|
||||
final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, CLOCK.instant().minus(PERSIST_DELAY.plusSeconds(1)));
|
||||
|
||||
// returning `0` indicates something not working correctly
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), anyList())).thenReturn(0);
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
|
||||
assertThrows(MessagePersistenceException.class,
|
||||
() -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, "test")));
|
||||
() -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnlinkOnFullQueue() {
|
||||
final String queueName = new String(
|
||||
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
|
||||
final int messageCount = 1;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
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);
|
||||
@@ -300,21 +473,18 @@ class MessagePersisterTest {
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
|
||||
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, "test"));
|
||||
messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty()));
|
||||
verify(accountsManager, exactly()).removeDevice(destinationAccount, DESTINATION_DEVICE_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTrimOnFullPrimaryQueue() {
|
||||
final byte[] queueName = MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, Device.PRIMARY_ID);
|
||||
final Instant now = Instant.now();
|
||||
|
||||
final List<MessageProtos.Envelope> cachedMessages = Stream.generate(() -> generateMessage(
|
||||
DESTINATION_ACCOUNT_UUID, UUID.randomUUID(), now.getEpochSecond(), ThreadLocalRandom.current().nextInt(100)))
|
||||
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 (MessageProtos.Envelope envelope : cachedMessages) {
|
||||
for (final MessageProtos.Envelope envelope : cachedMessages) {
|
||||
messagesCache.insert(UUID.fromString(envelope.getServerGuid()), DESTINATION_ACCOUNT_UUID, Device.PRIMARY_ID, envelope).join();
|
||||
}
|
||||
|
||||
@@ -326,7 +496,7 @@ class MessagePersisterTest {
|
||||
long total = 0L;
|
||||
for (int i = 0; i < 100; i++) {
|
||||
final UUID guid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope envelope = generateMessage(DESTINATION_ACCOUNT_UUID, guid, now.getEpochSecond(), 13);
|
||||
final MessageProtos.Envelope envelope = generateMessage(DESTINATION_ACCOUNT_UUID, guid, CLOCK.instant().getEpochSecond(), 13);
|
||||
persistedMessages.add(envelope);
|
||||
if (total < expectedClearedBytes) {
|
||||
total += envelope.getSerializedSize();
|
||||
@@ -334,8 +504,6 @@ class MessagePersisterTest {
|
||||
}
|
||||
}
|
||||
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
|
||||
final Device primary = mock(Device.class);
|
||||
when(primary.getId()).thenReturn((byte) 1);
|
||||
when(primary.isPrimary()).thenReturn(true);
|
||||
@@ -351,29 +519,20 @@ class MessagePersisterTest {
|
||||
when(messagesManager.delete(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(10), () ->
|
||||
messagePersister.persistNextQueues(Clock.systemUTC().instant()));
|
||||
assertThrows(MessagePersistenceException.class, () ->
|
||||
messagePersister.persistQueue(destinationAccount, primary, Tags.empty()));
|
||||
|
||||
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());
|
||||
|
||||
final List<String> queuesToPersist = messagesCache.getQueuesToPersist(SlotHash.getSlot(queueName),
|
||||
Clock.systemUTC().instant(), 1);
|
||||
assertEquals(1, queuesToPersist.size());
|
||||
assertEquals(new String(queueName, StandardCharsets.UTF_8), queuesToPersist.getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFailedUnlinkOnFullQueueThrowsForRetry() {
|
||||
final String queueName = new String(
|
||||
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
|
||||
final int messageCount = 1;
|
||||
final Instant now = Instant.now();
|
||||
|
||||
insertMessages(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID, messageCount, now);
|
||||
setNextSlotToPersist(SlotHash.getSlot(queueName));
|
||||
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);
|
||||
@@ -403,25 +562,13 @@ class MessagePersisterTest {
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), anyList())).thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
|
||||
when(accountsManager.removeDevice(destinationAccount, DESTINATION_DEVICE_ID)).thenThrow(new RuntimeException());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, "test"));
|
||||
assertThrows(RuntimeException.class, () -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE, Tags.empty()));
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
private static String generateRandomQueueNameForSlot(final int slot) {
|
||||
|
||||
while (true) {
|
||||
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final String queueNameBase = "user_queue::{" + uuid + "::";
|
||||
|
||||
for (byte deviceId = 1; deviceId < Device.MAXIMUM_DEVICE_ID; deviceId++) {
|
||||
final String queueName = queueNameBase + deviceId + "}";
|
||||
|
||||
if (SlotHash.getSlot(queueName) == slot) {
|
||||
return queueName;
|
||||
}
|
||||
}
|
||||
}
|
||||
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,
|
||||
@@ -444,9 +591,4 @@ class MessagePersisterTest {
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.build();
|
||||
}
|
||||
|
||||
private void setNextSlotToPersist(final int nextSlot) {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(MessagesCache.NEXT_SLOT_TO_PERSIST_KEY, String.valueOf(nextSlot - 1)));
|
||||
}
|
||||
}
|
||||
+69
-14
@@ -24,9 +24,9 @@ import static org.mockito.Mockito.when;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.lettuce.core.RedisCommandTimeoutException;
|
||||
import io.lettuce.core.RedisFuture;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.lettuce.core.cluster.api.reactive.RedisAdvancedClusterReactiveCommands;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.protocol.AsyncCommand;
|
||||
import io.lettuce.core.protocol.RedisCommand;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -42,10 +42,12 @@ import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -98,9 +100,10 @@ class MessagesCacheTest {
|
||||
private MessagesCache messagesCache;
|
||||
|
||||
private static final UUID DESTINATION_UUID = UUID.randomUUID();
|
||||
|
||||
private static final byte DESTINATION_DEVICE_ID = 7;
|
||||
|
||||
private static final Duration NODE_CLAIM_TTL = Duration.ofHours(1);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
@@ -390,22 +393,74 @@ class MessagesCacheTest {
|
||||
StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
public void testGetQueuesToPersist(final boolean sealedSender) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
@Test
|
||||
void claimNextNodeToPersist() {
|
||||
final int partitionCount =
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> connection.getPartitions().size());
|
||||
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid, sealedSender)).join();
|
||||
final int slot = SlotHash.getSlot(DESTINATION_UUID + "::" + DESTINATION_DEVICE_ID);
|
||||
final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
assertTrue(messagesCache.getQueuesToPersist(slot + 1, Instant.now().plusSeconds(60), 100).isEmpty());
|
||||
for (int i = 0; i < partitionCount; i++) {
|
||||
assertTrue(messagesCache.claimNextNodeToPersist(persisterId, NODE_CLAIM_TTL).isPresent());
|
||||
}
|
||||
|
||||
final List<String> queues = messagesCache.getQueuesToPersist(slot, Instant.now().plusSeconds(60), 100);
|
||||
assertTrue(messagesCache.claimNextNodeToPersist(persisterId, NODE_CLAIM_TTL).isEmpty(),
|
||||
"Should not be able to claim a node when all nodes are already claimed");
|
||||
}
|
||||
|
||||
assertEquals(1, queues.size());
|
||||
assertEquals(DESTINATION_UUID, MessagesCache.getAccountUuidFromQueueName(queues.getFirst()));
|
||||
assertEquals(DESTINATION_DEVICE_ID, MessagesCache.getDeviceIdFromQueueName(queues.getFirst()));
|
||||
@Test
|
||||
void claimNextNodeToPersistRotation() {
|
||||
final int partitionCount =
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection -> connection.getPartitions().size());
|
||||
|
||||
final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
final Set<RedisClusterNode> claimedNodes = new HashSet<>();
|
||||
|
||||
for (int i = 0; i < partitionCount; i++) {
|
||||
final Optional<RedisClusterNode> maybeNode = messagesCache.claimNextNodeToPersist(persisterId, NODE_CLAIM_TTL);
|
||||
assertTrue(maybeNode.isPresent());
|
||||
|
||||
claimedNodes.add(maybeNode.get());
|
||||
messagesCache.releaseNodeClaim(maybeNode.get(), persisterId);
|
||||
}
|
||||
|
||||
assertEquals(partitionCount, claimedNodes.size(),
|
||||
"Persisters should cycle through all available partitions when claims are uncontested");
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimNode() {
|
||||
final RedisClusterNode node =
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.getPartitions().stream().findFirst().orElseThrow());
|
||||
|
||||
final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
assertTrue(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL));
|
||||
assertFalse(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL), "Should not be able to claim a node twice");
|
||||
|
||||
messagesCache.releaseNodeClaim(node, persisterId);
|
||||
assertTrue(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL), "Should be able to claim node after releasing claim");
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseNodeClaim() {
|
||||
final RedisClusterNode node =
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.getPartitions().stream().findFirst().orElseThrow());
|
||||
|
||||
final String persisterId = UUID.randomUUID().toString();
|
||||
final String competingPersisterId = UUID.randomUUID().toString();
|
||||
|
||||
messagesCache.claimNode(node, competingPersisterId, NODE_CLAIM_TTL);
|
||||
|
||||
assertFalse(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL),
|
||||
"Should not be able to claim a node claimed by another persister");
|
||||
|
||||
messagesCache.releaseNodeClaim(node, persisterId);
|
||||
assertFalse(messagesCache.claimNode(node, persisterId, NODE_CLAIM_TTL),
|
||||
"Should not be able to release/claim a node claimed by another persister");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
Reference in new issue
Block a user