diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 788896cae..760428658 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -336,6 +336,7 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend import org.whispersystems.textsecuregcm.workers.ServerVersionCommand; import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask; import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand; +import org.whispersystems.textsecuregcm.workers.TrimOversizedFoundationDbMessageQueuesCommand; import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand; import org.whispersystems.textsecuregcm.workers.UnlinkDevicesWithIdlePrimaryCommand; import org.whispersystems.textsecuregcm.workers.ZkParamsCommand; @@ -395,6 +396,7 @@ public class WhisperServerService extends Application> accountDeviceIdentifiers, final Instant cutoffTime) { foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime); } + + /// Trim the provided message queue if needed. + /// + /// @param aci The ACI of the message queue to trim + /// @param device The device of the message queue to trim + /// @param maxQueueSizeBytes The threshold size beyond which the message queue will be trimmed + /// @param targetQueueSizeBytes The target size to trim to + /// @param rangeSplitChunkSizeBytes The approximate chunk size in bytes used to split the range covered by the message queue + /// @param dryRun Whether to actually trim the provided queue + public Mono trimQueue( + final AciServiceIdentifier aci, + final Device device, + final long maxQueueSizeBytes, + final long targetQueueSizeBytes, + final long rangeSplitChunkSizeBytes, + final boolean dryRun) { + // All trims will be considered successful during a dry run + final UnaryOperator> deleteModifier = dryRun ? _ -> Mono.just(true) : UnaryOperator.identity(); + return foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, deleteModifier); + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java index 8a6c6ca02..1b54047b8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java @@ -1,6 +1,9 @@ package org.whispersystems.textsecuregcm.storage.foundationdb; +import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; + import com.apple.foundationdb.Database; +import com.apple.foundationdb.KeyArrayResult; import com.apple.foundationdb.MutationType; import com.apple.foundationdb.Range; import com.apple.foundationdb.Transaction; @@ -11,7 +14,10 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.hash.Hashing; import io.dropwizard.util.DataSize; import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.DistributionSummary; 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.nio.ByteBuffer; import java.time.Clock; @@ -22,21 +28,34 @@ import java.util.Arrays; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; +import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; +import org.whispersystems.textsecuregcm.storage.Device; +import org.whispersystems.textsecuregcm.util.Pair; import org.whispersystems.textsecuregcm.util.UUIDUtil; import org.whispersystems.textsecuregcm.util.Util; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.util.function.Tuple3; +import reactor.util.function.Tuples; /// An implementation of a message store backed by FoundationDB. /// @@ -82,6 +101,8 @@ public class FoundationDbMessageStore { public static final int MAX_EPOCHS = 4; public static final int MAX_SHARDS = 64; + private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(FoundationDbMessageStore.class, "queueSize"); + private static final Counter INSERT_MESSAGE_COUNTER = Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessage")); @@ -94,6 +115,10 @@ public class FoundationDbMessageStore { private static final Timer DELETE_MESSAGE_TIMER = Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer")); + private static final Counter ESTIMATED_TRIMMED_BYTES_COUNTER = Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "estimatedTrimmedBytes")); + private static final String TRIM_QUEUE_COUNTER_NAME = MetricsUtil.name(FoundationDbMessageStore.class, "trimQueue"); + private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStore.class); + /// Result of inserting a message for a particular device /// /// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty @@ -402,12 +427,7 @@ public class FoundationDbMessageStore { return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, Util.NOOP); } - @VisibleForTesting - FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, - final byte deviceId, - final int maxMessagesPerScan, - final Runnable doAfterCleanup) { - + Database[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) { // For each configured database epoch, which database held (or holds) the messages for this ACI/device pair? final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length]; @@ -415,6 +435,17 @@ public class FoundationDbMessageStore { databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch); } + return databasesForQueueByEpoch; + } + + @VisibleForTesting + FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, + final byte deviceId, + final int maxMessagesPerScan, + final Runnable doAfterCleanup) { + + final Database[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci); + return new FoundationDbMessageStream(this, aci, deviceId, @@ -537,7 +568,6 @@ public class FoundationDbMessageStore { return versionstamp.getUserVersion() & 0x3f; } - @VisibleForTesting static Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) { return getDeviceSubspace(aci, deviceId).get("Q"); } @@ -546,6 +576,146 @@ public class FoundationDbMessageStore { return getAccountSubspace(aci).get(deviceId); } + @VisibleForTesting + record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map> splitPointsByDatabase) {} + + private Flux getDistinctDatabasesForAci(final AciServiceIdentifier aci) { + return Flux.fromStream(Arrays.stream(getDatabasesByEpochForAci(aci)).filter(Objects::nonNull).distinct()); + } + + /// Estimates the size of the provided queue in bytes. + /// + /// @param aci The ACI of the message queue to estimate the size of + /// @param deviceId The device ID of the message queue to estimate the size of + @VisibleForTesting + Mono estimateQueueSize(final AciServiceIdentifier aci, final byte deviceId) { + final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range(); + + return getDistinctDatabasesForAci(aci) + .flatMap(database -> Mono.fromFuture(() -> FoundationDbUtil.safeRunAsync(database, transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange)))) + .reduce(0L, Long::sum); + } + + /// Estimates the size of the provided queue in bytes and computes a set of keys per database that split the range + /// covered by the queue in that database into roughly equally sized chunks. + /// + /// @param aci The ACI of the message queue to estimate the size of + /// @param deviceId The device ID of the message queue to estimate the size of + /// @param rangeSplitChunkSize The approximate chunk size in bytes used to split the range covered by the message queue + @VisibleForTesting + Mono estimateQueueSizeAndSplitPoints( + final AciServiceIdentifier aci, + final byte deviceId, + final long rangeSplitChunkSize) { + return getDistinctDatabasesForAci(aci) + .flatMap(database -> Mono.fromFuture(() -> estimateQueueSizeAndRangeSplitsForDatabase(database, aci, deviceId, rangeSplitChunkSize)) + .map(pair -> Tuples.of(pair.first(), database, pair.second().getKeys()))) + .collect(Collectors.teeing( + Collectors.summingLong(Tuple3::getT1), + Collectors.toMap(Tuple3::getT2, Tuple3::getT3), + QueueSizeAndRangeSplitPoints::new)); + } + + private CompletableFuture> estimateQueueSizeAndRangeSplitsForDatabase( + final Database database, + final AciServiceIdentifier aci, + final byte deviceId, + final long rangeSplitChunkSize) { + return FoundationDbUtil.safeRunAsync(database, transaction -> { + final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range(); + final CompletableFuture estimatedQueueSizeFuture = transaction.getEstimatedRangeSizeBytes(deviceQueueRange); + + final CompletableFuture rangeSplitPointsFuture = transaction.getRangeSplitPoints(deviceQueueRange, rangeSplitChunkSize); + return estimatedQueueSizeFuture.thenCombine(rangeSplitPointsFuture, Pair::new); + }); + } + + public Mono trimQueue(final AciServiceIdentifier aci, + final Device device, + final long maxQueueSizeBytes, + final long targetQueueSizeBytes, + final long rangeSplitChunkSizeBytes, + final UnaryOperator> deleteModifier) { + final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device) + .map(platform -> platform.name().toLowerCase(Locale.ROOT)) + .orElse("unknown")); + + return estimateQueueSizeAndSplitPoints(aci, device.getId(), rangeSplitChunkSizeBytes) + .doOnNext(queueSizeAndRangeSplitPoints -> + DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME) + .tags(Tags.of(platformTag)) + .register(Metrics.globalRegistry) + .record(queueSizeAndRangeSplitPoints.estimatedQueueSize())) + .flatMap(queueSizeAndRangeSplits -> { + if (queueSizeAndRangeSplits.estimatedQueueSize() < maxQueueSizeBytes) { + Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "needed", "false").increment(); + return Mono.empty(); + } + + final List orderedDatabases; + { + // Trim messages from the database(s) in the inactive epoch(s) before trimming from the database in the active epoch + final List orderedEpochsToTrim = new ArrayList<>(Arrays.stream(liveEpochs) + .filter(i -> i != activeEpoch) + .boxed() + .toList()); + orderedEpochsToTrim.add(activeEpoch); + orderedDatabases = orderedEpochsToTrim.stream().map(e -> getShardForAci(aci, e)).distinct().toList(); + } + + final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, device.getId()); + + final AtomicLong remainingBytesToDelete = new AtomicLong(queueSizeAndRangeSplits.estimatedQueueSize() - targetQueueSizeBytes); + return Flux.fromIterable(orderedDatabases) + .concatMap(database -> { + if (remainingBytesToDelete.get() <= 0) { + return Mono.just(true); + } + + // We used the same set of databases to compute the split points, so an entry must exist. + final List splitPoints = queueSizeAndRangeSplits.splitPointsByDatabase().get(database); + + assert splitPoints.size() >= 2; + + final int chunksToDelete = Math.min(Math.toIntExact(Math.ceilDiv(remainingBytesToDelete.get(), rangeSplitChunkSizeBytes)), splitPoints.size() - 1); + final byte[] endKeyExclusive = splitPoints.get(chunksToDelete); + + // Trim the oldest messages in the queue. + final Range range = new Range(deviceQueueSubspace.range().begin, endKeyExclusive); + + final Mono deleteMono = Mono.fromFuture(() -> trimQueue(database, range)) + .doOnSuccess(_ -> { + final long estimatedDeletedBytes = chunksToDelete * rangeSplitChunkSizeBytes; + remainingBytesToDelete.addAndGet(-estimatedDeletedBytes); + ESTIMATED_TRIMMED_BYTES_COUNTER.increment(estimatedDeletedBytes); + }) + .flatMap(_ -> Mono.just(true)); + + return deleteModifier.apply(deleteMono) + .onErrorResume(throwable -> { + LOGGER.warn("Failed to trim message queue for {}:{}", aci, device.getId(), throwable); + return Mono.just(false); + }); + }) + .reduce(true, (a, b) -> a && b) + .doOnSuccess(trimSucceeded -> Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "needed", "true", "success", String.valueOf(trimSucceeded)).increment()) + .then(); + }) + .onErrorResume(throwable -> { + // If we error out on estimating queue size, we don't know if this queue needed trimming + Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "success", "false").increment(); + LOGGER.warn("Failed to estimate queue size for {}:{}", aci, device.getId(), throwable); + return Mono.empty(); + }); + } + + private CompletableFuture trimQueue(final Database database, final Range range) { + return FoundationDbUtil.safeRunAsync(database, transaction -> { + transaction.clear(range); + return CompletableFuture.completedFuture(null); + }); + } + private static Subspace getAccountSubspace(final AciServiceIdentifier aci) { return MESSAGES_SUBSPACE.get(aci.uuid()); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java new file mode 100644 index 000000000..7ca8b9ce8 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommand.java @@ -0,0 +1,139 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.workers; + +import com.google.common.annotations.VisibleForTesting; +import io.dropwizard.util.DataSize; +import io.micrometer.core.instrument.Metrics; +import net.sourceforge.argparse4j.inf.Subparser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; +import org.whispersystems.textsecuregcm.identity.IdentityType; +import org.whispersystems.textsecuregcm.metrics.MetricsUtil; +import org.whispersystems.textsecuregcm.storage.Account; +import org.whispersystems.textsecuregcm.storage.MessagesManager; +import org.whispersystems.textsecuregcm.util.Pair; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class TrimOversizedFoundationDbMessageQueuesCommand extends AbstractSinglePassCrawlAccountsCommand { + @VisibleForTesting + static final String DRY_RUN_ARGUMENT = "dry-run"; + + @VisibleForTesting + static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency"; + + @VisibleForTesting + static final String MAX_QUEUE_SIZE_BYTES_ARGUMENT = "max-queue-size-bytes"; + + @VisibleForTesting + static final String TARGET_QUEUE_SIZE_BYTES_ARGUMENT = "target-queue-size-bytes"; + + @VisibleForTesting + static final String RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT = "range-split-chunk-size-bytes"; + + @VisibleForTesting + static final long DEFAULT_MAX_QUEUE_SIZE_BYTES = DataSize.gigabytes(10).toBytes(); + + @VisibleForTesting + static final long DEFAULT_TARGET_QUEUE_SIZE_BYTES = DataSize.gigabytes(9).toBytes(); + + @VisibleForTesting + static final long DEFAULT_RANGE_SPLIT_CHUNK_SIZE_BYTES = DataSize.gigabytes(1).toBytes(); + + private static final String QUEUES_INSPECTED_COUNTER_NAME = MetricsUtil.name( + TrimOversizedFoundationDbMessageQueuesCommand.class, "trimmedQueues"); + private static final int DEFAULT_MAX_CONCURRENCY = 16; + private static final Logger LOGGER = LoggerFactory.getLogger(TrimOversizedFoundationDbMessageQueuesCommand.class); + + public TrimOversizedFoundationDbMessageQueuesCommand() { + super("trim-oversized-fdb-message-queues", "Trims oversized message queues in FoundationDB"); + } + + @Override + public void configure(final Subparser subparser) { + super.configure(subparser); + + subparser.addArgument("--dry-run") + .type(Boolean.class) + .dest(DRY_RUN_ARGUMENT) + .required(false) + .setDefault(true) + .help("If true, don't actually trim any message queues."); + + subparser.addArgument("--max-concurrency") + .type(Integer.class) + .dest(MAX_CONCURRENCY_ARGUMENT) + .required(false) + .setDefault(DEFAULT_MAX_CONCURRENCY) + .help("Max concurrency for FoundationDB operations"); + + subparser.addArgument("--max-queue-size-bytes") + .type(Long.class) + .dest(MAX_QUEUE_SIZE_BYTES_ARGUMENT) + .required(false) + .setDefault(DEFAULT_MAX_QUEUE_SIZE_BYTES) + .help("If a message queue size exceeds this limit, trim it down."); + + subparser.addArgument("--target-queue-size-bytes") + .type(Long.class) + .dest(TARGET_QUEUE_SIZE_BYTES_ARGUMENT) + .required(false) + .setDefault(DEFAULT_TARGET_QUEUE_SIZE_BYTES) + .help("If trimming a message queue, the queue size to target."); + + subparser.addArgument("--range-split-chunk-size-bytes") + .type(Long.class) + .dest(RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT) + .required(false) + .setDefault(DEFAULT_RANGE_SPLIT_CHUNK_SIZE_BYTES) + .help(""" + The chunk size to use when determining split points for the range of keys covered by a message queue. + FoundationDB does not provide any documentation on this parameter, but observationally, + setting this value greater than 1 MB should be okay. + """); + } + + @Override + protected void crawlAccounts(final Flux accounts) { + final long maxQueueSizeBytes = getNamespace().getLong(MAX_QUEUE_SIZE_BYTES_ARGUMENT); + final long targetQueueSizeBytes = getNamespace().getLong(TARGET_QUEUE_SIZE_BYTES_ARGUMENT); + final long rangeSplitChunkSizeBytes = getNamespace().getLong(RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT); + + if (targetQueueSizeBytes <= 0) { + throw new IllegalArgumentException("target-queue-size-bytes must be positive"); + } + + if (targetQueueSizeBytes >= maxQueueSizeBytes) { + throw new IllegalArgumentException("target-queue-size-bytes must be less than max-queue-size-bytes"); + } + + if (rangeSplitChunkSizeBytes <= 0) { + throw new IllegalArgumentException("range-split-chunk-size-bytes must be positive"); + } + + final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT); + final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT); + + final MessagesManager messagesManager = getCommandDependencies().messagesManager(); + + accounts + .flatMapIterable(account -> + account.getDevices().stream().map( + device -> new Pair<>(new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)), device)).toList()) + .doOnNext(_ -> Metrics.counter(QUEUES_INSPECTED_COUNTER_NAME, "dryRun", String.valueOf(dryRun)).increment()) + .flatMap(accountAndDevice -> + messagesManager.trimQueue(accountAndDevice.first(), accountAndDevice.second(), maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, dryRun), + maxConcurrency) + .onErrorResume(e -> { + LOGGER.error("Failed to trim queue", e); + return Mono.empty(); + }) + .then() + .block(); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java index 313c65b23..19d9642e3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java @@ -9,6 +9,8 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; 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.apple.foundationdb.Database; import com.apple.foundationdb.KeyValue; @@ -45,6 +47,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.function.Supplier; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; @@ -52,7 +55,6 @@ import javax.annotation.Nullable; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; @@ -1143,6 +1145,89 @@ class FoundationDbMessageStoreTest { .block(); } + @ParameterizedTest + @ValueSource(ints = {5, 10, 20}) + void estimateQueueSizeAndSplitPoints(final long totalQueueSizeMb) { + final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID()); + final byte deviceId = Device.PRIMARY_ID; + final AtomicLong serialTimestamp = new AtomicLong(); + + // FoundationDB values must be less than 100 KB + final int contentSize = Math.toIntExact(DataSize.kilobytes(50).toBytes()); + + final long totalQueueSize = DataSize.megabytes(totalQueueSizeMb).toBytes(); + final long totalQueueSizePerEpoch = totalQueueSize / 2; + final int numMessagesPerEpoch = (int) totalQueueSizePerEpoch / contentSize; + + generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.FUTURE_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize); + generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.DEFAULT_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize); + + final long rangeSplitChunkBytes = DataSize.megabytes(1).toBytes(); + final FoundationDbMessageStore.QueueSizeAndRangeSplitPoints queueSizeAndSplitPoints = foundationDbMessageStore.estimateQueueSizeAndSplitPoints(aci, deviceId, rangeSplitChunkBytes).block(); + + assertNotNull(queueSizeAndSplitPoints); + + // The docs assert that if the returned size is larger than 3 MB, it can be considered accurate. + // Our queue sizes are greater than that, but even so, provide a 5% margin for error. + assertEquals(totalQueueSize, queueSizeAndSplitPoints.estimatedQueueSize(), totalQueueSize * 0.05); + queueSizeAndSplitPoints.splitPointsByDatabase().forEach((_, splitPointKeys) -> { + // FoundationDB's getRangeSplitPoints appears to use the provided chunk size as an exclusive upper bound + // on the bytes covered by each pair of split points. + // Splitting an x MB range with a 1 MB chunk size will generate chunk sizes < 1 MB, + // which in turn generates x+1 chunks or x+2 split point keys. + final long expectedNumChunks = Math.toIntExact(Math.ceilDiv(totalQueueSizePerEpoch, rangeSplitChunkBytes - DataSize.bytes(1).toBytes())); + assertEquals(expectedNumChunks + 1, splitPointKeys.size()); + }); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void trimQueue(final long rangeSplitSizeMb) { + final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID()); + final Device device = mock(Device.class); + final byte deviceId = Device.PRIMARY_ID; + when(device.getId()).thenReturn(deviceId); + final AtomicLong serialTimestamp = new AtomicLong(); + + // FoundationDB values must be less than 100 KB + final int contentSize = Math.toIntExact(DataSize.kilobytes(50).toBytes()); + + final long totalQueueSize = DataSize.megabytes(10).toBytes(); + final long totalQueueSizePerEpoch = totalQueueSize / 2; + final int numMessagesPerEpoch = (int) totalQueueSizePerEpoch / contentSize; + + final List inactiveEpochMessages = generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.FUTURE_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize); + generateAndInsertMessages(aci, deviceId, FoundationDbMessageStoreTest.DEFAULT_EPOCH, numMessagesPerEpoch, serialTimestamp::incrementAndGet, contentSize); + + final long maxQueueSizeBytes = DataSize.megabytes(4).toBytes(); + final long targetQueueSizeBytes = DataSize.megabytes(3).toBytes(); + final long rangeSplitSizeBytes = DataSize.megabytes(rangeSplitSizeMb).toBytes(); + + // Trim all the messages in the non-active epoch and ~2 MB worth of messages in the active epoch + foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitSizeBytes, UnaryOperator.identity()).block(); + + final Long remainingQueueSize = foundationDbMessageStore.estimateQueueSize(aci, deviceId).block(); + + // We expect to be within a delta of the target queue size, where the delta is upper bounded by the range split chunk size. + assertNotNull(remainingQueueSize); + assertEquals(targetQueueSizeBytes, remainingQueueSize, rangeSplitSizeBytes); + + // Check that all the retrieved messages have a timestamp greater than the last message in the inactive epoch + final long lastTimestampInInactiveEpoch = inactiveEpochMessages.getLast().getServerTimestamp(); + final List retrievedEntries = new ArrayList<>(); + + final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, + FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, + Util.NOOP); + StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())) + .recordWith(() -> retrievedEntries) + .expectNextMatches(entry -> entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message) + && message.getServerTimestamp() > lastTimestampInInactiveEpoch) + .thenConsumeWhile(entry -> !(entry instanceof MessageStreamEntry.QueueEmpty)) + .expectNext(new MessageStreamEntry.QueueEmpty()) + .verifyTimeout(Duration.ofSeconds(1)); + } + static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) { return generateRandomMessage(ephemeral, contentSize, CLOCK.millis()); } @@ -1164,15 +1249,15 @@ class FoundationDbMessageStoreTest { final byte deviceId, final int epoch, final int messageCount, - final Supplier timestampSupplier) { - + final Supplier timestampSupplier, + final int contentSize) { final MessageGuidCodec messageGuidCodec = new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher); return IntStream.range(0, messageCount) .mapToObj(_ -> { final MessageProtos.Envelope message = - generateRandomMessage(false, 16, timestampSupplier.get()); + generateRandomMessage(false, contentSize, timestampSupplier.get()); final FoundationDbMessageStore.InsertResult insertResult = foundationDbMessageStore.insert(aci, Map.of(deviceId, message), epoch).join().get(deviceId); @@ -1185,6 +1270,14 @@ class FoundationDbMessageStoreTest { .toList(); } + private List generateAndInsertMessages(final AciServiceIdentifier aci, + final byte deviceId, + final int epoch, + final int messageCount, + final Supplier timestampSupplier) { + return generateAndInsertMessages(aci, deviceId, epoch, messageCount, timestampSupplier, 16); + } + @Nullable private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java new file mode 100644 index 000000000..3bf33aad9 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.workers; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.sourceforge.argparse4j.inf.Namespace; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; +import org.whispersystems.textsecuregcm.identity.IdentityType; +import org.whispersystems.textsecuregcm.storage.Account; +import org.whispersystems.textsecuregcm.storage.Device; +import org.whispersystems.textsecuregcm.storage.MessagesManager; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class TrimOversizedFoundationDbMessageQueuesCommandTest { + private final MessagesManager messagesManager = mock(MessagesManager.class); + + private static class TestTrimOversizedFoundationDbMessageQueuesCommand extends + TrimOversizedFoundationDbMessageQueuesCommand { + private final CommandDependencies commandDependencies; + private final boolean dryRun; + + public TestTrimOversizedFoundationDbMessageQueuesCommand( + final MessagesManager messagesManager, + 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); + this.dryRun = dryRun; + } + + @Override + protected CommandDependencies getCommandDependencies() { + return commandDependencies; + } + + @Override + protected Namespace getNamespace() { + return new Namespace(Map.of( + TrimOversizedFoundationDbMessageQueuesCommand.DRY_RUN_ARGUMENT, dryRun, + TrimOversizedFoundationDbMessageQueuesCommand.MAX_CONCURRENCY_ARGUMENT, 4, + TrimOversizedFoundationDbMessageQueuesCommand.MAX_QUEUE_SIZE_BYTES_ARGUMENT, TrimOversizedFoundationDbMessageQueuesCommand.DEFAULT_MAX_QUEUE_SIZE_BYTES, + TrimOversizedFoundationDbMessageQueuesCommand.TARGET_QUEUE_SIZE_BYTES_ARGUMENT, TrimOversizedFoundationDbMessageQueuesCommand.DEFAULT_TARGET_QUEUE_SIZE_BYTES, + TrimOversizedFoundationDbMessageQueuesCommand.RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT, TrimOversizedFoundationDbMessageQueuesCommand.DEFAULT_RANGE_SPLIT_CHUNK_SIZE_BYTES + )); + } + } + + @ParameterizedTest + @ValueSource(booleans={true, false}) + void crawlAccounts(final boolean dryRun) { + final TestTrimOversizedFoundationDbMessageQueuesCommand trimOversizedFoundationDbMessageQueuesCommand = + new TestTrimOversizedFoundationDbMessageQueuesCommand(messagesManager, dryRun); + + final Device device = mock(Device.class); + when(device.getId()).thenReturn(Device.PRIMARY_ID); + + final UUID uuid = UUID.randomUUID(); + final Account account = mock(Account.class); + when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid); + when(account.getDevices()).thenReturn(List.of(device)); + + when(messagesManager.trimQueue(any(), any(), anyLong(), anyLong(), anyLong(), anyBoolean())).thenReturn(Mono.empty()); + + trimOversizedFoundationDbMessageQueuesCommand.crawlAccounts(Flux.just(account)); + + verify(messagesManager).trimQueue( + eq(new AciServiceIdentifier(uuid)), + eq(device), + eq(TrimOversizedFoundationDbMessageQueuesCommand.DEFAULT_MAX_QUEUE_SIZE_BYTES), + eq(TrimOversizedFoundationDbMessageQueuesCommand.DEFAULT_TARGET_QUEUE_SIZE_BYTES), + eq(TrimOversizedFoundationDbMessageQueuesCommand.DEFAULT_RANGE_SPLIT_CHUNK_SIZE_BYTES), + eq(dryRun) + ); + } +}