mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:16:50 +00:00
Establish presence when fetching messages from FoundationDB
This commit is contained in:
1 parent
fa4d3c7ca9
commit
8790514b8a
7 files changed
+535
-121
No files matched your search
@@ -621,6 +621,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.threads(16).build();
|
||||
final ScheduledExecutorService registrationIdentityTokenRefreshExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "registrationIdentityTokenRefresh").threads(1).build();
|
||||
final ScheduledExecutorService presenceRenewalExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(4).build();
|
||||
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
ExecutorServiceBuilder.of(environment, "messageDelivery")
|
||||
@@ -751,6 +753,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
|
||||
presenceRenewalExecutor,
|
||||
Clock.systemUTC());
|
||||
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
|
||||
recurringJobExecutor,
|
||||
|
||||
+177
-53
@@ -5,7 +5,23 @@ import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -13,28 +29,60 @@ 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;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/// 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;
|
||||
private final Clock clock;
|
||||
/// Keeps track of the key from which to start reading on the next iteration
|
||||
private volatile KeySelector beginKeyCursor;
|
||||
/// 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;
|
||||
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
|
||||
private final int maxMessagesPerScan;
|
||||
|
||||
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
|
||||
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
|
||||
@Nullable private final byte[] presenceKey;
|
||||
|
||||
// An ID for this specific stream for use when checking "ownership" of a presence value.
|
||||
private final int streamId = NEXT_STREAM_ID.getAndIncrement();
|
||||
|
||||
/// 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;
|
||||
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// 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;
|
||||
|
||||
private final Flux<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
|
||||
/// Reference to the sink we publish messages to.
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> emitter;
|
||||
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
/// A future for refreshing the connected client's presence value at regular intervals.
|
||||
@Nullable private ScheduledFuture<?> renewPresenceFuture;
|
||||
|
||||
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
enum State {
|
||||
/// Messages are likely available in the queue. Initial state.
|
||||
@@ -70,49 +118,52 @@ class FoundationDbMessagePublisher {
|
||||
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<FoundationDbMessageStreamEntry.Message> messagePublisher;
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// 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 publish messages to.
|
||||
private volatile FluxSink<FoundationDbMessageStreamEntry.Message> 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 Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.database = database;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
this.messagePublisher = Flux.create(emitter -> {
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
Objects.requireNonNull(presenceKey);
|
||||
Objects.requireNonNull(presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
emitter.onDispose(this::onDispose);
|
||||
}).doOnSubscribe(_ -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence immediately and block until we do. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
database.run(transaction -> {
|
||||
setPresence(transaction);
|
||||
return null;
|
||||
});
|
||||
|
||||
// Refresh presence at regular intervals
|
||||
startPresenceRenewal(presenceRenewalExecutorService);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,18 +172,22 @@ class FoundationDbMessagePublisher {
|
||||
/// cases when callers need to "catch up" on stored messages without following fresh updates (for example, when a
|
||||
/// client first connects and needs to load stored messages before receiving a "live" stream of new messages).
|
||||
public static FoundationDbMessagePublisher createFinitePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
beforePageFetch);
|
||||
}
|
||||
|
||||
@@ -140,17 +195,23 @@ class FoundationDbMessagePublisher {
|
||||
/// It waits for new messages and publishes them in a loop. Useful when a client has finished receiving its stored
|
||||
/// messages and is now waiting for a live stream of new messages.
|
||||
public static FoundationDbMessagePublisher createInfinitePublisher(
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final Database database,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
|
||||
return new FoundationDbMessagePublisher(beginKeyInclusive,
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
null,
|
||||
beforePageFetch);
|
||||
@@ -345,15 +406,6 @@ class FoundationDbMessagePublisher {
|
||||
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() {
|
||||
@@ -362,4 +414,76 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
|
||||
final long renewalIntervalMillis =
|
||||
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
|
||||
|
||||
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
|
||||
renewalIntervalMillis,
|
||||
renewalIntervalMillis,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private synchronized void renewPresence() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
return;
|
||||
}
|
||||
|
||||
database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
|
||||
terminateWithError(throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setPresence(final Transaction transaction) {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void clearPresence() {
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(true);
|
||||
}
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
|
||||
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
|
||||
|
||||
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}))
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void terminateWithError(final Throwable throwable) {
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.ERROR, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
|
||||
emitter.error(throwable);
|
||||
}
|
||||
|
||||
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();
|
||||
clearPresence();
|
||||
}
|
||||
}
|
||||
+64
-12
@@ -13,10 +13,12 @@ import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
@@ -24,14 +26,16 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
@@ -52,10 +56,16 @@ public class FoundationDbMessageStore {
|
||||
private final int[] liveEpochs;
|
||||
private final int activeEpoch;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
|
||||
private static final int PRESENCE_VALUE_LENGTH = 28;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
|
||||
/// 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
|
||||
@@ -88,6 +98,7 @@ public class FoundationDbMessageStore {
|
||||
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpochMap,
|
||||
final int activeEpoch,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
|
||||
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
|
||||
@@ -99,6 +110,7 @@ public class FoundationDbMessageStore {
|
||||
this.liveEpochs = IntStream.range(0, MAX_EPOCHS).filter(e -> databasesByEpochArray[e] != null).toArray();
|
||||
this.activeEpoch = activeEpoch;
|
||||
this.versionstampUUIDCipher = versionstampUUIDCipher;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.versionstampClocks = databasesByEpochMap.values().stream()
|
||||
.flatMap(List::stream)
|
||||
.distinct()
|
||||
@@ -373,12 +385,15 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
|
||||
getPresenceKey(aci, deviceId),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
databasesForQueueByEpoch,
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup);
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
clock);
|
||||
}
|
||||
|
||||
/// Record the versionstamp for the current time in each database's versionstamp clock.
|
||||
@@ -501,19 +516,56 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
static byte[] getServerId() {
|
||||
return SERVER_ID;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(final byte[] presenceValueBytes) {
|
||||
if (presenceValueBytes == null) {
|
||||
static byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("p");
|
||||
}
|
||||
|
||||
static byte[] getPresenceValue(final Instant timestamp, final int streamId) {
|
||||
return ByteBuffer.allocate(PRESENCE_VALUE_LENGTH)
|
||||
.put(SERVER_ID)
|
||||
.putInt(streamId)
|
||||
.putLong(timestamp.toEpochMilli())
|
||||
.array();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getPresenceServerId(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return Arrays.copyOfRange(presenceValue, 0, 16);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int getPresenceStreamId(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return ByteBuffer.wrap(presenceValue).getInt(16);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Instant getPresenceTimestamp(final byte[] presenceValue) {
|
||||
if (presenceValue.length != PRESENCE_VALUE_LENGTH) {
|
||||
throw new IllegalArgumentException("Unexpected presence value length: " + presenceValue.length);
|
||||
}
|
||||
|
||||
return Instant.ofEpochMilli(ByteBuffer.wrap(presenceValue).getLong(20));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(@Nullable final byte[] presenceValue) {
|
||||
if (presenceValue == null) {
|
||||
return false;
|
||||
}
|
||||
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
|
||||
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
|
||||
// containing the timestamp (seconds since epoch) that the client updates periodically.
|
||||
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= PRESENCE_STALE_THRESHOLD.toSeconds();
|
||||
|
||||
return Duration.between(getPresenceTimestamp(presenceValue), clock.instant()).compareTo(PRESENCE_STALE_THRESHOLD) <= 0;
|
||||
}
|
||||
}
|
||||
+18
-3
@@ -13,6 +13,7 @@ import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.IdentityHashMap;
|
||||
@@ -23,6 +24,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
@@ -41,6 +43,7 @@ import reactor.util.function.Tuples;
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database[] databasesByEpoch;
|
||||
private final MessageGuidCodec messageGuidCodec;
|
||||
@@ -48,6 +51,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final int maxMessagesPerScan;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
private final Runnable doAfterCleanup;
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
|
||||
|
||||
@@ -70,19 +75,25 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] presenceKey,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Database[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.databasesByEpoch = databasesByEpoch;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.clock = clock;
|
||||
|
||||
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
|
||||
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
|
||||
@@ -161,9 +172,10 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
() -> this.clearAcknowledgedMessages(database))
|
||||
.getMessages())
|
||||
@@ -190,10 +202,13 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
|
||||
return FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
database,
|
||||
clock,
|
||||
infinitePublisherBeginKey,
|
||||
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
() -> clearAcknowledgedMessages(database)).getMessages();
|
||||
})
|
||||
|
||||
+3
@@ -221,6 +221,8 @@ public record CommandDependencies(
|
||||
.threads(1).build();
|
||||
final ScheduledExecutorService retryExecutor = ScheduledExecutorServiceBuilder.of(environment, "retry")
|
||||
.threads(1).build();
|
||||
final ScheduledExecutorService presenceRenewalExecutor =
|
||||
ScheduledExecutorServiceBuilder.of(environment, "presenceRenewal").threads(1).build();
|
||||
|
||||
ExternalServiceCredentialsGenerator storageCredentialsGenerator = SecureStorageController.credentialsGenerator(
|
||||
configuration.getSecureStorageServiceConfiguration());
|
||||
@@ -316,6 +318,7 @@ public record CommandDependencies(
|
||||
configuration.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
|
||||
presenceRenewalExecutor,
|
||||
Clock.systemUTC());
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
configuration.getCdnConfiguration().bucket());
|
||||
|
||||
+102
-10
@@ -16,20 +16,27 @@ import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.async.AsyncIterable;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.stubbing.Answer;
|
||||
@@ -46,6 +53,8 @@ class FoundationDbMessagePublisherTest {
|
||||
private Database database;
|
||||
private List<FoundationDbMessagePublisher.State> stateTransitions;
|
||||
|
||||
private static ScheduledExecutorService presenceRenewalExecutorService;
|
||||
|
||||
private static final AciServiceIdentifier SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
private static final Range SUBSPACE_RANGE =
|
||||
@@ -56,6 +65,15 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
private static final Supplier<Consumer<Transaction>> NOOP_ON_PAGE_FETCH = () -> _ -> {};
|
||||
|
||||
private static final Clock CLOCK = Clock.systemUTC();
|
||||
|
||||
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
database = mock(Database.class);
|
||||
@@ -65,8 +83,15 @@ class FoundationDbMessagePublisherTest {
|
||||
new SecureRandom().nextBytes(messageGuidCodecKey);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void finitePublisherMultipleBatches() throws InvalidProtocolBufferException {
|
||||
void finitePublisherMultipleBatches() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message3 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
@@ -95,11 +120,14 @@ class FoundationDbMessagePublisherTest {
|
||||
});
|
||||
|
||||
final FoundationDbMessagePublisher finitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
database,
|
||||
2, // With 3 messages and batch size set to 2, we'll need to grab 2 batches.
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
@@ -166,10 +194,13 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(watchFuture3);
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
database,
|
||||
2,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(oldState, newState) -> {
|
||||
stateTransitions.add(newState);
|
||||
@@ -215,7 +246,7 @@ class FoundationDbMessagePublisherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageAvailableWatchSignalBuffered() throws InvalidProtocolBufferException {
|
||||
void messageAvailableWatchSignalBuffered() {
|
||||
final MessageProtos.Envelope message1 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final MessageProtos.Envelope message2 = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
|
||||
@@ -248,10 +279,13 @@ class FoundationDbMessagePublisherTest {
|
||||
.thenReturn(watchFuture2);
|
||||
|
||||
final FoundationDbMessagePublisher infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
database,
|
||||
2,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(oldState, newState) -> {
|
||||
stateTransitions.add(newState);
|
||||
@@ -292,12 +326,15 @@ class FoundationDbMessagePublisherTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "resource"})
|
||||
void watchCanceledOnSubscriptionCancel() throws InvalidProtocolBufferException {
|
||||
void watchCanceledOnSubscriptionCancel() {
|
||||
final FoundationDbMessagePublisher infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
|
||||
database,
|
||||
100,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
() -> _ -> {});
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
@@ -325,6 +362,61 @@ class FoundationDbMessagePublisherTest {
|
||||
verify(watchFuture).cancel(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "resource"})
|
||||
void terminateWithError() {
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
|
||||
final KeyValue keyValue = mockKeyValue((byte) 5, message);
|
||||
|
||||
final AsyncIterable<KeyValue> keyValues = mock(AsyncIterable.class);
|
||||
when(keyValues.asList()).thenReturn(CompletableFuture.completedFuture(List.of(keyValue)));
|
||||
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
when(transaction.getRange(any(KeySelector.class), any(KeySelector.class), anyInt(), anyBoolean(), any(StreamingMode.class)))
|
||||
.thenReturn(keyValues);
|
||||
when(transaction.get(FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID)))
|
||||
.thenAnswer(_ -> CompletableFuture.completedFuture(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
when(transaction.watch(any()))
|
||||
.thenReturn(new CompletableFuture<>());
|
||||
|
||||
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 infinitePublisher = new FoundationDbMessagePublisher(
|
||||
database,
|
||||
CLOCK,
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
2,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
);
|
||||
|
||||
final RuntimeException streamTerminationException = new RuntimeException("Stream terminated");
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
.expectNext(getExpectedMessageStreamEntry(keyValue))
|
||||
.then(() -> infinitePublisher.terminateWithError(streamTerminationException))
|
||||
.verifyErrorMatches(throwable -> throwable.equals(streamTerminationException));
|
||||
|
||||
assertEquals(List.of(
|
||||
FoundationDbMessagePublisher.State.FETCHING_MESSAGES,
|
||||
FoundationDbMessagePublisher.State.QUEUE_EMPTY,
|
||||
FoundationDbMessagePublisher.State.AWAITING_NEW_MESSAGES,
|
||||
FoundationDbMessagePublisher.State.ERROR
|
||||
),
|
||||
stateTransitions
|
||||
);
|
||||
}
|
||||
|
||||
private FoundationDbMessageStreamEntry.Message getExpectedMessageStreamEntry(final KeyValue keyValue) {
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(FoundationDbMessageStore.getVersionstamp(keyValue.getKey()),
|
||||
|
||||
+168
-43
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -18,9 +19,11 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -34,6 +37,9 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
@@ -43,6 +49,8 @@ import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -50,6 +58,7 @@ import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
@@ -60,7 +69,6 @@ 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.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
@@ -77,11 +85,20 @@ class FoundationDbMessageStoreTest {
|
||||
private VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
private static ScheduledExecutorService presenceRenewalExecutorService;
|
||||
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.ofEpochSecond(500));
|
||||
|
||||
private static final int DEFAULT_EPOCH = 0;
|
||||
private static final int FUTURE_EPOCH = 2;
|
||||
|
||||
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
@@ -101,9 +118,17 @@ class FoundationDbMessageStoreTest {
|
||||
),
|
||||
DEFAULT_EPOCH,
|
||||
versionstampUUIDCipher,
|
||||
presenceRenewalExecutorService,
|
||||
CLOCK);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insert(final long presenceUpdatedBeforeSeconds,
|
||||
@@ -117,7 +142,7 @@ class FoundationDbMessageStoreTest {
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, 1, presenceUpdatedBeforeSeconds));
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, presenceUpdatedBeforeSeconds));
|
||||
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
@@ -221,13 +246,12 @@ class FoundationDbMessageStoreTest {
|
||||
@Test
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 10L);
|
||||
foundationDbMessageStore.insert(Map.of(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false)))).join();
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> secondMessageInsertResult = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
|
||||
final Optional<Versionstamp> messagesAvailableWatchVersionstamp = getMessagesAvailableWatch(aci);
|
||||
assertTrue(messagesAvailableWatchVersionstamp.isPresent());
|
||||
assertEquals(
|
||||
secondMessageInsertResult.get(Device.PRIMARY_ID).versionstamp(),
|
||||
messagesAvailableWatchVersionstamp);
|
||||
@@ -241,7 +265,7 @@ class FoundationDbMessageStoreTest {
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
// Only 1 device has a recent presence, the others do not have presence keys present.
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 10L);
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> result = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
@@ -271,7 +295,24 @@ class FoundationDbMessageStoreTest {
|
||||
"Non-ephemeral messages must always be stored");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPresenceServerId() {
|
||||
assertArrayEquals(FoundationDbMessageStore.getServerId(),
|
||||
FoundationDbMessageStore.getPresenceServerId(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPresenceStreamId() {
|
||||
assertEquals(STREAM_ID,
|
||||
FoundationDbMessageStore.getPresenceStreamId(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPresenceTimestamp() {
|
||||
assertEquals(CLOCK.instant().truncatedTo(ChronoUnit.MILLIS),
|
||||
FoundationDbMessageStore.getPresenceTimestamp(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -285,14 +326,14 @@ class FoundationDbMessageStoreTest {
|
||||
Arguments.argumentSet("Presence value doesn't exist",
|
||||
null, false),
|
||||
Arguments.argumentSet("Presence updated recently",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(5))), true),
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minusSeconds(5), STREAM_ID), true),
|
||||
Arguments.argumentSet("Presence updated same second as current time",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(0))), true),
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID), true),
|
||||
Arguments.argumentSet(
|
||||
"Presence updated exactly at the second before which it would have been considered offline",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(300))), true),
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minus(FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD), STREAM_ID), true),
|
||||
Arguments.argumentSet("Presence expired",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(400))), false)
|
||||
FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minus(FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.plusSeconds(1)), STREAM_ID), false)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -336,7 +377,7 @@ class FoundationDbMessageStoreTest {
|
||||
final List<AciServiceIdentifier> acis = acisByConfig.get(i);
|
||||
final MultiRecipientTestConfig testConfig = testConfigs.get(i);
|
||||
if (testConfig.devicePresent()) {
|
||||
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L));
|
||||
acis.forEach(aci -> writePresenceKey(aci, Device.PRIMARY_ID, 10L));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,7 +555,6 @@ class FoundationDbMessageStoreTest {
|
||||
@MethodSource
|
||||
void getMessages(final int numMessages, final int batchSize) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
final List<Versionstamp> expectedVersionstamps = IntStream.range(0, numMessages)
|
||||
.mapToObj(_ -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join()
|
||||
@@ -591,9 +631,6 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
});
|
||||
|
||||
writePresenceKey(aci, deviceId, 1, 5L, DEFAULT_EPOCH);
|
||||
writePresenceKey(aci, deviceId, 1, 5L, FUTURE_EPOCH);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(existingDefaultEpochMessages.size() + existingFutureEpochMessages.size())
|
||||
@@ -622,7 +659,6 @@ class FoundationDbMessageStoreTest {
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
final MessageProtos.Envelope message1 = generateRandomMessage(false);
|
||||
final Versionstamp versionstamp1 = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message1)).join()
|
||||
.get(Device.PRIMARY_ID)
|
||||
@@ -678,7 +714,7 @@ class FoundationDbMessageStoreTest {
|
||||
@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());
|
||||
@@ -687,7 +723,7 @@ class FoundationDbMessageStoreTest {
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
// Wait until queue is empty
|
||||
// Wait for a first message to get consumed
|
||||
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
|
||||
// Then publish more messages
|
||||
for (int i = 0; i < 16; i++) {
|
||||
@@ -713,6 +749,116 @@ class FoundationDbMessageStoreTest {
|
||||
.verifyTimeout(Duration.ofSeconds(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMessagesPresence() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
for (int i = 0; i < 16; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
|
||||
assertFalse(isPresent(aci, Device.PRIMARY_ID));
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 16)
|
||||
.expectNextCount(16)
|
||||
.then(() -> assertFalse(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should not be present until infinite stream begins"))
|
||||
.thenRequest(1)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(() -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join())
|
||||
.thenRequest(1)
|
||||
.expectNextCount(1)
|
||||
.then(() -> assertTrue(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should be present after infinite stream begins"))
|
||||
.verifyTimeout(Duration.ofSeconds(3));
|
||||
|
||||
final Instant deadline = Instant.now().plus(Duration.ofSeconds(1));
|
||||
boolean presenceCleared = false;
|
||||
|
||||
while (!presenceCleared && Instant.now().isBefore(deadline)) {
|
||||
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
|
||||
.thenApply(Objects::isNull)
|
||||
.join();
|
||||
}
|
||||
|
||||
assertTrue(presenceCleared,
|
||||
"Presence should be cleared after subscription disposal");
|
||||
}
|
||||
|
||||
private enum PresenceConflictType {
|
||||
SERVER_ID,
|
||||
STREAM_ID
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
void getMessagesPresenceConflictAtDisposal(final PresenceConflictType presenceConflictType) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
for (int i = 0; i < 16; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
|
||||
assertFalse(isPresent(aci, Device.PRIMARY_ID));
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), 16)
|
||||
.expectNextCount(16)
|
||||
.then(() -> assertFalse(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should not be present until infinite stream begins"))
|
||||
.thenRequest(1)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(() -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join())
|
||||
.thenRequest(1)
|
||||
.expectNextCount(1)
|
||||
.then(() -> assertTrue(isPresent(aci, Device.PRIMARY_ID),
|
||||
"Client should be present after infinite stream begins"))
|
||||
.then(() -> {
|
||||
// Overwrite some part of the presence value to simulate a conflict with another server or stream
|
||||
final byte [] presenceValue = switch (presenceConflictType) {
|
||||
case SERVER_ID -> ByteBuffer.wrap(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID))
|
||||
.putLong(0, ThreadLocalRandom.current().nextLong())
|
||||
.putLong(8, ThreadLocalRandom.current().nextLong())
|
||||
.array();
|
||||
|
||||
case STREAM_ID -> ByteBuffer.wrap(FoundationDbMessageStore.getPresenceValue(CLOCK.instant(), STREAM_ID))
|
||||
.putInt(16, STREAM_ID + 1)
|
||||
.array();
|
||||
};
|
||||
|
||||
foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction -> {
|
||||
transaction.set(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID), presenceValue);
|
||||
return null;
|
||||
});
|
||||
})
|
||||
.thenCancel()
|
||||
.verify();
|
||||
|
||||
final Instant deadline = Instant.now().plus(Duration.ofSeconds(1));
|
||||
boolean presenceCleared = false;
|
||||
|
||||
while (!presenceCleared && Instant.now().isBefore(deadline)) {
|
||||
presenceCleared = foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).runAsync(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, Device.PRIMARY_ID)))
|
||||
.thenApply(Objects::isNull)
|
||||
.join();
|
||||
}
|
||||
|
||||
assertFalse(presenceCleared,
|
||||
"Presence should not be cleared if presence was established on another instance");
|
||||
}
|
||||
|
||||
private boolean isPresent(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction ->
|
||||
transaction.get(FoundationDbMessageStore.getPresenceKey(aci, deviceId))
|
||||
.thenApply(foundationDbMessageStore::isClientPresent))
|
||||
.join();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void acknowledgeMessages(final int numMessages, final Set<Integer> unacknowledgedMessages)
|
||||
@@ -720,7 +866,6 @@ class FoundationDbMessageStoreTest {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
final List<Versionstamp> versionstamps = IntStream.range(0, numMessages)
|
||||
.mapToObj(
|
||||
@@ -851,7 +996,6 @@ class FoundationDbMessageStoreTest {
|
||||
final int maxUnacknowledgedMessages = 3;
|
||||
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
|
||||
for (int i = 0; i < numMessages; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
@@ -873,7 +1017,7 @@ class FoundationDbMessageStoreTest {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), Device.PRIMARY_ID, versionstampUUIDCipher);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 5L);
|
||||
|
||||
// Insert an ephemeral message that will be read by the finite publisher and immediately acknowledged and discarded
|
||||
final Versionstamp acknowledgedVersionstamp = foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(true)))
|
||||
@@ -1068,35 +1212,16 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int serverId,
|
||||
final long secondsBeforeCurrentTime) {
|
||||
|
||||
writePresenceKey(aci, deviceId, serverId, secondsBeforeCurrentTime, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int serverId,
|
||||
final long secondsBeforeCurrentTime,
|
||||
final int epoch) {
|
||||
|
||||
foundationDbMessageStore.getShardForAci(aci, epoch).run(transaction -> {
|
||||
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
|
||||
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
|
||||
transaction.set(presenceKey, Conversions.longToByteArray(presenceValue));
|
||||
foundationDbMessageStore.getShardForAci(aci, DEFAULT_EPOCH).run(transaction -> {
|
||||
final byte[] presenceKey = FoundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final byte[] presenceValue = FoundationDbMessageStore.getPresenceValue(CLOCK.instant().minusSeconds(secondsBeforeCurrentTime), STREAM_ID);
|
||||
transaction.set(presenceKey, presenceValue);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static long getEpochSecondsBeforeClock(final long secondsBefore) {
|
||||
return CLOCK.instant().minusSeconds(secondsBefore).getEpochSecond();
|
||||
}
|
||||
|
||||
private static long constructPresenceValue(final int serverId, final long presenceUpdateEpochSeconds) {
|
||||
return (long) (serverId & 0x0ffff) << 48 | (presenceUpdateEpochSeconds & 0x0000ffffffffffffL);
|
||||
}
|
||||
|
||||
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber) {
|
||||
return generateRandomAciForShard(shardNumber, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user