Remove executor for acquiring locks in AccountLockManager

This commit is contained in:
Ameya Lokare authored and Jon Chambers committed 2026-09-02 16:33:49 -04:00
1 parent 1c28620b65
commit 9483f358cd
13 files changed
+37 -102

No files matched your search

@@ -668,10 +668,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(receiptSenderQueue)
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
.minThreads(8)
.maxThreads(8)
.build();
// unbounded executor (same as cachedThreadPool)
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
.minThreads(0)
@@ -801,10 +797,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
config.getRegistrationTotpConfiguration().maxValidationDelay());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
@@ -10,9 +10,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@@ -47,15 +44,12 @@ public class AccountLockManager {
///
/// @param phoneNumberIdentifiers the phone number identifiers for which to acquire a distributed, pessimistic lock
/// @param task the task to execute once locks have been acquired
/// @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
/// should not use virtual threads.
///
/// @return the value returned by the given {@code task}
///
/// @throws E if an exception is thrown by the given {@code task}
public <V, E extends Exception> V withLock(final Set<UUID> phoneNumberIdentifiers,
final ThrowingSupplier<V, E> task,
final Executor lockAcquisitionExecutor) throws E {
final ThrowingSupplier<V, E> task) throws E {
if (phoneNumberIdentifiers.isEmpty()) {
throw new IllegalArgumentException("List of PNIs to lock must not be empty");
@@ -64,30 +58,22 @@ public class AccountLockManager {
final List<LockItem> lockItems = new ArrayList<>(phoneNumberIdentifiers.size());
try {
// Offload the acquire/release tasks to the dedicated lock acquisition executor. The lock client performs blocking
// operations while holding locks which forces thread pinning when this method runs on a virtual thread.
// https://github.com/awslabs/amazon-dynamodb-lock-client/issues/97
CompletableFuture.runAsync(() -> {
for (final UUID pni : phoneNumberIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
throw new CompletionException(e);
}
for (final UUID pni : phoneNumberIdentifiers) {
try {
lockItems.add(lockClient.acquireLock(AcquireLockOptions.builder(pni.toString())
.withAcquireReleasedLocksConsistently(true)
.build()));
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
}, lockAcquisitionExecutor).join();
}
return task.get();
} finally {
CompletableFuture.runAsync(() -> {
for (final LockItem lockItem : lockItems) {
lockClient.releaseLock(ReleaseLockOptions.builder(lockItem)
.withBestEffort(true)
.build());
}
}, lockAcquisitionExecutor).join();
for (final LockItem lockItem : lockItems) {
lockClient.releaseLock(ReleaseLockOptions.builder(lockItem)
.withBestEffort(true)
.build());
}
}
}
@@ -104,15 +90,12 @@ public class AccountLockManager {
///
/// @param account the account for which to acquire a distributed, pessimistic lock
/// @param task the task to execute once locks have been acquired
/// @param lockAcquisitionExecutor the executor on which to run blocking lock acquire/release tasks. this executor
/// should not use virtual threads.
///
/// @return the value returned by the given {@code task}
///
/// @throws E if an exception is thrown by the given {@code task}
public <V, E extends Exception> V withSingleAccountLock(Account account,
final ThrowingSupplier<V, E> task,
final Executor lockAcquisitionExecutor) throws E {
return withLock(Set.of(account.getPhoneNumberIdentifier().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor);
public <V, E extends Exception> V withSingleAccountLock(final Account account,
final ThrowingSupplier<V, E> task) throws E {
return withLock(Set.of(account.getPhoneNumberIdentifier().orElse(account.getAccountIdentifier())), task);
}
}
@@ -50,7 +50,6 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -142,7 +141,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private final SecureValueRecoveryClient secureValueRecovery2Client;
private final DisconnectionRequestManager disconnectionRequestManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final Executor accountLockExecutor;
private final ScheduledExecutorService messagesPollExecutor;
private final ScheduledExecutorService retryExecutor;
private final Clock clock;
@@ -299,7 +297,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final SecureValueRecoveryClient secureValueRecovery2Client,
final DisconnectionRequestManager disconnectionRequestManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final Executor accountLockExecutor,
final ScheduledExecutorService messagesPollExecutor,
final ScheduledExecutorService retryExecutor,
final Clock clock,
@@ -318,7 +315,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
this.secureValueRecovery2Client = secureValueRecovery2Client;
this.disconnectionRequestManager = disconnectionRequestManager;
this.phoneNumberRecoveryPasswordsManager = requireNonNull(phoneNumberRecoveryPasswordsManager);
this.accountLockExecutor = accountLockExecutor;
this.messagesPollExecutor = messagesPollExecutor;
this.retryExecutor = retryExecutor;
this.clock = requireNonNull(clock);
@@ -454,7 +450,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return Metrics.timer(CREATE_TIMER_NAME, HAS_NUMBER_TAG_NAME, "true").record(() -> {
try {
return accountLockManager.withLock(Set.of(pni),
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent), accountLockExecutor);
() -> create(Optional.of(number), Optional.of(pni), Optional.empty(), Optional.empty(), accountAttributes, aciIdentityKey, Optional.of(pniIdentityKey), primaryDeviceSpec, userAgent));
} catch (final ReceiptAlreadyRedeemedException e) {
throw new AssertionError("ReceiptAlreadyRedeemedException must never be thrown for accounts with numbers");
} catch (final RuntimeException e) {
@@ -613,7 +609,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
reclaimAccount(account, existingAccount, primaryDeviceSpec, accountAttributes);
return account;
}, accountLockExecutor);
});
final PushTokenType pushTokenType = PushTokenType.fromDeviceSpec(primaryDeviceSpec);
final PushTokenType previousPushTokenType = PushTokenType.fromDevice(existingAccount.getPrimaryDevice());
@@ -711,8 +707,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withSingleAccountLock(account,
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
() -> addDevice(accountIdentifier, deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS));
}
private Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries)
@@ -909,8 +904,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.orElseThrow(() -> new IllegalArgumentException("Account not found: " + accountIdentifier));
return accountLockManager.withSingleAccountLock(account,
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
() -> removeDevice(accountIdentifier, deviceId, MAX_UPDATE_ATTEMPTS));
}
private Account removeDevice(final UUID accountIdentifier, final byte deviceId, final int retries) {
@@ -976,7 +970,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
try {
return accountLockManager.withLock(new HashSet<>(List.of(originalPhoneNumberIdentifier, targetPhoneNumberIdentifier)),
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds), accountLockExecutor);
() -> changeNumber(account, targetNumber, targetPhoneNumberIdentifier, pniIdentityKey, pniSignedPreKeys, pniPqLastResortPreKeys, pniRegistrationIds));
} catch (final RuntimeException e) {
logger.error("Unexpected exception when changing phone number", e);
throw e;
@@ -1280,7 +1274,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
return maybeUpdatedAccount;
}, accountLockExecutor);
});
}
/**
@@ -1488,7 +1482,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
accountLockManager.withSingleAccountLock(account, () -> {
delete(account);
return null;
}, accountLockExecutor);
});
Metrics.counter(DELETE_COUNTER_NAME,
COUNTRY_CODE_TAG_NAME, Util.getCountryCode(account),
@@ -2002,7 +1996,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
accountLockManager.withSingleAccountLock(account, () -> {
migrateAccountRecoveryPassword(account.getAccountIdentifier(), MAX_UPDATE_ATTEMPTS);
return null;
}, accountLockExecutor);
});
}
private void migrateAccountRecoveryPassword(final UUID accountIdentifier, final int retries) {
@@ -206,8 +206,6 @@ public record CommandDependencies(
.maxThreads(8).minThreads(8).build();
ExecutorService storageServiceExecutor = ExecutorServiceBuilder.of(environment, "storageService")
.maxThreads(8).minThreads(8).build();
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
.minThreads(8).maxThreads(8).build();
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
@@ -358,7 +356,7 @@ public record CommandDependencies(
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, configuration.getLinkDeviceSecretConfiguration().secret().value(),
configuration.getRegistrationTotpConfiguration().maxValidationDelay());
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
@@ -173,7 +173,6 @@ public class AccountCreationDeletionIntegrationTest {
phoneNumberRecoveryPasswordsManager,
executor,
executor,
executor,
CLOCK,
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
@@ -15,17 +15,12 @@ import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class AccountLockManagerTest {
private AmazonDynamoDBLockClient lockClient;
private ExecutorService executor;
private AccountLockManager accountLockManager;
@@ -36,22 +31,12 @@ class AccountLockManagerTest {
@BeforeEach
void setUp() {
lockClient = mock(AmazonDynamoDBLockClient.class);
executor = Executors.newSingleThreadExecutor();
accountLockManager = new AccountLockManager(lockClient);
}
@AfterEach
void tearDown() throws InterruptedException {
executor.shutdown();
//noinspection ResultOfMethodCallIgnored
executor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void withLock() throws Exception {
accountLockManager.withLock(Set.of(FIRST_PNI, SECOND_PNI), () -> null, executor);
accountLockManager.withLock(Set.of(FIRST_PNI, SECOND_PNI), () -> null);
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
@@ -61,7 +46,7 @@ class AccountLockManagerTest {
void withLockTaskThrowsException() throws InterruptedException {
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(Set.of(FIRST_PNI, SECOND_PNI), () -> {
throw new RuntimeException();
}, executor));
}));
verify(lockClient, times(2)).acquireLock(any());
verify(lockClient, times(2)).releaseLock(any(ReleaseLockOptions.class));
@@ -71,8 +56,7 @@ class AccountLockManagerTest {
void withLockEmptyList() {
final Runnable task = mock(Runnable.class);
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptySet(), () -> null,
executor));
assertThrows(IllegalArgumentException.class, () -> accountLockManager.withLock(Collections.emptySet(), () -> null));
verify(task, never()).run();
}
@@ -82,7 +66,7 @@ class AccountLockManagerTest {
when(account.getAccountIdentifier()).thenReturn(ACI);
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.of(FIRST_PNI));
accountLockManager.withSingleAccountLock(account, () -> null, executor);
accountLockManager.withSingleAccountLock(account, () -> null);
verify(lockClient, times(1)).acquireLock(
AcquireLockOptions.builder(FIRST_PNI.toString()).withAcquireReleasedLocksConsistently(true).build());
}
@@ -93,7 +77,7 @@ class AccountLockManagerTest {
when(account.getAccountIdentifier()).thenReturn(ACI);
when(account.getPhoneNumberIdentifier()).thenReturn(Optional.empty());
accountLockManager.withSingleAccountLock(account, () -> null, executor);
accountLockManager.withSingleAccountLock(account, () -> null);
verify(lockClient, times(1)).acquireLock(
AcquireLockOptions.builder(ACI.toString()).withAcquireReleasedLocksConsistently(true).build());
}
@@ -153,7 +153,6 @@ class AccountsManagerChangeNumberIntegrationTest {
phoneNumberRecoveryPasswordsManager,
executor,
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
@@ -105,7 +105,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
doAnswer(invocation -> {
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
return task.get();
}).when(accountLockManager).withLock(anySet(), any(), any());
}).when(accountLockManager).withLock(anySet(), any());
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(anyString()))
@@ -132,7 +132,6 @@ class AccountsManagerConcurrentModificationIntegrationTest {
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
mock(Executor.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
mock(Clock.class),
@@ -18,7 +18,6 @@ import java.util.Base64;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
@@ -68,7 +67,6 @@ public class AccountsManagerDeviceTransferIntegrationTest {
mock(SecureValueRecoveryClient.class),
mock(DisconnectionRequestManager.class),
mock(PhoneNumberRecoveryPasswordsManager.class),
mock(ExecutorService.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
Clock.systemUTC(),
@@ -139,7 +139,6 @@ public class AccountsManagerMigrateRecoveryPasswordIntegrationTest {
phoneNumberRecoveryPasswordsManager,
executor,
executor,
executor,
mock(Clock.class),
"link-device-secret".getBytes(StandardCharsets.UTF_8),
AccountsManager.TOTP.getTimeStep().dividedBy(2));
@@ -58,7 +58,6 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
@@ -210,12 +209,12 @@ class AccountsManagerTest {
doAnswer(invocation -> {
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
return task.get();
}).when(accountLockManager).withLock(anySet(), any(), any());
}).when(accountLockManager).withLock(anySet(), any());
doAnswer(invocation -> {
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
return task.get();
}).when(accountLockManager).withSingleAccountLock(any(Account.class), any(), any());
}).when(accountLockManager).withSingleAccountLock(any(Account.class), any());
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
mock(PhoneNumberRecoveryPasswordsManager.class);
@@ -251,7 +250,6 @@ class AccountsManagerTest {
svr2Client,
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
mock(Executor.class),
mock(ScheduledExecutorService.class),
mock(ScheduledExecutorService.class),
CLOCK,
@@ -119,7 +119,7 @@ class AccountsManagerUsernameIntegrationTest {
doAnswer(invocation -> {
final ThrowingSupplier<?, ?> task = invocation.getArgument(1);
return task.get();
}).when(accountLockManager).withLock(anySet(), any(), any());
}).when(accountLockManager).withLock(anySet(), any());
final PhoneNumberIdentifiers phoneNumberIdentifiers =
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.PNI.tableName());
@@ -153,7 +153,6 @@ class AccountsManagerUsernameIntegrationTest {
mock(SecureValueRecoveryClient.class),
disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager,
Executors.newSingleThreadExecutor(),
Executors.newSingleThreadScheduledExecutor(),
Executors.newSingleThreadScheduledExecutor(),
Clock.systemUTC(),
@@ -21,10 +21,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -72,7 +69,6 @@ public class AddRemoveDeviceIntegrationTest {
@RegisterExtension
static final S3LocalStackExtension S3_EXTENSION = new S3LocalStackExtension("testbucket");
private ExecutorService accountLockExecutor;
private ScheduledExecutorService scheduledExecutorService;
private KeysManager keysManager;
@@ -109,7 +105,6 @@ public class AddRemoveDeviceIntegrationTest {
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS.tableName(),
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
accountLockExecutor = Executors.newSingleThreadExecutor();
scheduledExecutorService = mock(ScheduledExecutorService.class);
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
@@ -157,7 +152,6 @@ public class AddRemoveDeviceIntegrationTest {
svr2Client,
mock(DisconnectionRequestManager.class),
phoneNumberRecoveryPasswordsManager,
accountLockExecutor,
scheduledExecutorService,
scheduledExecutorService,
clock,
@@ -170,11 +164,6 @@ public class AddRemoveDeviceIntegrationTest {
@AfterEach
void tearDown() throws InterruptedException {
accountsManager.stop();
accountLockExecutor.shutdown();
//noinspection ResultOfMethodCallIgnored
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
}
@Test