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 b4742c08d..182a2fa7d 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 @@ -339,7 +339,7 @@ class FoundationDbMessagePublisher { return keyValues; }); - }) + }, FoundationDbUtil.Context.GET_MESSAGES_BATCH) .thenApply(keyValues -> { if (keyValues.size() < maxMessages) { transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES); @@ -492,7 +492,7 @@ class FoundationDbMessagePublisher { return FoundationDbUtil.safeRunAsync(database, transaction -> { transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId)); return CompletableFuture.completedFuture(null); - }); + }, FoundationDbUtil.Context.SET_PRESENCE); } @VisibleForTesting @@ -505,7 +505,7 @@ class FoundationDbMessagePublisher { if (!isPresenceContested(presenceValue)) { transaction.clear(presenceKey); } - })) + }), FoundationDbUtil.Context.CLEAR_PRESENCE) .whenComplete((_, throwable) -> { if (throwable != null) { LOGGER.warn("Failed to clear presence on disposal", throwable); 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 899536143..f08b3e5cf 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 @@ -285,7 +285,7 @@ public class FoundationDbMessageStore { .map(MessageProtos.Envelope::getEphemeral) .orElseThrow(() -> new IllegalStateException("One or more bundles is empty")); - return getDatabases(epoch)[shardId].runAsync(transaction -> { + return FoundationDbUtil.safeRunAsync(getDatabases(epoch)[shardId], transaction -> { messagesByAccountIdentifier.forEach(entry -> insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), epoch, shardId, transaction))); @@ -303,7 +303,7 @@ public class FoundationDbMessageStore { } return CompletableFuture.completedFuture(Optional.empty()); }); - }) + }, FoundationDbUtil.Context.INSERT_MESSAGE_BATCH) .thenCompose(Function.identity()) .thenApply(maybeVersionstamp -> insertFuturesByAci.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> { @@ -391,10 +391,10 @@ public class FoundationDbMessageStore { final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp)); - return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> { + return FoundationDbUtil.safeRunAsync(databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)], transaction -> { transaction.clear(messageKey); return CompletableFuture.completedFuture(null); - }) + }, FoundationDbUtil.Context.DELETE_MESSAGE) .thenRun(() -> { sample.stop(DELETE_MESSAGE_TIMER); DELETE_MESSAGE_COUNTER.increment(); @@ -590,7 +590,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)))) + .flatMap(database -> Mono.fromFuture(() -> FoundationDbUtil.safeRunAsync(database, transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange), FoundationDbUtil.Context.ESTIMATE_QUEUE_SIZE))) .reduce(0L, Long::sum); } @@ -625,7 +625,7 @@ public class FoundationDbMessageStore { final CompletableFuture rangeSplitPointsFuture = transaction.getRangeSplitPoints(deviceQueueRange, rangeSplitChunkSize); return estimatedQueueSizeFuture.thenCombine(rangeSplitPointsFuture, Pair::new); - }); + }, FoundationDbUtil.Context.ESTIMATE_QUEUE_SIZE_AND_RANGE_SPLITS); } public Mono trimQueue(final AciServiceIdentifier aci, @@ -714,7 +714,7 @@ public class FoundationDbMessageStore { transaction.options().setRetryLimit(batchPriorityTransactionRetryLimit); transaction.clear(range); return CompletableFuture.completedFuture(null); - }); + }, FoundationDbUtil.Context.TRIM_QUEUE); } @VisibleForTesting 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 ada7b4e7c..5eb2423a0 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 @@ -206,7 +206,7 @@ public class FoundationDbMessageStream implements MessageStream { /// @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 -> - transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()) + transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList(), FoundationDbUtil.Context.GET_END_OF_QUEUE) .>thenApply(items -> { if (items.isEmpty()) { return Optional.empty(); 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 c48d3fbf2..3150e18ce 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,24 +1,61 @@ 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 { - /// 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. + public enum Context { + INSERT_MESSAGE_BATCH("insertMessageBatch"), + GET_MESSAGES_BATCH("getMessagesBatch"), + SET_PRESENCE("setPresence"), + CLEAR_PRESENCE("clearPresence"), + GET_END_OF_QUEUE("getEndOfQueue"), + ESTIMATE_QUEUE_SIZE("estimateQueueSize"), + ESTIMATE_QUEUE_SIZE_AND_RANGE_SPLITS("estimateQueueSizeAndRangeSplits"), + TRIM_QUEUE("trimQueue"), + DELETE_MESSAGE("deleteMessage"); + + private final String name; + + Context(final String name) { + this.name = name; + } + + public String getName() { + return name; + } + } + + 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 database the FoundationDB database instance - /// @param retryable the block of transaction logic to execute /// @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 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()); } }