diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java index a33023145..052db7360 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java @@ -1316,6 +1316,16 @@ public class Accounts { .map(Accounts::fromItem))); } + boolean accountExists(final UUID aci) { + final GetItemResponse response = dynamoDbClient.getItem(GetItemRequest.builder() + .tableName(accountsTableName) + .key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(aci))) + .projectionExpression(KEY_ACCOUNT_UUID) + .consistentRead(true) + .build()); + return response.hasItem() && !response.item().isEmpty(); + } + private TransactWriteItem buildPutDeletedAccount(final UUID aci, final UUID pni) { return TransactWriteItem.builder() .put(Put.builder() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java index be45727a9..727fd2e39 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -78,6 +78,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey; import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey; import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest; import org.whispersystems.textsecuregcm.entities.TransferArchiveResult; +import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection; @@ -1496,6 +1497,10 @@ public class AccountsManager extends RedisPubSubAdapter implemen } } + public boolean accountExists(final AciServiceIdentifier accountIdentifier) { + return accounts.accountExists(accountIdentifier.uuid()); + } + private void delete(final Account account) { final List additionalWriteItems = new ArrayList<>(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java index 3f0a1b864..b1178fe09 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -47,6 +46,8 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbUtil; import org.whispersystems.textsecuregcm.util.ManagedExecutors; 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; public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithDependencies { @@ -153,10 +154,11 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD void clearOrphanedQueues(final Stream databases, final AccountsManager accountsManager, final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit, final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager, - final Executor executor) { + final ExecutorService executor) { + final Scheduler scheduler = Schedulers.fromExecutorService(executor); Flux.fromStream(databases) .flatMap(database -> crawlAcisInShard(database, accountsManager, concurrency, dryRun, maxAcisPerTransaction, - transactionRetryLimit, transactionTimeout, numChunks, accountLockManager, executor)) + transactionRetryLimit, transactionTimeout, numChunks, accountLockManager, scheduler)) .then() .block(); } @@ -164,19 +166,19 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD private Mono crawlAcisInShard(final FaultTolerantDatabase database, final AccountsManager accountsManager, final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit, final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager, - final Executor executor) { + final Scheduler scheduler) { return getAcisInShard(database, maxAcisPerTransaction, transactionRetryLimit, transactionTimeout, numChunks) .doOnNext(_ -> Metrics.counter(ACCOUNTS_CRAWLED_COUNTER, "dryRun", String.valueOf(dryRun)).increment()) - .flatMap(aci -> Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(aci.uuid())) - .flatMap(maybeAccount -> { - if (maybeAccount.isEmpty()) { - return Mono.just(aci); - } - return Mono.empty(); + .flatMap(aci -> Mono.fromCallable(() -> accountsManager.accountExists(aci)) + .subscribeOn(scheduler) + .flatMap(exists -> { + // This looks odd, but we want to delete accounts that don't exist i.e deleted accounts, so only + // pass the ACI downstream if the account does not exist. + return exists ? Mono.empty() : Mono.just(aci); }) .retryWhen(Retry.backoff(2, Duration.ofSeconds(1))) .onErrorResume(t -> { - logger.warn("Failed to fetch account by ACI", t); + logger.warn("Failed to check account existence by ACI", t); return Mono.empty(); }) , concurrency) @@ -186,7 +188,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD return Mono.just(true); } return clearQueueWithAciLock(database, aci, transactionRetryLimit, transactionTimeout, accountsManager, - accountLockManager, executor) + accountLockManager, scheduler) .thenReturn(true) .onErrorResume(t -> { logger.error("Failed to clear orphaned queue for ACI: {}", aci.uuid(), t); @@ -202,16 +204,16 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD private Mono clearQueueWithAciLock(final FaultTolerantDatabase database, final AciServiceIdentifier aci, final long transactionRetryLimit, final Duration transactionTimeout, final AccountsManager accountsManager, final AccountLockManager accountLockManager, - final Executor executor) { - return Mono.fromFuture( - () -> CompletableFuture.runAsync(() -> accountLockManager.withLock(Set.of(aci.uuid()), () -> { - if (accountsManager.getByAccountIdentifier(aci.uuid()).isPresent()) { + final Scheduler scheduler) { + return Mono.fromRunnable(() -> accountLockManager.withLock(Set.of(aci.uuid()), () -> { + if (accountsManager.accountExists(aci)) { logger.info("ACI re-used after we checked for existence, not clearing its queues: {}", aci.uuid()); return null; } clearQueue(database, aci, transactionRetryLimit, transactionTimeout); return null; - }), executor)); + })) + .subscribeOn(scheduler); } private void clearQueue(final FaultTolerantDatabase database, final AciServiceIdentifier aci, final long transactionRetryLimit, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java index 625868bbc..23f971add 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java @@ -2300,6 +2300,18 @@ class AccountsTest { assertEquals(originalUsernameConstraints, regeneratedUsernameConstraints); } + @Test + void accountExists() { + final UUID existingUuid = UUID.randomUUID(); + final Account account = + generateAccount("+14151112222", existingUuid, UUID.randomUUID(), List.of(generateDevice(DEVICE_ID_1))); + + createAccount(account); + + assertThat(accounts.accountExists(existingUuid)).isTrue(); + assertThat(accounts.accountExists(UUID.randomUUID())).isFalse(); + } + private void writeAccountRecordWithoutConstraints(final Account account) { final AttributeValue accountData; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java index 21b98c678..876cfb6a4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java @@ -26,10 +26,8 @@ import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; @@ -37,7 +35,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.whispersystems.textsecuregcm.entities.MessageProtos; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; -import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountLockManager; import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.Device; @@ -100,11 +97,9 @@ class ClearOrphanedFoundationDbQueuesCommandTest { // Assume that a subset of accounts are deleted final Set deletedAccounts = new HashSet<>(accounts.subList(0, 3)); - when(accountsManager.getByAccountIdentifierAsync(any())) - .thenReturn(CompletableFuture.completedFuture(Optional.of(mock(Account.class)))); + when(accountsManager.accountExists(any())).thenReturn(true); for (final AciServiceIdentifier deletedAccount : deletedAccounts) { - when(accountsManager.getByAccountIdentifierAsync(deletedAccount.uuid())) - .thenReturn(CompletableFuture.completedFuture(Optional.empty())); + when(accountsManager.accountExists(deletedAccount)).thenReturn(false); } final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(); @@ -155,11 +150,9 @@ class ClearOrphanedFoundationDbQueuesCommandTest { foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join(); foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join(); - // Stub that the initial existence check returns empty, but the second check under the ACI lock returns present i.e the ACI has been re-used + // Stub that the initial existence check returns absent, but the second check under the ACI lock returns present i.e the ACI has been re-used // since the initial check - when(accountsManager.getByAccountIdentifierAsync(aci.uuid())) - .thenReturn(CompletableFuture.completedFuture(Optional.empty())); - when(accountsManager.getByAccountIdentifier(aci.uuid())).thenReturn(Optional.of(mock(Account.class))); + when(accountsManager.accountExists(aci)).thenReturn(false, true); final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(); command.clearOrphanedQueues(