mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:16:50 +00:00
Always read "live" messages from FoundationDB
This commit is contained in:
1 parent
4dd84f4fc8
commit
746304935d
11 files changed
+283
-694
No files matched your search
@@ -1296,7 +1296,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager, experimentEnrollmentManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController());
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
@@ -1358,7 +1358,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, asnInfoProviderSupplier, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager, experimentEnrollmentManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController());
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
|
||||
+1
-55
@@ -5,72 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
|
||||
@Path("/v1/keepalive")
|
||||
@Tag(name = "Keep Alive")
|
||||
public class KeepAliveController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedDevice> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!(experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), MessagesManager.READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME) ||
|
||||
redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId()))) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
logger.debug("***** No local subscription found for {}::{}; age = {}ms, User-Agent = {}",
|
||||
auth.accountIdentifier(), auth.deviceId(), age.toMillis(),
|
||||
context.getClient().getUserAgent());
|
||||
|
||||
context.getClient().close(1000, "OK");
|
||||
|
||||
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(age);
|
||||
}
|
||||
});
|
||||
|
||||
public Response getKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
|
||||
+56
-97
@@ -7,13 +7,11 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -65,17 +63,6 @@ public class MessagesManager {
|
||||
|
||||
private static final String INSERT_FDB_EXCEPTIONS_COUNTER_NAME = name(MessagesManager.class, "insertExceptions");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
public static final String READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME = "foundationDbReadLiveMessages";
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
@@ -122,45 +109,48 @@ public class MessagesManager {
|
||||
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
|
||||
|
||||
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture;
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
|
||||
// latter for FoundationDB
|
||||
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier, MIRROR_INSERTS_EXPERIMENT_NAME)) {
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
|
||||
// latter for FoundationDB
|
||||
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
|
||||
|
||||
foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.exceptionally(e -> {
|
||||
if (ExceptionUtils.unwrap(e) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
|
||||
.increment();
|
||||
} else {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.exceptionally(e -> {
|
||||
if (ExceptionUtils.unwrap(e) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
|
||||
.increment();
|
||||
} else {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(e);
|
||||
});
|
||||
} else {
|
||||
foundationDbInsertFuture = CompletableFuture.completedFuture(Collections.emptyMap());
|
||||
}
|
||||
throw ExceptionUtils.wrap(e);
|
||||
});
|
||||
|
||||
return foundationDbInsertFuture.thenCompose(foundationDbInsertResults -> {
|
||||
final boolean useFoundationDbPresence =
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME);
|
||||
foundationDbInsertResults.forEach((deviceId, insertResult) ->
|
||||
devicePresenceById.put(deviceId, insertResult.present()));
|
||||
|
||||
if (useFoundationDbPresence) {
|
||||
foundationDbInsertResults.forEach((deviceId, insertResult) ->
|
||||
devicePresenceById.put(deviceId, insertResult.present()));
|
||||
}
|
||||
messagesByDeviceId.forEach((deviceId, message) -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid()) && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
foundationDbInsertResults.get(deviceId).messageGuid().ifPresent(messageGuid -> {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
|
||||
.map(deviceIdAndMessage -> {
|
||||
@@ -178,20 +168,6 @@ public class MessagesManager {
|
||||
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid()) && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
}
|
||||
|
||||
if (!useFoundationDbPresence) {
|
||||
devicePresenceById.put(deviceId, present);
|
||||
}
|
||||
|
||||
if (foundationDbInsertResults.containsKey(deviceId)) {
|
||||
Metrics.counter(PRESENCE_MATCH_COUNTER_NAME,
|
||||
"match", String.valueOf(present == foundationDbInsertResults.get(deviceId).present()))
|
||||
@@ -305,24 +281,11 @@ public class MessagesManager {
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME)) {
|
||||
return new ConcatenatingMessageStream(
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice, true),
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
);
|
||||
}
|
||||
|
||||
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
|
||||
return new ConcatenatingMessageStream(
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice, false);
|
||||
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
destinationUuid, destinationDevice, true),
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
);
|
||||
}
|
||||
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@@ -334,33 +297,29 @@ public class MessagesManager {
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}", destinationUuid, e);
|
||||
}
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}", destinationUuid, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return messagesCache.clear(destinationUuid);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final byte deviceId) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e);
|
||||
}
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return messagesCache.clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
-348
@@ -1,348 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.SignalType;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Counter CONFLICTING_CONSUMER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "conflictingConsumer"));
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
private static final Counter MESSAGE_MISMATCHES_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "messageMismatches"));
|
||||
|
||||
private static final String STREAM_AGREEMENTS = MetricsUtil.name(MirroringMessageStream.class, "streamAgreements");
|
||||
|
||||
private static final String MISSING_MESSAGES_COUNTER =
|
||||
MetricsUtil.name(MirroringMessageStream.class, "missingMessages");
|
||||
|
||||
private static final DistributionSummary MISSING_MESSAGE_AGE_DISTRIBUTION =
|
||||
DistributionSummary.builder(MetricsUtil.name(MirroringMessageStream.class, "missingMessageAge"))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final int MAX_WINDOW_SIZE = 1024;
|
||||
|
||||
private final Map<UUID, HashCode> redisDynamoMessageWindow = new HashMap<>();
|
||||
private final Map<UUID, HashCode> foundationDbMessageWindow = new HashMap<>();
|
||||
|
||||
private boolean stopAgreementVerification = false;
|
||||
|
||||
@Nullable
|
||||
private Tags agreementFailureTags;
|
||||
|
||||
private final Set<UUID> recentFoundationDbUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private final Set<UUID> recentRedisDynamoEphemeralUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private enum Stream {
|
||||
REDIS_DYNAMO("redisDynamo"),
|
||||
FOUNDATION_DB("foundationDb");
|
||||
|
||||
private final String name;
|
||||
|
||||
Stream(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
private final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
|
||||
|
||||
private class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case final MessageStreamEntry.Envelope envelopeEntry -> {
|
||||
final boolean isUUIDv8 = UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
if (isUUIDv8) {
|
||||
verifyMessageAgreement(envelopeEntry, Stream.REDIS_DYNAMO);
|
||||
}
|
||||
yield isUUIDv8;
|
||||
}
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> true;
|
||||
};
|
||||
|
||||
if (isMirroredMessage) {
|
||||
request(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnError(final Throwable throwable) {
|
||||
switch (ExceptionUtils.unwrap(throwable)) {
|
||||
case ConflictingMessageConsumerException _ -> CONFLICTING_CONSUMER_COUNTER.increment();
|
||||
case CallNotPermittedException _ -> {
|
||||
// CallNotPermittedExceptions are already instrumented by metrics, so do nothing
|
||||
}
|
||||
case FDBException _ -> {
|
||||
// FDBExceptions are already instrumented by metrics, so do nothing
|
||||
}
|
||||
default -> super.hookOnError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
protected void hookOnNext(final MessageStreamEntry messageStreamEntry) {
|
||||
if (messageStreamEntry instanceof final MessageStreamEntry.Envelope envelope) {
|
||||
verifyMessageAgreement(envelope, Stream.FOUNDATION_DB);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookFinally(final SignalType type) {
|
||||
super.hookFinally(type);
|
||||
publishStreamAgreementMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doOnError(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConflictingMessageConsumerException) {
|
||||
CONFLICTING_CONSUMER_COUNTER.increment();
|
||||
}
|
||||
})
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
subscriber.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)
|
||||
&&
|
||||
messageNotDeliveredOnFoundationDbStream(messageGuid)) {
|
||||
foundationDbMessageStream.acknowledgeAndGetMessage(messageGuid)
|
||||
.thenAccept(deleteMessage -> {
|
||||
if (deleteMessage.isEmpty()) {
|
||||
handleMissingFoundationDbMessage(messageGuid, serverTimestamp);
|
||||
return;
|
||||
}
|
||||
verifyMessageAgreement(deleteMessage.get(), Stream.FOUNDATION_DB);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private synchronized void verifyMessageAgreement(final MessageStreamEntry.Envelope envelope,
|
||||
final Stream stream) {
|
||||
|
||||
if (stopAgreementVerification) {
|
||||
return;
|
||||
}
|
||||
|
||||
final UUID messageUUID = UUIDUtil.fromByteString(envelope.message().getServerGuid());
|
||||
|
||||
if (envelope.message().getEphemeral()) {
|
||||
// We don't compare ephemeral messages across streams because the two systems have different ways of handling and
|
||||
// delivering ephemeral messages. However, we track recently seen ephemeral UUIDs on the Redis/Dynamo stream
|
||||
// to answer whether a message missing from FoundationDB was ephemeral or not.
|
||||
if (stream == Stream.REDIS_DYNAMO) {
|
||||
recentRedisDynamoEphemeralUuids.add(messageUUID);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// There could be a race where a FoundationDB message is delivered on the stream right after it was acknowledged,
|
||||
// so we don't want to add it to the window again; check it against a set of recently seen UUIDs before adding.
|
||||
if (Stream.FOUNDATION_DB == stream && !recentFoundationDbUuids.add(messageUUID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Map<UUID, HashCode> thisStreamWindow;
|
||||
final Map<UUID, HashCode> otherStreamWindow;
|
||||
if (Stream.REDIS_DYNAMO == stream) {
|
||||
thisStreamWindow = redisDynamoMessageWindow;
|
||||
otherStreamWindow = foundationDbMessageWindow;
|
||||
} else {
|
||||
thisStreamWindow = foundationDbMessageWindow;
|
||||
otherStreamWindow = redisDynamoMessageWindow;
|
||||
}
|
||||
|
||||
final HashCode thisStreamMessageHashCode = hashCode(envelope.message());
|
||||
|
||||
final HashCode otherStreamMessageHashCode = otherStreamWindow.remove(messageUUID);
|
||||
if (otherStreamMessageHashCode != null) {
|
||||
if (!otherStreamMessageHashCode.equals(thisStreamMessageHashCode)) {
|
||||
MESSAGE_MISMATCHES_COUNTER.increment();
|
||||
}
|
||||
} else {
|
||||
thisStreamWindow.put(messageUUID, thisStreamMessageHashCode);
|
||||
if (thisStreamWindow.size() >= MAX_WINDOW_SIZE) {
|
||||
// Stream is way ahead of the other, stop comparing further
|
||||
stopAgreementVerification = true;
|
||||
thisStreamWindow.clear();
|
||||
otherStreamWindow.clear();
|
||||
recentFoundationDbUuids.clear();
|
||||
setAgreementFailure(Tags.of("reason", "overflow", "stream", stream.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean messageNotDeliveredOnFoundationDbStream(final UUID messageGuid) {
|
||||
return redisDynamoMessageWindow.containsKey(messageGuid);
|
||||
}
|
||||
|
||||
private synchronized void setAgreementFailure(final Tags tags) {
|
||||
if (agreementFailureTags == null) {
|
||||
agreementFailureTags = tags;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void publishStreamAgreementMetrics() {
|
||||
|
||||
Tags tags = Tags.of("success", String.valueOf(agreementFailureTags == null));
|
||||
if (agreementFailureTags != null) {
|
||||
tags = tags.and(agreementFailureTags);
|
||||
}
|
||||
|
||||
Metrics.counter(STREAM_AGREEMENTS, tags).increment();
|
||||
}
|
||||
|
||||
private synchronized void handleMissingFoundationDbMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
final Boolean ephemeral;
|
||||
if (redisDynamoMessageWindow.containsKey(messageGuid)) {
|
||||
// The comparison window always contains non-ephemeral messages since we ignore ephemeral messages for comparison
|
||||
ephemeral = false;
|
||||
} else if (recentRedisDynamoEphemeralUuids.contains(messageGuid)) {
|
||||
ephemeral = true;
|
||||
} else {
|
||||
ephemeral = null;
|
||||
}
|
||||
setAgreementFailure(Tags.of("reason", "missingMessages"));
|
||||
Metrics.counter(MISSING_MESSAGES_COUNTER, "ephemeral", ephemeral == null ? "unknown" : ephemeral.toString())
|
||||
.increment();
|
||||
MISSING_MESSAGE_AGE_DISTRIBUTION.record(System.currentTimeMillis() - serverTimestamp);
|
||||
}
|
||||
|
||||
private static HashCode hashCode(final MessageProtos.Envelope envelope) {
|
||||
final byte[] serialized = new byte[envelope.getSerializedSize()];
|
||||
final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(serialized);
|
||||
codedOutputStream.useDeterministicSerialization();
|
||||
try {
|
||||
envelope.writeTo(codedOutputStream);
|
||||
codedOutputStream.flush();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return Hashing.murmur3_128().hashBytes(serialized);
|
||||
}
|
||||
|
||||
}
|
||||
+7
-2
@@ -227,9 +227,14 @@ class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow
|
||||
|
||||
synchronized void handleMessageAcknowledged() {
|
||||
acknowledgedEntries += 1;
|
||||
assert acknowledgedEntries <= publishedEntries;
|
||||
|
||||
maybeGenerateMessageSource();
|
||||
if (!terminated) {
|
||||
// As a temporary migration measure, we may receive additional acknowledgements after the stream has terminated
|
||||
// (i.e. we're mirroring deletions from FoundationDB)
|
||||
assert acknowledgedEntries <= publishedEntries;
|
||||
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean maybeSendQueueEmptySignal() {
|
||||
|
||||
+69
-21
@@ -14,11 +14,14 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -57,11 +60,13 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Sinks;
|
||||
@@ -78,16 +83,19 @@ class MessageDispatcherIntegrationTest {
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1);
|
||||
|
||||
private static ExecutorService sharedExecutorService;
|
||||
private static ScheduledExecutorService sharedScheduledExecutorService;
|
||||
private static Scheduler messageDeliveryScheduler;
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private ReportMessageManager reportMessageManager;
|
||||
private Account account;
|
||||
private Device device;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
private MessageDispatcher messageDispatcher;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
@@ -95,6 +103,7 @@ class MessageDispatcherIntegrationTest {
|
||||
@BeforeAll
|
||||
static void beforeAll() {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
sharedScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
}
|
||||
|
||||
@@ -113,10 +122,22 @@ class MessageDispatcherIntegrationTest {
|
||||
sharedExecutorService);
|
||||
redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
sharedExecutorService, sharedExecutorService);
|
||||
reportMessageManager = mock(ReportMessageManager.class);
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
new SecureRandom().nextBytes(versionstampCipherKey);
|
||||
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher = new VersionstampUUIDCipher(0, versionstampCipherKey);
|
||||
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
Map.of(0, Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases())),
|
||||
0,
|
||||
versionstampUUIDCipher,
|
||||
sharedScheduledExecutorService,
|
||||
Clock.systemUTC(),
|
||||
Duration.ofSeconds(5),
|
||||
10);
|
||||
|
||||
when(account.getNumber()).thenReturn(Optional.of("+18005551234"));
|
||||
when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID());
|
||||
@@ -126,28 +147,33 @@ class MessageDispatcherIntegrationTest {
|
||||
|
||||
messageDispatcher = new MessageDispatcher(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, mock(FoundationDbMessageStore.class), redisMessageAvailabilityManager, reportMessageManager,
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
|
||||
mock(ReportMessageManager.class),
|
||||
sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
mock(DisconnectionRequestManager.class),
|
||||
clientReleaseManager);
|
||||
mock(ClientReleaseManager.class));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
void tearDown() {
|
||||
redisMessageAvailabilityManager.stop();
|
||||
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void afterAll() throws InterruptedException {
|
||||
sharedExecutorService.shutdown();
|
||||
sharedScheduledExecutorService.shutdown();
|
||||
final Mono<Void> schedulerShutdownMono = messageDeliveryScheduler.disposeGracefully();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
sharedScheduledExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
|
||||
schedulerShutdownMono.timeout(Duration.ofSeconds(2))
|
||||
.onErrorResume(TimeoutException.class, _ -> Mono.fromRunnable(() -> messageDeliveryScheduler.dispose()))
|
||||
.block();
|
||||
@@ -156,12 +182,13 @@ class MessageDispatcherIntegrationTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"207, 173",
|
||||
"323, 0",
|
||||
"0, 221",
|
||||
"207, 173, 77",
|
||||
"323, 0, 0",
|
||||
"0, 221, 0",
|
||||
"0, 0, 87"
|
||||
})
|
||||
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
|
||||
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount, final int foundationDbMessageCount) {
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, foundationDbMessageCount);
|
||||
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final List<Envelope> receivedMessages = messageDispatcher
|
||||
.getMessages(true, null, account, device, acks.asFlux())
|
||||
@@ -178,7 +205,7 @@ class MessageDispatcherIntegrationTest {
|
||||
final int persistedMessageCount = 77;
|
||||
final int cachedMessageCount = 104;
|
||||
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, 0);
|
||||
final AtomicInteger remainingMessages = new AtomicInteger(persistedMessageCount + cachedMessageCount);
|
||||
final int additionalMessageCount = 67;
|
||||
|
||||
@@ -191,10 +218,10 @@ class MessageDispatcherIntegrationTest {
|
||||
acks.tryEmitNext(UUIDUtil.fromByteString(envelope.getServerGuid()));
|
||||
if (remainingMessages.addAndGet(-1) == 60) {
|
||||
sharedExecutorService
|
||||
.submit(() -> expectedMessages.addAll(fillRandomMessages(0, additionalMessageCount)));
|
||||
.submit(() -> expectedMessages.addAll(fillRandomMessages(0, 0, additionalMessageCount)));
|
||||
}
|
||||
})
|
||||
.take(persistedMessageCount + cachedMessageCount + additionalMessageCount)
|
||||
.take(persistedMessageCount + cachedMessageCount + additionalMessageCount)
|
||||
.collectList()
|
||||
.block(Duration.ofSeconds(15));
|
||||
assertEquals(expectedMessages.size(), receivedMessages.size());
|
||||
@@ -206,25 +233,26 @@ class MessageDispatcherIntegrationTest {
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
|
||||
final Set<Envelope> receivedMessages = Collections.newSetFromMap(new ConcurrentHashMap<Envelope, Boolean>());
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
|
||||
final Set<Envelope> receivedMessages = Collections.newSetFromMap(new ConcurrentHashMap<>());
|
||||
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount, 0);
|
||||
final TestPublisher<UUID> acks = TestPublisher.create();
|
||||
final Exception thrown = assertThrows(Exception.class, () -> messageDispatcher
|
||||
.getMessages(true, null, account, device, acks.flux())
|
||||
.doOnNext(response -> {
|
||||
assertTrue(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(),
|
||||
device.getId()));
|
||||
assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(), device.getId()),
|
||||
"Client should not be present until initial queue is cleared");
|
||||
receivedMessages.add(response.getEnvelope());
|
||||
acks.error(new IOException("test exception"));
|
||||
})
|
||||
.collectList()
|
||||
.block());
|
||||
|
||||
assertInstanceOf(IOException.class, thrown.getCause());
|
||||
assertTrue(expectedMessages.containsAll(receivedMessages));
|
||||
assertFalse(redisMessageAvailabilityManager.isLocallyPresent(account.getAccountIdentifier(), device.getId()));
|
||||
}
|
||||
|
||||
private List<Envelope> fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
private List<Envelope> fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount, final int foundationDbMessageCount) {
|
||||
|
||||
final List<Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
for (int i = 0; i < persistedMessageCount; i++) {
|
||||
@@ -240,6 +268,26 @@ class MessageDispatcherIntegrationTest {
|
||||
messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join();
|
||||
expectedMessages.add(envelope);
|
||||
}
|
||||
|
||||
for (int i = 0; i < foundationDbMessageCount; i++) {
|
||||
final Envelope envelope = generateRandomMessage(UUID.randomUUID())
|
||||
.toBuilder()
|
||||
.clearServerGuid()
|
||||
.build();
|
||||
|
||||
final UUID messageGuid = foundationDbMessageStore.insert(new AciServiceIdentifier(account.getAccountIdentifier()),
|
||||
Map.of(device.getId(), envelope))
|
||||
.join()
|
||||
.get(device.getId())
|
||||
.messageGuid()
|
||||
.orElseThrow();
|
||||
|
||||
expectedMessages.add(envelope
|
||||
.toBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(messageGuid))
|
||||
.build());
|
||||
}
|
||||
|
||||
return expectedMessages;
|
||||
}
|
||||
|
||||
|
||||
+30
-1
@@ -8,25 +8,54 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.apple.foundationdb.Range;
|
||||
import java.io.IOException;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
public class FoundationDbClusterExtension implements AutoCloseable, BeforeAllCallback, BeforeEachCallback {
|
||||
|
||||
private final FoundationDbDatabaseLifecycleManager[] databaseLifecycleManagers;
|
||||
private final FaultTolerantDatabase[] databases;
|
||||
|
||||
private final CircuitBreakerConfiguration circuitBreakerConfiguration;
|
||||
private final BulkheadConfiguration bulkheadConfiguration;
|
||||
|
||||
private static final Range ALL_KEYS_RANGE = new Range(new byte[] {}, new byte[] {(byte) 0xff});
|
||||
|
||||
public FoundationDbClusterExtension() {
|
||||
this(1);
|
||||
}
|
||||
|
||||
public FoundationDbClusterExtension(final int numInstances) {
|
||||
this(numInstances, new CircuitBreakerConfiguration(), new BulkheadConfiguration());
|
||||
}
|
||||
|
||||
public FoundationDbClusterExtension(final int numInstances,
|
||||
final CircuitBreakerConfiguration circuitBreakerConfiguration,
|
||||
final BulkheadConfiguration bulkheadConfiguration) {
|
||||
|
||||
this.databaseLifecycleManagers = new FoundationDbDatabaseLifecycleManager[numInstances];
|
||||
this.databases = new FaultTolerantDatabase[numInstances];
|
||||
|
||||
this.circuitBreakerConfiguration = circuitBreakerConfiguration;
|
||||
this.bulkheadConfiguration = bulkheadConfiguration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeAll(final ExtensionContext context) throws IOException {
|
||||
final String resilienceConfigurationName = "foundationdb-test-" + RandomStringUtils.insecure().nextAlphanumeric(6);
|
||||
|
||||
ResilienceUtil.getCircuitBreakerRegistry().addConfiguration(resilienceConfigurationName,
|
||||
circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
|
||||
ResilienceUtil.getBulkheadRegistry().addConfiguration(resilienceConfigurationName,
|
||||
bulkheadConfiguration.toBulkheadConfig().build());
|
||||
|
||||
if (databaseLifecycleManagers[0] == null) {
|
||||
final String serviceContainerNamePrefix = System.getProperty("foundationDb.serviceContainerNamePrefix");
|
||||
|
||||
@@ -36,7 +65,7 @@ public class FoundationDbClusterExtension implements AutoCloseable, BeforeAllCal
|
||||
: new TestcontainersFoundationDbDatabaseLifecycleManager();
|
||||
databaseLifecycleManager.initializeDatabase(FDB.selectAPIVersion(FoundationDbVersion.getFoundationDbApiVersion()));
|
||||
databaseLifecycleManagers[i] = databaseLifecycleManager;
|
||||
databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), null, null);
|
||||
databases[i] = new FaultTolerantDatabase(databaseLifecycleManager.getDatabase(), String.format("messages-%d", i), resilienceConfigurationName, resilienceConfigurationName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+50
-86
@@ -24,7 +24,6 @@ import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -39,8 +38,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
@@ -62,7 +60,6 @@ class MessagesManagerTest {
|
||||
private MessagesCache messagesCache;
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
private ReportMessageManager reportMessageManager;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
|
||||
|
||||
@@ -74,38 +71,33 @@ class MessagesManagerTest {
|
||||
messagesCache = mock(MessagesCache.class);
|
||||
foundationDbMessageStore = mock(FoundationDbMessageStore.class);
|
||||
reportMessageManager = mock(ReportMessageManager.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
when(messagesCache.insert(any(), any(), anyByte(), any())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore,
|
||||
mock(RedisMessageAvailabilityManager.class), reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK,
|
||||
experimentEnrollmentManager);
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void insert(@CartesianTest.Enum Envelope.Type envelopeType, @CartesianTest.Values(booleans = {true, false}) final boolean mirrorInsert) {
|
||||
@ParameterizedTest
|
||||
@EnumSource(Envelope.Type.class)
|
||||
void insert(final Envelope.Type envelopeType) {
|
||||
final UUID sourceAci = UUID.randomUUID();
|
||||
final Envelope message = Envelope.newBuilder()
|
||||
.setSourceServiceId(new AciServiceIdentifier(sourceAci).toCompactByteString())
|
||||
.setType(envelopeType)
|
||||
.build();
|
||||
|
||||
if (mirrorInsert) {
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_INSERTS_EXPERIMENT_NAME)))
|
||||
.thenReturn(true);
|
||||
when(foundationDbMessageStore.insert(any(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final Map<Byte, Envelope> messagesByDeviceId = invocation.getArgument(1);
|
||||
|
||||
when(foundationDbMessageStore.insert(any(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final Map<Byte, Envelope> messagesByDeviceId = invocation.getArgument(1);
|
||||
|
||||
return CompletableFuture.completedFuture(messagesByDeviceId.keySet().stream()
|
||||
.collect(Collectors.toMap(deviceId -> deviceId,
|
||||
_ -> new FoundationDbMessageStore.InsertResult(Optional.of(Versionstamp.fromBytes(new byte[12])),
|
||||
Optional.of(MessageGuidUtil.generateRandomV8UUID()),
|
||||
true))));
|
||||
});
|
||||
}
|
||||
return CompletableFuture.completedFuture(messagesByDeviceId.keySet().stream()
|
||||
.collect(Collectors.toMap(deviceId -> deviceId,
|
||||
_ -> new FoundationDbMessageStore.InsertResult(Optional.of(Versionstamp.fromBytes(new byte[12])),
|
||||
Optional.of(MessageGuidUtil.generateRandomV8UUID()),
|
||||
true))));
|
||||
});
|
||||
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
|
||||
@@ -121,9 +113,9 @@ class MessagesManagerTest {
|
||||
|
||||
verifyNoMoreInteractions(reportMessageManager);
|
||||
|
||||
verify(foundationDbMessageStore, times(mirrorInsert ? 2 : 0)).insert(any(), any());
|
||||
verify(foundationDbMessageStore, times(2)).insert(any(), any());
|
||||
verify(messagesCache, times(2))
|
||||
.insert(argThat(messageGuid -> messageGuid.version() == (mirrorInsert ? 8 : 4)),
|
||||
.insert(argThat(messageGuid -> messageGuid.version() == 8),
|
||||
eq(destinationUuid),
|
||||
eq(Device.PRIMARY_ID),
|
||||
any());
|
||||
@@ -136,9 +128,6 @@ class MessagesManagerTest {
|
||||
.setSourceServiceId(new AciServiceIdentifier(sourceAci).toCompactByteString())
|
||||
.build();
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_INSERTS_EXPERIMENT_NAME)))
|
||||
.thenReturn(true);
|
||||
|
||||
when(foundationDbMessageStore.insert(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RuntimeException()));
|
||||
|
||||
@@ -173,24 +162,18 @@ class MessagesManagerTest {
|
||||
return new UUID(mostSignificantBits, ThreadLocalRandom.current().nextLong());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void insertMultiRecipientMessage(final boolean mirrorInsert) throws InvalidMessageException, InvalidVersionException {
|
||||
if (mirrorInsert) {
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_INSERTS_EXPERIMENT_NAME)))
|
||||
.thenReturn(true);
|
||||
@Test
|
||||
void insertMultiRecipientMessage() throws InvalidMessageException, InvalidVersionException {
|
||||
when(foundationDbMessageStore.insert(any(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final Map<Byte, Envelope> messagesByDeviceId = invocation.getArgument(1);
|
||||
|
||||
when(foundationDbMessageStore.insert(any(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final Map<Byte, Envelope> messagesByDeviceId = invocation.getArgument(1);
|
||||
|
||||
return CompletableFuture.completedFuture(messagesByDeviceId.keySet().stream()
|
||||
.collect(Collectors.toMap(deviceId -> deviceId,
|
||||
_ -> new FoundationDbMessageStore.InsertResult(Optional.of(Versionstamp.fromBytes(new byte[12])),
|
||||
Optional.of(generateRandomV8UUID()),
|
||||
true))));
|
||||
});
|
||||
}
|
||||
return CompletableFuture.completedFuture(messagesByDeviceId.keySet().stream()
|
||||
.collect(Collectors.toMap(deviceId -> deviceId,
|
||||
_ -> new FoundationDbMessageStore.InsertResult(Optional.of(Versionstamp.fromBytes(new byte[12])),
|
||||
Optional.of(generateRandomV8UUID()),
|
||||
true))));
|
||||
});
|
||||
|
||||
final AciServiceIdentifier singleDeviceAccountAciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final PniServiceIdentifier singleDeviceAccountPniServiceIdentifier = new PniServiceIdentifier(UUID.randomUUID());
|
||||
@@ -230,12 +213,7 @@ class MessagesManagerTest {
|
||||
|
||||
final Map<Account, Map<Byte, Boolean>> expectedPresenceByAccountAndDeviceId = Map.of(
|
||||
singleDeviceAccount, Map.of(Device.PRIMARY_ID, true),
|
||||
multiDeviceAccount, Map.of(Device.PRIMARY_ID, false, (byte) (Device.PRIMARY_ID + 1), true)
|
||||
);
|
||||
|
||||
final Map<UUID, Map<Byte, Boolean>> presenceByAccountIdentifierAndDeviceId = Map.of(
|
||||
singleDeviceAccountAciServiceIdentifier.uuid(), Map.of(Device.PRIMARY_ID, true),
|
||||
multiDeviceAccountAciServiceIdentifier.uuid(), Map.of(Device.PRIMARY_ID, false, (byte) (Device.PRIMARY_ID + 1), true)
|
||||
multiDeviceAccount, Map.of(Device.PRIMARY_ID, true, (byte) (Device.PRIMARY_ID + 1), true)
|
||||
);
|
||||
|
||||
final byte[] sharedMrmKey = "shared-mrm-key".getBytes(StandardCharsets.UTF_8);
|
||||
@@ -243,16 +221,6 @@ class MessagesManagerTest {
|
||||
when(messagesCache.insertSharedMultiRecipientMessagePayload(eq(multiRecipientMessage), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(sharedMrmKey));
|
||||
|
||||
when(messagesCache.insert(any(), any(), anyByte(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final UUID accountIdentifier = invocation.getArgument(1);
|
||||
final byte deviceId = invocation.getArgument(2);
|
||||
|
||||
return CompletableFuture.completedFuture(
|
||||
presenceByAccountIdentifierAndDeviceId.getOrDefault(accountIdentifier, Collections.emptyMap())
|
||||
.getOrDefault(deviceId, false));
|
||||
});
|
||||
|
||||
final long clientTimestamp = System.currentTimeMillis();
|
||||
final boolean isStory = ThreadLocalRandom.current().nextBoolean();
|
||||
final boolean isEphemeral = ThreadLocalRandom.current().nextBoolean();
|
||||
@@ -293,37 +261,33 @@ class MessagesManagerTest {
|
||||
anyByte(),
|
||||
any());
|
||||
|
||||
if (mirrorInsert) {
|
||||
final Envelope prototypeExpectedFoundationDbMessage = prototypeExpectedMessage.toBuilder().clearSharedMrmKey().build();
|
||||
final Envelope prototypeExpectedFoundationDbMessage = prototypeExpectedMessage.toBuilder().clearSharedMrmKey().build();
|
||||
|
||||
verify(foundationDbMessageStore).insert(singleDeviceAccountAciServiceIdentifier,
|
||||
Map.of(Device.PRIMARY_ID, prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(singleDeviceAccountAciServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Aci(singleDeviceAccountAciServiceIdentifier.uuid())))))
|
||||
.build()));
|
||||
verify(foundationDbMessageStore).insert(singleDeviceAccountAciServiceIdentifier,
|
||||
Map.of(Device.PRIMARY_ID, prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(singleDeviceAccountAciServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Aci(singleDeviceAccountAciServiceIdentifier.uuid())))))
|
||||
.build()));
|
||||
|
||||
verify(foundationDbMessageStore).insert(singleDeviceAccountAciServiceIdentifier,
|
||||
Map.of(Device.PRIMARY_ID, prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(singleDeviceAccountPniServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Pni(singleDeviceAccountPniServiceIdentifier.uuid())))))
|
||||
.build()));
|
||||
verify(foundationDbMessageStore).insert(singleDeviceAccountAciServiceIdentifier,
|
||||
Map.of(Device.PRIMARY_ID, prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(singleDeviceAccountPniServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Pni(singleDeviceAccountPniServiceIdentifier.uuid())))))
|
||||
.build()));
|
||||
|
||||
verify(foundationDbMessageStore).insert(multiDeviceAccountAciServiceIdentifier,
|
||||
Map.of(
|
||||
Device.PRIMARY_ID, prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Aci(multiDeviceAccountAciServiceIdentifier.uuid())))))
|
||||
.build(),
|
||||
(byte) (Device.PRIMARY_ID + 1), prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Aci(multiDeviceAccountAciServiceIdentifier.uuid())))))
|
||||
.build())
|
||||
);
|
||||
verify(foundationDbMessageStore).insert(multiDeviceAccountAciServiceIdentifier,
|
||||
Map.of(
|
||||
Device.PRIMARY_ID, prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Aci(multiDeviceAccountAciServiceIdentifier.uuid())))))
|
||||
.build(),
|
||||
(byte) (Device.PRIMARY_ID + 1), prototypeExpectedFoundationDbMessage.toBuilder()
|
||||
.setDestinationServiceId(multiDeviceAccountAciServiceIdentifier.toCompactByteString())
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(multiRecipientMessage.getRecipients().get(new ServiceId.Aci(multiDeviceAccountAciServiceIdentifier.uuid())))))
|
||||
.build())
|
||||
);
|
||||
|
||||
verify(foundationDbMessageStore, never()).insert(eq(unresolvedAccountAciServiceIdentifier), any());
|
||||
} else {
|
||||
verifyNoInteractions(foundationDbMessageStore);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
|
||||
class MirroringMessageStreamTest {
|
||||
|
||||
private FoundationDbMessageStream foundationDbMessageStream;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private MirroringMessageStream mirroringMessageStream;
|
||||
|
||||
private static final AciServiceIdentifier ACCOUNT_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
mirroringMessageStream = new MirroringMessageStream(
|
||||
mock(RedisDynamoDbMessageStream.class),
|
||||
foundationDbMessageStream,
|
||||
experimentEnrollmentManager,
|
||||
ACCOUNT_IDENTIFIER.uuid(),
|
||||
DEVICE_ID);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void acknowledgeMessage(final boolean enrolled, final UUID messageGuid, final boolean expectFoundationDbDeletion) {
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)))
|
||||
.thenReturn(enrolled);
|
||||
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
mirroringMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
|
||||
if (expectFoundationDbDeletion) {
|
||||
verify(foundationDbMessageStream).acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
} else {
|
||||
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Arguments> acknowledgeMessage() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Not enrolled, v4 UUID", false, UUID.randomUUID(), false),
|
||||
Arguments.argumentSet("Not enrolled, v8 UUID", false, MessageGuidUtil.generateRandomV8UUID(), false),
|
||||
Arguments.argumentSet("Enrolled, v4 UUID", true, UUID.randomUUID(), false),
|
||||
Arguments.argumentSet("Enrolled, v8 UUID", true, MessageGuidUtil.generateRandomV8UUID(), true)
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -19,7 +19,7 @@ import com.apple.foundationdb.tuple.Versionstamp;
|
||||
|
||||
class VersionstampClockTest {
|
||||
@RegisterExtension
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1);
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension();
|
||||
|
||||
private final TestClock clock = TestClock.now();
|
||||
private final VersionstampClock versionstampClock = new VersionstampClock(
|
||||
|
||||
+67
-7
@@ -23,10 +23,13 @@ import static org.mockito.Mockito.when;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -37,7 +40,9 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
@@ -45,6 +50,8 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
@@ -62,11 +69,13 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
@@ -83,7 +92,18 @@ class WebSocketConnectionIntegrationTest {
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
@RegisterExtension
|
||||
static final FoundationDbClusterExtension FOUNDATION_DB_EXTENSION;
|
||||
|
||||
static {
|
||||
final BulkheadConfiguration bulkheadConfiguration = new BulkheadConfiguration();
|
||||
bulkheadConfiguration.setMaxConcurrentCalls(256);
|
||||
|
||||
FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(1, new CircuitBreakerConfiguration(), bulkheadConfiguration);
|
||||
}
|
||||
|
||||
private ExecutorService sharedExecutorService;
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
@@ -96,6 +116,13 @@ class WebSocketConnectionIntegrationTest {
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
private static ScheduledExecutorService presenceRenewalExecutorService;
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
@@ -118,6 +145,20 @@ class WebSocketConnectionIntegrationTest {
|
||||
webSocketClient = mock(WebSocketClient.class);
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
new SecureRandom().nextBytes(versionstampCipherKey);
|
||||
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher = new VersionstampUUIDCipher(0, versionstampCipherKey);
|
||||
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
Map.of(0, Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases())),
|
||||
0,
|
||||
versionstampUUIDCipher,
|
||||
presenceRenewalExecutorService,
|
||||
Clock.systemUTC(),
|
||||
Duration.ofSeconds(5),
|
||||
10);
|
||||
|
||||
when(account.getNumber()).thenReturn(Optional.of("+18005551234"));
|
||||
when(account.getAccountIdentifier()).thenReturn(UUID.randomUUID());
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
@@ -139,6 +180,14 @@ class WebSocketConnectionIntegrationTest {
|
||||
.block();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() throws InterruptedException {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
presenceRenewalExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"207, 173",
|
||||
@@ -148,7 +197,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, mock(FoundationDbMessageStore.class), redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
@@ -222,7 +271,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesMultipleSegments() {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, mock(FoundationDbMessageStore.class), redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
@@ -273,11 +322,22 @@ class WebSocketConnectionIntegrationTest {
|
||||
if (remainingMessages.decrementAndGet() == 60) {
|
||||
sharedExecutorService.submit(() -> {
|
||||
for (int i = 0; i < additionalMessageCount; i++) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope envelope = generateRandomMessage(messageGuid);
|
||||
final Envelope envelope = generateRandomMessage(UUID.randomUUID())
|
||||
.toBuilder()
|
||||
.clearServerGuid()
|
||||
.build();
|
||||
|
||||
messagesCache.insert(messageGuid, account.getAccountIdentifier(), device.getId(), envelope).join();
|
||||
expectedMessages.add(envelope);
|
||||
final UUID messageGuid =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(account.getAccountIdentifier()),
|
||||
Map.of(device.getId(), envelope))
|
||||
.join()
|
||||
.get(device.getId())
|
||||
.messageGuid()
|
||||
.orElseThrow();
|
||||
|
||||
expectedMessages.add(envelope.toBuilder()
|
||||
.setServerGuid(UUIDUtil.toByteString(messageGuid))
|
||||
.build());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -316,7 +376,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesClientClosed() {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, mock(FoundationDbMessageStore.class), redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC(), mock(ExperimentEnrollmentManager.class)),
|
||||
new MessageMetrics(),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
|
||||
Reference in new issue
Block a user