diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java index 1bf9d7afd..832abee43 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcher.java @@ -18,7 +18,6 @@ import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener; import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager; import org.whispersystems.textsecuregcm.entities.MessageProtos; -import org.whispersystems.textsecuregcm.identity.IdentityType; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.push.PushNotificationManager; @@ -38,7 +37,6 @@ import reactor.adapter.JdkFlowAdapter; import reactor.core.observability.micrometer.Micrometer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.core.publisher.Signal; import reactor.core.publisher.Sinks; /// A MessageDispatcher is used to stream messages to an authenticated device and coordinates message acknowledgement, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java index 629577558..b0a323ebe 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/MessagesManager.java @@ -7,11 +7,13 @@ package org.whispersystems.textsecuregcm.storage; import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; import com.apple.foundationdb.FDBException; +import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Metrics; import java.time.Clock; import java.time.Instant; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; @@ -55,14 +57,14 @@ public class MessagesManager { private static final Counter PERSIST_MESSAGE_BYTES_COUNTER = Metrics.counter( name(MessagesManager.class, "persistMessageBytes")); - private static final String MAY_HAVE_MESSAGES_COUNTER_NAME = - MetricsUtil.name(MessagesManager.class, "mayHaveMessages"); - private static final String PRESENCE_MATCH_COUNTER_NAME = MetricsUtil.name(MessagesManager.class, "presenceMatch"); private static final String INSERT_FDB_EXCEPTIONS_COUNTER_NAME = name(MessagesManager.class, "insertExceptions"); + @VisibleForTesting + static final String EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME = "foundationDbExclusiveInsert"; + private final MessagesDynamoDb messagesDynamoDb; private final MessagesCache messagesCache; private final FoundationDbMessageStore foundationDbMessageStore; @@ -152,6 +154,10 @@ public class MessagesManager { } }); + if (experimentEnrollmentManager.isEnrolled(accountIdentifier, EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME)) { + return CompletableFuture.completedFuture(null); + } + return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream() .map(deviceIdAndMessage -> { final byte deviceId = deviceIdAndMessage.getKey(); @@ -207,7 +213,13 @@ public class MessagesManager { final long serverTimestamp = clock.millis(); - return insertSharedMultiRecipientMessagePayload(multiRecipientMessage, resolvedRecipients.keySet()) + // Don't insert shared payloads for recipients enrolled in the "only insert into FoundationDB" experiment + final Set unenrolledResolvedRecipients = resolvedRecipients.entrySet().stream() + .filter(entry -> !experimentEnrollmentManager.isEnrolled(entry.getValue().getAccountIdentifier(), EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME)) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + + return insertSharedMultiRecipientMessagePayload(multiRecipientMessage, unenrolledResolvedRecipients) .thenCompose(maybeSharedMrmKey -> { final Envelope.Builder envelopeBuilder = Envelope.newBuilder() .setType(Envelope.Type.UNIDENTIFIED_SENDER) @@ -251,33 +263,24 @@ public class MessagesManager { } public CompletableFuture mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) { - return messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice); + return foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()) + .thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice), (a, b) -> a || b); } public CompletableFuture mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) { - return messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId()) - .thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice), - (mayHaveCachedMessages, mayHavePersistedMessages) -> { - final String outcome; + @SuppressWarnings("unchecked") final CompletableFuture[] mayHaveMessagesFutures = new CompletableFuture[] { + foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()), + messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId()), + messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice) + }; - if (mayHaveCachedMessages && mayHavePersistedMessages) { - outcome = "both"; - } else if (mayHaveCachedMessages) { - outcome = "cached"; - } else if (mayHavePersistedMessages) { - outcome = "persisted"; - } else { - outcome = "none"; - } - - Metrics.counter(MAY_HAVE_MESSAGES_COUNTER_NAME, "outcome", outcome).increment(); - - return mayHaveCachedMessages || mayHavePersistedMessages; - }); + return CompletableFuture.allOf(mayHaveMessagesFutures) + .thenApply(_ -> Arrays.stream(mayHaveMessagesFutures).anyMatch(CompletableFuture::resultNow)); } public CompletableFuture mayHaveUrgentPersistedMessages(final UUID destinationUuid, final Device destinationDevice) { - return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice); + return foundationDbMessageStore.mayHaveUrgentMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()) + .thenCombine(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice), (a, b) -> a || b); } public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) { @@ -368,7 +371,10 @@ public class MessagesManager { // If there's any message in the persisted layer, return the oldest return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp) // If not, return the oldest message in the cache - .switchIfEmpty(messagesCache.getEarliestUndeliveredTimestamp(destinationUuid, destinationDevice.getId())) + .switchIfEmpty(Mono.defer(() -> messagesCache.getEarliestUndeliveredTimestamp(destinationUuid, destinationDevice.getId()))) + // And if there are none there, then check FoundationDB + .switchIfEmpty(Mono.fromFuture(() -> foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())) + .mapNotNull(maybeTimestamp -> maybeTimestamp.map(Instant::toEpochMilli).orElse(null))) .map(epochMilli -> Optional.of(Instant.ofEpochMilli(epochMilli))) .switchIfEmpty(Mono.just(Optional.empty())) .toFuture(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabase.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabase.java index 73e75188c..f091d6aef 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabase.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/foundationdb/FaultTolerantDatabase.java @@ -171,6 +171,9 @@ public class FaultTolerantDatabase { READ_STATUS("readStatus"), READ_VERSIONSTAMP("readVersionstamp"), RECORD_VERSIONSTAMP_AND_TIME("recordVersionstampAndTime"), + GET_HAS_MESSAGES("hasMessages"), + GET_HAS_URGENT_MESSAGES("hasUrgentMessages"), + GET_EARLIEST_TIMESTAMP("getEarliestTimestamp"), TEST("test"); private final String name; 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 e745077ae..ffaf0b140 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 @@ -92,6 +92,9 @@ public class FoundationDbMessageStore { @VisibleForTesting static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5); + @VisibleForTesting + static final int MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT = 20; + /// The (approximate) transaction size beyond which we do not add more messages in a transaction. The estimated size /// includes only message payloads (and not key reads/writes) which we assume will dominate the total /// transaction size. Note that the FDB [docs](https://apple.github.io/foundationdb/known-limitations.html) currently @@ -486,6 +489,80 @@ public class FoundationDbMessageStore { clock); } + /// Checks whether the message queue belonging to a specific device contains any messages. + /// + /// @param aci the account identifier for the queue to check + /// @param deviceId the account-specific device identifier for the queue to check + /// + /// @return a future that yields `true` if the identified queue contains any messages or `false` if the queue is empty + public CompletableFuture hasMessages(final AciServiceIdentifier aci, final byte deviceId) { + return getDistinctDatabasesForAci(aci) + .flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction -> + transaction.getRange(getDeviceSubspace(aci, deviceId).range(), 1).asList(), + FaultTolerantDatabase.Context.GET_HAS_MESSAGES))) + .map(keyValues -> !keyValues.isEmpty()) + .any(hasMessages -> hasMessages) + .toFuture(); + } + + /// Checks whether the message queue belonging to a specific device contains an urgent message within the first + /// {@value MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT} messages. + /// + /// @param aci the account identifier for the queue to check + /// @param deviceId the account-specific device identifier for the queue to check + /// + /// @return a future that yields `true` if the identified queue contains an urgent message within a sample or `false` + /// otherwise + public CompletableFuture mayHaveUrgentMessages(final AciServiceIdentifier aci, final byte deviceId) { + return getDistinctDatabasesForAci(aci) + .flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction -> + transaction.getRange(getDeviceSubspace(aci, deviceId).range(), MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT).asList(), + FaultTolerantDatabase.Context.GET_HAS_URGENT_MESSAGES)) + .flatMapMany(keyValues -> Flux.fromIterable(keyValues) + .handle((keyValue, sink) -> { + try { + sink.next(MessageProtos.Envelope.parseFrom(keyValue.getValue())); + } catch (final InvalidProtocolBufferException e) { + sink.error(e); + } + }))) + .any(MessageProtos.Envelope::getUrgent) + .toFuture(); + } + + /// Gets the server timestamp of the earliest message in the queue for a specific device + /// + /// @param aci the account identifier for the queue to check + /// @param deviceId the account-specific device identifier for the queue to check + /// + /// @return a future that yields the server timestamp of the earliest message in the queue, or empty if the queue + /// contains no messages + public CompletableFuture> getEarliestUndeliveredMessageTimestamp(final AciServiceIdentifier aci, + final byte deviceId) { + + return getDistinctDatabasesForAci(aci) + .flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction -> + transaction.getRange(getDeviceSubspace(aci, deviceId).range(), 1).asList(), + FaultTolerantDatabase.Context.GET_EARLIEST_TIMESTAMP)) + .mapNotNull(keyValues -> { + if (keyValues.isEmpty()) { + return null; + } + + try { + return Instant.ofEpochMilli(MessageProtos.Envelope.parseFrom(keyValues.getFirst().getValue()) + .getServerTimestamp()); + } catch (final InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + })) + .sort() + .next() + .map(Optional::of) + .switchIfEmpty(Mono.just(Optional.empty())) + .toFuture(); + } + /// Record the versionstamp for the current time in each database's versionstamp clock. public void recordVersionstamps() { for (VersionstampClock versionstampClock : versionstampClocks.values()) { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java index 17e988e29..ee530ed84 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/MessagesManagerTest.java @@ -16,7 +16,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -38,11 +37,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.signal.libsignal.protocol.InvalidMessageException; import org.signal.libsignal.protocol.InvalidVersionException; import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage; import org.signal.libsignal.protocol.ServiceId; +import org.testcontainers.shaded.org.checkerframework.checker.nullness.qual.Nullable; import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; @@ -60,6 +61,7 @@ class MessagesManagerTest { private MessagesCache messagesCache; private FoundationDbMessageStore foundationDbMessageStore; private ReportMessageManager reportMessageManager; + private ExperimentEnrollmentManager experimentEnrollmentManager; private static final TestClock CLOCK = TestClock.pinned(Instant.now()); @@ -71,23 +73,32 @@ class MessagesManagerTest { messagesCache = mock(MessagesCache.class); foundationDbMessageStore = mock(FoundationDbMessageStore.class); reportMessageManager = mock(ReportMessageManager.class); + experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class); when(messagesCache.insert(any(), any(), anyByte(), any())).thenReturn(CompletableFuture.completedFuture(true)); - messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, - mock(RedisMessageAvailabilityManager.class), reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK, - mock(ExperimentEnrollmentManager.class)); + messagesManager = new MessagesManager(messagesDynamoDb, + messagesCache, + foundationDbMessageStore, + mock(RedisMessageAvailabilityManager.class), + reportMessageManager, + Executors.newSingleThreadExecutor(), + CLOCK, + experimentEnrollmentManager); } - @ParameterizedTest - @EnumSource(Envelope.Type.class) - void insert(final Envelope.Type envelopeType) { + @CartesianTest + void insert(@CartesianTest.Enum final Envelope.Type envelopeType, + @CartesianTest.Values(booleans = {true, false}) final boolean exclusiveFoundationDbWrite) { final UUID sourceAci = UUID.randomUUID(); final Envelope message = Envelope.newBuilder() .setSourceServiceId(new AciServiceIdentifier(sourceAci).toCompactByteString()) .setType(envelopeType) .build(); + when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME))) + .thenReturn(exclusiveFoundationDbWrite); + when(foundationDbMessageStore.insert(any(), any())) .thenAnswer(invocation -> { final Map messagesByDeviceId = invocation.getArgument(1); @@ -114,11 +125,16 @@ class MessagesManagerTest { verifyNoMoreInteractions(reportMessageManager); verify(foundationDbMessageStore, times(2)).insert(any(), any()); - verify(messagesCache, times(2)) - .insert(argThat(messageGuid -> messageGuid.version() == 8), - eq(destinationUuid), - eq(Device.PRIMARY_ID), - any()); + + if (exclusiveFoundationDbWrite) { + verify(messagesCache, never()).insert(any(), any(), anyByte(), any()); + } else { + verify(messagesCache, times(2)) + .insert(argThat(messageGuid -> messageGuid.version() == 8), + eq(destinationUuid), + eq(Device.PRIMARY_ID), + any()); + } } @Test @@ -162,8 +178,12 @@ class MessagesManagerTest { return new UUID(mostSignificantBits, ThreadLocalRandom.current().nextLong()); } - @Test - void insertMultiRecipientMessage() throws InvalidMessageException, InvalidVersionException { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void insertMultiRecipientMessage(final boolean exclusiveFoundationDbWrite) throws InvalidMessageException, InvalidVersionException { + when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.EXCLUSIVE_FOUNDATIONDB_INSERT_EXPERIMENT_NAME))) + .thenReturn(exclusiveFoundationDbWrite); + when(foundationDbMessageStore.insert(any(), any())) .thenAnswer(invocation -> { final Map messagesByDeviceId = invocation.getArgument(1); @@ -241,25 +261,29 @@ class MessagesManagerTest { assertEquals(expectedPresenceByAccountAndDeviceId, messagesManager.insertMultiRecipientMessage(multiRecipientMessage, resolvedRecipients, clientTimestamp, isStory, isEphemeral, isUrgent).join()); - verify(messagesCache).insert(any(), - eq(singleDeviceAccountAciServiceIdentifier.uuid()), - eq(Device.PRIMARY_ID), - eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountAciServiceIdentifier.toCompactByteString()).build())); + if (exclusiveFoundationDbWrite) { + verify(messagesCache, never()).insert(any(), any(), anyByte(), any()); + } else { + verify(messagesCache).insert(any(), + eq(singleDeviceAccountAciServiceIdentifier.uuid()), + eq(Device.PRIMARY_ID), + eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountAciServiceIdentifier.toCompactByteString()).build())); - verify(messagesCache).insert(any(), - eq(singleDeviceAccountAciServiceIdentifier.uuid()), - eq(Device.PRIMARY_ID), - eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountPniServiceIdentifier.toCompactByteString()).build())); + verify(messagesCache).insert(any(), + eq(singleDeviceAccountAciServiceIdentifier.uuid()), + eq(Device.PRIMARY_ID), + eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(singleDeviceAccountPniServiceIdentifier.toCompactByteString()).build())); - verify(messagesCache).insert(any(), - eq(multiDeviceAccountAciServiceIdentifier.uuid()), - eq((byte) (Device.PRIMARY_ID + 1)), - eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toCompactByteString()).build())); + verify(messagesCache).insert(any(), + eq(multiDeviceAccountAciServiceIdentifier.uuid()), + eq((byte) (Device.PRIMARY_ID + 1)), + eq(prototypeExpectedMessage.toBuilder().setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toCompactByteString()).build())); - verify(messagesCache, never()).insert(any(), - eq(unresolvedAccountAciServiceIdentifier.uuid()), - anyByte(), - any()); + verify(messagesCache, never()).insert(any(), + eq(unresolvedAccountAciServiceIdentifier.uuid()), + anyByte(), + any()); + } final Envelope prototypeExpectedFoundationDbMessage = prototypeExpectedMessage.toBuilder().clearSharedMrmKey().build(); @@ -290,14 +314,11 @@ class MessagesManagerTest { verify(foundationDbMessageStore, never()).insert(eq(unresolvedAccountAciServiceIdentifier), any()); } - @ParameterizedTest - @CsvSource({ - "false, false, false", - "false, true, true", - "true, false, true", - "true, true, true" - }) - void mayHaveMessages(final boolean hasCachedMessages, final boolean hasPersistedMessages, final boolean expectMayHaveMessages) { + @CartesianTest + void mayHaveMessages(@CartesianTest.Values(booleans = {true, false}) final boolean hasCachedMessages, + @CartesianTest.Values(booleans = {true, false}) final boolean hasPersistedMessages, + @CartesianTest.Values(booleans = {true, false}) final boolean hasFoundationDbMessages) { + final UUID accountIdentifier = UUID.randomUUID(); final Device device = mock(Device.class); when(device.getId()).thenReturn(Device.PRIMARY_ID); @@ -308,32 +329,42 @@ class MessagesManagerTest { when(messagesDynamoDb.mayHaveMessages(accountIdentifier, device)) .thenReturn(CompletableFuture.completedFuture(hasPersistedMessages)); - if (hasCachedMessages) { - verifyNoInteractions(messagesDynamoDb); - } + when(foundationDbMessageStore.hasMessages(new AciServiceIdentifier(accountIdentifier), Device.PRIMARY_ID)) + .thenReturn(CompletableFuture.completedFuture(hasFoundationDbMessages)); - assertEquals(expectMayHaveMessages, messagesManager.mayHaveMessages(accountIdentifier, device).join()); + assertEquals(hasCachedMessages || hasPersistedMessages || hasFoundationDbMessages, + messagesManager.mayHaveMessages(accountIdentifier, device).join()); } @ParameterizedTest @CsvSource({ - ",,", - "1,,1", - ",1,1", - "2,1,1", - "1,2,2" + ",,,", + "1,,,1", + ",1,,1", + "2,1,,1", + "1,2,,2", + "1,2,3,2", + ",,3,3" }) - public void oldestMessageTimestamp(Long oldestCached, Long oldestPersisted, Long expected) { + public void oldestMessageTimestamp(@Nullable final Long oldestCached, + @Nullable final Long oldestPersisted, + @Nullable final Long oldestInFoundationDb, + @Nullable final Long expected) { final UUID accountIdentifier = UUID.randomUUID(); final Device device = mock(Device.class); when(device.getId()).thenReturn(Device.PRIMARY_ID); when(messagesCache.getEarliestUndeliveredTimestamp(accountIdentifier, Device.PRIMARY_ID)) .thenReturn(oldestCached == null ? Mono.empty() : Mono.just(oldestCached)); + when(messagesDynamoDb.load(accountIdentifier, device, 1)) .thenReturn(oldestPersisted == null ? Mono.empty() : Mono.just(Envelope.newBuilder().setServerTimestamp(oldestPersisted).build())); + + when(foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(new AciServiceIdentifier(accountIdentifier), Device.PRIMARY_ID)) + .thenReturn(CompletableFuture.completedFuture(Optional.ofNullable(oldestInFoundationDb).map(Instant::ofEpochMilli))); + final Optional earliest = messagesManager.getEarliestUndeliveredTimestampForDevice(accountIdentifier, device).join(); assertEquals(Optional.ofNullable(expected).map(Instant::ofEpochMilli), earliest); 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 9f8da9ae6..4f9deeca7 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 @@ -1266,6 +1266,58 @@ class FoundationDbMessageStoreTest { .verify(); } + @Test + void hasMessages() { + final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID()); + final byte deviceId = Device.PRIMARY_ID; + + assertFalse(foundationDbMessageStore.hasMessages(aci, deviceId).join()); + + foundationDbMessageStore.insert(aci, Map.of(deviceId, generateRandomMessage(false))).join(); + + assertTrue(foundationDbMessageStore.hasMessages(aci, deviceId).join()); + } + + @Test + void mayHaveUrgentMessages() { + final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID()); + final byte deviceId = Device.PRIMARY_ID; + + assertFalse(foundationDbMessageStore.mayHaveUrgentMessages(aci, deviceId).join()); + + foundationDbMessageStore.insert(aci, Map.of(deviceId, generateRandomMessage(false).toBuilder() + .setUrgent(false) + .build())) + .join(); + + assertFalse(foundationDbMessageStore.mayHaveUrgentMessages(aci, deviceId).join()); + + foundationDbMessageStore.insert(aci, Map.of(deviceId, generateRandomMessage(false).toBuilder() + .setUrgent(true) + .build())) + .join(); + + assertTrue(foundationDbMessageStore.mayHaveUrgentMessages(aci, deviceId).join()); + } + + @Test + void getEarliestUndeliveredMessageTimestamp() { + final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID()); + final byte deviceId = Device.PRIMARY_ID; + + assertEquals(Optional.empty(), + foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(aci, deviceId).join()); + + final long earliestTimestamp = System.currentTimeMillis(); + final AtomicLong incrementingTimestamp = new AtomicLong(earliestTimestamp); + + generateAndInsertMessages(aci, deviceId, DEFAULT_EPOCH, 3, incrementingTimestamp::getAndIncrement); + generateAndInsertMessages(aci, deviceId, FUTURE_EPOCH, 3, incrementingTimestamp::getAndIncrement); + + assertEquals(Optional.of(Instant.ofEpochMilli(earliestTimestamp)), + foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(aci, deviceId).join()); + } + static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) { return generateRandomMessage(ephemeral, contentSize, CLOCK.millis()); }