diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 77352ed57..02d1daf4c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -316,6 +316,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand; import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand; import org.whispersystems.textsecuregcm.workers.CertificateCommand; import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand; +import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand; import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand; import org.whispersystems.textsecuregcm.workers.CopyToS3Command; import org.whispersystems.textsecuregcm.workers.DeleteUserCommand; @@ -391,6 +392,7 @@ public class WhisperServerService extends Application> accountDeviceIdentifiers, final Instant cutoffTime) { + foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime); + } } 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 9e1bf934c..f30f17a03 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 @@ -430,6 +430,15 @@ public class FoundationDbMessageStore { } } + /// Remove any entries from each database's versionstamp-clock namespace that are strictly older than the given timestamp. + /// + /// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp + public void expireOldVersionstamps(final Instant oldestRetainedEntryTimestamp) { + for (VersionstampClock versionstampClock : versionstampClocks.values()) { + versionstampClock.clearExpiredEntries(oldestRetainedEntryTimestamp); + } + } + /// Delete messages for the given devices that were inserted before the given time. /// /// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB @@ -447,7 +456,6 @@ public class FoundationDbMessageStore { /// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted /// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to /// date. - @VisibleForTesting public void deleteMessagesBefore(final Map> accountDeviceIdentifiers, final Instant cutoffTime) { final Map> queueSubspacesToTrimByDatabase = new IdentityHashMap<>(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java new file mode 100644 index 000000000..9779b7867 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommand.java @@ -0,0 +1,112 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.workers; + +import com.google.common.annotations.VisibleForTesting; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.stream.Collectors; +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.storage.Account; +import org.whispersystems.textsecuregcm.storage.Device; +import org.whispersystems.textsecuregcm.storage.MessagesManager; +import reactor.core.publisher.Flux; + +public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassCrawlAccountsCommand { + + private final Clock clock; + + @VisibleForTesting + static final String DRY_RUN_ARGUMENT = "dry-run"; + + @VisibleForTesting + static final String BATCH_SIZE_ARGUMENT = "batch-size"; + + @VisibleForTesting + static final String MESSAGE_TTL_DAYS_ARGUMENT = "message-ttl-days"; + + @VisibleForTesting + static final String VERSIONSTAMP_TTL_DAYS_ARGUMENT = "versionstamp-ttl-days"; + + @VisibleForTesting + static final Duration TIMESTAMP_RETENTION_PERIOD = Duration.ofDays(60); + + private static final Logger log = LoggerFactory.getLogger(ClearExpiredFoundationDbMessagesCommand.class); + + public ClearExpiredFoundationDbMessagesCommand(final Clock clock) { + super("clear-expired-foundationdb-messages", "Removes expired messages from FoundationDB"); + + this.clock = clock; + } + + @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 delete any messages (but do still make entries in the versionstamp clock)"); + + subparser.addArgument("--batch-size") + .type(Integer.class) + .dest(BATCH_SIZE_ARGUMENT) + .required(false) + .setDefault(10000) + .help("Maximum number of queues to trim in a single transaction"); + + subparser.addArgument("--message-ttl-days") + .type(Integer.class) + .dest(MESSAGE_TTL_DAYS_ARGUMENT) + .required(true) + .help("Desired message TTL in days"); + + subparser.addArgument("--versionstamp-ttl-days") + .type(Integer.class) + .dest(VERSIONSTAMP_TTL_DAYS_ARGUMENT) + .required(false) + .setDefault(180) + .help("Desired versionstamp-clock TTL in days"); + } + + @Override + protected void crawlAccounts(final Flux accounts) { + final MessagesManager messagesManager = getCommandDependencies().messagesManager(); + + // Record the current versionstamp/time pair for the benefit of future runs. Because this job runs regularly, it has + // the dual role of clearing messages and keeping the versionstamp/time mappings populated. + messagesManager.recordFoundationDbVersionstamps(); + + final int batchSize = getNamespace().getInt(BATCH_SIZE_ARGUMENT); + final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT); + final int messageTtlDays = getNamespace().getInt(MESSAGE_TTL_DAYS_ARGUMENT); + final int versionstampTtlDays = getNamespace().getInt(VERSIONSTAMP_TTL_DAYS_ARGUMENT); + + final Instant oldestMessageTime = clock.instant().minus(Duration.ofDays(messageTtlDays)); + final Instant oldestVersionstampTime = clock.instant().minus(Duration.ofDays(versionstampTtlDays)); + + accounts + .buffer(batchSize) + .map(batch -> batch.stream().collect( + Collectors.toMap( + account -> new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)), + account -> account.getDevices().stream().map(Device::getId).toList()))) + .doOnNext( + dryRun ? _ -> {} + : deviceIdsByAccountIdentifier -> messagesManager.deleteFoundationDbMessagesBefore(deviceIdsByAccountIdentifier, oldestMessageTime)) + .then() + .block(); + + messagesManager.expireOldFoundationDbVersionstamps(oldestVersionstampTime); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java new file mode 100644 index 000000000..3de68185c --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java @@ -0,0 +1,124 @@ +/* + * 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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +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 org.whispersystems.textsecuregcm.util.TestClock; +import reactor.core.publisher.Flux; + +class ClearExpiredFoundationDbMessagesCommandTest { + + private MessagesManager messagesManager = mock(MessagesManager.class); + + private static class TestClearExpiredFoundationDbMessagesCommand extends ClearExpiredFoundationDbMessagesCommand { + + private final CommandDependencies commandDependencies; + + private final boolean dryRun; + + public TestClearExpiredFoundationDbMessagesCommand(final MessagesManager messagesManager, + final boolean dryRun, + final Clock clock) { + + super(clock); + + this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); + this.dryRun = dryRun; + } + + @Override + protected CommandDependencies getCommandDependencies() { + return commandDependencies; + } + + @Override + protected Namespace getNamespace() { + return new Namespace(Map.of( + ClearExpiredFoundationDbMessagesCommand.BATCH_SIZE_ARGUMENT, 4, + ClearExpiredFoundationDbMessagesCommand.DRY_RUN_ARGUMENT, dryRun, + ClearExpiredFoundationDbMessagesCommand.MESSAGE_TTL_DAYS_ARGUMENT, 1, + ClearExpiredFoundationDbMessagesCommand.VERSIONSTAMP_TTL_DAYS_ARGUMENT, 10 + )); + } + } + + @ParameterizedTest + @ValueSource(booleans={true, false}) + void crawlAccounts(final boolean dryRun) { + + final Clock clock = TestClock.pinned(Instant.now()); + final Instant messageCutoffTime = clock.instant().minus(Duration.ofDays(1)); + final Instant versionstampCutoffTime = clock.instant().minus(Duration.ofDays(10)); + + final TestClearExpiredFoundationDbMessagesCommand clearExpiredFoundationDbMessagesCommand = + new TestClearExpiredFoundationDbMessagesCommand(messagesManager, + dryRun, + clock); + + final List accounts = new ArrayList<>(); + final AciServiceIdentifier[] acis = new AciServiceIdentifier[10]; + for (int i = 0; i < 10; i++) { + final UUID accountIdentifier = UUID.randomUUID(); + final byte primaryDeviceId = Device.PRIMARY_ID; + final byte linkedDeviceId = 2; + + final Device primaryDevice = mock(Device.class); + when(primaryDevice.getId()).thenReturn(primaryDeviceId); + + final Device linkedDevice = mock(Device.class); + when(linkedDevice.getId()).thenReturn(linkedDeviceId); + + final Account account = mock(Account.class); + when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier); + when(account.getDevices()).thenReturn(i % 2 == 0 ? List.of(primaryDevice) : List.of(primaryDevice, linkedDevice)); + + accounts.add(account); + acis[i] = new AciServiceIdentifier(accountIdentifier); + } + + clearExpiredFoundationDbMessagesCommand.crawlAccounts(Flux.fromIterable(accounts)); + + final List oneDeviceId = List.of(Device.PRIMARY_ID); + final List twoDeviceIds = List.of(Device.PRIMARY_ID, (byte) 2); + if (!dryRun) { + verify(messagesManager).deleteFoundationDbMessagesBefore( + Map.of(acis[0], oneDeviceId, acis[1], twoDeviceIds, acis[2], oneDeviceId, acis[3], twoDeviceIds), + messageCutoffTime); + verify(messagesManager).deleteFoundationDbMessagesBefore( + Map.of(acis[4], oneDeviceId, acis[5], twoDeviceIds, acis[6], oneDeviceId, acis[7], twoDeviceIds), + messageCutoffTime); + verify(messagesManager).deleteFoundationDbMessagesBefore( + Map.of(acis[8], oneDeviceId, acis[9], twoDeviceIds), + messageCutoffTime); + } else { + verify(messagesManager, never()).deleteFoundationDbMessagesBefore(any(), any()); + } + + verify(messagesManager).recordFoundationDbVersionstamps(); + verify(messagesManager) + .expireOldFoundationDbVersionstamps(versionstampCutoffTime); + } +}