Remove asynchronous account update plumbing

This commit is contained in:
Jon Chambers authored and Jon Chambers committed 2026-03-05 09:54:05 -05:00
1 parent de458c3e6a
commit 31de1fc1a3
8 files changed
+37 -191

No files matched your search

@@ -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<Void> 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<Void> 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<Void> updateTransactionallyAsync(final Account account,
@@ -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<String, String> implemen
});
}
public CompletableFuture<Account> updateAsync(Account account, Consumer<Account> 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<String, String> implemen
});
}
private CompletableFuture<Account> updateAsync(final Account account, final Function<Account, Boolean> 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 <E extends Exception> Account updateWithRetries(Account account,
final Function<Account, Boolean> updater,
final ThrowingConsumer<Account, E> persister,
@@ -1066,42 +1038,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
throw new OptimisticLockRetryLimitExceededException();
}
private CompletionStage<Account> updateWithRetriesAsync(Account account,
final Function<Account, Boolean> updater,
final Function<Account, CompletionStage<Void>> persister,
final Supplier<CompletionStage<Account>> 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<Device> deviceUpdater) {
return update(account, a -> {
a.getDevice(deviceId).ifPresent(deviceUpdater);
@@ -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<Void> 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))
@@ -241,7 +241,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().clearRegistrationLock(ClearRegistrationLockRequest.newBuilder().build()));
verify(accountsManager, never()).updateAsync(any(), any());
verify(accountsManager, never()).update(any(), any());
}
@Test
@@ -138,15 +138,6 @@ class AccountsManagerTest {
return null;
};
private static final Answer<CompletableFuture<Void>> 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();
@@ -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);
}
@@ -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:
* <ul>
* <li>{@link AccountsManager#update(Account, Consumer)}</li>
* <li>{@link AccountsManager#updateAsync(Account, Consumer)}</li>
* <li>{@link AccountsManager#updateDevice(Account, byte, Consumer)}</li>
* </ul>
*
@@ -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);
@@ -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<Consumer<Account>> 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<Account> consumer = updaterCaptor.getValue();
consumer.accept(hasHolds);
verify(hasHolds, times(1)).setUsernameHolds(argThat(holds ->