From 100ab61c82627582c867d19e1c0561ba2781e927 Mon Sep 17 00:00:00 2001 From: Katherine Date: Tue, 8 Sep 2026 14:36:52 -0400 Subject: [PATCH] Add circuit breakers to FoundationDB operations --- .../textsecuregcm/WhisperServerService.java | 12 ++-- .../FoundationDbMessagesConfiguration.java | 4 +- .../foundationdb/FaultTolerantDatabase.java | 72 +++++++++++++++++++ .../foundationdb/FoundationDBWarmup.java | 6 +- .../FoundationDbMessagePublisher.java | 15 ++-- .../FoundationDbMessageStore.java | 48 ++++++------- .../FoundationDbMessageStream.java | 15 ++-- .../foundationdb/FoundationDbUtil.java | 35 +-------- .../foundationdb/VersionstampClock.java | 7 +- ...learOrphanedFoundationDbQueuesCommand.java | 28 ++++---- .../workers/CommandDependencies.java | 14 ++-- ...FoundationDbMessagesConfigurationTest.java | 24 ++++--- .../storage/FoundationDbClusterExtension.java | 13 ++-- .../FaultTolerantDatabaseTest.java | 66 +++++++++++++++++ .../FoundationDbMessagePublisherTest.java | 19 ++--- .../FoundationDbMessageStoreTest.java | 8 +-- ...OrphanedFoundationDbQueuesCommandTest.java | 8 +-- 17 files changed, 258 insertions(+), 136 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabase.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 51b528d7c..d7019b554 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -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> messageDatabasesByEpoch; + final Map> messageDatabasesByEpoch; { - final Map databasesByName = + final Map faultTolerantDatabasesByName = config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream() .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, entry -> { @@ -513,7 +514,8 @@ public class WhisperServerService extends Application 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(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfiguration.java index c8e54d796..471a980bd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfiguration.java @@ -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 T run(final Function 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 the return type of retryable + /// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)] + public CompletableFuture runAsync(final Function> 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 read(final Function retryable) { + return circuitBreaker.executeSupplier(() -> database.read(retryable)); + } + + public CompletableFuture readAsync( + final Function> retryable) { + return circuitBreaker.executeCompletionStage(() -> database.readAsync(retryable)) + .toCompletableFuture(); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDBWarmup.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDBWarmup.java index d40172752..eef1d411a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDBWarmup.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDBWarmup.java @@ -13,7 +13,7 @@ import org.whispersystems.textsecuregcm.metrics.MetricsUtil; public class FoundationDBWarmup implements Managed { - private final Map databasesByName; + private final Map 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 databasesByName) { + public FoundationDBWarmup(final Map 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) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java index 182a2fa7d..4071be4c4 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisher.java @@ -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 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); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java index 277688a45..7ab2034c5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStore.java @@ -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 versionstampClocks; + private final FaultTolerantDatabase[][] databasesByEpoch; + private final Map 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> databasesByEpochMap, + public FoundationDbMessageStore(final Map> 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 action) { + private void doForAllDatabasesWithMessages(final AciServiceIdentifier aci, final Consumer 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> accountDeviceIdentifiers, final Instant cutoffTime) { - final Map> queueSubspacesToTrimByDatabase = new IdentityHashMap<>(); + final Map> 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> splitPointsByDatabase) {} + record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map> splitPointsByDatabase) {} - private Flux getDistinctDatabasesForAci(final AciServiceIdentifier aci) { + private Flux 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> 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 estimatedQueueSizeFuture = transaction.getEstimatedRangeSizeBytes(deviceQueueRange); @@ -681,7 +679,7 @@ public class FoundationDbMessageStore { return Mono.empty(); } - final List orderedDatabases; + final List orderedDatabases; { // Trim messages from the database(s) in the inactive epoch(s) before trimming from the database in the active epoch final List orderedEpochsToTrim = new ArrayList<>(Arrays.stream(liveEpochs) @@ -738,8 +736,8 @@ public class FoundationDbMessageStore { }); } - private CompletableFuture trimQueue(final Database database, final Range range) { - return FoundationDbUtil.safeRunAsync(database, transaction -> { + private CompletableFuture trimQueue(final FaultTolerantDatabase database, final Range range) { + return database.runAsync(transaction -> { transaction.options().setPriorityBatch(); transaction.options().setTimeout(batchPriorityTransactionTimeout.toMillis()); transaction.options().setRetryLimit(batchPriorityTransactionRetryLimit); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStream.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStream.java index cd654d6b9..07ead87c2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStream.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStream.java @@ -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 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 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 databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList(); + final List 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[] finitePublishers = endOfQueueKeysByDatabase.entrySet().stream() .map(entry -> { - final Database database = entry.getKey(); + final FaultTolerantDatabase database = entry.getKey(); final Optional maybeEndOfQueueKeyExclusive = entry.getValue(); return maybeEndOfQueueKeyExclusive @@ -165,7 +164,7 @@ public class FoundationDbMessageStream implements MessageStream { @SuppressWarnings("unchecked") final Flux[] infinitePublishers = endOfQueueKeysByDatabase.entrySet().stream() .map(entry -> { - final Database database = entry.getKey(); + final FaultTolerantDatabase database = entry.getKey(); final Optional 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> getEndOfQueueKeyExclusive(final Database database) { - return FoundationDbUtil.safeRunAsync(database, transaction -> + private CompletableFuture> getEndOfQueueKeyExclusive(final FaultTolerantDatabase database) { + return database.runAsync(transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList(), FoundationDbUtil.Context.GET_END_OF_QUEUE) .>thenApply(items -> { if (items.isEmpty()) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbUtil.java index 3150e18ce..f6b3ade5c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbUtil.java @@ -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 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 CompletableFuture safeRunAsync(final Database database, - final Function> 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"); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/VersionstampClock.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/VersionstampClock.java index ee31366e3..d4cb008fe 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/VersionstampClock.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/VersionstampClock.java @@ -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; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java index ac0d27821..3f0a1b864 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommand.java @@ -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 databases = configuration.getFoundationDbMessagesConfiguration().clusters().values().stream() - .map(databaseFactory -> { + final Stream 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 databases, final AccountsManager accountsManager, + void clearOrphanedQueues(final Stream 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 crawlAcisInShard(final Database database, final AccountsManager accountsManager, + private Mono 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 clearQueueWithAciLock(final Database database, final AciServiceIdentifier aci, + private Mono 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 getAcisInShard(final Database database, final int maxAcisPerTransaction, + Flux 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> splitSubspace(final Database database, final int numChunks) { + CompletableFuture> 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 getAcisInChunk(final Database database, final int maxAcisPerTransaction, + Flux 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 acis, byte[] cursor) {} private Mono readAciBatch( - final Database database, + final FaultTolerantDatabase database, final byte[] beginInclusive, final byte[] endExclusive, final int maxAcisPerTransaction, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 51969cca9..43151533f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -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> messageDatabasesByEpoch; + final Map> messageDatabasesByEpoch; { - final Map databasesByName = + final Map 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())); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java index 69285143e..a29e24f8d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/configuration/FoundationDbMessagesConfigurationTest.java @@ -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()); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java index 32b5b7994..6f7459f06 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/FoundationDbClusterExtension.java @@ -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; } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java new file mode 100644 index 000000000..01e19aa33 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabaseTest.java @@ -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()))); + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java index 53a536a41..0bd4fb6d6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessagePublisherTest.java @@ -56,6 +56,7 @@ import reactor.test.StepVerifier; class FoundationDbMessagePublisherTest { private Database database; + private FaultTolerantDatabase ftDatabase; private List 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), diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java index f0a2836e7..5f9717593 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/foundationdb/FoundationDbMessageStoreTest.java @@ -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 databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases()); + final List 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(); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java index 078b23338..21b98c678 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearOrphanedFoundationDbQueuesCommandTest.java @@ -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 databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases()); + final List databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases()); accountsManager = mock(AccountsManager.class); accountLockManager = mock(AccountLockManager.class); @@ -132,7 +132,7 @@ class ClearOrphanedFoundationDbQueuesCommandTest { final List 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 keyValues = database.readAsync(transaction -> AsyncUtil.collect(transaction.getRange(accountRange, 1))).join();