From 31de1fc1a308160bd9ce1468cf990d1876d42208 Mon Sep 17 00:00:00 2001 From: Jon Chambers Date: Tue, 24 Feb 2026 23:05:51 -0500 Subject: [PATCH] Remove asynchronous account update plumbing --- .../textsecuregcm/storage/Accounts.java | 72 ++++++------------- .../storage/AccountsManager.java | 64 ----------------- .../RemoveExpiredUsernameHoldsCommand.java | 7 +- .../grpc/AccountsGrpcServiceTest.java | 2 +- .../storage/AccountsManagerTest.java | 37 ---------- .../textsecuregcm/storage/AccountsTest.java | 20 +++--- .../tests/util/AccountsHelper.java | 19 ----- ...RemoveExpiredUsernameHoldsCommandTest.java | 7 +- 8 files changed, 37 insertions(+), 191 deletions(-) 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 815cac224..acd415c08 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/Accounts.java @@ -4,13 +4,12 @@ */ package org.whispersystems.textsecuregcm.storage; -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; import static java.util.Objects.requireNonNull; +import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Throwables; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Timer; import java.io.IOException; @@ -30,7 +29,6 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -70,6 +68,7 @@ import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledExcepti import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException; import software.amazon.awssdk.services.dynamodb.model.Update; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; +import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; import software.amazon.awssdk.services.dynamodb.paginators.ScanPublisher; import software.amazon.awssdk.utils.CompletableFutureUtils; @@ -990,53 +989,28 @@ public class Accounts { } } - @Nonnull - public CompletionStage updateAsync(final Account account) { - return AsyncTimerUtil.record(UPDATE_TIMER, () -> { - final UpdateItemRequest updateItemRequest = UpdateAccountSpec - .forAccount(accountsTableName, account) - .updateItemRequest(); - - return dynamoDbAsyncClient.updateItem(updateItemRequest) - .thenApply(response -> { - account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1)); - return (Void) null; - }) - .exceptionallyCompose(throwable -> { - final Throwable unwrapped = ExceptionUtils.unwrap(throwable); - if (unwrapped instanceof TransactionConflictException) { - throw new ContestedOptimisticLockException(); - } else if (unwrapped instanceof ConditionalCheckFailedException e) { - // the exception doesn't give details about which condition failed, - // but we can infer it was an optimistic locking failure if the UUID is known - return getByAccountIdentifierAsync(account.getUuid()) - .thenAccept(refreshedAccount -> { - throw refreshedAccount.isPresent() ? new ContestedOptimisticLockException() : e; - }); - } else { - // rethrow - throw CompletableFutureUtils.errorAsCompletionException(throwable); - } - }); - }); - } - - private static void joinAndUnwrapUpdateFuture(CompletionStage future) { - try { - future.toCompletableFuture().join(); - } catch (final CompletionException e) { - // unwrap CompletionExceptions, throw as long is it's unchecked - Throwables.throwIfUnchecked(ExceptionUtils.unwrap(e)); - - // if we otherwise somehow got a wrapped checked exception, - // rethrow the checked exception wrapped by the original CompletionException - log.error("Unexpected checked exception thrown from dynamo update", e); - throw e; - } - } - public void update(final Account account) throws ContestedOptimisticLockException { - joinAndUnwrapUpdateFuture(updateAsync(account)); + final Timer.Sample sample = Timer.start(); + + try { + final UpdateItemResponse response = dynamoDbClient.updateItem(UpdateAccountSpec + .forAccount(accountsTableName, account) + .updateItemRequest()); + + account.setVersion(AttributeValues.getInt(response.attributes(), "V", account.getVersion() + 1)); + } catch (final TransactionConflictException _) { + throw new ContestedOptimisticLockException(); + } catch (final ConditionalCheckFailedException e) { + // the exception doesn't give details about which condition failed, + // but we can infer it was an optimistic locking failure if the UUID is known + if (getByAccountIdentifier(account.getUuid()).isPresent()) { + throw new ContestedOptimisticLockException(); + } else { + throw e; + } + } finally { + sample.stop(UPDATE_TIMER); + } } public CompletionStage updateTransactionallyAsync(final Account account, 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 5d1fdbc49..98f083ae8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/AccountsManager.java @@ -45,7 +45,6 @@ import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; @@ -947,14 +946,6 @@ public class AccountsManager extends RedisPubSubAdapter implemen }); } - public CompletableFuture updateAsync(Account account, Consumer updater) { - return updateAsync(account, a -> { - updater.accept(a); - // assume that all updaters passed to the public method actually modify the account - return true; - }); - } - /** * Specialized version of {@link #updateDevice(Account, byte, Consumer)} that minimizes potentially contentious and * redundant updates of {@code device.lastSeen} @@ -1006,25 +997,6 @@ public class AccountsManager extends RedisPubSubAdapter implemen }); } - private CompletableFuture updateAsync(final Account account, final Function updater) { - - final Timer.Sample timerSample = Timer.start(); - - return redisDeleteAsync(account) - .thenCompose(ignored -> { - final UUID uuid = account.getUuid(); - - return updateWithRetriesAsync(account, - updater, - a -> accounts.updateAsync(a).toCompletableFuture(), - () -> accounts.getByAccountIdentifierAsync(uuid).thenApply(Optional::orElseThrow), - AccountChangeValidator.GENERAL_CHANGE_VALIDATOR, - MAX_UPDATE_ATTEMPTS); - }) - .thenCompose(updatedAccount -> redisSetAsync(updatedAccount).thenApply(ignored -> updatedAccount)) - .whenComplete((_, _) -> timerSample.stop(updateTimer)); - } - private Account updateWithRetries(Account account, final Function updater, final ThrowingConsumer persister, @@ -1066,42 +1038,6 @@ public class AccountsManager extends RedisPubSubAdapter implemen throw new OptimisticLockRetryLimitExceededException(); } - private CompletionStage updateWithRetriesAsync(Account account, - final Function updater, - final Function> persister, - final Supplier> retriever, - final AccountChangeValidator changeValidator, - final int remainingTries) { - - final Account originalAccount = AccountUtil.cloneAccountAsNotStale(account); - - if (!updater.apply(account)) { - return CompletableFuture.completedFuture(account); - } - - if (remainingTries > 0) { - return persister.apply(account) - .thenApply(ignored -> { - final Account updatedAccount = AccountUtil.cloneAccountAsNotStale(account); - account.markStale(); - - changeValidator.validateChange(originalAccount, updatedAccount); - - return updatedAccount; - }) - .exceptionallyCompose(throwable -> { - if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException) { - return retriever.get().thenCompose(refreshedAccount -> - updateWithRetriesAsync(refreshedAccount, updater, persister, retriever, changeValidator, remainingTries - 1)); - } else { - throw ExceptionUtils.wrap(throwable); - } - }); - } - - return CompletableFuture.failedFuture(new OptimisticLockRetryLimitExceededException()); - } - public Account updateDevice(Account account, byte deviceId, Consumer deviceUpdater) { return update(account, a -> { a.getDevice(deviceId).ifPresent(deviceUpdater); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java index 55cd693eb..427727471 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommand.java @@ -22,9 +22,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountsManager; -import org.whispersystems.textsecuregcm.util.Util; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import reactor.util.retry.Retry; public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAccountsCommand { @@ -85,8 +85,9 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc final int holdsToRemove = removeExpired(holds); final Mono purgeMono = isDryRun || holdsToRemove == 0 ? Mono.empty() - : Mono.fromFuture(() -> - accountManager.updateAsync(account, a -> a.setUsernameHolds(holds)).thenRun(Util.NOOP)); + : Mono.fromRunnable(() -> accountManager.update(account, a -> a.setUsernameHolds(holds))) + .subscribeOn(Schedulers.boundedElastic()) + .then(); Metrics.counter(INSPECTED_ACCOUNTS_COUNTER_NAME, "dryRun", String.valueOf(isDryRun), "expiredHolds", String.valueOf(holdsToRemove > 0)) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java index 460777bdc..01bbf941c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AccountsGrpcServiceTest.java @@ -241,7 +241,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest authenticatedServiceStub().clearRegistrationLock(ClearRegistrationLockRequest.newBuilder().build())); - verify(accountsManager, never()).updateAsync(any(), any()); + verify(accountsManager, never()).update(any(), any()); } @Test diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java index f6e518a18..498fcf667 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsManagerTest.java @@ -138,15 +138,6 @@ class AccountsManagerTest { return null; }; - private static final Answer> ACCOUNT_UPDATE_ASYNC_ANSWER = invocation -> { - // it is implicit in the update() contract is that a successful call will - // result in an incremented version - final Account updatedAccount = invocation.getArgument(0, Account.class); - updatedAccount.setVersion(updatedAccount.getVersion() + 1); - - return CompletableFuture.completedFuture(null); - }; - @BeforeEach void setup() throws Exception { accounts = mock(Accounts.class); @@ -169,7 +160,6 @@ class AccountsManagerTest { when(asyncClusterCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture("OK")); when(asyncClusterCommands.setex(any(), anyLong(), any())).thenReturn(MockRedisFuture.completedFuture("OK")); - when(accounts.updateAsync(any())).thenReturn(CompletableFuture.completedFuture(null)); when(accounts.updateTransactionallyAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null)); when(accounts.delete(any(), any())).thenReturn(CompletableFuture.completedFuture(null)); @@ -643,33 +633,6 @@ class AccountsManagerTest { verifyNoMoreInteractions(accounts); } - @Test - void testUpdateAsync_optimisticLockingFailure() { - UUID uuid = UUID.randomUUID(); - UUID pni = UUID.randomUUID(); - Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); - - when(asyncClusterCommands.get(eq("Account3::" + uuid))).thenReturn(null); - - when(accounts.getByAccountIdentifierAsync(uuid)).thenReturn(CompletableFuture.completedFuture( - Optional.of(AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH])))); - - when(accounts.updateAsync(any())) - .thenReturn(CompletableFuture.failedFuture(new ContestedOptimisticLockException())) - .thenAnswer(ACCOUNT_UPDATE_ASYNC_ANSWER); - - final IdentityKey identityKey = new IdentityKey(ECKeyPair.generate().getPublicKey()); - - account = accountsManager.updateAsync(account, a -> a.setIdentityKey(identityKey)).join(); - - assertEquals(1, account.getVersion()); - assertEquals(identityKey, account.getIdentityKey(IdentityType.ACI)); - - verify(accounts, times(1)).getByAccountIdentifierAsync(uuid); - verify(accounts, times(2)).updateAsync(any()); - verifyNoMoreInteractions(accounts); - } - @Test void testUpdate_dynamoOptimisticLockingFailureDuringCreate() throws AccountAlreadyExistsException { UUID uuid = UUID.randomUUID(); 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 2362bf351..bb3419ab7 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/AccountsTest.java @@ -604,15 +604,14 @@ class AccountsTest { verifyStoredState("+14151112222", account.getUuid(), account.getPhoneNumberIdentifier(), null, account, true); } - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void testUpdateWithMockTransactionConflictException(boolean wrapException) { + @Test + void testUpdateWithMockTransactionConflictException() { - final DynamoDbAsyncClient dynamoDbAsyncClient = mock(DynamoDbAsyncClient.class); + final DynamoDbClient dynamoDbClient = mock(DynamoDbClient.class); accounts = new Accounts( clock, - mock(DynamoDbClient.class), - dynamoDbAsyncClient, + dynamoDbClient, + mock(DynamoDbAsyncClient.class), Tables.ACCOUNTS.tableName(), Tables.NUMBERS.tableName(), Tables.PNI_ASSIGNMENTS.tableName(), @@ -620,13 +619,10 @@ class AccountsTest { Tables.DELETED_ACCOUNTS.tableName(), Tables.USED_LINK_DEVICE_TOKENS.tableName()); - Exception e = TransactionConflictException.builder().build(); - e = wrapException ? new CompletionException(e) : e; + when(dynamoDbClient.updateItem(any(UpdateItemRequest.class))) + .thenThrow(TransactionConflictException.builder().build()); - when(dynamoDbAsyncClient.updateItem(any(UpdateItemRequest.class))) - .thenReturn(CompletableFuture.failedFuture(e)); - - Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID()); + final Account account = generateAccount("+14151112222", UUID.randomUUID(), UUID.randomUUID()); assertThatThrownBy(() -> accounts.update(account)).isInstanceOfAny(ContestedOptimisticLockException.class); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java index 121582a31..68cae7e80 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/AccountsHelper.java @@ -20,7 +20,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.mockito.MockingDetails; import org.mockito.stubbing.Stubbing; @@ -65,7 +64,6 @@ public class AccountsHelper { * Sets up stubbing for: *
    *
  • {@link AccountsManager#update(Account, Consumer)}
  • - *
  • {@link AccountsManager#updateAsync(Account, Consumer)}
  • *
  • {@link AccountsManager#updateDevice(Account, byte, Consumer)}
  • *
* @@ -91,16 +89,6 @@ public class AccountsHelper { return copyAndMarkStale(account); }); - when(mockAccountsManager.updateAsync(any(), any())).thenAnswer(answer -> { - final Account account = answer.getArgument(0, Account.class); - - for (int i = 0; i < retryCount; i++) { - answer.getArgument(1, Consumer.class).accept(account); - } - - return CompletableFuture.completedFuture(copyAndMarkStale(account)); - }); - when(mockAccountsManager.updateDevice(any(), anyByte(), any())).thenAnswer(answer -> { final Account account = answer.getArgument(0, Account.class); final byte deviceId = answer.getArgument(1, Byte.class); @@ -122,13 +110,6 @@ public class AccountsHelper { return markStale ? copyAndMarkStale(account) : account; }); - when(mockAccountsManager.updateAsync(any(), any())).thenAnswer(answer -> { - final Account account = answer.getArgument(0, Account.class); - answer.getArgument(1, Consumer.class).accept(account); - - return CompletableFuture.completedFuture(markStale ? copyAndMarkStale(account) : account); - }); - when(mockAccountsManager.updateDevice(any(), anyByte(), any())).thenAnswer(answer -> { final Account account = answer.getArgument(0, Account.class); final byte deviceId = answer.getArgument(1, Byte.class); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java index 7fa9ce98f..644a40b73 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RemoveExpiredUsernameHoldsCommandTest.java @@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.workers; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.mock; @@ -24,7 +23,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Consumer; import java.util.stream.IntStream; @@ -75,9 +73,6 @@ class RemoveExpiredUsernameHoldsCommandTest { final TestClock clock = TestClock.pinned(Instant.EPOCH.plus(Duration.ofSeconds(1))); final AccountsManager accountsManager = mock(AccountsManager.class); - when(accountsManager.updateAsync(any(), any())) - .thenReturn(CompletableFuture.completedFuture(null)); - final RemoveExpiredUsernameHoldsCommand removeExpiredUsernameHoldsCommand = new TestRemoveExpiredUsernameHoldsCommand(clock, accountsManager, isDryRun); @@ -97,7 +92,7 @@ class RemoveExpiredUsernameHoldsCommandTest { verifyNoInteractions(accountsManager); } else { ArgumentCaptor> updaterCaptor = ArgumentCaptor.forClass(Consumer.class); - verify(accountsManager, times(1)).updateAsync(eq(hasHolds), updaterCaptor.capture()); + verify(accountsManager, times(1)).update(eq(hasHolds), updaterCaptor.capture()); final Consumer consumer = updaterCaptor.getValue(); consumer.accept(hasHolds); verify(hasHolds, times(1)).setUsernameHolds(argThat(holds ->