Add gRPC message retrieval

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-06-11 11:34:07 -05:00
1 parent 329d229ac7
commit b6317a1b43
12 files changed
+1367 -44

No files matched your search

@@ -165,6 +165,7 @@ import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
@@ -988,6 +989,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(zkSecretParams, Clock.systemUTC());
final MessageMetrics messageMetrics = new MessageMetrics();
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
pushNotificationManager, pushNotificationScheduler, messageDeliveryLoopMonitor, disconnectionRequestManager,
clientReleaseManager);
final CertificateGenerator certificateGenerator =
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
@@ -1001,7 +1006,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileCdnPolicySigner, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
@@ -1093,7 +1098,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
final MessageMetrics messageMetrics = new MessageMetrics();
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
// because we handle serialization of http responses on the websocket on our own and can
@@ -0,0 +1,273 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.micrometer.core.instrument.Metrics;
import java.time.Duration;
import java.util.UUID;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Signal;
import reactor.core.publisher.Sinks;
/// A MessageDispatcher is used to stream messages to an authenticated device and coordinates message acknowledgement,
/// backpressure, disconnection signals, and receipts.
public class MessageDispatcher {
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
@VisibleForTesting
static final int MAX_UNACKED_MESSAGES = 256;
@VisibleForTesting
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
private static final GetMessagesResponse CONFLICTING_STREAM_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setConflictingStream(Empty.getDefaultInstance()))
.build();
private static final GetMessagesResponse REAUTHENTICATION_REQUIRED_RESPONSE = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setReauthenticationRequired(Empty.getDefaultInstance()))
.build();
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(MessageDispatcher.class, "sendMessages");
private final ReceiptSender receiptSender;
private final MessagesManager messagesManager;
private final MessageMetrics messageMetrics;
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ClientReleaseManager clientReleaseManager;
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
private final DisconnectionRequestManager disconnectionRequestManager;
public MessageDispatcher(final ReceiptSender receiptSender,
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final PushNotificationScheduler pushNotificationScheduler,
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
final DisconnectionRequestManager disconnectionRequestManager,
final ClientReleaseManager clientReleaseManager) {
this.receiptSender = receiptSender;
this.messagesManager = messagesManager;
this.messageMetrics = messageMetrics;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
this.disconnectionRequestManager = disconnectionRequestManager;
this.clientReleaseManager = clientReleaseManager;
}
/// Retrieve messages for the device.
///
/// ## Termination
/// The returned message stream is potentially infinite. It will terminate if the device acknowledgement stream
/// terminates for any reason. The error from the client will be propagated to the returned flux. The stream may also
/// terminate with any other error encountered retrieving messages or processing acknowledgements.
///
/// The returned flux will emit a [GetMessagesResponse.Terminated] and then complete if
/// - A disconnection request (typically indicating a change in authorization credentials) is received.
/// - A client requests messages for the same account/device while this stream is still active
///
/// When the stream terminates for any reason and the client has messages remaining in their queue, a push
/// notification is scheduled to encourage the client to wake up and try again after a delay.
///
/// ## Queue Empty
/// The returned flux will emit a queue empty indicator when the device has successfully drained their waiting queue
/// and acknowledged all of them. A queue empty response guarantees all messages that were waiting for the client when
/// they first connected have been delivered and removed from storage, though it's possible the queue empty response
/// also waits for messages that arrived in the intervening period.
///
/// ## Acknowledgement
/// When the device acknowledges a message GUID it is removed from storage. If applicable, a delivery receipt is sent
/// to the original sender of the message.
///
///
/// @param shouldDropStories if true, stories will not be delivered in the response stream (and will be
/// removed from persistent storage)
/// @param userAgentString the userAgent of the requesting device
/// @param account the account to retrieve messages for
/// @param device the device to retrieve messages for
/// @param acknowledgedMessageGuids A flux that should emit the server guid of messages when they have been
/// acknowledged by the device
/// @return The message stream
public Flux<GetMessagesResponse> getMessages(
final boolean shouldDropStories,
@Nullable final String userAgentString,
final Account account,
final Device device,
final Flux<UUID> acknowledgedMessageGuids) {
final MessageStream messageStream = messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device);
@Nullable final UserAgent userAgent = UserAgentUtil.maybeParseUserAgentString(userAgentString);
final PendingAcknowledgementTracker pendingAcknowledgementTracker = new PendingAcknowledgementTracker(messageMetrics, userAgent);
pushNotificationManager.handleMessagesRetrieved(account, device, userAgentString);
final Flux<GetMessagesResponse> messages = JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
// Check the first message we send for message-delivery loops
.switchOnFirst((firstEntry, flux) -> {
recordDeliveryAttempt(account, device, userAgentString, firstEntry);
return flux;
})
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
if (envelope.getStory() && shouldDropStories) {
// Just immediately delete stories if the device doesn't want them
yield Mono.fromFuture(() -> messageStream.acknowledgeMessage(serverGuid, envelope.getServerTimestamp()))
.then(Mono.empty());
}
pendingAcknowledgementTracker.addUnacknowledgedEnvelope(envelope);
final MessageProtos.Envelope stripped = envelope.toBuilder().clearEphemeral().build();
messageMetrics.measureAccountEnvelopeUuidMismatches(account, envelope);
messageMetrics.measureMessageSent(stripped.getSerializedSize());
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).build());
}
case MessageStreamEntry.QueueEmpty _ -> {
pendingAcknowledgementTracker.markEndOfQueue();
yield Mono.empty();
}
}, MAX_UNACKED_MESSAGES);
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
// after that a permit is emitted every time we receive an ack.
final Sinks.Many<Boolean> ackPermits = Sinks.many().unicast().onBackpressureBuffer();
final Flux<Boolean> permits = Flux.range(0, MAX_UNACKED_MESSAGES)
.map(_ -> true)
.concatWith(ackPermits.asFlux());
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
.flatMap(guid -> {
final PendingAcknowledgementTracker.UnacknowledgedEnvelope unacked = pendingAcknowledgementTracker.takeUnacknowledgedEnvelope(guid);
if (unacked == null) {
// This is fine, the client may have sent a duplicate-ack
return Mono.empty();
}
messageMetrics.measureOutgoingMessageLatency(
unacked.getServerTimestamp(), MessageMetrics.GRPC_CHANNEL, device.isPrimary(),
unacked.isUrgent(), unacked.isEphemeral(), userAgent, clientReleaseManager);
maybeSendDeliveryReceipt(device, unacked);
return Mono.fromFuture(() -> messageStream.acknowledgeMessage(unacked.getServerGuid(), unacked.getServerTimestamp()))
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
// Just have to emit some value that indicates we can release a permit
.thenReturn(true);
}, MAX_UNACKED_MESSAGES)
.doOnNext(_ -> ackPermits.tryEmitNext(true))
.ignoreElements()
.cast(GetMessagesResponse.class);
return Flux.merge(
// Emit messages, but only when a permit is available
messages.zipWith(permits, (resp, _) -> resp),
// Will only emit errors, but those should terminate the stream
ackCompletions,
// Emits a queue empty once all messages prior to the queueEmpty signal have been acked
pendingAcknowledgementTracker.queueDrained(),
// Emit a Terminated response if we receive a disconnection request
disconnectionSignal(account, device))
.onErrorResume(ConflictingMessageConsumerException.class, _ -> Mono.just(CONFLICTING_STREAM_RESPONSE))
.takeUntil(response -> switch (response.getResponseCase()) {
case ENVELOPE, QUEUE_EMPTY -> false;
case TERMINATED -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent,
response.getTerminated().hasConflictingStream());
yield true;
}
case RESPONSE_NOT_SET -> throw new IllegalStateException("tried to return an invalid GetMessagesResponse");
})
.doFinally(_ -> maybeSchedulePush(account, device));
}
/// If the device potentially has more messages available, schedule a push notification.
private void maybeSchedulePush(final Account account, final Device device) {
messagesManager.mayHaveMessages(account.getIdentifier(IdentityType.ACI), device)
.thenAccept(mayHaveMessages -> {
if (mayHaveMessages) {
pushNotificationScheduler.scheduleDelayedNotification(account, device,
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
}
});
}
/// Watch for a disconnection signal from the [DisconnectionRequestManager]
///
/// @return Mono that completes with a [org.signal.chat.messages.GetMessagesResponse.Terminated] response if the
/// device receives a disconnection request
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device) {
return Mono.create(sink -> {
final DisconnectionRequestListener listener = () -> sink.success(REAUTHENTICATION_REQUIRED_RESPONSE);
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
});
}
private void recordDeliveryAttempt(final Account account, final Device device, final String userAgent,
final Signal<? extends MessageStreamEntry> firstEntry) {
if (firstEntry.get() instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getIdentifier(IdentityType.ACI),
device.getId(),
UUIDUtil.fromByteString(message.getServerGuid()),
userAgent,
MessageMetrics.GRPC_CHANNEL);
}
}
private void maybeSendDeliveryReceipt(
final Device device,
final PendingAcknowledgementTracker.UnacknowledgedEnvelope unacknowledgedEnvelope) {
if (unacknowledgedEnvelope.getSourceServiceId() == null) {
return;
}
try {
receiptSender.sendReceipt(
unacknowledgedEnvelope.getDestinationServiceId(),
device.getId(),
unacknowledgedEnvelope.getSourceServiceId(),
unacknowledgedEnvelope.getClientTimestamp());
} catch (final Exception e) {
log.warn("Failed to send receipt", e);
}
}
}
@@ -12,8 +12,13 @@ import com.google.protobuf.Empty;
import java.time.Clock;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Flow;
import java.util.stream.Collectors;
import io.grpc.StatusRuntimeException;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.GetMessagesRequest;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
@@ -38,6 +43,11 @@ import org.whispersystems.textsecuregcm.spam.SpamCheckResult;
import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import javax.annotation.Nullable;
public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
@@ -46,6 +56,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
private final MessageSender messageSender;
private final CardinalityEstimator messageByteLimitEstimator;
private final SpamChecker spamChecker;
private final MessageDispatcher messageDispatcher;
private final Clock clock;
private static final SendMessageAuthenticatedSenderResponse SEND_MESSAGE_SUCCESS_RESPONSE =
@@ -56,6 +67,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
final MessageSender messageSender,
final CardinalityEstimator messageByteLimitEstimator,
final SpamChecker spamChecker,
final MessageDispatcher messageDispatcher,
final Clock clock) {
this.accountsManager = accountsManager;
@@ -63,9 +75,49 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
this.messageSender = messageSender;
this.messageByteLimitEstimator = messageByteLimitEstimator;
this.spamChecker = spamChecker;
this.messageDispatcher = messageDispatcher;
this.clock = clock;
}
@Override
public Flow.Publisher<GetMessagesResponse> getMessages(final Flow.Publisher<GetMessagesRequest> request) throws Exception {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = accountsManager
.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
final Flux<GetMessagesRequest> requestFlux = JdkFlowAdapter.flowPublisherToFlux(request);
return JdkFlowAdapter.publisherToFlowPublisher(requestFlux.switchOnFirst((firstSignal, flux) -> {
@Nullable final GetMessagesRequest streamRequest = firstSignal.get();
if (streamRequest == null) {
// Just forward the error or completion signal
return flux.then().cast(GetMessagesResponse.class);
}
if (!streamRequest.hasOptions()) {
throw GrpcExceptions.fieldViolation("request", "the first request must be GetMessageOptions");
}
final boolean dropStories = streamRequest.getOptions().getDropStories();
return messageDispatcher.getMessages(dropStories, userAgent, account, device,
flux.skip(1).map(MessagesGrpcService::extractAckGuid));
}));
}
private static UUID extractAckGuid(final GetMessagesRequest ack) throws StatusRuntimeException {
if (!ack.hasServerGuidAck()) {
throw GrpcExceptions.fieldViolation("request", "All non-initial GetMessageRequests must contain a server_guid_ack");
}
try {
return UUIDUtil.fromByteString(ack.getServerGuidAck());
} catch (final IllegalArgumentException e) {
throw GrpcExceptions.fieldViolation("server_guid_ack", "invalid server_guid_ack");
}
}
@Override
public SendMessageAuthenticatedSenderResponse sendMessage(final SendAuthenticatedSenderMessageRequest request)
throws RateLimitExceededException {
@@ -0,0 +1,170 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.micrometer.core.instrument.Timer;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.util.ClosableEpoch;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
/// Track messages while they are in-flight so they can later be retrieved for acknowledgement, as well as when
/// acknowledgement completes.
///
/// # Example Usage
/// ```java
/// PendingAcknowledgement tracker = new PendingAcknowledgementTracker(...);
/// tracker.addUnacknowledgedEnvelope(envelope);
/// sendEnvelopeToDevice(envelope);
///
/// // Later, when the device acklowedges the envelope
/// UnacknowledgedEnvelope envelope = takeUnacknowledgedEnvelope(uuid);
/// removeFromStorage(envelope);
/// envelope.handleMessageAcknowledged();
/// ```
class PendingAcknowledgementTracker {
private final ConcurrentHashMap<UUID, UnacknowledgedEnvelope> unacknowledgedEnvelopes = new ConcurrentHashMap<>();
private final AtomicLong sentMessageCounter = new AtomicLong();
private final Sinks.One<GetMessagesResponse> queueDrained = Sinks.one();
private final ClosableEpoch queueDrainEpoch = new ClosableEpoch(() ->
queueDrained.tryEmitValue(MessageDispatcher.QUEUE_EMPTY_RESPONSE));
private final Timer.Sample queueDrainStart = Timer.start();
private final MessageMetrics messageMetrics;
@Nullable private final UserAgent userAgent;
PendingAcknowledgementTracker(final MessageMetrics messageMetrics, @Nullable final UserAgent userAgent) {
this.messageMetrics = messageMetrics;
this.userAgent = userAgent;
}
/// Store an envelope so it can be retrieved later via [#takeUnacknowledgedEnvelope].
///
/// @param envelope An envelope that has been sent to a device and is waiting to be acknowledged
void addUnacknowledgedEnvelope(final MessageProtos.Envelope envelope) {
sentMessageCounter.incrementAndGet();
final UUID messageGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
final AciServiceIdentifier sourceId = envelope.hasSourceServiceId() && envelope.getType() != MessageProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT
? AciServiceIdentifier.fromByteString(envelope.getSourceServiceId())
: null;
final ServiceIdentifier destinationId = ServiceIdentifier.fromByteString(envelope.getDestinationServiceId());
final UnacknowledgedEnvelope unacknowledgedEnvelope = new UnacknowledgedEnvelope(messageGuid,
envelope.getServerTimestamp(), envelope.getClientTimestamp(),
envelope.getUrgent(), envelope.getEphemeral(),
destinationId, sourceId);
unacknowledgedEnvelopes.put(messageGuid, unacknowledgedEnvelope);
}
/// Take a previously stored envelope so it can be acknowledged. When the message is successfully removed from
/// storage, call [UnacknowledgedEnvelope#handleMessageAcknowledged()].
///
/// @param guid The server GUID of the envelope previously stored with [#addUnacknowledgedEnvelope(MessageProtos.Envelope)].
/// @return The previously stored envelope, or null if no envelope with the provided guid was stored
@Nullable
UnacknowledgedEnvelope takeUnacknowledgedEnvelope(final UUID guid) {
return unacknowledgedEnvelopes.remove(guid);
}
/// Signal that we've observed the end of the initial message queue. The Mono returned by [#queueDrained] will emit a
/// value when all current envelopes tracked with [#addUnacknowledgedEnvelope] have been marked [UnacknowledgedEnvelope#handleMessageAcknowledged()]
void markEndOfQueue() {
messageMetrics
.measureQueueDrain(MessageMetrics.GRPC_CHANNEL, userAgent, sentMessageCounter.get(), queueDrainStart);
queueDrainEpoch.close();
}
/// Determine when a queue has been drained.
///
/// @return A mono that completes with a QueueEmpty response when all messages tracked before [#markEndOfQueue] have
/// been acknowledged.
Mono<GetMessagesResponse> queueDrained() {
return queueDrained.asMono();
}
class UnacknowledgedEnvelope {
private final UUID serverGuid;
private final long serverTimestamp;
private final Timer.Sample sample;
private final boolean inDrainEpoch;
private final long clientTimestamp;
private final boolean urgent;
private final boolean ephemeral;
private final ServiceIdentifier destinationServiceId;
@Nullable private final AciServiceIdentifier sourceServiceId;
private UnacknowledgedEnvelope(
final UUID serverGuid,
final long serverTimestamp,
final long clientTimestamp,
final boolean urgent,
final boolean ephemeral,
final ServiceIdentifier destinationServiceId,
@Nullable final AciServiceIdentifier sourceServiceId) {
this.serverGuid = serverGuid;
this.serverTimestamp = serverTimestamp;
this.clientTimestamp = clientTimestamp;
this.urgent = urgent;
this.ephemeral = ephemeral;
this.destinationServiceId = destinationServiceId;
this.sample = Timer.start();
this.inDrainEpoch = queueDrainEpoch.tryArrive();
this.sourceServiceId = sourceServiceId;
}
void handleMessageAcknowledged() {
messageMetrics.measureSendMessageDuration(MessageMetrics.GRPC_CHANNEL, userAgent, sample);
if (inDrainEpoch) {
queueDrainEpoch.depart();
}
}
public UUID getServerGuid() {
return serverGuid;
}
public long getServerTimestamp() {
return serverTimestamp;
}
public long getClientTimestamp() {
return clientTimestamp;
}
public boolean isUrgent() {
return urgent;
}
public boolean isEphemeral() {
return ephemeral;
}
public ServiceIdentifier getDestinationServiceId() {
return destinationServiceId;
}
/// Get the sender of this message
///
/// @return the ServiceIdentifier of the source of this message. `null` if the message sender was not identified or
/// if the envelope was for a server delivery receipt
@Nullable
public AciServiceIdentifier getSourceServiceId() {
return sourceServiceId;
}
}
}
@@ -19,24 +19,31 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
public final class MessageMetrics {
private static final Logger logger = LoggerFactory.getLogger(MessageMetrics.class);
public static String GRPC_CHANNEL = "grpc";
public static String WEBSOCKET_CHANNEL = "websocket";
@VisibleForTesting
static final String MISMATCHED_ACCOUNT_ENVELOPE_UUID_COUNTER_NAME = name(MessageMetrics.class,
"mismatchedAccountEnvelopeUuid");
public static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
// Uses [WebSocketConnection] for backwards compatibility
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
private static final String INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME = name(WebSocketConnection.class, "initialQueueLength");
private static final String INITIAL_QUEUE_DRAIN_TIMER_NAME = name(WebSocketConnection.class, "drainInitialQueue");
private static final String SLOW_QUEUE_DRAIN_COUNTER_NAME = name(WebSocketConnection.class, "slowQueueDrain");
@@ -84,7 +91,7 @@ public final class MessageMetrics {
final boolean isPrimaryDevice,
final boolean isUrgent,
final boolean isEphemeral,
final String userAgent,
@Nullable final UserAgent userAgent,
final ClientReleaseManager clientReleaseManager) {
final List<Tag> tags = new ArrayList<>();
@@ -104,25 +111,26 @@ public final class MessageMetrics {
public void measureMessageStreamDisplaced(
final String channel,
final Tags platformTag,
@Nullable final UserAgent userAgent,
final boolean connectedElsewhere) {
metricRegistry.counter(
DISPLACEMENT_COUNTER_NAME,
platformTag
.and("connectedElsewhere", Boolean.toString(connectedElsewhere))
.and("channel", channel))
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("connectedElsewhere", Boolean.toString(connectedElsewhere)),
Tag.of("channel", channel)))
.increment();
}
public void measureQueueDrain(
final String channel,
final Tags platformTag,
@Nullable final UserAgent userAgent,
final long messagesDrained,
final Timer.Sample drainStart) {
metricRegistry.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, platformTag.and("channel", channel)).record(messagesDrained);
final long drainDurationNanos = drainStart.stop(metricRegistry.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, platformTag));
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel));
metricRegistry.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(messagesDrained);
final long drainDurationNanos = drainStart.stop(metricRegistry.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags));
if (Duration.ofNanos(drainDurationNanos).compareTo(SLOW_DRAIN_THRESHOLD) > 0) {
metricRegistry.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, platformTag.and("channel", channel)).increment();
metricRegistry.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
}
}
@@ -131,9 +139,9 @@ public final class MessageMetrics {
bytesSentCounter.increment(messageByteLength);
}
public void measureSendMessageDuration(final String channel, final Tags platformTag, final Timer.Sample sample) {
public void measureSendMessageDuration(final String channel, @Nullable final UserAgent userAgent, final Timer.Sample sample) {
sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
.tags(platformTag.and("channel", channel))
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
.register(metricRegistry));
}
}
@@ -6,9 +6,11 @@
package org.whispersystems.textsecuregcm.util.ua;
import com.vdurmont.semver4j.Semver;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
public class UserAgentUtil {
@@ -31,4 +33,12 @@ public class UserAgentUtil {
throw new UnrecognizedUserAgentException();
}
public static @Nullable UserAgent maybeParseUserAgentString(final String userAgentString) {
try {
return parseUserAgentString(userAgentString);
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
}
@@ -24,6 +24,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StaticException;
import org.slf4j.Logger;
@@ -50,6 +51,8 @@ import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
import org.whispersystems.websocket.WebSocketClient;
import org.whispersystems.websocket.WebSocketResourceProvider;
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
@@ -58,7 +61,6 @@ import reactor.core.Disposable;
import reactor.core.observability.micrometer.Micrometer;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import javax.annotation.Nullable;
public class WebSocketConnection implements DisconnectionRequestListener {
@@ -98,7 +100,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
private final Device authenticatedDevice;
private final MessageStream messageStream;
private final WebSocketClient client;
private final Tags platformTag;
private final @Nullable UserAgent userAgent;
private final LongAdder sentMessageCounter = new LongAdder();
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
@@ -137,7 +139,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
this.messageStream =
messagesManager.getMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice);
this.platformTag = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
this.userAgent = UserAgentUtil.maybeParseUserAgentString(client.getUserAgent());
}
public void start() {
@@ -155,7 +157,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
// it's also not ideal.
.doOnError(ConflictingMessageConsumerException.class, _ -> {
messageMetrics.measureMessageStreamDisplaced("websocket", platformTag, true);
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, true);
client.close(4409, "Connected elsewhere");
})
.doOnNext(entry -> {
@@ -165,7 +167,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
authenticatedDevice.getId(),
UUIDUtil.fromByteString(message.getServerGuid()),
client.getUserAgent(),
"websocket");
MessageMetrics.WEBSOCKET_CHANNEL);
}
}
})
@@ -177,7 +179,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
.subscribe(
entry -> {
if (entry instanceof MessageStreamEntry.QueueEmpty) {
messageMetrics.measureQueueDrain("websocket", platformTag, sentMessageCounter.sum(), queueDrainStart);
messageMetrics.measureQueueDrain(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, sentMessageCounter.sum(), queueDrainStart);
client.sendRequest("PUT", "/api/v1/queue/empty",
Collections.singletonList(HeaderUtils.getTimestampHeader()), Optional.empty());
}
@@ -259,11 +261,11 @@ public class WebSocketConnection implements DisconnectionRequestListener {
sendFailuresCounter.increment();
} else {
messageMetrics.measureOutgoingMessageLatency(serverTimestamp,
"websocket",
MessageMetrics.WEBSOCKET_CHANNEL,
authenticatedDevice.isPrimary(),
isUrgent,
isEphemeral,
client.getUserAgent(),
userAgent,
clientReleaseManager);
}
}).thenCompose(response -> {
@@ -283,7 +285,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
}
}
} else {
Tags tags = platformTag.and(STATUS_CODE_TAG, String.valueOf(response.getStatus()));
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of(STATUS_CODE_TAG, String.valueOf(response.getStatus())));
// TODO Remove this once we've identified the cause of message rejections from desktop clients
if (StringUtils.isNotBlank(response.getMessage())) {
@@ -297,7 +299,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
return result;
})
.thenRun(() -> messageMetrics.measureSendMessageDuration("websocket", platformTag, sample));
.thenRun(() -> messageMetrics.measureSendMessageDuration(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, sample));
}
@VisibleForTesting
@@ -321,8 +323,10 @@ public class WebSocketConnection implements DisconnectionRequestListener {
errorType = "other";
}
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER,
platformTag.and(ERROR_TYPE_TAG, errorType, EXCEPTION_TYPE_TAG, e.getClass().getSimpleName()))
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(ERROR_TYPE_TAG, errorType),
Tag.of(EXCEPTION_TYPE_TAG, e.getClass().getSimpleName())))
.increment();
}
@@ -336,7 +340,7 @@ public class WebSocketConnection implements DisconnectionRequestListener {
@Override
public void handleDisconnectionRequest() {
messageMetrics.measureMessageStreamDisplaced("websocket", platformTag, false);
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, false);
client.close(4401, "Reauthentication required");
}
}
@@ -16,6 +16,8 @@ import "org/signal/chat/require.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/tag.proto";
import "TextSecure.proto";
// Provides methods for sending "unsealed sender" messages.
service Messages {
@@ -31,6 +33,69 @@ service Messages {
// Sends a "sync" message to all other devices linked to the authenticated
// sender's account.
rpc SendSyncMessage(SendSyncMessageRequest) returns (SendMessageAuthenticatedSenderResponse) {}
// Retrieve messages for the authenticated device. When the caller receives
// and successfully processes a message returned in a GetMessagesResponse they
// must send a corresponding GetMessagesRequest indicating that the message
// has been processed (an ack). Acks should only be sent for messages
// delivered via the currently open RPC.
//
// Only the first GetMessagesRequest may contain request parameters that
// configure the stream. The first request must not contain an ack.
//
// The server will keep the stream open until the client disconnects or the
// connection is displaced as indicated by a Terminated response.
rpc GetMessages(stream GetMessagesRequest) returns (stream GetMessagesResponse) {}
}
message GetMessagesRequest {
message GetMessageOptions {
// If present and true, the server will not deliver any messages with the
// story flag set. This flag may only be set on the first GetMessagesRequest
// sent from the client to the server in an RPC stream.
bool drop_stories = 1;
}
oneof request {
// Configuration options for the message stream. Required for the first
// request of the stream, forbidden on subsequent reqeusts.
GetMessageOptions options = 1;
// The server_guid of an envelope previously returned in a
// GetMessagesResponse that has been successfully processed by the caller.
// Forbidden on the first request of the stream, required on subsequent
// requests.
bytes server_guid_ack = 2;
}
}
message GetMessagesResponse {
// The reason why a GetMessages RPC is being closed by the server.
message Terminated {
oneof reason {
// The account's credentials have been updated and the caller must reauthenticate.
google.protobuf.Empty reauthentication_required = 1;
// Another caller has opened a GetMessages stream for the same device.
google.protobuf.Empty conflicting_stream = 2;
}
}
oneof response {
// A message. On successful receipt of an envelope the caller should ack
// the envelope by sending a GetMessagesRequest with the envelope's server
// guid. Acks should only be sent for envelopes received on the currently
// open RPC.
textsecure.Envelope envelope = 1;
// An indicator that all outstanding messages for the device have been
// drained and acked by the client. The stream will remain open and continue
// to deliver newly arrived messages.
google.protobuf.Empty queue_empty = 2;
// Indicates that the stream is about to be closed.
Terminated terminated = 3;
}
}
// Provides methods for sending "sealed sender" messages.
@@ -0,0 +1,260 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
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;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.signal.chat.messages.GetMessagesRequest;
import org.signal.chat.messages.GetMessagesResponse;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
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.MessagesCache;
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.publisher.TestPublisher;
@Timeout(value = 30, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class MessageDispatcherIntegrationTest {
@RegisterExtension
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.MESSAGES);
@RegisterExtension
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
private static ExecutorService sharedExecutorService;
private static Scheduler messageDeliveryScheduler;
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();
@BeforeAll
static void beforeAll() {
sharedExecutorService = Executors.newSingleThreadExecutor();
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
}
@BeforeEach
void setUp() throws Exception {
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
mock(DynamicConfigurationManager.class);
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
messageDeliveryScheduler, sharedExecutorService, mock(ScheduledExecutorService.class), Clock.systemUTC());
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
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);
when(account.getNumber()).thenReturn("+18005551234");
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
when(device.getId()).thenReturn(Device.PRIMARY_ID);
redisMessageAvailabilityManager.start();
messageDispatcher = new MessageDispatcher(
mock(ReceiptSender.class),
new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, reportMessageManager,
sharedExecutorService, Clock.systemUTC()),
new MessageMetrics(),
mock(PushNotificationManager.class),
mock(PushNotificationScheduler.class),
mock(MessageDeliveryLoopMonitor.class),
mock(DisconnectionRequestManager.class),
clientReleaseManager);
}
@AfterEach
void tearDown() throws Exception {
redisMessageAvailabilityManager.stop();
}
@AfterAll
static void afterAll() throws InterruptedException {
sharedExecutorService.shutdown();
final Mono<Void> schedulerShutdownMono = messageDeliveryScheduler.disposeGracefully();
//noinspection ResultOfMethodCallIgnored
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
schedulerShutdownMono.timeout(Duration.ofSeconds(2))
.onErrorResume(TimeoutException.class, _ -> Mono.fromRunnable(() -> messageDeliveryScheduler.dispose()))
.block();
}
@ParameterizedTest
@CsvSource({
"207, 173",
"323, 0",
"0, 221",
})
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
final List<Envelope> receivedMessages = messageDispatcher
.getMessages(true, null, account, device, acks.asFlux())
.takeWhile(response -> !response.hasQueueEmpty())
.doOnNext(response -> acks.tryEmitNext(UUIDUtil.fromByteString(response.getEnvelope().getServerGuid())))
.map(GetMessagesResponse::getEnvelope)
.collectList()
.block(Duration.ofSeconds(15));
assertEquals(expectedMessages, receivedMessages);
}
@Test
void testProcessStoredMessagesMultipleSegments() {
final int persistedMessageCount = 77;
final int cachedMessageCount = 104;
final List<Envelope> expectedMessages = fillRandomMessages(persistedMessageCount, cachedMessageCount);
final AtomicInteger remainingMessages = new AtomicInteger(persistedMessageCount + cachedMessageCount);
final int additionalMessageCount = 67;
final Sinks.Many<UUID> acks = Sinks.many().unicast().onBackpressureBuffer();
final List<Envelope> receivedMessages = messageDispatcher
.getMessages(true, null, account, device, acks.asFlux())
.filter(response -> !response.hasQueueEmpty())
.map(GetMessagesResponse::getEnvelope)
.doOnNext(envelope -> {
acks.tryEmitNext(UUIDUtil.fromByteString(envelope.getServerGuid()));
if (remainingMessages.addAndGet(-1) == 60) {
sharedExecutorService
.submit(() -> expectedMessages.addAll(fillRandomMessages(0, additionalMessageCount)));
}
})
.take(persistedMessageCount + cachedMessageCount + additionalMessageCount)
.collectList()
.block(Duration.ofSeconds(15));
assertEquals(expectedMessages.size(), receivedMessages.size());
assertEquals(expectedMessages, receivedMessages);
}
@Test
void testProcessStoredMessagesClientClosed() {
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 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.getIdentifier(IdentityType.ACI),
device.getId()));
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.getIdentifier(IdentityType.ACI), device.getId()));
}
private List<Envelope> fillRandomMessages(final int persistedMessageCount, final int cachedMessageCount) {
final List<Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
for (int i = 0; i < persistedMessageCount; i++) {
final Envelope envelope = generateRandomMessage(UUID.randomUUID());
expectedMessages.add(envelope);
}
messagesDynamoDb.store(expectedMessages, account.getIdentifier(IdentityType.ACI), device);
for (int i = 0; i < cachedMessageCount; i++) {
final UUID messageGuid = UUID.randomUUID();
final Envelope envelope = generateRandomMessage(messageGuid);
messagesCache.insert(messageGuid, account.getIdentifier(IdentityType.ACI), device.getId(), envelope).join();
expectedMessages.add(envelope);
}
return expectedMessages;
}
private Envelope generateRandomMessage(final UUID messageGuid) {
final long timestamp = serialTimestamp++;
return Envelope.newBuilder()
.setClientTimestamp(timestamp)
.setServerTimestamp(timestamp)
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
.setType(Envelope.Type.CIPHERTEXT)
.setServerGuid(new AciServiceIdentifier(messageGuid).toCompactByteString())
.setDestinationServiceId(new AciServiceIdentifier(UUID.randomUUID()).toCompactByteString())
.build();
}
}
@@ -0,0 +1,375 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.signal.chat.messages.GetMessagesResponse;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStream;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
class MessageDispatcherTest {
private static final GetMessagesResponse QUEUE_EMPTY =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
private static final GetMessagesResponse REQUIRES_REAUTH = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setReauthenticationRequired(Empty.getDefaultInstance())
.build())
.build();
private static final GetMessagesResponse CONFLICTING_STREAM = GetMessagesResponse.newBuilder()
.setTerminated(GetMessagesResponse.Terminated.newBuilder()
.setConflictingStream(Empty.getDefaultInstance())
.build())
.build();
private static final UUID ACI = UUID.randomUUID();
private static final byte DEVICE_ID = 2;
private static final int SOURCE_DEVICE_ID = 1;
private static final String TEST_UA = "test-user-agent";
private Account account;
private Device device;
private MessagesManager messagesManager;
private ReceiptSender receiptSender;
private PushNotificationManager pushNotificationManager;
private MessageDispatcher dispatcher;
private DisconnectionRequestManager disconnectionRequestManager;
private PushNotificationScheduler pushNotificationScheduler;
private MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
@BeforeEach
void setUp() {
account = mock(Account.class);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(ACI);
when(account.getUuid()).thenReturn(ACI);
device = mock(Device.class);
messagesManager = mock(MessagesManager.class);
receiptSender = mock(ReceiptSender.class);
pushNotificationManager = mock(PushNotificationManager.class);
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
pushNotificationScheduler = mock(PushNotificationScheduler.class);
messageDeliveryLoopMonitor = mock(MessageDeliveryLoopMonitor.class);
when(device.getId()).thenReturn(DEVICE_ID);
when(device.isPrimary()).thenReturn(true);
dispatcher = new MessageDispatcher(
receiptSender,
messagesManager,
new MessageMetrics(),
pushNotificationManager,
pushNotificationScheduler,
messageDeliveryLoopMonitor,
disconnectionRequestManager,
mock(ClientReleaseManager.class));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void drainSingleMessage(final boolean mayHaveMoreMessages) {
final ServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final long timestamp = 17;
final Envelope message = createMessage(sourceServiceId, ACI, timestamp, "hello");
mockMessages(message);
final Flux<GetMessagesResponse> responses =
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
final Envelope expectedEnvelope = message.toBuilder().clearEphemeral().build();
when(messagesManager.mayHaveMessages(any(), any())).thenReturn(
CompletableFuture.completedFuture(mayHaveMoreMessages));
StepVerifier.create(responses)
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
.then(() -> verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), any()))
.thenCancel()
.verify(Duration.ofSeconds(5));
verify(messageDeliveryLoopMonitor, times(1))
.recordDeliveryAttempt(ACI, DEVICE_ID, UUIDUtil.fromByteString(message.getServerGuid()), TEST_UA, "grpc");
verify(disconnectionRequestManager).removeListener(eq(ACI), eq(DEVICE_ID), any());
verify(pushNotificationManager).handleMessagesRetrieved(account, device, TEST_UA);
verify(messagesManager).mayHaveMessages(ACI, device);
verify(pushNotificationScheduler, times(mayHaveMoreMessages ? 1 : 0))
.scheduleDelayedNotification(account, device, MessageDispatcher.CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
verifyNoInteractions(receiptSender);
}
@Test
void ackMessages() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
final List<UUID> guids = messages.stream().map(Envelope::getServerGuid).map(UUIDUtil::fromByteString).toList();
final List<Long> timestamps = messages.stream().map(Envelope::getServerTimestamp).toList();
final List<GetMessagesResponse> expectedMessages = messages.stream()
.map(e -> e.toBuilder().clearEphemeral().build())
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
.toList();
final MessageStream messageStream = mockMessages(messages);
final TestPublisher<UUID> acks = TestPublisher.create();
final Flux<GetMessagesResponse> responses =
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
StepVerifier.create(responses)
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
// Sending an ack should allow another message to come back
.then(() -> acks.next(guids.get(0)))
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES))
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(0), timestamps.get(0)))
.expectNoEvent(Duration.ofMillis(1))
// Send another one
.then(() -> acks.next(guids.get(1)))
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES + 1))
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(1), timestamps.get(1)))
.expectNoEvent(Duration.ofMillis(1))
.thenCancel()
.verify(Duration.ofSeconds(5));
verify(receiptSender, times(1))
.sendReceipt(new AciServiceIdentifier(ACI), DEVICE_ID, sourceServiceId, 0);
verify(receiptSender, times(1))
.sendReceipt(new AciServiceIdentifier(ACI), DEVICE_ID, sourceServiceId, 1);
verifyNoMoreInteractions(receiptSender);
}
@Test
void maxOutstandingAllowsGaps() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final int totalMessages = MessageDispatcher.MAX_UNACKED_MESSAGES * 2;
final List<Envelope> messages = IntStream
.range(0, totalMessages)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
final List<UUID> ackRequests = messages.stream()
.map(Envelope::getServerGuid).map(UUIDUtil::fromByteString)
.toList();
final List<GetMessagesResponse> expectedMessages = messages.stream()
.map(e -> e.toBuilder().clearEphemeral().build())
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
.toList();
mockMessages(messages);
final TestPublisher<UUID> acks = TestPublisher.create();
final Flux<GetMessagesResponse> responses =
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
StepVerifier.create(responses)
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> {
for (int i = 0; i < MessageDispatcher.MAX_UNACKED_MESSAGES; i++) {
if (i != 2) {
acks.next(ackRequests.get(i));
}
}
})
.expectNext(expectedMessages.subList(MessageDispatcher.MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> acks.next(ackRequests.get(2)))
.expectNext(expectedMessages.get(totalMessages - 1))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> {
for (int i = MessageDispatcher.MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
acks.next(ackRequests.get(i));
}
})
.expectNext(QUEUE_EMPTY)
.thenCancel()
.verify(Duration.ofSeconds(5));
}
@Test
void duplicateAckIgnored() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
final List<UUID> ackRequests = messages.stream()
.map(Envelope::getServerGuid).map(UUIDUtil::fromByteString)
.toList();
final TestPublisher<UUID> acks = TestPublisher.create();
mockMessages(messages);
StepVerifier
.create(dispatcher.getMessages(true, TEST_UA, account, device, acks.flux()))
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
.expectNoEvent(Duration.ofMillis(1))
// Ack a message, we should then get a new message
.then(() -> acks.next(ackRequests.get(0)))
.expectNextCount(1)
// Ack the same message again, there should be no additional message (or error)
.then(() -> acks.next(ackRequests.get(0)))
.expectNoEvent(Duration.ofMillis(1))
// Ack a different message, we should get a message back
.then(() -> acks.next(ackRequests.get(1)))
.expectNextCount(1)
.thenCancel()
.verify(Duration.ofSeconds(5));
}
@Test
void disconnectionRequest() {
final ServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final long timestamp = 17;
final Envelope message = createMessage(sourceServiceId, ACI, timestamp, "hello");
final Envelope expectedEnvelope = message.toBuilder().clearEphemeral().build();
mockMessages(message);
final Flux<GetMessagesResponse> responses =
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
ArgumentCaptor<DisconnectionRequestListener> listener = ArgumentCaptor.forClass(DisconnectionRequestListener.class);
StepVerifier.create(responses)
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
.then(() -> {
verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), listener.capture());
listener.getValue().handleDisconnectionRequest();
})
.expectNext(REQUIRES_REAUTH)
.verifyComplete();
}
@Test
void conflictingConsumer() {
mockMessages(Flux.error(new ConflictingMessageConsumerException()));
final Flux<GetMessagesResponse> responses =
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
StepVerifier.create(responses)
.expectNext(CONFLICTING_STREAM)
.verifyComplete();
}
@Test
void conflictingConsumerWhileWaitingForAcks() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<MessageStreamEntry.Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.map(MessageStreamEntry.Envelope::new)
.toList();
final TestPublisher<MessageStreamEntry> source = TestPublisher.create();
mockMessages(source.flux());
StepVerifier
.create(dispatcher.getMessages(true, TEST_UA, account, device, Flux.never()))
.then(() -> messages.forEach(source::next))
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
.expectNoEvent(Duration.ofMillis(1))
// The error should make it to us immediately even though there are max-unacked messages outstanding
.then(() -> source.error(new ConflictingMessageConsumerException()))
.expectNext(CONFLICTING_STREAM)
.verifyComplete();
}
/// Set envelopes to return when a message stream is created. A [MessageStreamEntry.QueueEmpty] will be emitted after
/// the provided messages
private MessageStream mockMessages(final List<MessageProtos.Envelope> messages) {
return mockMessages(messages.toArray(MessageProtos.Envelope[]::new));
}
/// Set envelopes to return when a message stream is created. A [MessageStreamEntry.QueueEmpty] will be emitted after
/// the provided messages
private MessageStream mockMessages(final MessageProtos.Envelope... messages) {
return mockMessages(Flux.concat(
Flux.fromStream(Arrays.stream(messages).map(MessageStreamEntry.Envelope::new)),
Flux.just(new MessageStreamEntry.QueueEmpty())));
}
private MessageStream mockMessages(final Flux<MessageStreamEntry> messages) {
final MessageStream mockMessageStream = mock(MessageStream.class);
when(mockMessageStream.getMessages()).thenReturn(JdkFlowAdapter.publisherToFlowPublisher(messages));
when(mockMessageStream.acknowledgeMessage(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.getMessages(ACI, device)).thenReturn(mockMessageStream);
return mockMessageStream;
}
private static Envelope createMessage(final ServiceIdentifier sourceId,
final UUID destinationUuid,
final long clientTimestamp,
final String content) {
final UUID serverGuid = UUID.randomUUID();
return Envelope.newBuilder()
.setServerGuid(UUIDUtil.toByteString(serverGuid))
.setType(Envelope.Type.CIPHERTEXT)
.setClientTimestamp(clientTimestamp)
.setServerTimestamp(0)
.setSourceServiceId(sourceId.toCompactByteString())
.setSourceDevice(SOURCE_DEVICE_ID)
.setDestinationServiceId(new AciServiceIdentifier(destinationUuid).toCompactByteString())
.setContent(ByteString.copyFrom(content.getBytes(StandardCharsets.UTF_8)))
.build();
}
}
@@ -6,11 +6,15 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -20,7 +24,11 @@ import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.grpc.Channel;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.BlockingClientCall;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
@@ -29,18 +37,30 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.mockito.Mock;
import org.signal.chat.messages.ChallengeRequired;
import org.signal.chat.messages.GetMessagesRequest;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.IndividualRecipientMessageBundle;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.MessagesGrpc;
import org.signal.chat.messages.MismatchedDevices;
import org.signal.chat.messages.SendAuthenticatedSenderMessageRequest;
import org.signal.chat.messages.SendMessageAuthenticatedSenderResponse;
import org.signal.chat.messages.SendMessageType;
import org.signal.chat.messages.SendSyncMessageRequest;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
@@ -62,11 +82,16 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Flux;
import reactor.test.publisher.TestPublisher;
class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, MessagesGrpc.MessagesBlockingStub> {
class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, MessagesGrpc.MessagesBlockingV2Stub> {
@Mock
private AccountsManager accountsManager;
@@ -98,6 +123,9 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Mock
private Device secondLinkedDevice;
@Mock
private MessageDispatcher messageDispatcher;
private static final int AUTHENTICATED_REGISTRATION_ID = 7;
private static final byte LINKED_DEVICE_ID = AUTHENTICATED_DEVICE_ID + 1;
@@ -108,6 +136,11 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
@Override
protected MessagesGrpc.MessagesBlockingV2Stub createStub(final Channel channel) {
return MessagesGrpc.newBlockingV2Stub(channel);
}
@Override
protected MessagesGrpcService createServiceBeforeEachTest() {
return new MessagesGrpcService(accountsManager,
@@ -115,11 +148,14 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
messageSender,
messageByteLimitEstimator,
spamChecker,
messageDispatcher,
CLOCK);
}
@BeforeEach
void setUp() {
CLOCK.pin(Instant.now());
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
when(rateLimiters.getInboundMessageBytes()).thenReturn(rateLimiter);
@@ -130,6 +166,8 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
when(authenticatedDevice.getId()).thenReturn(AUTHENTICATED_DEVICE_ID);
when(authenticatedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(AUTHENTICATED_REGISTRATION_ID);
when(authenticatedDevice.getLastSeen()).thenReturn(CLOCK.instant().toEpochMilli());
when(authenticatedDevice.isPrimary()).thenReturn(true);
when(linkedDevice.getId()).thenReturn(LINKED_DEVICE_ID);
when(linkedDevice.getRegistrationId(IdentityType.ACI)).thenReturn(LINKED_DEVICE_REGISTRATION_ID);
@@ -144,9 +182,12 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
when(authenticatedAccount.getDevice(LINKED_DEVICE_ID)).thenReturn(Optional.of(linkedDevice));
when(authenticatedAccount.getDevice(SECOND_LINKED_DEVICE_ID)).thenReturn(Optional.of(secondLinkedDevice));
when(authenticatedAccount.getDevices()).thenReturn(List.of(authenticatedDevice, linkedDevice, secondLinkedDevice));
when(authenticatedAccount.getPrimaryDevice()).thenReturn(authenticatedDevice);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI)))
.thenReturn(Optional.of(authenticatedAccount));
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(authenticatedAccount));
}
@Nested
@@ -157,7 +198,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@CartesianTest.Values(booleans = {true, false}) final boolean ephemeral,
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
@CartesianTest.Values(booleans = {true, false}) final boolean includeReportSpamToken)
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -252,7 +293,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.build());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
.sendMessage(generateRequest(serviceIdentifier, false, true, messages)));
verifyNoInteractions(messageSender);
@@ -260,7 +301,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Test
void mismatchedDevices()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -298,7 +339,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Test
void destinationNotFound()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final Map<Byte, IndividualRecipientMessageBundle.Message> messages =
@@ -343,7 +384,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.build());
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded(retryDuration,
assertRateLimitExceeded(retryDuration,
() -> authenticatedServiceStub().sendMessage(
generateRequest(serviceIdentifier, false, true, messages)));
@@ -374,7 +415,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().sendMessage(
generateRequest(serviceIdentifier, false, true, messages)));
}
@@ -407,7 +448,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
Optional.empty()));
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.RESOURCE_EXHAUSTED, () -> authenticatedServiceStub()
assertStatusException(Status.RESOURCE_EXHAUSTED, () -> authenticatedServiceStub()
.sendMessage(generateRequest(serviceIdentifier, false, true, messages)));
verify(spamChecker).checkForIndividualRecipientSpamGrpc(MessageType.INDIVIDUAL_IDENTIFIED_SENDER,
@@ -420,7 +461,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Test
void spamWithResponse()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
final byte deviceId = Device.PRIMARY_ID;
final int registrationId = 7;
@@ -489,7 +530,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
assertStatusException(Status.UNAVAILABLE,
() -> authenticatedServiceStub().sendMessage(generateRequest(serviceIdentifier, false, false, messages)));
}
@@ -520,7 +561,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
void sendMessage(@CartesianTest.Enum(mode = CartesianTest.Enum.Mode.EXCLUDE, names = {"UNSPECIFIED", "UNRECOGNIZED", "UNIDENTIFIED_SENDER"}) final SendMessageType messageType,
@CartesianTest.Values(booleans = {true, false}) final boolean urgent,
@CartesianTest.Values(booleans = {true, false}) final boolean includeReportSpamToken)
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(AUTHENTICATED_ACI);
final byte[] payload = TestRandomUtil.nextBytes(128);
@@ -604,7 +645,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
@Test
void mismatchedDevices()
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException {
throws MessageTooLargeException, MismatchedDevicesException, MessageDeliveryNotAllowedException, StatusException {
final byte missingDeviceId = Device.PRIMARY_ID;
final byte extraDeviceId = missingDeviceId + 1;
final byte staleDeviceId = extraDeviceId + 1;
@@ -650,7 +691,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.build());
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded(retryDuration, () ->
assertRateLimitExceeded(retryDuration, () ->
authenticatedServiceStub().sendSyncMessage(generateRequest(true, messages)));
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
@@ -680,7 +721,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub()
.sendSyncMessage( generateRequest( true, messages)));
}
@@ -707,7 +748,7 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
.when(messageSender).sendMessages(any(), any(), any(), any(), any(), any());
//noinspection ResultOfMethodCallIgnored,ThrowableNotThrown
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
assertStatusException(Status.UNAVAILABLE,
() -> authenticatedServiceStub().sendSyncMessage(generateRequest(false, messages)));
}
@@ -727,4 +768,65 @@ class MessagesGrpcServiceTest extends SimpleBaseGrpcTest<MessagesGrpcService, Me
return requestBuilder.build();
}
}
@Timeout(value = 1, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
@Nested
class Retrieval {
@Test
public void invalidFirstRequest() throws InterruptedException, StatusException {
final BlockingClientCall<GetMessagesRequest, GetMessagesResponse> blockingCall = authenticatedServiceStub().getMessages();
blockingCall.write(GetMessagesRequest.newBuilder().setServerGuidAck(UUIDUtil.toByteString(UUID.randomUUID())).build());
assertStatusException(Status.INVALID_ARGUMENT, () -> blockingCall.read());
}
static Stream<Arguments> invalidAckMessages() {
return Stream.of(
Arguments.argumentSet("Includes initial stream configuration", GetMessagesRequest.newBuilder()
.setOptions(GetMessagesRequest.GetMessageOptions.getDefaultInstance())
.build()),
Arguments.argumentSet("Missing ack guid", GetMessagesRequest.getDefaultInstance())
);
}
@ParameterizedTest
@MethodSource
void invalidAckMessages(final GetMessagesRequest request)
throws StatusException, InterruptedException, TimeoutException {
doAnswer(invocation -> {
Flux<UUID> ackArg = invocation.getArgument(4);
// use mapNotNull instead of `then` because there is an interaction between the blocking client and
// simple-grpc where losing the per-request demand (that is, requesting an item on every delivery) prevents
// the blocking write channel from accepting writes.
return ackArg.mapNotNull(_ -> null).cast(GetMessagesResponse.class);
}).when(messageDispatcher).getMessages(anyBoolean(), any(), any(), any(), any());
final BlockingClientCall<GetMessagesRequest, GetMessagesResponse> blockingCall = authenticatedServiceStub().getMessages();
final CompletableFuture<StatusException> reader = CompletableFuture.supplyAsync(() -> assertThrows(StatusException.class, () -> blockingCall.read()));
blockingCall.write(GetMessagesRequest.newBuilder().setOptions(GetMessagesRequest.GetMessageOptions.getDefaultInstance()).build());
blockingCall.write(request);
assertEquals(Status.INVALID_ARGUMENT.getCode(), reader.join().getStatus().getCode());
}
}
private static Executable convertStatusException(final Executable serviceCall) {
return () -> {
try {
serviceCall.execute();
} catch (final StatusException e) {
throw new StatusRuntimeException(e.getStatus(), e.getTrailers());
}
};
}
private static StatusRuntimeException assertStatusException(final Status expected, final Executable serviceCall) {
return GrpcTestUtils.assertStatusException(expected, convertStatusException(serviceCall));
}
private static void assertRateLimitExceeded(final Duration expectedRetryAfter, final Executable serviceCall) {
GrpcTestUtils.assertRateLimitExceeded(expectedRetryAfter, convertStatusException(serviceCall));
}
}
@@ -273,7 +273,7 @@ class WebSocketConnectionIntegrationTest {
when(successResponse.getStatus()).thenReturn(200);
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any()))
.thenAnswer(_ -> {
if (remainingMessages.addAndGet(-1) == 60) {
if (remainingMessages.decrementAndGet() == 60) {
sharedExecutorService.submit(() -> {
for (int i = 0; i < additionalMessageCount; i++) {
final UUID messageGuid = UUID.randomUUID();