Compare commits

..
12 changed files with 252 additions and 21 deletions

No files matched your search

@@ -450,6 +450,8 @@ public class DeviceController {
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
.filter(DeviceCapability::preventDowngrade)
.filter(account::hasCapability)
.collect(Collectors.toSet());
@@ -164,6 +164,9 @@ public class MessageController {
.register(Metrics.globalRegistry);
}
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// for additional details.
@@ -455,6 +458,12 @@ public class MessageController {
userAgent);
} catch (final MismatchedDevicesException e) {
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
if (messageType == MessageType.SYNC) {
Metrics.counter(INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME,
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.increment();
}
throw new WebApplicationException(Response.status(410)
.type(MediaType.APPLICATION_JSON)
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
@@ -25,7 +25,8 @@ import io.micrometer.statsd.StatsdMeterRegistry;
import java.time.Duration;
import java.util.Optional;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
@@ -35,6 +36,8 @@ import org.whispersystems.textsecuregcm.util.Constants;
public class MetricsUtil {
private static final Logger log = LoggerFactory.getLogger(MetricsUtil.class);
public static final String PREFIX = "chat";
private static volatile boolean registeredMetrics = false;
@@ -155,6 +158,14 @@ public class MetricsUtil {
return config;
}
if (config.getMinimumExpectedValueAsDouble() == null || config.getMaximumExpectedValueAsDouble() == null) {
log.error("Distribution {} does not specify lower or upper bounds, not exporting histograms", id.getName());
return DistributionStatisticConfig.builder()
.percentilesHistogram(false)
.build()
.merge(config);
}
final double lowerBound = config.getMinimumExpectedValueAsDouble();
final double upperBound = config.getMaximumExpectedValueAsDouble();
@@ -22,6 +22,7 @@ import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -58,16 +59,17 @@ public class MessagePersister implements Managed {
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.publishPercentileHistogram(true)
.register(Metrics.globalRegistry);
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
static final int QUEUE_BATCH_LIMIT = 100;
static final int MESSAGE_BATCH_LIMIT = 100;
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
name(MessagePersister.class, "queueCount"))
.publishPercentiles(new double[0])
.serviceLevelObjectives(IntStream.range(1, QUEUE_BATCH_LIMIT + 1).mapToDouble(i -> i).toArray())
.register(Metrics.globalRegistry);
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
@@ -0,0 +1,97 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.subspace.Subspace;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.Hashing;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
/// An implementation of a message store backed by FoundationDB.
///
/// @implNote The layout of elements in FoundationDB is as follows:
/// * messages
/// * {aci}
/// * last => versionstamp
/// * {deviceId}
/// * queue
/// * {versionstamp_1} => envelope_1
/// * {versionstamp_2} => envelope_2
public class FoundationDbMessageStore {
private final Database[] databases;
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
private final Executor executor;
public FoundationDbMessageStore(final Database[] databases, final Executor executor) {
this.databases = databases;
this.executor = executor;
}
/**
* Insert a message bundle for a set of devices belonging to a single recipient
*
* @param aci destination account identifier
* @param messagesByDeviceId a map of deviceId => message envelope
* @return a future that completes with a {@link Versionstamp} of the committed transaction
*/
public CompletableFuture<Versionstamp> insert(final AciServiceIdentifier aci,
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
// for details.
return getShardForAci(aci).runAsync(transaction -> {
insert(aci, messagesByDeviceId, transaction);
return CompletableFuture.completedFuture(transaction.getVersionstamp());
})
.thenComposeAsync(Function.identity(), executor)
.thenApply(Versionstamp::complete);
}
private void insert(final AciServiceIdentifier aci, final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
final Transaction transaction) {
messagesByDeviceId.forEach((deviceId, message) -> {
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY, deviceQueueSubspace.packWithVersionstamp(Tuple.from(
Versionstamp.incomplete())), message.toByteArray());
});
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getLastMessageKey(aci),
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
}
private Database getShardForAci(final AciServiceIdentifier aci) {
return databases[hashAciToShardNumber(aci)];
}
private int hashAciToShardNumber(final AciServiceIdentifier aci) {
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
}
@VisibleForTesting
Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).get("Q");
}
private Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getAccountSubspace(aci).get(deviceId);
}
private Subspace getAccountSubspace(final AciServiceIdentifier aci) {
return MESSAGES_SUBSPACE.get(aci.uuid());
}
@VisibleForTesting
byte[] getLastMessageKey(final AciServiceIdentifier aci) {
return getAccountSubspace(aci).pack("l");
}
}
@@ -229,7 +229,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
try {
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
} catch (StripeException e) {
final String errorCode = e.getCode().toLowerCase(Locale.ROOT);
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
switch (errorCode) {
case "amount_too_small","amount_too_large" ->
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
@@ -117,7 +117,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
private final AtomicBoolean sentInitialQueueEmptyMessage = new AtomicBoolean(false);
private final LongAdder sentMessageCounter = new LongAdder();
private final AtomicLong queueDrainStartTime = new AtomicLong();
private final AtomicLong queueDrainStartNanoTime = new AtomicLong();
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
private final Scheduler messageDeliveryScheduler;
@@ -159,7 +159,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
public void start() {
pushNotificationManager.handleMessagesRetrieved(authenticatedAccount, authenticatedDevice, client.getUserAgent());
queueDrainStartTime.set(System.currentTimeMillis());
queueDrainStartNanoTime.set(System.nanoTime());
processStoredMessages();
}
@@ -280,12 +280,12 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
// Cleared the queue! Send a queue empty message if we need to
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
final long drainDurationNanos = System.nanoTime() - queueDrainStartNanoTime.get();
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDuration, TimeUnit.MILLISECONDS);
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDurationNanos, TimeUnit.NANOSECONDS);
if (drainDuration > SLOW_DRAIN_THRESHOLD) {
if (drainDurationNanos > SLOW_DRAIN_THRESHOLD) {
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
}
@@ -348,7 +348,8 @@ class DeviceControllerTest {
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
final int expectedStatus =
capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE
&& capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/link")
@@ -70,7 +70,7 @@ import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class FaultTolerantRedisClusterClientTest {
private static final Duration TIMEOUT = Duration.ofMillis(50);
private static final Duration TIMEOUT = Duration.ofMillis(200);
private static final RetryConfiguration RETRY_CONFIGURATION = new RetryConfiguration();
@@ -11,7 +11,7 @@ import java.io.IOException;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
public class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
private static FoundationDbDatabaseLifecycleManager databaseLifecycleManager;
@@ -193,11 +193,11 @@ class RedisDynamoDbMessagePublisherTest {
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
final CountDownLatch countDownLatch = new CountDownLatch(2);
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
Thread.ofVirtual().start(() -> {
try {
countDownLatch.await();
queueEmptyCountDownLatch.await();
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
@@ -210,7 +210,11 @@ class RedisDynamoDbMessagePublisherTest {
});
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
.doOnNext(_ -> countDownLatch.countDown()))
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.QueueEmpty) {
queueEmptyCountDownLatch.countDown();
}
}))
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
.expectNext(new MessageStreamEntry.QueueEmpty())
@@ -228,11 +232,11 @@ class RedisDynamoDbMessagePublisherTest {
final RedisDynamoDbMessagePublisher messagePublisher =
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
final CountDownLatch countDownLatch = new CountDownLatch(2);
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
Thread.ofVirtual().start(() -> {
try {
countDownLatch.await();
queueEmptyCountDownLatch.await();
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
@@ -245,7 +249,11 @@ class RedisDynamoDbMessagePublisherTest {
});
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
.doOnNext(_ -> countDownLatch.countDown()))
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.QueueEmpty) {
queueEmptyCountDownLatch.countDown();
}
}))
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
.expectNext(new MessageStreamEntry.QueueEmpty())
@@ -0,0 +1,101 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.FoundationDbExtension;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class FoundationDbMessageStoreTest {
@RegisterExtension
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
private FoundationDbMessageStore foundationDbMessageStore;
@BeforeEach
void setup() {
foundationDbMessageStore = new FoundationDbMessageStore(
new Database[]{FOUNDATION_DB_EXTENSION.getDatabase()},
Executors.newVirtualThreadPerTaskExecutor());
}
@Test
void insert() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
.mapToObj(i -> (byte) i)
.toList();
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage()));
final Versionstamp versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
assertNotNull(versionstamp);
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
.collect(Collectors.toMap(Function.identity(), deviceId -> {
try {
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp));
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
}));
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
assertEquals(versionstamp, getLastMessageVersionstamp(aci),
"last message versionstamp should be the versionstamp of the last insert transaction");
}
@Test
void versionstampCorrectlyUpdatedOnMultipleInserts() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
final Versionstamp secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
assertEquals(secondMessageVersionstamp, getLastMessageVersionstamp(aci));
}
private static MessageProtos.Envelope generateRandomMessage() {
return MessageProtos.Envelope.newBuilder()
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
.build();
}
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
final Versionstamp versionstamp) {
return FOUNDATION_DB_EXTENSION.getDatabase().read(transaction -> {
final byte[] key = foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
.pack(Tuple.from(versionstamp));
return transaction.get(key);
}).join();
}
private Versionstamp getLastMessageVersionstamp(final AciServiceIdentifier aci) {
return FOUNDATION_DB_EXTENSION.getDatabase()
.read(transaction -> transaction.get(foundationDbMessageStore.getLastMessageKey(aci))
.thenApply(Tuple::fromBytes)
.thenApply(t -> t.getVersionstamp(0)))
.join();
}
}