FoundationDB message stream implementation

This commit is contained in:
Ameya Lokare authored and Jon Chambers committed 2026-03-31 15:40:57 -04:00
1 parent 4a8313eb67
commit e454b29c6a
5 files changed
+862 -2

No files matched your search

@@ -0,0 +1,325 @@
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;
import com.google.protobuf.InvalidProtocolBufferException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import javax.annotation.Nullable;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
/// catching up to end-of-queue,and an infinite stream for live updates.
class FoundationDbMessagePublisher {
private final Database database;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The end key at which we stop reading messages. For finite publisher, this is just past the end-of-queue key at the
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
/// Keeps track of the key from which to start reading on the next iteration
private volatile KeySelector beginKeyCursor;
enum State {
/// Messages are likely available in the queue. Initial state.
MESSAGES_AVAILABLE,
/// We're actively fetching messages from FoundationDB.
FETCHING_MESSAGES,
/// We have read all available messages in the queue.
QUEUE_EMPTY,
/// The message available watch triggered while other stuff was going on. We record it as a state so that we can
/// fetch new messages at a more opportune time.
MESSAGE_AVAILABLE_SIGNAL_BUFFERED,
/// Waiting for the message available watch to trigger that signals new messages have arrived.
AWAITING_NEW_MESSAGES,
/// Terminal state indicating no more messages will be published. Either we have successfully published all messages
/// in the case of a finite publisher, or the subscriber has indicated that it has terminated.
TERMINATED,
/// Terminal state reached when there is an error fetching or publishing messages.
ERROR
}
enum Event {
/// Downstream subscriber requested more items.
DEMAND_REQUESTED,
/// The FoundationDB range query returned less than the batch size.
FETCHED_ALL_AVAILABLE_MESSAGES,
/// We have successfully fetched and published a message batch
PUBLISHED_MESSAGES,
/// The message available watch triggered indicating new messages have arrived.
MESSAGE_AVAILABLE_WATCH_TRIGGERED,
/// Internal self-trigger used to immediately transition to the next state.
INTERNAL_TRIGGER,
/// An error occurred during fetching from FoundationDB or publishing messages to the sink.
FETCH_OR_PUBLISH_ERROR_OCCURRED
}
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
/// is "infinite" and will continue to wait for new messages and publish them in a loop.
@Nullable private final byte[] messagesAvailableWatchKey;
/// Listener to watch for state machine transitions; used for testing.
private final BiConsumer<State, State> stateChangeListener;
private final Flux<MessageStreamEntry.Envelope> messagePublisher;
/// Whether the publisher is finite or infinite.
private final boolean terminateOnQueueEmpty;
/// Tracks the current state of the publisher state machine. Initial state presumes that messages are available in the queue.
private State state = State.MESSAGES_AVAILABLE;
/// Reference to the sink we publishes messages to.
private volatile FluxSink<MessageStreamEntry.Envelope> emitter;
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
FoundationDbMessagePublisher(
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
@Nullable final byte[] messagesAvailableWatchKey,
@Nullable final BiConsumer<State, State> stateChangeListener) {
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.database = database;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
this.messagePublisher = Flux.create(emitter -> {
this.emitter = emitter;
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
emitter.onDispose(this::onDispose);
});
}
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
/// yields the last message that was present in the queue at the time the publisher was created. This is helpful in
/// 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 KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan) {
return new FoundationDbMessagePublisher(beginKeyInclusive, endKeyExclusive, database, maxMessagesPerScan, null, null);
}
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
/// 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 KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final Database database,
final int maxMessagesPerScan,
final byte[] messagesAvailableWatchKey) {
return new FoundationDbMessagePublisher(beginKeyInclusive, endKeyExclusive, database, maxMessagesPerScan, messagesAvailableWatchKey, null);
}
private synchronized void setState(final State newState, final Event event) {
LOGGER.debug("Transitioned from state {} to state {} on event {}", state, newState, event);
final State oldState = state;
state = newState;
stateChangeListener.accept(oldState, newState);
}
/// Called when an event occurs. Transitions the current state to a new state if this is a defined transition.
///
/// @param event the {@link Event} that has occurred
protected synchronized void transitionStateOnEvent(final Event event) {
assert emitter != null;
boolean knownTransition = true;
switch (state) {
case MESSAGES_AVAILABLE -> {
switch (event) {
case DEMAND_REQUESTED -> {
setState(State.FETCHING_MESSAGES, event);
emitMessages();
}
case INTERNAL_TRIGGER -> {
if (emitter.requestedFromDownstream() > 0) {
setState(State.FETCHING_MESSAGES, event);
emitMessages();
}
}
default -> knownTransition = false;
}
}
case FETCHING_MESSAGES -> {
switch (event) {
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.QUEUE_EMPTY, event);
case PUBLISHED_MESSAGES -> {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
case FETCH_OR_PUBLISH_ERROR_OCCURRED -> setState(State.ERROR, event);
default -> knownTransition = false;
}
}
case QUEUE_EMPTY -> {
if (terminateOnQueueEmpty) {
switch (event) {
case PUBLISHED_MESSAGES -> {
setState(State.TERMINATED, event);
emitter.complete();
}
case FETCHED_ALL_AVAILABLE_MESSAGES -> setState(State.ERROR, event);
default -> knownTransition = false;
}
} else {
switch (event) {
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> setState(State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED, event);
case PUBLISHED_MESSAGES -> setState(State.AWAITING_NEW_MESSAGES, event);
default -> knownTransition = false;
}
}
}
case MESSAGE_AVAILABLE_SIGNAL_BUFFERED -> {
switch (event) {
case PUBLISHED_MESSAGES -> {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
default -> knownTransition = false;
}
}
case AWAITING_NEW_MESSAGES -> {
switch (event) {
case MESSAGE_AVAILABLE_WATCH_TRIGGERED -> {
setState(State.MESSAGES_AVAILABLE, event);
transitionStateOnEvent(Event.INTERNAL_TRIGGER);
}
default -> knownTransition = false;
}
}
default -> knownTransition = false;
}
if (!knownTransition) {
LOGGER.debug("Unhandled event {} on state {}", event, state);
}
}
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
/// subsequent scans
///
/// @return a future of a list of [MessageStreamEntry] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<MessageStreamEntry.Envelope>> getMessagesBatch() {
return database.runAsync(transaction -> getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
.thenApply(lastKeyReadAndItems -> {
// Set our beginning key to just past the last key read so that we're ready for our next fetch
lastKeyReadAndItems.first().ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
final List<MessageStreamEntry.Envelope> items = lastKeyReadAndItems.second();
if (items.size() < maxMessagesPerScan) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
if (!terminateOnQueueEmpty) {
setWatch(transaction);
}
}
return items;
})
);
}
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
///
/// @param transaction the FoundationDB transaction in which to perform the read query
/// @param beginInclusive the range start key (inclusive)
/// @param endExclusive the range end key (exclusive)
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
private static CompletableFuture<Pair<Optional<byte[]>, List<MessageStreamEntry.Envelope>>> getItemsInRange(
final Transaction transaction,
final KeySelector beginInclusive,
final KeySelector endExclusive,
final int maxMessagesPerScan) {
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
.thenApply(keyValues -> {
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
? Optional.empty()
: Optional.of(keyValues.getLast().getKey());
final List<MessageStreamEntry.Envelope> messages = keyValues.stream()
.map(keyValue -> {
try {
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.parseFrom(keyValue.getValue()));
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
})
.toList();
return new Pair<>(lastKeyRead, messages);
});
}
/// Fetch and publish messages. Messages are fetched in batches of [#maxMessagesPerScan] to avoid excessive memory
/// consumption. After each fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading
/// from. If the fetch operation returns fewer items than the batch size, we infer that we have fetched all available
/// messages and [Event#FETCHED_ALL_AVAILABLE_MESSAGES] is sent to the state machine. See [#getMessagesBatch()]
/// for details. Additionally, after we successfully publish the batch of messages, {@link Event#PUBLISHED_MESSAGES}
/// is emitted. If there's an error while fetching or publishing, [Event#FETCH_OR_PUBLISH_ERROR_OCCURRED] is emitted
/// instead.
private void emitMessages() {
getMessagesBatch()
.thenAccept(messageStreamEntries -> {
messageStreamEntries.forEach(emitter::next);
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
})
.exceptionally(t -> {
transitionStateOnEvent(Event.FETCH_OR_PUBLISH_ERROR_OCCURRED);
emitter.error(t);
return null;
});
}
/// Get the stream of messages.
///
/// @return [Flux] of messages
public Flux<MessageStreamEntry.Envelope> getMessages() {
return this.messagePublisher;
}
private synchronized void setWatch(final Transaction transaction) {
assert messagesAvailableWatchKey != null;
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
watchFuture = transaction.watch(messagesAvailableWatchKey);
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
}
private synchronized void onDispose() {
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
// in evaluating the state machine when there's no live subscription.
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
}
cancelWatch();
}
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
private synchronized void cancelWatch() {
if (watchFuture != null) {
watchFuture.cancel(true);
}
}
}
@@ -22,6 +22,8 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.util.Conversions;
/// An implementation of a message store backed by FoundationDB.
@@ -246,6 +248,18 @@ public class FoundationDbMessageStore {
}, executor);
}
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice, final int maxMessagesPerScan) {
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
getMessagesAvailableWatchKey(aci),
getShardForAci(aci),
maxMessagesPerScan);
}
@VisibleForTesting
Database getShardForAci(final AciServiceIdentifier aci) {
return databases[hashAciToShardNumber(aci)];
@@ -0,0 +1,97 @@
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.subspace.Subspace;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/// A [MessageStream] implementation that fetches messages from FoundationDB
public class FoundationDbMessageStream implements MessageStream {
private final Subspace deviceQueueSubspace;
private final byte[] messagesAvailableWatchKey;
private final Database database;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
FoundationDbMessageStream(final Subspace deviceQueueSubspace, final byte[] messagesAvailableWatchKey,
final Database database, final int maxMessagesPerScan) {
this.deviceQueueSubspace = deviceQueueSubspace;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
this.database = database;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
return this.messageStreamPublisher;
}
/// Create a message publisher
///
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
/// @implNote The message publisher is stitched together by concatenating:
/// 1. **A finite message publisher**: On initial request, we record the current end-of-queue key in the device mailbox.
/// Then, we fetch all messages in order until the recorded key and finally complete the stream
/// 2. **A queue-empty signal** is emitted
/// 3. **An infinite message publisher**: We start reading from where the finite publisher left off. When all messages
/// are read, we wait for new messages, publish them, then wait again in a loop forever (until the flux is canceled
/// explicitly or due to an error). This is accomplished by setting a FoundationDB [watch](https://github.com/apple/foundationdb/wiki/An-Overview-how-Watches-Work)
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
/// See [FoundationDbMessageStore] for more details on the message insert process.
private Flux<MessageStreamEntry> createMessagePublisher() {
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
final Flux<MessageStreamEntry.Envelope> finitePublisher = maybeEndOfQueueKeyExclusive
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive, database, maxMessagesPerScan).getMessages())
.orElseGet(Flux::empty);
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
final Flux<MessageStreamEntry.Envelope> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
database, maxMessagesPerScan, messagesAvailableWatchKey).getMessages();
return Flux.concat(
finitePublisher,
Mono.just(new MessageStreamEntry.QueueEmpty()),
infinitePublisher
);
});
}
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows
/// us to query keys up to and including the greatest key, and sets us up to begin reading from the next key in
/// a subsequent scan.
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
return database.runAsync(
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
.thenApply(items -> {
if (items.isEmpty()) {
return Optional.empty();
}
assert items.size() == 1;
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
}));
}
@Override
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
throw new UnsupportedOperationException("Not implemented");
}
}
@@ -0,0 +1,312 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.KeyValue;
import com.apple.foundationdb.Range;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.async.AsyncIterable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import reactor.test.StepVerifier;
/// NOTE: most of the happy-path test cases are already covered in {@link FoundationDbMessageStoreTest}, this test
/// mostly exercises edge-cases and error handling that are hard to test without mocks
class FoundationDbMessagePublisherTest {
private final Range subspaceRange = new Range(new byte[]{(byte) 0}, new byte[]{(byte) 100});
private final byte[] messagesAvailableWatchKey = new byte[]{(byte) 42};
private Database database;
private List<FoundationDbMessagePublisher.State> stateTransitions;
@BeforeEach
void setUp() {
database = mock(Database.class);
stateTransitions = new ArrayList<>();
}
@Test
void finitePublisherMultipleBatches() {
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final KeyValue keyValue1 = mockKeyValue((byte) 5, message1);
final KeyValue keyValue2 = mockKeyValue((byte) 6, message2);
final KeyValue keyValue3 = mockKeyValue((byte) 7, message3);
final AsyncIterable<KeyValue> batch1 = mock(AsyncIterable.class);
when(batch1.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue1, keyValue2)));
final AsyncIterable<KeyValue> batch2 = mock(AsyncIterable.class);
when(batch2.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue3)));
final Transaction transaction = mock(Transaction.class);
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(
StreamingMode.class)))
.thenReturn(batch1)
.thenReturn(batch2);
when(database.runAsync(any(Function.class))).thenAnswer(
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
0);
return f.apply(transaction);
});
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
KeySelector.firstGreaterOrEqual(subspaceRange.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
database,
2, // With 3 messages and batch size set to 2, we'll need to grab 2 batches.
null,
(oldState, newState) -> stateTransitions.add(newState)
);
StepVerifier.create(finitePublisher.getMessages())
.expectNext(new MessageStreamEntry.Envelope(message1))
.expectNext(new MessageStreamEntry.Envelope(message2))
.expectNext(new MessageStreamEntry.Envelope(message3))
.verifyComplete();
assertEquals(List.of(
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 1
FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE,
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 2
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.TERMINATED
),
stateTransitions
);
}
@Test
@SuppressWarnings({"unchecked", "resource"})
void infinitePublisher() {
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final KeyValue keyValue1 = mockKeyValue((byte) 5, message1);
final KeyValue keyValue2 = mockKeyValue((byte) 6, message2);
final KeyValue keyValue3 = mockKeyValue((byte) 7, message3);
// Each message in a separate batch; the latter 2 when the messages available watch triggers
final AsyncIterable<KeyValue> batch1 = mock(AsyncIterable.class);
when(batch1.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue1)));
final AsyncIterable<KeyValue> batch2 = mock(AsyncIterable.class);
when(batch2.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue2)));
final AsyncIterable<KeyValue> batch3 = mock(AsyncIterable.class);
when(batch3.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue3)));
final Transaction transaction = mock(Transaction.class);
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(
StreamingMode.class)))
.thenReturn(batch1)
.thenReturn(batch2)
.thenReturn(batch3);
when(database.runAsync(any(Function.class))).thenAnswer(
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
0);
return f.apply(transaction);
});
final CompletableFuture<Void> watchFuture1 = new CompletableFuture<>();
final CompletableFuture<Void> watchFuture2 = new CompletableFuture<>();
final CompletableFuture<Void> watchFuture3 = new CompletableFuture<>(); // this one will not be completed
when(transaction.watch(messagesAvailableWatchKey))
.thenReturn(watchFuture1)
.thenReturn(watchFuture2)
.thenReturn(watchFuture3);
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
KeySelector.firstGreaterOrEqual(subspaceRange.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
database,
2,
messagesAvailableWatchKey,
(oldState, newState) -> {
stateTransitions.add(newState);
if (newState == FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES) {
// We trigger the watch in "awaiting new messages" state to simulate a "live stream" of changes
final long numAwaitingStates = stateTransitions.stream()
.filter(s -> s == FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES)
.count();
// We simulate the arrival of 2 new messages, so we don't complete the 3rd watch.
if (numAwaitingStates == 1) {
watchFuture1.complete(null);
} else if (numAwaitingStates == 2) {
watchFuture2.complete(null);
}
}
}
);
StepVerifier.create(infinitePublisher.getMessages())
.expectNext(new MessageStreamEntry.Envelope(message1))
.expectNext(new MessageStreamEntry.Envelope(message2))
.expectNext(new MessageStreamEntry.Envelope(message3))
.verifyTimeout(Duration.ofSeconds(1));
assertEquals(List.of(
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 1
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE, // Watch 1 triggered
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 2
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE, // Watch 2 triggered
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 3
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
FoundationDbMessagePublisher.State.TERMINATED
),
stateTransitions
);
assertTrue(watchFuture3.isCancelled());
}
@Test
void messageAvailableWatchSignalBuffered() {
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
final KeyValue keyValue1 = mockKeyValue((byte) 5, message1);
final KeyValue keyValue2 = mockKeyValue((byte) 6, message2);
final AsyncIterable<KeyValue> batch1 = mock(AsyncIterable.class);
when(batch1.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue1)));
final AsyncIterable<KeyValue> batch2 = mock(AsyncIterable.class);
when(batch2.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue2)));
final Transaction transaction = mock(Transaction.class);
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(
StreamingMode.class)))
.thenReturn(batch1)
.thenReturn(batch2);
when(database.runAsync(any(Function.class))).thenAnswer(
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
0);
return f.apply(transaction);
});
final CompletableFuture<Void> watchFuture1 = new CompletableFuture<>();
final CompletableFuture<Void> watchFuture2 = new CompletableFuture<>(); // this one will not be completed
when(transaction.watch(messagesAvailableWatchKey))
.thenReturn(watchFuture1)
.thenReturn(watchFuture2);
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
KeySelector.firstGreaterOrEqual(subspaceRange.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
database,
2,
messagesAvailableWatchKey,
(oldState, newState) -> {
stateTransitions.add(newState);
// Simulate an edge case where the messages available watch could trigger right after queue empty, but before
// all messages have been published. This exploits the fact that the state transitions and the listener calls
// are synchronized, and for an already completed future, the callback runs in the calling thread, which
// ensures that the watch is triggered before the messages are published.
if (newState == FoundationDbMessagePublisher.State.QUEUE_EMPTY &&
stateTransitions.stream()
.filter(s -> s == FoundationDbMessagePublisher.State.QUEUE_EMPTY)
.count() == 1) {
watchFuture1.complete(null);
}
}
);
StepVerifier.create(infinitePublisher.getMessages())
.expectNext(new MessageStreamEntry.Envelope(message1))
.expectNext(new MessageStreamEntry.Envelope(message2))
.verifyTimeout(Duration.ofSeconds(1));
assertEquals(List.of(
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 1
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.MESSAGE_AVAILABLE_SIGNAL_BUFFERED,
// Watch triggered but messages aren't published yet
FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE,
FoundationDbMessagePublisher.State.FETCHING_MESSAGES, // Batch 2
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
FoundationDbMessagePublisher.State.TERMINATED
),
stateTransitions
);
assertTrue(watchFuture2.isCancelled());
}
@Test
@SuppressWarnings({"unchecked", "resource"})
void watchCanceledOnSubscriptionCancel() {
final FoundationDbMessagePublisher infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
KeySelector.firstGreaterOrEqual(subspaceRange.begin),
KeySelector.firstGreaterThan(subspaceRange.end),
database,
100,
messagesAvailableWatchKey);
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
final Transaction transaction = mock(Transaction.class);
final KeyValue keyValue = mock(KeyValue.class);
when(keyValue.getKey()).thenReturn(new byte[]{(byte) 5});
when(keyValue.getValue()).thenReturn(message.toByteArray());
final AsyncIterable<KeyValue> asyncIterable = mock(AsyncIterable.class);
when(asyncIterable.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue)));
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(
StreamingMode.class)))
.thenReturn(asyncIterable);
final CompletableFuture<Void> watchFuture = mock(CompletableFuture.class);
when(transaction.watch(messagesAvailableWatchKey)).thenReturn(watchFuture);
when(database.runAsync(any(Function.class))).thenAnswer(
(Answer<CompletableFuture<List<? extends MessageStreamEntry>>>) invocationOnMock -> {
final Function<Transaction, CompletableFuture<List<? extends MessageStreamEntry>>> f = invocationOnMock.getArgument(
0);
return f.apply(transaction);
});
StepVerifier.create(infinitePublisher.getMessages())
.expectNext(new MessageStreamEntry.Envelope(message))
.thenCancel()
.verify(Duration.ofMillis(100));
verify(watchFuture).cancel(true);
}
private KeyValue mockKeyValue(final byte key, final MessageProtos.Envelope message) {
final KeyValue keyValue = mock(KeyValue.class);
when(keyValue.getKey()).thenReturn(new byte[]{key});
when(keyValue.getValue()).thenReturn(message.toByteArray());
return keyValue;
}
}
@@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import com.apple.foundationdb.KeyValue;
import com.apple.foundationdb.async.AsyncUtil;
@@ -14,6 +15,7 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Collections;
@@ -25,7 +27,9 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -43,8 +47,12 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.test.StepVerifier;
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class FoundationDbMessageStoreTest {
@@ -358,11 +366,115 @@ class FoundationDbMessageStoreTest {
Map.of(generateRandomAciForShard(0), Collections.emptyMap())));
}
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
@ParameterizedTest
@MethodSource
void getMessages(final int numMessages, final int batchSize) {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
for (int i = 0; i < numMessages; i++) {
final MessageProtos.Envelope message = generateRandomMessage(false);
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message)).join());
}
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.expectNextCount(numMessages)
.expectNext(new MessageStreamEntry.QueueEmpty())
.verifyTimeout(Duration.ofSeconds(1));
}
static Stream<Arguments> getMessages() {
final int batchSize = 16;
return Stream.of(
Arguments.argumentSet("Single message", 1, batchSize),
Arguments.argumentSet("Queue is empty", 0, batchSize),
Arguments.argumentSet("Multiple of batch size", batchSize * 4, batchSize),
Arguments.argumentSet("Non-multiple of batch size", (batchSize * 4) + 1, batchSize)
);
}
@Test
void getMessagesPublishMoreAfterQueueEmpty() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
final MessageProtos.Envelope message1 = generateRandomMessage(false);
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message1)).join());
final MessageProtos.Envelope message2 = generateRandomMessage(false);
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message2)).join());
final CountDownLatch latch = new CountDownLatch(1);
final MessageProtos.Envelope message3 = generateRandomMessage(false);
Thread.ofVirtual().start(() -> {
try {
// Wait until queue is empty
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
// Then publish more messages
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message3)).join());
} catch (final InterruptedException e) {
fail(e);
}
});
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
.expectNext(new MessageStreamEntry.Envelope(message1))
.expectNext(new MessageStreamEntry.Envelope(message2))
.expectNext(new MessageStreamEntry.QueueEmpty())
.then(latch::countDown)
.expectNext(new MessageStreamEntry.Envelope(message3))
.verifyTimeout(Duration.ofSeconds(3));
}
@Test
void getMessagesPublishMoreAfterSubscriptionStarts() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
for (int i = 0; i < 16; i++) {
final MessageProtos.Envelope message = generateRandomMessage(false);
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message)).join());
}
final CountDownLatch latch = new CountDownLatch(1);
Thread.ofVirtual().start(() -> {
try {
// Wait until queue is empty
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
// Then publish more messages
for (int i = 0; i < 16; i++) {
final MessageProtos.Envelope message = generateRandomMessage(false);
assertNotNull(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message)).join());
}
} catch (final InterruptedException e) {
fail(e);
}
});
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
// Initially only request a single message, then give the go ahead to the publisher. This verifies that we get the
// queue empty signal when we consume the initial batch of messages even though the publisher keeps publishing in
// the meantime.
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 1)
.expectNextCount(1)
.then(latch::countDown)
.thenRequest(100)
.expectNextCount(15)
.expectNext(new MessageStreamEntry.QueueEmpty())
.expectNextCount(16)
.verifyTimeout(Duration.ofSeconds(3));
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
return generateRandomMessage(ephemeral, 16);
}
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
return MessageProtos.Envelope.newBuilder()
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(contentSize)))
.setEphemeral(ephemeral)