Add server timestamp to all responses in message delivery streams

This commit is contained in:
Jonathan Klabunde Tomer authored and Jonathan Klabunde Tomer committed 2026-10-28 14:44:58 -07:00
1 parent 8e37334d2a
commit ca7a105f15
6 files changed
+33 -21

No files matched your search

@@ -1112,7 +1112,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
final MessageMetrics messageMetrics = new MessageMetrics();
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
pushNotificationManager, disconnectionRequestManager, clientReleaseManager);
pushNotificationManager, disconnectionRequestManager, clientReleaseManager, Clock.systemUTC());
final CertificateGenerator certificateGenerator =
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
@@ -8,6 +8,8 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.util.UUID;
import javax.annotation.Nullable;
@@ -51,8 +53,6 @@ public class MessageDispatcher {
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 StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
.setConflictingStream(Empty.getDefaultInstance())
@@ -66,19 +66,22 @@ public class MessageDispatcher {
private final PushNotificationManager pushNotificationManager;
private final ClientReleaseManager clientReleaseManager;
private final DisconnectionRequestManager disconnectionRequestManager;
private final Clock clock;
public MessageDispatcher(final ReceiptSender receiptSender,
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final DisconnectionRequestManager disconnectionRequestManager,
final ClientReleaseManager clientReleaseManager) {
final ClientReleaseManager clientReleaseManager,
final Clock clock) {
this.receiptSender = receiptSender;
this.messagesManager = messagesManager;
this.messageMetrics = messageMetrics;
this.pushNotificationManager = pushNotificationManager;
this.disconnectionRequestManager = disconnectionRequestManager;
this.clientReleaseManager = clientReleaseManager;
this.clock = clock;
}
/// Retrieve messages for the device.
@@ -144,7 +147,7 @@ public class MessageDispatcher {
final MessageProtos.Envelope stripped = envelope.toBuilder().clearEphemeral().build();
messageMetrics.measureAccountEnvelopeUuidMismatches(account, envelope);
messageMetrics.measureMessageSent(stripped.getSerializedSize());
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).build());
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).setServerTimeEpochMillis(clock.millis()).build());
}
case MessageStreamEntry.QueueEmpty _ -> {
pendingAcknowledgementTracker.markEndOfQueue();
@@ -190,7 +193,8 @@ public class MessageDispatcher {
// 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(),
pendingAcknowledgementTracker.queueDrained().map(
_ -> GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).setServerTimeEpochMillis(clock.millis()).build()),
// Emit an invalid credentials error if we receive a disconnection request
disconnectionSignal(account, device, userAgent))
.doFinally(_ -> maybeSendNewMessagePushNotification(account, device));
@@ -9,7 +9,6 @@ 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;
@@ -39,9 +38,8 @@ 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 Sinks.One<Boolean> queueDrained = Sinks.one();
private final ClosableEpoch queueDrainEpoch = new ClosableEpoch(() -> queueDrained.tryEmitValue(true));
private final Timer.Sample queueDrainStart = Timer.start();
private final MessageMetrics messageMetrics;
@@ -92,7 +90,7 @@ class PendingAcknowledgementTracker {
///
/// @return A mono that completes with a QueueEmpty response when all messages tracked before [#markEndOfQueue] have
/// been acknowledged.
Mono<GetMessagesResponse> queueDrained() {
Mono<Boolean> queueDrained() {
return queueDrained.asMono();
}
@@ -95,6 +95,12 @@ message GetMessagesResponse {
// to deliver newly arrived messages.
google.protobuf.Empty queue_empty = 2;
}
// The time, in milliseconds since the Unix epoch, at which this response
// was sent, according to the server's clock. This can be helpful for detecting
// clock drift between the client and server, which can be important for
// time-sensitive messages.
uint64 server_time_epoch_millis = 3;
}
// Provides methods for sending "sealed sender" messages.
@@ -160,7 +160,8 @@ class MessageDispatcherIntegrationTest {
new MessageMetrics(),
mock(PushNotificationManager.class),
disconnectionRequestManager,
mock(ClientReleaseManager.class));
mock(ClientReleaseManager.class),
Clock.systemUTC());
}
@AfterEach
@@ -20,7 +20,9 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.grpc.Status;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@@ -38,7 +40,6 @@ 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.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
@@ -52,6 +53,7 @@ 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.TestClock;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
@@ -60,13 +62,13 @@ import reactor.test.publisher.TestPublisher;
class MessageDispatcherTest {
private static final GetMessagesResponse QUEUE_EMPTY =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).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 static final Clock CLOCK = TestClock.pinned(Instant.now());
private static final GetMessagesResponse QUEUE_EMPTY =
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).setServerTimeEpochMillis(CLOCK.millis()).build();
private Account account;
private Device device;
@@ -97,7 +99,8 @@ class MessageDispatcherTest {
new MessageMetrics(),
pushNotificationManager,
disconnectionRequestManager,
mock(ClientReleaseManager.class));
mock(ClientReleaseManager.class),
CLOCK);
}
@ParameterizedTest
@@ -117,7 +120,7 @@ class MessageDispatcherTest {
CompletableFuture.completedFuture(mayHaveMoreMessages));
StepVerifier.create(responses)
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).build())
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).setServerTimeEpochMillis(CLOCK.millis()).build())
.then(() -> verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), any()))
.thenCancel()
.verify(Duration.ofSeconds(5));
@@ -143,7 +146,7 @@ class MessageDispatcherTest {
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())
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).setServerTimeEpochMillis(CLOCK.millis()).build())
.toList();
final MessageStream messageStream = mockMessages(messages);
@@ -194,7 +197,7 @@ class MessageDispatcherTest {
.toList();
final List<GetMessagesResponse> expectedMessages = messages.stream()
.map(e -> e.toBuilder().clearEphemeral().build())
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).build())
.map(e -> GetMessagesResponse.newBuilder().setEnvelope(e).setServerTimeEpochMillis(CLOCK.millis()).build())
.toList();
mockMessages(messages);
@@ -276,7 +279,7 @@ class MessageDispatcherTest {
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())
.expectNext(GetMessagesResponse.newBuilder().setEnvelope(expectedEnvelope).setServerTimeEpochMillis(CLOCK.millis()).build())
.then(() -> {
verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), listener.capture());
listener.getValue().handleDisconnectionRequest();