Make adding/removing devices blocking and remove async update plumbing

This commit is contained in:
Jon Chambers authored and Jon Chambers committed 2026-03-05 09:54:05 -05:00
1 parent 31de1fc1a3
commit 405b04f07b
15 files changed
+240 -266

No files matched your search

@@ -43,7 +43,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@@ -166,7 +165,7 @@ public class DeviceController {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
accounts.removeDevice(account, deviceId).join();
accounts.removeDevice(account, deviceId);
}
/**
@@ -294,7 +293,7 @@ public class DeviceController {
}
try {
return accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account, new DeviceSpec(accountAttributes.getName(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
@@ -307,18 +306,14 @@ public class DeviceController {
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode())
.thenApply(accountAndDevice -> new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId()))
.join();
} catch (final CompletionException e) {
if (e.getCause() instanceof LinkDeviceTokenAlreadyUsedException) {
throw new ForbiddenException();
}
linkDeviceRequest.verificationCode());
throw e;
return new LinkDeviceResponse(
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId());
} catch (final LinkDeviceTokenAlreadyUsedException e) {
throw new ForbiddenException();
}
}
@@ -377,8 +372,8 @@ public class DeviceController {
.map(deviceInfo -> Response.status(Response.Status.OK).entity(deviceInfo).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.exceptionally(ExceptionUtils.exceptionallyHandler(IllegalArgumentException.class,
e -> Response.status(Response.Status.BAD_REQUEST).build()))
.whenComplete((response, throwable) -> {
_ -> Response.status(Response.Status.BAD_REQUEST).build()))
.whenComplete((response, _) -> {
linkedDeviceListenerCounter.decrementAndGet();
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
@@ -568,7 +563,7 @@ public class DeviceController {
.thenApply(maybeTransferArchive -> maybeTransferArchive
.map(transferArchive -> Response.status(Response.Status.OK).entity(transferArchive).build())
.orElseGet(() -> Response.status(Response.Status.NO_CONTENT).build()))
.whenComplete((response, throwable) -> {
.whenComplete((response, _) -> {
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
accountAndSample.second().stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
.tags(Tags.of(
@@ -82,7 +82,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
final byte deviceId = DeviceIdUtil.validate(request.getId());
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId).join();
accountsManager.removeDevice(getAuthenticatedAccount(), deviceId);
return RemoveDeviceResponse.getDefaultInstance();
}
@@ -1013,40 +1013,37 @@ public class Accounts {
}
}
public CompletionStage<Void> updateTransactionallyAsync(final Account account,
final Collection<TransactWriteItem> additionalWriteItems) {
public void updateTransactionally(final Account account, final Collection<TransactWriteItem> additionalWriteItems)
throws ContestedOptimisticLockException {
return AsyncTimerUtil.record(UPDATE_TRANSACTIONALLY_TIMER, () -> {
final Timer.Sample sample = Timer.start();
try {
final List<TransactWriteItem> writeItems = new ArrayList<>(additionalWriteItems.size() + 1);
writeItems.add(UpdateAccountSpec.forAccount(accountsTableName, account).transactItem());
writeItems.addAll(additionalWriteItems);
return dynamoDbAsyncClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build())
.thenApply(_ -> {
account.setVersion(account.getVersion() + 1);
return (Void) null;
})
.exceptionally(throwable -> {
final Throwable unwrapped = ExceptionUtils.unwrap(throwable);
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder()
.transactItems(writeItems)
.build());
if (unwrapped instanceof TransactionCanceledException transactionCanceledException) {
if (CONDITIONAL_CHECK_FAILED.equals(transactionCanceledException.cancellationReasons().getFirst().code())) {
throw new ContestedOptimisticLockException();
}
account.setVersion(account.getVersion() + 1);
} catch (final TransactionCanceledException transactionCanceledException) {
if (CONDITIONAL_CHECK_FAILED.equals(transactionCanceledException.cancellationReasons().getFirst().code())) {
throw new ContestedOptimisticLockException();
}
if (transactionCanceledException.cancellationReasons()
.stream()
.anyMatch(reason -> TRANSACTION_CONFLICT.equals(reason.code()))) {
if (transactionCanceledException.cancellationReasons()
.stream()
.anyMatch(reason -> TRANSACTION_CONFLICT.equals(reason.code()))) {
throw new ContestedOptimisticLockException();
}
}
throw new ContestedOptimisticLockException();
}
throw CompletableFutureUtils.errorAsCompletionException(throwable);
});
});
throw transactionCanceledException;
} finally {
sample.stop(UPDATE_TRANSACTIONALLY_TIMER);
}
}
public TransactWriteItem buildTransactWriteItemForLinkDevice(final String linkDeviceToken, final Duration tokenTtl) {
@@ -439,88 +439,92 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return account;
}
public CompletableFuture<Pair<Account, Device>> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken) {
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
public Pair<Account, Device> addDevice(final Account account, final DeviceSpec deviceSpec, final String linkDeviceToken)
throws LinkDeviceTokenAlreadyUsedException {
try {
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> addDevice(account.getIdentifier(IdentityType.ACI), deviceSpec, linkDeviceToken, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
} catch (final LinkDeviceTokenAlreadyUsedException | RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private CompletableFuture<Pair<Account, Device>> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries) {
return accounts.getByAccountIdentifierAsync(accountIdentifier)
.thenApply(maybeAccount -> maybeAccount.orElseThrow(ContestedOptimisticLockException::new))
.thenCompose(account -> {
final byte nextDeviceId = account.getNextDeviceId();
private Pair<Account, Device> addDevice(final UUID accountIdentifier, final DeviceSpec deviceSpec, final String linkDeviceToken, final int retries)
throws LinkDeviceTokenAlreadyUsedException {
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ContestedOptimisticLockException::new);
return CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
messagesManager.clear(account.getUuid(), nextDeviceId))
.thenApply(ignored -> new Pair<>(account, nextDeviceId));
})
.thenCompose(accountAndNextDeviceId -> {
final Account account = accountAndNextDeviceId.first();
final byte nextDeviceId = accountAndNextDeviceId.second();
final byte nextDeviceId = account.getNextDeviceId();
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
messagesManager.clear(account.getUuid(), nextDeviceId))
.join();
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
nextDeviceId,
deviceSpec.aciSignedPreKey(),
deviceSpec.pniSignedPreKey(),
deviceSpec.aciPqLastResortPreKey(),
deviceSpec.pniPqLastResortPreKey()));
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION));
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(keysManager.buildWriteItemsForNewDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
nextDeviceId,
deviceSpec.aciSignedPreKey(),
deviceSpec.pniSignedPreKey(),
deviceSpec.aciPqLastResortPreKey(),
deviceSpec.pniPqLastResortPreKey()));
return accounts.updateTransactionallyAsync(account, additionalWriteItems)
.thenApply(ignored -> new Pair<>(account, account.getDevice(nextDeviceId).orElseThrow()));
})
.thenCompose(updatedAccountAndDevice -> redisDeleteAsync(updatedAccountAndDevice.first())
.thenApply(ignored -> updatedAccountAndDevice))
.exceptionallyCompose(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException && retries > 0) {
return addDevice(accountIdentifier, deviceSpec, linkDeviceToken, retries - 1);
} else if (ExceptionUtils.unwrap(throwable) instanceof TransactionCanceledException transactionCanceledException) {
// We can be confident the transaction was canceled because the linked device token was already used if the
// "check token" transaction write item is the only one that failed. That SHOULD be the last one in the
// list.
final long cancelledTransactions = transactionCanceledException.cancellationReasons().stream()
.filter(cancellationReason -> !"None".equals(cancellationReason.code()))
.count();
additionalWriteItems.add(accounts.buildTransactWriteItemForLinkDevice(linkDeviceToken, LINK_DEVICE_TOKEN_EXPIRATION_DURATION));
final boolean tokenReuseConditionFailed =
"ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().getLast().code());
try {
accounts.updateTransactionally(account, additionalWriteItems);
redisDelete(account);
if (cancelledTransactions == 1 && tokenReuseConditionFailed) {
return CompletableFuture.failedFuture(new LinkDeviceTokenAlreadyUsedException());
final String key = getLinkedDeviceKey(getLinkDeviceTokenIdentifier(linkDeviceToken));
final String deviceInfoJson;
try {
deviceInfoJson = SystemMapper.jsonMapper().writeValueAsString(DeviceInfo.forDevice(account.getDevice(nextDeviceId).orElseThrow()));
} catch (final JsonProcessingException e) {
throw new UncheckedIOException(e);
}
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection ->
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
.whenComplete((_, pubSubThrowable) -> {
if (pubSubThrowable != null) {
logger.warn("Failed to record recently-created device", pubSubThrowable);
}
}
});
return CompletableFuture.failedFuture(throwable);
})
.whenComplete((updatedAccountAndDevice, _) -> {
if (updatedAccountAndDevice != null) {
final String key = getLinkedDeviceKey(getLinkDeviceTokenIdentifier(linkDeviceToken));
final String deviceInfoJson;
return new Pair<>(account, account.getDevice(nextDeviceId).orElseThrow());
} catch (final ContestedOptimisticLockException e) {
if (retries > 0) {
return addDevice(accountIdentifier, deviceSpec, linkDeviceToken, retries - 1);
}
try {
deviceInfoJson = SystemMapper.jsonMapper().writeValueAsString(DeviceInfo.forDevice(updatedAccountAndDevice.second()));
} catch (final JsonProcessingException e) {
throw new UncheckedIOException(e);
}
throw e;
} catch (final TransactionCanceledException transactionCanceledException) {
// We can be confident the transaction was canceled because the linked device token was already used if the
// "check token" transaction write item is the only one that failed. That SHOULD be the last one in the
// list.
final long cancelledTransactions = transactionCanceledException.cancellationReasons().stream()
.filter(cancellationReason -> !"None".equals(cancellationReason.code()))
.count();
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeCompletionStage(retryExecutor, () -> pubSubRedisClient.withConnection(connection ->
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
.whenComplete((_, pubSubThrowable) -> {
if (pubSubThrowable != null) {
logger.warn("Failed to record recently-created device", pubSubThrowable);
}
});
}
});
final boolean tokenReuseConditionFailed =
"ConditionalCheckFailed".equals(transactionCanceledException.cancellationReasons().getLast().code());
if (cancelledTransactions == 1 && tokenReuseConditionFailed) {
throw new LinkDeviceTokenAlreadyUsedException();
}
throw transactionCanceledException;
}
}
private Mac getInitializedMac() {
@@ -630,53 +634,58 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
*
* @return the updated Account
*/
public CompletableFuture<Account> removeDevice(final Account account, final byte deviceId) {
public Account removeDevice(final Account account, final byte deviceId) {
if (deviceId == Device.PRIMARY_ID) {
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLockAsync(Set.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
try {
return accountLockManager.withLock(Set.of(account.getPhoneNumberIdentifier()),
() -> removeDevice(account.getIdentifier(IdentityType.ACI), deviceId, MAX_UPDATE_ATTEMPTS),
accountLockExecutor);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private CompletableFuture<Account> removeDevice(final UUID accountIdentifier, final byte deviceId, final int retries) {
return accounts.getByAccountIdentifierAsync(accountIdentifier)
.thenApply(maybeAccount -> maybeAccount.orElseThrow(ContestedOptimisticLockException::new))
.thenCompose(account -> CompletableFuture.allOf(
private Account removeDevice(final UUID accountIdentifier, final byte deviceId, final int retries) {
final Account account = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ContestedOptimisticLockException::new);
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
.thenApply(ignored -> account))
.thenCompose(account -> {
account.removeDevice(deviceId);
.join();
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(
keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
deviceId));
account.removeDevice(deviceId);
return accounts.updateTransactionallyAsync(account, additionalWriteItems)
.thenApply(ignored -> account);
})
.thenCompose(updatedAccount -> redisDeleteAsync(updatedAccount).thenApply(ignored -> updatedAccount))
// Ensure any messages/single-use pre-keys that came in while we were working are also removed
.thenCompose(account -> CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
.thenApply(ignored -> account))
.exceptionallyCompose(throwable -> {
if (ExceptionUtils.unwrap(throwable) instanceof ContestedOptimisticLockException && retries > 0) {
return removeDevice(accountIdentifier, deviceId, retries - 1);
}
final List<TransactWriteItem> additionalWriteItems = new ArrayList<>(
keysManager.buildWriteItemsForRemovedDevice(
account.getIdentifier(IdentityType.ACI),
account.getIdentifier(IdentityType.PNI),
deviceId));
return CompletableFuture.failedFuture(throwable);
})
.whenComplete((ignored, throwable) -> {
if (throwable == null) {
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
}
});
try {
accounts.updateTransactionally(account, additionalWriteItems);
redisDelete(account);
// Ensure any messages/single-use pre-keys that came in while we were working are also removed
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
.join();
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
return account;
} catch (final ContestedOptimisticLockException e) {
if (retries > 0) {
return removeDevice(accountIdentifier, deviceId, retries - 1);
}
throw e;
}
}
public Account changeNumber(final Account account,
@@ -22,7 +22,6 @@ import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -249,7 +248,7 @@ public class MessagePersister implements Managed {
throw new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed");
} else {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
accountsManager.removeDevice(account, deviceId).join();
accountsManager.removeDevice(account, deviceId);
}
} finally {
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
@@ -130,7 +130,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
return Flux.fromIterable(expiredDevices)
.flatMap(deviceId ->
Mono.fromFuture(() -> getCommandDependencies().accountsManager().removeDevice(account, deviceId))
Mono.fromRunnable(() -> getCommandDependencies().accountsManager().removeDevice(account, deviceId))
.retryWhen(Retry.backoff(maxRetries, Duration.ofSeconds(1))
.doAfterRetry(ignored -> retryCounter.increment())
.onRetryExhaustedThrow((spec, rs) -> rs.failure()))
@@ -5,11 +5,8 @@
package org.whispersystems.textsecuregcm.workers;
import com.fasterxml.jackson.databind.DeserializationFeature;
import io.dropwizard.core.Application;
import io.dropwizard.core.cli.EnvironmentCommand;
import io.dropwizard.core.setup.Environment;
import java.util.List;
import java.util.UUID;
import net.sourceforge.argparse4j.impl.Arguments;
@@ -64,7 +61,7 @@ public class UnlinkDeviceCommand extends AbstractCommandWithDependencies {
for (byte deviceId : deviceIds) {
/** see {@link org.whispersystems.textsecuregcm.controllers.DeviceController#removeDevice} */
System.out.format("Removing device %s::%d\n", aci, deviceId);
deps.accountsManager().removeDevice(account, deviceId).join();
deps.accountsManager().removeDevice(account, deviceId);
}
}
}
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.function.Tuples;
import reactor.util.retry.Retry;
@@ -96,7 +97,8 @@ public class UnlinkDevicesWithIdlePrimaryCommand extends AbstractSinglePassCrawl
.flatMap(accountAndLinkedDeviceId -> {
final Mono<Account> unlinkDeviceMono = isDryRun
? Mono.empty()
: Mono.fromFuture(() -> accountsManager.removeDevice(accountAndLinkedDeviceId.getT1(), accountAndLinkedDeviceId.getT2()));
: Mono.fromSupplier(() -> accountsManager.removeDevice(accountAndLinkedDeviceId.getT1(), accountAndLinkedDeviceId.getT2()))
.subscribeOn(Schedulers.boundedElastic());
return unlinkDeviceMono
.doOnSuccess(ignored -> unlinkDeviceCounter.increment())