mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:16:50 +00:00
Re-use ACI / clear account queues under a pessimistic ACI lock
This commit is contained in:
1 parent
cc50ff7074
commit
1c28620b65
10 files changed
+107
-25
No files matched your search
@@ -522,7 +522,15 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
additionalWriteItems.add(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, phoneNumberRecoveryPassword))));
|
||||
|
||||
if (maybeNumber.isPresent()) {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
if (maybeRecentlyDeletedAccountIdentifier.isPresent()) {
|
||||
// If we are re-using a recently deleted ACI, also obtain a lock for it so that clearing queues for the ACI synchronize against it
|
||||
accountLockManager.withLock(Set.of(maybeRecentlyDeletedAccountIdentifier.get()), () -> {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
return null;
|
||||
}, accountLockExecutor);
|
||||
} else {
|
||||
accounts.create(account, additionalWriteItems);
|
||||
}
|
||||
} else {
|
||||
assert accountAttributes.recoveryPassword().isPresent();
|
||||
accounts.create(account,
|
||||
|
||||
+37
-10
@@ -25,7 +25,10 @@ import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
import java.util.function.Function;
|
||||
@@ -37,8 +40,10 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
@@ -132,26 +137,32 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
final ExecutorService executorService = ManagedExecutors.newVirtualThreadPerTaskExecutor("clearOrphanedQueues",
|
||||
configuration.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(), environment);
|
||||
clearOrphanedQueues(databases, commandDependencies.accountsManager(), concurrency, dryRun, maxAcisPerTransaction,
|
||||
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit(),
|
||||
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(),
|
||||
chunksPerShard);
|
||||
chunksPerShard,
|
||||
commandDependencies.accountLockManager(),
|
||||
executorService);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void clearOrphanedQueues(final Stream<Database> databases, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks) {
|
||||
final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
Flux.fromStream(databases)
|
||||
.flatMap(database -> crawlAcisInShard(database, accountsManager, concurrency, dryRun, maxAcisPerTransaction,
|
||||
transactionRetryLimit, transactionTimeout, numChunks))
|
||||
transactionRetryLimit, transactionTimeout, numChunks, accountLockManager, executor))
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
private Mono<Void> crawlAcisInShard(final Database database, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks) {
|
||||
final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
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()))
|
||||
@@ -172,7 +183,8 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
logger.info("Would have cleared queue for ACI: {}", aci.uuid());
|
||||
return Mono.just(true);
|
||||
}
|
||||
return clearQueue(database, aci, transactionRetryLimit, transactionTimeout)
|
||||
return clearQueueWithAciLock(database, aci, transactionRetryLimit, transactionTimeout, accountsManager,
|
||||
accountLockManager, executor)
|
||||
.thenReturn(true)
|
||||
.onErrorResume(t -> {
|
||||
logger.error("Failed to clear orphaned queue for ACI: {}", aci.uuid(), t);
|
||||
@@ -185,15 +197,30 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Void> clearQueue(final Database database, final AciServiceIdentifier aci,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout) {
|
||||
return Mono.fromFuture(() -> database.runAsync(transaction -> {
|
||||
private Mono<Void> clearQueueWithAciLock(final Database 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()) {
|
||||
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), executor));
|
||||
}
|
||||
|
||||
private void clearQueue(final Database database, final AciServiceIdentifier aci, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout) {
|
||||
database.run(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
transaction.options().setRetryLimit(transactionRetryLimit);
|
||||
transaction.options().setTimeout(transactionTimeout.toMillis());
|
||||
transaction.clear(getAccountSubspace(messagesSubspace, aci).range());
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+4
-3
@@ -126,7 +126,8 @@ public record CommandDependencies(
|
||||
DynamoDbClient dynamoDbClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager,
|
||||
FDB fdb) {
|
||||
FDB fdb,
|
||||
AccountLockManager accountLockManager) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
@@ -460,8 +461,8 @@ public record CommandDependencies(
|
||||
dynamoDbClient,
|
||||
phoneNumberIdentifiers,
|
||||
dynamoDbRecoveryManager,
|
||||
fdb
|
||||
);
|
||||
fdb,
|
||||
accountLockManager);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -22,7 +22,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -45,7 +44,8 @@ class ClearExpiredFoundationDbMessagesCommandTest {
|
||||
|
||||
super(clock);
|
||||
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
|
||||
null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
|
||||
+50
-5
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -38,12 +39,14 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
|
||||
|
||||
class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
|
||||
@@ -54,6 +57,9 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private AccountLockManager accountLockManager;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
@@ -61,6 +67,15 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
|
||||
final List<Database> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
accountLockManager = mock(AccountLockManager.class);
|
||||
|
||||
when(accountLockManager.withLock(any(), any(), any())).thenAnswer(invocation -> {
|
||||
//noinspection rawtypes
|
||||
final ThrowingSupplier supplier = invocation.getArgument(1);
|
||||
return supplier.get();
|
||||
});
|
||||
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
Map.of(0, databases),
|
||||
0,
|
||||
@@ -85,7 +100,6 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
// Assume that a subset of accounts are deleted
|
||||
final Set<AciServiceIdentifier> deletedAccounts = new HashSet<>(accounts.subList(0, 3));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.getByAccountIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(mock(Account.class))));
|
||||
for (final AciServiceIdentifier deletedAccount : deletedAccounts) {
|
||||
@@ -98,7 +112,10 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8,
|
||||
3,
|
||||
Duration.ofSeconds(2),
|
||||
2);
|
||||
2,
|
||||
accountLockManager,
|
||||
Executors.newVirtualThreadPerTaskExecutor()
|
||||
);
|
||||
|
||||
for (final AciServiceIdentifier aci : accounts) {
|
||||
assertEquals(!deletedAccounts.contains(aci), queueExists(FoundationDbMessageStore.getAccountSubspace(aci)));
|
||||
@@ -110,15 +127,18 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
// create accounts in a test subspace that doesn't conflict with the main messages subspace
|
||||
final Subspace testMessagesSubspace = new Subspace(
|
||||
Tuple.from("MT"));
|
||||
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(testMessagesSubspace);
|
||||
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(
|
||||
testMessagesSubspace);
|
||||
final List<AciServiceIdentifier> acis = IntStream.range(0, 128)
|
||||
.mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID()))
|
||||
.toList();
|
||||
final Database database = FOUNDATION_DB_EXTENSION.getDatabases()[0];
|
||||
database.run(transaction -> {
|
||||
acis.forEach(aci -> {
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")), new byte[]{42});
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")), new byte[]{43});
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")),
|
||||
new byte[]{42});
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")),
|
||||
new byte[]{43});
|
||||
});
|
||||
return null;
|
||||
});
|
||||
@@ -129,6 +149,31 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
assertEquals(new HashSet<>(acis), new HashSet<>(fetchedAcis));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aciReusedAfterExistenceCheck() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
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
|
||||
// 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)));
|
||||
|
||||
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand();
|
||||
command.clearOrphanedQueues(
|
||||
Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8,
|
||||
3,
|
||||
Duration.ofSeconds(2),
|
||||
2,
|
||||
accountLockManager,
|
||||
Executors.newVirtualThreadPerTaskExecutor()
|
||||
);
|
||||
|
||||
assertTrue(queueExists(FoundationDbMessageStore.getAccountSubspace(aci)));
|
||||
}
|
||||
|
||||
/// Returns whether any key exists under the account's prefix in any shard
|
||||
private boolean queueExists(final Subspace accountSpace) {
|
||||
final Range accountRange = accountSpace.range();
|
||||
|
||||
+1
@@ -88,6 +88,7 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
//noinspection unchecked
|
||||
|
||||
+1
-1
@@ -18,7 +18,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.IdleDeviceNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -69,6 +68,7 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
+1
@@ -55,6 +55,7 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
|
||||
null,
|
||||
null,
|
||||
dynamoDbRecoveryManager,
|
||||
null,
|
||||
null);
|
||||
|
||||
namespace = new Namespace(Map.of(
|
||||
|
||||
+1
-1
@@ -22,7 +22,6 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment;
|
||||
import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -77,6 +76,7 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -20,7 +20,6 @@ import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -40,7 +39,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest {
|
||||
final boolean dryRun) {
|
||||
|
||||
super();
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user