mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:06:50 +00:00
Add circuit breakers to FoundationDB operations
This commit is contained in:
1 parent
4d48c40ce1
commit
100ab61c82
17 files changed
+258
-136
No files matched your search
@@ -294,6 +294,7 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
@@ -499,9 +500,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
|
||||
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
@@ -513,7 +514,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
database.options().setTransactionRetryLimit(
|
||||
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
|
||||
|
||||
return database;
|
||||
return new FaultTolerantDatabase(database, entry.getKey(),
|
||||
config.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -522,10 +524,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.map(faultTolerantDatabasesByName::get)
|
||||
.toList()));
|
||||
|
||||
environment.lifecycle().manage(new FoundationDBWarmup(databasesByName));
|
||||
environment.lifecycle().manage(new FoundationDBWarmup(faultTolerantDatabasesByName));
|
||||
}
|
||||
|
||||
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
|
||||
|
||||
+3
-1
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
@@ -33,7 +34,8 @@ public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid Fou
|
||||
@NotNull Duration transactionTimeout,
|
||||
@PositiveOrZero long transactionRetryLimit,
|
||||
@NotNull Duration batchPriorityTransactionTimeout,
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit,
|
||||
@Nullable String circuitBreakerConfigurationName) {
|
||||
|
||||
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
|
||||
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbUtil.TRANSACTION_ERRORS_COUNTER;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.apple.foundationdb.ReadTransaction;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.annotation.Nullable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
public class FaultTolerantDatabase {
|
||||
private final Database database;
|
||||
private final CircuitBreaker circuitBreaker;
|
||||
|
||||
public FaultTolerantDatabase(
|
||||
final Database database,
|
||||
final String circuitBreakerName,
|
||||
@Nullable final String circuitBreakerConfigurationName) {
|
||||
this.database = database;
|
||||
this.circuitBreaker = circuitBreakerConfigurationName != null
|
||||
? ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName, circuitBreakerConfigurationName)
|
||||
: ResilienceUtil.getCircuitBreakerRegistry().circuitBreaker(circuitBreakerName);
|
||||
}
|
||||
|
||||
public <T> T run(final Function<? super Transaction, T> retryable) {
|
||||
return circuitBreaker.executeSupplier(() -> database.run(retryable));
|
||||
}
|
||||
|
||||
/// Returns a cancellation-safe version of the result from [Database#runAsync(Function)]. Since the final stage
|
||||
/// of the result from [Database#runAsync(Function)] is a cleanup stage that closes the transaction, the
|
||||
/// transaction leaks if the future gets cancelled and the cleanup stage is skipped. So, we add another dummy stage
|
||||
/// that serves as the cancellation target and the cleanup can proceed as normal.
|
||||
///
|
||||
/// @param retryable the block of transaction logic to execute
|
||||
/// @param <T> the return type of retryable
|
||||
/// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)]
|
||||
public <T> CompletableFuture<T> runAsync(final Function<? super Transaction, ? extends CompletableFuture<T>> retryable,
|
||||
final FoundationDbUtil.Context context) {
|
||||
return circuitBreaker.executeCompletionStage(() -> database.runAsync(retryable)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
|
||||
"context", context.getName(),
|
||||
"code", String.valueOf(fdbException.getCode())
|
||||
).increment();
|
||||
}
|
||||
})
|
||||
.thenApply(Function.identity()))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public <T> T read(final Function<? super ReadTransaction, T> retryable) {
|
||||
return circuitBreaker.executeSupplier(() -> database.read(retryable));
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> readAsync(
|
||||
final Function<? super ReadTransaction, ? extends CompletableFuture<T>> retryable) {
|
||||
return circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -13,7 +13,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
public class FoundationDBWarmup implements Managed {
|
||||
|
||||
private final Map<String, Database> databasesByName;
|
||||
private final Map<String, FaultTolerantDatabase> databasesByName;
|
||||
|
||||
private static final Duration RETRY_DELAY = Duration.ofMillis(500);
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
@@ -32,7 +32,7 @@ public class FoundationDBWarmup implements Managed {
|
||||
System.arraycopy(suffix, 0, STATUS_JSON_KEY, 2, suffix.length);
|
||||
}
|
||||
|
||||
public FoundationDBWarmup(final Map<String, Database> databasesByName) {
|
||||
public FoundationDBWarmup(final Map<String, FaultTolerantDatabase> databasesByName) {
|
||||
this.databasesByName = databasesByName;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class FoundationDBWarmup implements Managed {
|
||||
///
|
||||
/// @param databaseName the name of the database to read from
|
||||
/// @param database the FoundationDB [Database] instance
|
||||
private void readStatusKey(final String databaseName, final Database database) {
|
||||
private void readStatusKey(final String databaseName, final FaultTolerantDatabase database) {
|
||||
int attempts = 0;
|
||||
final Timer.Sample sample = Timer.start();
|
||||
while (true) {
|
||||
|
||||
+7
-8
@@ -1,6 +1,5 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
@@ -35,7 +34,7 @@ import reactor.core.publisher.Mono;
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
class FoundationDbMessagePublisher {
|
||||
|
||||
private final Database database;
|
||||
private final FaultTolerantDatabase database;
|
||||
private final Clock clock;
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
@@ -128,7 +127,7 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
|
||||
FoundationDbMessagePublisher(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
@@ -175,7 +174,7 @@ class FoundationDbMessagePublisher {
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive) {
|
||||
@@ -195,7 +194,7 @@ class FoundationDbMessagePublisher {
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
@@ -312,7 +311,7 @@ class FoundationDbMessagePublisher {
|
||||
throw new IllegalArgumentException("Max messages must be positive");
|
||||
}
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
return database.runAsync(transaction -> {
|
||||
final CompletableFuture<Void> checkPresenceFuture;
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
@@ -489,7 +488,7 @@ class FoundationDbMessagePublisher {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
|
||||
}
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
return database.runAsync(transaction -> {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}, FoundationDbUtil.Context.SET_PRESENCE);
|
||||
@@ -501,7 +500,7 @@ class FoundationDbMessagePublisher {
|
||||
renewPresenceFuture.cancel(true);
|
||||
|
||||
renewPresenceFuture.whenComplete((_, _) ->
|
||||
FoundationDbUtil.safeRunAsync(database, transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
if (!isPresenceContested(presenceValue)) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
|
||||
+23
-25
@@ -2,7 +2,6 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyArrayResult;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.Range;
|
||||
@@ -72,8 +71,8 @@ import reactor.util.function.Tuples;
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[][] databasesByEpoch;
|
||||
private final Map<Database, VersionstampClock> versionstampClocks;
|
||||
private final FaultTolerantDatabase[][] databasesByEpoch;
|
||||
private final Map<FaultTolerantDatabase, VersionstampClock> versionstampClocks;
|
||||
private final int[] liveEpochs;
|
||||
private final int activeEpoch;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
@@ -132,7 +131,7 @@ public class FoundationDbMessageStore {
|
||||
boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
|
||||
public FoundationDbMessageStore(final Map<Integer, List<FaultTolerantDatabase>> databasesByEpochMap,
|
||||
final int activeEpoch,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@@ -140,10 +139,10 @@ public class FoundationDbMessageStore {
|
||||
final Duration batchPriorityTransactionTimeout,
|
||||
final long batchPriorityTransactionRetryLimit) {
|
||||
|
||||
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
|
||||
final FaultTolerantDatabase[][] databasesByEpochArray = new FaultTolerantDatabase[MAX_EPOCHS][];
|
||||
|
||||
databasesByEpochMap.forEach((epoch, databases) ->
|
||||
databasesByEpochArray[epoch] = databases.toArray(Database[]::new));
|
||||
databasesByEpochArray[epoch] = databases.toArray(FaultTolerantDatabase[]::new));
|
||||
|
||||
this.databasesByEpoch = databasesByEpochArray;
|
||||
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
|
||||
@@ -287,7 +286,7 @@ public class FoundationDbMessageStore {
|
||||
.map(MessageProtos.Envelope::getEphemeral)
|
||||
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(getDatabases(epoch)[shardId], transaction -> {
|
||||
return getDatabases(epoch)[shardId].runAsync(transaction -> {
|
||||
messagesByAccountIdentifier.forEach(entry ->
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), epoch, shardId, transaction)));
|
||||
|
||||
@@ -393,7 +392,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)], transaction -> {
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}, FoundationDbUtil.Context.DELETE_MESSAGE)
|
||||
@@ -420,7 +419,7 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
transaction.clear(messageKey);
|
||||
return Optional.of(value);
|
||||
}))
|
||||
}), FoundationDbUtil.Context.DELETE_MESSAGE)
|
||||
.whenComplete((_, _) -> sample.stop(DELETE_MESSAGE_TIMER))
|
||||
.thenApply(maybeValue -> maybeValue.map(value -> {
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
@@ -446,7 +445,7 @@ public class FoundationDbMessageStore {
|
||||
}));
|
||||
}
|
||||
|
||||
private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer<Database> action) {
|
||||
private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer<FaultTolerantDatabase> action) {
|
||||
IntStream.range(0, databasesByEpoch.length)
|
||||
.filter(epoch -> databasesByEpoch[epoch] != null)
|
||||
.mapToObj(epoch -> databasesByEpoch[epoch][hashAciToShardNumber(aci, epoch)])
|
||||
@@ -458,9 +457,9 @@ public class FoundationDbMessageStore {
|
||||
return getMessages(aci, deviceId, Util.NOOP);
|
||||
}
|
||||
|
||||
Database[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
|
||||
FaultTolerantDatabase[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
|
||||
final FaultTolerantDatabase[] databasesForQueueByEpoch = new FaultTolerantDatabase[databasesByEpoch.length];
|
||||
|
||||
for (final int epoch : liveEpochs) {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
@@ -474,7 +473,7 @@ public class FoundationDbMessageStore {
|
||||
final byte deviceId,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
final Database[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
|
||||
final FaultTolerantDatabase[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
|
||||
|
||||
return new FoundationDbMessageStream(this,
|
||||
aci,
|
||||
@@ -520,7 +519,7 @@ public class FoundationDbMessageStore {
|
||||
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
|
||||
/// date.
|
||||
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
final Map<FaultTolerantDatabase, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
|
||||
accountDeviceIdentifiers.forEach((aci, deviceIds) -> {
|
||||
for (final byte deviceId : deviceIds) {
|
||||
@@ -555,15 +554,14 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci, final int epoch) {
|
||||
FaultTolerantDatabase getShardForAci(final AciServiceIdentifier aci, final int epoch) {
|
||||
return getDatabases(epoch)[hashAciToShardNumber(aci, epoch)];
|
||||
}
|
||||
|
||||
private Database[] getDatabases(final int epoch) {
|
||||
private FaultTolerantDatabase[] getDatabases(final int epoch) {
|
||||
if (databasesByEpoch[epoch] == null) {
|
||||
throw new IllegalStateException("Epoch (%d) not in static configuration".formatted(epoch));
|
||||
}
|
||||
|
||||
return databasesByEpoch[epoch];
|
||||
}
|
||||
|
||||
@@ -606,9 +604,9 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<Database, List<byte[]>> splitPointsByDatabase) {}
|
||||
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<FaultTolerantDatabase, List<byte[]>> splitPointsByDatabase) {}
|
||||
|
||||
private Flux<Database> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
|
||||
private Flux<FaultTolerantDatabase> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
|
||||
return Flux.fromStream(Arrays.stream(getDatabasesByEpochForAci(aci)).filter(Objects::nonNull).distinct());
|
||||
}
|
||||
|
||||
@@ -621,7 +619,7 @@ public class FoundationDbMessageStore {
|
||||
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
|
||||
|
||||
return getDistinctDatabasesForAci(aci)
|
||||
.flatMap(database -> Mono.fromFuture(() -> FoundationDbUtil.safeRunAsync(database, transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange), FoundationDbUtil.Context.ESTIMATE_QUEUE_SIZE)))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange), FoundationDbUtil.Context.ESTIMATE_QUEUE_SIZE)))
|
||||
.reduce(0L, Long::sum);
|
||||
}
|
||||
|
||||
@@ -646,11 +644,11 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
private CompletableFuture<Pair<Long, KeyArrayResult>> estimateQueueSizeAndRangeSplitsForDatabase(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final long rangeSplitChunkSize) {
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
return database.runAsync( transaction -> {
|
||||
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
|
||||
final CompletableFuture<Long> estimatedQueueSizeFuture = transaction.getEstimatedRangeSizeBytes(deviceQueueRange);
|
||||
|
||||
@@ -681,7 +679,7 @@ public class FoundationDbMessageStore {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
final List<Database> orderedDatabases;
|
||||
final List<FaultTolerantDatabase> orderedDatabases;
|
||||
{
|
||||
// Trim messages from the database(s) in the inactive epoch(s) before trimming from the database in the active epoch
|
||||
final List<Integer> orderedEpochsToTrim = new ArrayList<>(Arrays.stream(liveEpochs)
|
||||
@@ -738,8 +736,8 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> trimQueue(final Database database, final Range range) {
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
private CompletableFuture<Void> trimQueue(final FaultTolerantDatabase database, final Range range) {
|
||||
return database.runAsync(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
transaction.options().setTimeout(batchPriorityTransactionTimeout.toMillis());
|
||||
transaction.options().setRetryLimit(batchPriorityTransactionRetryLimit);
|
||||
|
||||
+7
-8
@@ -2,7 +2,6 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
@@ -42,7 +41,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database[] databasesByEpoch;
|
||||
private final FaultTolerantDatabase[] databasesByEpoch;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
@@ -71,7 +70,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final AciServiceIdentifier aciServiceIdentifier,
|
||||
final byte deviceId,
|
||||
final Database[] databasesByEpoch,
|
||||
final FaultTolerantDatabase[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@@ -126,7 +125,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
|
||||
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
|
||||
// `Flux#fromArray` cannot handle `null` elements
|
||||
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
final List<FaultTolerantDatabase> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
return Flux.fromIterable(databases)
|
||||
.flatMap(database -> Mono.fromFuture(() -> getEndOfQueueKeyExclusive(database))
|
||||
@@ -136,7 +135,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final FaultTolerantDatabase database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
@@ -165,7 +164,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] infinitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final FaultTolerantDatabase database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive
|
||||
@@ -204,8 +203,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// subsequent scan.
|
||||
///
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction ->
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final FaultTolerantDatabase database) {
|
||||
return database.runAsync(transaction ->
|
||||
transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList(), FoundationDbUtil.Context.GET_END_OF_QUEUE)
|
||||
.<Optional<KeySelector>>thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
|
||||
+3
-32
@@ -1,13 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class FoundationDbUtil {
|
||||
|
||||
@@ -15,10 +8,12 @@ public class FoundationDbUtil {
|
||||
INSERT_MESSAGE_BATCH("insertMessageBatch"),
|
||||
GET_MESSAGES_BATCH("getMessagesBatch"),
|
||||
SET_PRESENCE("setPresence"),
|
||||
GET_PRESENCE("getPresence"),
|
||||
CLEAR_PRESENCE("clearPresence"),
|
||||
GET_END_OF_QUEUE("getEndOfQueue"),
|
||||
ESTIMATE_QUEUE_SIZE("estimateQueueSize"),
|
||||
ESTIMATE_QUEUE_SIZE_AND_RANGE_SPLITS("estimateQueueSizeAndRangeSplits"),
|
||||
GET_RANGE_SPLITS("getRangeSplits"),
|
||||
TRIM_QUEUE("trimQueue"),
|
||||
DELETE_MESSAGE("deleteMessage");
|
||||
|
||||
@@ -33,29 +28,5 @@ public class FoundationDbUtil {
|
||||
}
|
||||
}
|
||||
|
||||
private static final String TRANSACTION_ERRORS_COUNTER = MetricsUtil.name(FoundationDbUtil.class, "transactionErrors");
|
||||
|
||||
/// Returns a cancellation-safe version of the result from [Database#runAsync(Function)]. Since the final stage of the
|
||||
/// result from [Database#runAsync(Function)] is a cleanup stage that closes the transaction, the transaction leaks if
|
||||
/// the future gets cancelled and the cleanup stage is skipped. So, we add another dummy stage that serves as the
|
||||
/// cancellation target and the cleanup can proceed as normal.
|
||||
///
|
||||
/// @param <T> the return type of retryable
|
||||
/// @param database the FoundationDB database instance
|
||||
/// @param retryable the block of transaction logic to execute
|
||||
/// @param context a context label for metrics purposes
|
||||
/// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)]
|
||||
public static <T> CompletableFuture<T> safeRunAsync(final Database database,
|
||||
final Function<? super Transaction, ? extends CompletableFuture<T>> retryable, final Context context) {
|
||||
return database.runAsync(retryable)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null && ExceptionUtils.unwrap(throwable) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(TRANSACTION_ERRORS_COUNTER,
|
||||
"context", context.getName(),
|
||||
"code", String.valueOf(fdbException.getCode())
|
||||
).increment();
|
||||
}
|
||||
})
|
||||
.thenApply(Function.identity());
|
||||
}
|
||||
static final String TRANSACTION_ERRORS_COUNTER = MetricsUtil.name(FoundationDbUtil.class, "transactionErrors");
|
||||
}
|
||||
+3
-4
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
@@ -29,15 +28,15 @@ public class VersionstampClock {
|
||||
@VisibleForTesting
|
||||
static final Subspace SUBSPACE = new Subspace(Tuple.from("V"));
|
||||
|
||||
private final Database database;
|
||||
private final FaultTolerantDatabase database;
|
||||
private final Clock clock;
|
||||
|
||||
public VersionstampClock(final Database database) {
|
||||
public VersionstampClock(final FaultTolerantDatabase database) {
|
||||
this(database, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public VersionstampClock(final Database database, final Clock clock) {
|
||||
public VersionstampClock(final FaultTolerantDatabase database, final Clock clock) {
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
+15
-13
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore.getAccountSubspace;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.Range;
|
||||
@@ -42,7 +41,9 @@ 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.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -129,10 +130,11 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
|
||||
final FDB fdb = commandDependencies.fdb();
|
||||
|
||||
final Stream<Database> databases = configuration.getFoundationDbMessagesConfiguration().clusters().values().stream()
|
||||
.map(databaseFactory -> {
|
||||
final Stream<FaultTolerantDatabase> databases = configuration.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.map(entry -> {
|
||||
try {
|
||||
return databaseFactory.build(fdb);
|
||||
return new FaultTolerantDatabase(entry.getValue().build(fdb), entry.getKey(),
|
||||
configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -148,7 +150,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void clearOrphanedQueues(final Stream<Database> databases, final AccountsManager accountsManager,
|
||||
void clearOrphanedQueues(final Stream<FaultTolerantDatabase> databases, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
@@ -159,7 +161,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
.block();
|
||||
}
|
||||
|
||||
private Mono<Void> crawlAcisInShard(final Database database, final AccountsManager accountsManager,
|
||||
private Mono<Void> crawlAcisInShard(final FaultTolerantDatabase database, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks, final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
@@ -197,7 +199,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Void> clearQueueWithAciLock(final Database database, final AciServiceIdentifier aci,
|
||||
private Mono<Void> clearQueueWithAciLock(final FaultTolerantDatabase database, final AciServiceIdentifier aci,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final AccountsManager accountsManager,
|
||||
final AccountLockManager accountLockManager,
|
||||
final Executor executor) {
|
||||
@@ -212,7 +214,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
}), executor));
|
||||
}
|
||||
|
||||
private void clearQueue(final Database database, final AciServiceIdentifier aci, final long transactionRetryLimit,
|
||||
private void clearQueue(final FaultTolerantDatabase database, final AciServiceIdentifier aci, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout) {
|
||||
database.run(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
@@ -224,7 +226,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Flux<AciServiceIdentifier> getAcisInShard(final Database database, final int maxAcisPerTransaction,
|
||||
Flux<AciServiceIdentifier> getAcisInShard(final FaultTolerantDatabase database, final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final int numChunks) {
|
||||
return Mono.fromFuture(() -> splitSubspace(database, numChunks))
|
||||
.flatMapIterable(Function.identity())
|
||||
@@ -238,12 +240,12 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
/// @param database the FDB instance
|
||||
/// @param numChunks the number of chunks to split the subspace into
|
||||
/// @return a list of key [Range]s representing chunk boundaries
|
||||
CompletableFuture<List<Range>> splitSubspace(final Database database, final int numChunks) {
|
||||
CompletableFuture<List<Range>> splitSubspace(final FaultTolerantDatabase database, final int numChunks) {
|
||||
return database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(messagesSubspace.range())
|
||||
.thenCompose(rangeSize -> {
|
||||
final long chunkSize = Math.ceilDiv(rangeSize, numChunks);
|
||||
return transaction.getRangeSplitPoints(messagesSubspace.range(), chunkSize);
|
||||
}))
|
||||
}), FoundationDbUtil.Context.GET_RANGE_SPLITS)
|
||||
.thenApply(result -> splitPointsToRanges(result.getKeys()));
|
||||
}
|
||||
|
||||
@@ -259,7 +261,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
return ranges;
|
||||
}
|
||||
|
||||
Flux<AciServiceIdentifier> getAcisInChunk(final Database database, final int maxAcisPerTransaction,
|
||||
Flux<AciServiceIdentifier> getAcisInChunk(final FaultTolerantDatabase database, final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final Range range) {
|
||||
return readAciBatch(database, range.begin, range.end, maxAcisPerTransaction, transactionRetryLimit,
|
||||
transactionTimeout)
|
||||
@@ -277,7 +279,7 @@ public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithD
|
||||
private record BatchReadResult(List<AciServiceIdentifier> acis, byte[] cursor) {}
|
||||
|
||||
private Mono<BatchReadResult> readAciBatch(
|
||||
final Database database,
|
||||
final FaultTolerantDatabase database,
|
||||
final byte[] beginInclusive,
|
||||
final byte[] endExclusive,
|
||||
final int maxAcisPerTransaction,
|
||||
|
||||
+8
-6
@@ -69,12 +69,12 @@ import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseKEMSignedPreKeyStore;
|
||||
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SingleUseECPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
@@ -150,9 +151,9 @@ public record CommandDependencies(
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
|
||||
configuration.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
@@ -164,7 +165,8 @@ public record CommandDependencies(
|
||||
database.options().setTransactionRetryLimit(
|
||||
configuration.getFoundationDbMessagesConfiguration().transactionRetryLimit());
|
||||
|
||||
return database;
|
||||
return new FaultTolerantDatabase(database, entry.getKey(),
|
||||
configuration.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -173,7 +175,7 @@ public record CommandDependencies(
|
||||
messageDatabasesByEpoch = configuration.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.map(faultTolerantDatabasesByName::get)
|
||||
.toList()));
|
||||
}
|
||||
|
||||
|
||||
+16
-8
@@ -28,7 +28,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochClusterConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -41,7 +42,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochClusterConfigured());
|
||||
}
|
||||
|
||||
@@ -57,7 +59,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochFreeOfDuplicates());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -70,7 +73,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isEveryEpochFreeOfDuplicates());
|
||||
}
|
||||
|
||||
@@ -86,7 +90,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isActiveEpochConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -99,7 +104,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isActiveEpochConfigured());
|
||||
}
|
||||
|
||||
@@ -115,7 +121,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isCurrentVersionstampCipherKeyConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
@@ -128,7 +135,8 @@ class FoundationDbMessagesConfigurationTest {
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
|
||||
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2,
|
||||
null
|
||||
).isCurrentVersionstampCipherKeyConfigured());
|
||||
}
|
||||
}
|
||||
+6
-7
@@ -5,21 +5,20 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
|
||||
public class FoundationDbClusterExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private FoundationDbDatabaseLifecycleManager[] databaseLifecycleManagers;
|
||||
private Database[] databases;
|
||||
private FaultTolerantDatabase[] databases;
|
||||
|
||||
public FoundationDbClusterExtension(final int numInstances) {
|
||||
this.databaseLifecycleManagers = new FoundationDbDatabaseLifecycleManager[numInstances];
|
||||
this.databases = new Database[numInstances];
|
||||
this.databases = new FaultTolerantDatabase[numInstances];
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -33,13 +32,13 @@ public class FoundationDbClusterExtension implements BeforeAllCallback, Extensio
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
databaseLifecycleManagers[i] = databaseLifecycleManager;
|
||||
databases[i] = databaseLifecycleManager.getDatabase();
|
||||
databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), null);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public Database[] getDatabases() {
|
||||
public FaultTolerantDatabase[] getDatabases() {
|
||||
return databases;
|
||||
}
|
||||
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
public class FaultTolerantDatabaseTest {
|
||||
private Database database;
|
||||
private FaultTolerantDatabase ftDatabase;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
database = mock(Database.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void circuitBreaker() throws InterruptedException {
|
||||
final String circuitBreakerConfigurationName = "testCircuitBreaker";
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration = new CircuitBreakerConfiguration();
|
||||
|
||||
circuitBreakerConfiguration.setSlidingWindowSize(2);
|
||||
circuitBreakerConfiguration.setSlidingWindowMinimumNumberOfCalls(2);
|
||||
circuitBreakerConfiguration.setPermittedNumberOfCallsInHalfOpenState(1);
|
||||
circuitBreakerConfiguration.setFailureRateThreshold(50);
|
||||
circuitBreakerConfiguration.setWaitDurationInOpenState(Duration.ofSeconds(1));
|
||||
|
||||
ResilienceUtil.getCircuitBreakerRegistry()
|
||||
.addConfiguration(circuitBreakerConfigurationName, circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "testCircuitBreaker",
|
||||
circuitBreakerConfigurationName);
|
||||
|
||||
when(database.read(any())).thenThrow(new FDBException("error", 1031));
|
||||
|
||||
assertThrows(FDBException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
assertThrows(FDBException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
assertThrows(CallNotPermittedException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
Thread.sleep(1001);
|
||||
|
||||
assertThrows(FDBException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
|
||||
assertThrows(CallNotPermittedException.class, () -> ftDatabase.read(t ->
|
||||
t.get("test_key".getBytes())));
|
||||
}
|
||||
}
|
||||
+11
-8
@@ -56,6 +56,7 @@ import reactor.test.StepVerifier;
|
||||
class FoundationDbMessagePublisherTest {
|
||||
|
||||
private Database database;
|
||||
private FaultTolerantDatabase ftDatabase;
|
||||
private List<FoundationDbMessagePublisher.State> stateTransitions;
|
||||
|
||||
private static ScheduledExecutorService presenceRenewalExecutorService;
|
||||
@@ -80,6 +81,8 @@ class FoundationDbMessagePublisherTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
database = mock(Database.class);
|
||||
ftDatabase = new FaultTolerantDatabase(database, getClass().getSimpleName() + "-testCircuitBreaker",
|
||||
null);
|
||||
stateTransitions = new ArrayList<>();
|
||||
|
||||
final byte[] messageGuidCodecKey = new byte[16];
|
||||
@@ -123,7 +126,7 @@ class FoundationDbMessagePublisherTest {
|
||||
});
|
||||
|
||||
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
@@ -200,7 +203,7 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
@@ -290,7 +293,7 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID + 1)));
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
@@ -344,7 +347,7 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
@@ -392,7 +395,7 @@ class FoundationDbMessagePublisherTest {
|
||||
@SuppressWarnings({"unchecked", "resource"})
|
||||
void watchCanceledOnSubscriptionCancel() {
|
||||
final FoundationDbMessagePublisher infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
|
||||
@@ -454,7 +457,7 @@ class FoundationDbMessagePublisherTest {
|
||||
});
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
@@ -520,7 +523,7 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
@@ -578,7 +581,7 @@ class FoundationDbMessagePublisherTest {
|
||||
});
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
ftDatabase,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
|
||||
+4
-4
@@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
@@ -110,7 +109,7 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
versionstampUUIDCipher = new VersionstampUUIDCipher(0, versionstampCipherKey);
|
||||
|
||||
final List<Database> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
final List<FaultTolerantDatabase> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
// Simulate a topology change by reversing the order of the (two) databases in the group in a second epoch. This
|
||||
@@ -841,7 +840,7 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
while (!presenceCleared && Instant.now().isBefore(deadline)) {
|
||||
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)), FoundationDbUtil.Context.GET_PRESENCE)
|
||||
.thenApply(Objects::isNull)
|
||||
.join();
|
||||
}
|
||||
@@ -905,7 +904,8 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
while (!presenceCleared && Instant.now().isBefore(deadline)) {
|
||||
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)),
|
||||
FoundationDbUtil.Context.GET_PRESENCE)
|
||||
.thenApply(Objects::isNull)
|
||||
.join();
|
||||
}
|
||||
|
||||
+4
-4
@@ -12,7 +12,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
@@ -43,6 +42,7 @@ 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.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
@@ -65,7 +65,7 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
new SecureRandom().nextBytes(versionstampCipherKey);
|
||||
|
||||
final List<Database> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
final List<FaultTolerantDatabase> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
accountLockManager = mock(AccountLockManager.class);
|
||||
@@ -132,7 +132,7 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
final List<AciServiceIdentifier> acis = IntStream.range(0, 128)
|
||||
.mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID()))
|
||||
.toList();
|
||||
final Database database = FOUNDATION_DB_EXTENSION.getDatabases()[0];
|
||||
final FaultTolerantDatabase database = FOUNDATION_DB_EXTENSION.getDatabases()[0];
|
||||
database.run(transaction -> {
|
||||
acis.forEach(aci -> {
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")),
|
||||
@@ -178,7 +178,7 @@ class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
private boolean queueExists(final Subspace accountSpace) {
|
||||
final Range accountRange = accountSpace.range();
|
||||
|
||||
for (final Database database : FOUNDATION_DB_EXTENSION.getDatabases()) {
|
||||
for (final FaultTolerantDatabase database : FOUNDATION_DB_EXTENSION.getDatabases()) {
|
||||
final List<KeyValue> keyValues = database.readAsync(transaction ->
|
||||
AsyncUtil.collect(transaction.getRange(accountRange, 1))).join();
|
||||
|
||||
|
||||
Reference in new issue
Block a user