Compare commits

...
22 changed files with 182 additions and 66 deletions

No files matched your search

@@ -992,7 +992,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters,
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()))
gcsAttachmentGenerator, tusAttachmentGenerator, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new PaymentsGrpcService(currencyManager))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1010,7 +1011,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, zkSecretParams),
new PaymentsGrpcService(currencyManager),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
ExternalServiceCredentialsAnonymousGrpcService.create(accountsManager, config))
@@ -82,6 +82,7 @@ import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExcepti
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotification;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.registration.ClientType;
@@ -655,8 +656,12 @@ public class VerificationController {
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount ->
pushNotificationManager.trySendVerificationCodeRequestedNotifications(existingAccount, clock.instant()));
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} catch (final NotPushRegisteredException _) {
}
});
} catch (final CancellationException e) {
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
} catch (final CompletionException e) {
@@ -6,11 +6,14 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.signal.chat.account.ClearRegistrationLockRequest;
import org.signal.chat.account.ClearRegistrationLockResponse;
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
@@ -62,6 +65,8 @@ import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
@@ -276,14 +281,24 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final byte[] zkCredentialKey = request.getPublicKey().toByteArray();
if (Arrays.equals(authenticatedAccount.getZkCredentialKey(), zkCredentialKey)) {
return SetZkCredentialKeyResponse.getDefaultInstance();
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(Objects.requireNonNull(authenticatedAccount.getZkCredentialKeyRotationId()))
.build();
}
rateLimiters.getSetZkCredentialKeyLimiter().validate(authenticatedDevice.accountIdentifier());
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> account.setZkCredentialKey(zkCredentialKey));
// It is technically fine from the credential's perspective if it is zero, but it's clearer to never have the default value
final long rotationId = SECURE_RANDOM.nextLong(1, Long.MAX_VALUE);
return SetZkCredentialKeyResponse.getDefaultInstance();
accountsManager.update(authenticatedDevice.accountIdentifier(), account -> {
account.setZkCredentialKey(zkCredentialKey);
account.setZkCredentialKeyRotationId(rotationId);
});
return SetZkCredentialKeyResponse.newBuilder()
.setRotationId(rotationId)
.build();
}
private Account getAuthenticatedAccount() {
@@ -19,6 +19,7 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -31,6 +32,7 @@ public class DeviceCapabilityUtil {
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
};
}
}
@@ -138,6 +138,10 @@ public class CallQualitySurveyManager {
pubSubMessageBuilder.setCallTelemetry(submitCallQualitySurveyRequest.getCallTelemetry());
}
if (submitCallQualitySurveyRequest.hasCallIdHash()) {
pubSubMessageBuilder.setCallIdHash(submitCallQualitySurveyRequest.getCallIdHash());
}
GoogleApiUtil.toCompletableFuture(pubSubPublisher.publish(PubsubMessage.newBuilder()
.setData(pubSubMessageBuilder.build().toByteString())
.build()), pubSubCallbackExecutor)
@@ -87,26 +87,21 @@ public class PushNotificationManager {
.thenApply(maybeResponse -> maybeResponse.orElseThrow(() -> new AssertionError("Responses must be present for urgent notifications")));
}
public CompletableFuture<Void> trySendVerificationCodeRequestedNotifications(final Account destination, final Instant requestTimestamp) {
final List<CompletableFuture<?>> sendNotificationFutures = new ArrayList<>();
public CompletableFuture<SendPushNotificationResult> sendVerificationCodeRequestedNotifications(final Account destination, final Instant requestTimestamp)
throws NotPushRegisteredException {
for (final Device device : destination.getDevices()) {
try {
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(device);
final Pair<String, PushNotification.TokenType> tokenAndType = getToken(destination.getPrimaryDevice());
sendNotificationFutures.add(sendNotification(new PushNotification(tokenAndType.first(),
tokenAndType.second(),
PushNotification.NotificationType.VERIFICATION_CODE_REQUESTED,
new VerificationCodeRequestData(requestTimestamp.toEpochMilli()),
destination,
device,
true,
VERIFICATION_CODE_TTL)));
} catch (final NotPushRegisteredException _) {
}
}
return CompletableFuture.allOf(sendNotificationFutures.toArray(CompletableFuture[]::new));
return sendNotification(new PushNotification(tokenAndType.first(),
tokenAndType.second(),
PushNotification.NotificationType.VERIFICATION_CODE_REQUESTED,
new VerificationCodeRequestData(requestTimestamp.toEpochMilli()),
destination,
destination.getPrimaryDevice(),
true,
VERIFICATION_CODE_TTL))
.thenApply(maybeResponse -> maybeResponse.orElseThrow(
() -> new AssertionError("Responses must be present for urgent notifications")));
}
public void handleMessagesRetrieved(final Account account, final Device device, final String userAgent) {
@@ -17,7 +17,6 @@ import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
@@ -131,6 +130,10 @@ public class Account {
@Nullable
private byte[] zkCredentialKey;
@JsonProperty("zckr")
@Nullable
private Long zkCredentialKeyRotationId;
@JsonProperty
private int version;
@@ -566,6 +569,15 @@ public class Account {
this.zkCredentialKey = zkCredentialKey;
}
@Nullable
public Long getZkCredentialKeyRotationId() {
return zkCredentialKeyRotationId;
}
public void setZkCredentialKeyRotationId(@Nullable final Long zkCredentialKeyRotationId) {
this.zkCredentialKeyRotationId = zkCredentialKeyRotationId;
}
public void markStale() {
stale = true;
}
@@ -16,7 +16,8 @@ public enum DeviceCapability {
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false);
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false),
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, true, true, false);
public enum AccountCapabilityMode {
/**
@@ -263,17 +263,18 @@ public class FoundationDbMessageStore {
public MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice) {
return getMessages(aci, destinationDevice, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
Util.NOOP);
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
}
@VisibleForTesting
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice,
final int maxMessagesPerScan, final Runnable doAfterCleanup) {
final int maxMessagesPerScan, final int maxUnacknowledgedMessages, final Runnable doAfterCleanup) {
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
getMessagesAvailableWatchKey(aci),
getShardForAci(aci),
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
maxMessagesPerScan,
maxUnacknowledgedMessages,
doAfterCleanup);
}
@@ -14,7 +14,6 @@ import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.apple.foundationdb.tuple.ByteArrayUtil;
import com.apple.foundationdb.tuple.Tuple;
@@ -40,13 +39,18 @@ public class FoundationDbMessageStream implements MessageStream {
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
private final int maxUnacknowledgedMessages;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
private int unacknowledgedMessages = 0;
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
@VisibleForTesting
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
@@ -55,6 +59,7 @@ public class FoundationDbMessageStream implements MessageStream {
final Database database,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final int maxUnacknowledgedMessages,
final Runnable doAfterCleanup) {
this.deviceQueueSubspace = deviceQueueSubspace;
@@ -62,6 +67,7 @@ public class FoundationDbMessageStream implements MessageStream {
this.database = database;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
}
@@ -78,10 +84,15 @@ public class FoundationDbMessageStream implements MessageStream {
/// first to keep track of versionstamps sent to the client.
private Flux<MessageStreamEntry> createMessagePublisher() {
return createFoundationDbMessagePublisher()
.doOnNext(messageStreamEntry -> {
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
onVersionstampSent(message.versionstamp());
final int numUnacknowledgedMessages = onVersionstampSent(message.versionstamp());
if (numUnacknowledgedMessages > maxUnacknowledgedMessages) {
sink.error(new TooManyUnacknowledgedMessagesException());
return;
}
}
sink.next(messageStreamEntry);
})
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
@@ -151,12 +162,17 @@ public class FoundationDbMessageStream implements MessageStream {
return;
}
unacknowledgedMessages--;
sentVersionstamps.put(versionstamp, true);
}
/// Returns the number of unacknowledged messages after sending the provided versionstamp
///
/// @param versionstamp The versionstamp being sent
@VisibleForTesting
synchronized void onVersionstampSent(final Versionstamp versionstamp) {
synchronized int onVersionstampSent(final Versionstamp versionstamp) {
sentVersionstamps.put(versionstamp, false);
return ++unacknowledgedMessages;
}
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
@@ -0,0 +1,9 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.foundationdb;
public class TooManyUnacknowledgedMessagesException extends RuntimeException {
}
@@ -125,4 +125,9 @@ message CallQualitySurveyResponsePubSubMessage {
// call; this is a serialized protobuf entity generated (and, critically,
// explained to the user!) by the calling library
optional bytes call_telemetry = 27;
// A hash of a call ID (shared between clients and never sent to the calling
// server) that can be used to correlate survey responses from multiple
// participants in a call
optional bytes call_id_hash = 28;
}
@@ -275,4 +275,9 @@ message SetZkCredentialKeyRequest {
}
message SetZkCredentialKeyResponse {
// A random, non-zero, value that must be included in credential requests using the key.
//
// This value allows the server to ratchet the resulting binding identity,
// as reverting to the previous key will result in a new rotation ID.
uint64 rotation_id = 1;
}
@@ -104,6 +104,11 @@ message SubmitCallQualitySurveyRequest {
// entity generated (and, critically, explained to the user!) by the calling
// library
optional bytes call_telemetry = 21;
// A hash of a call ID (shared between clients and never sent to the calling
// server) that can be used to correlate survey responses from multiple
// participants in a call
optional bytes call_id_hash = 22;
}
message SubmitCallQualitySurveyResponse {
@@ -84,6 +84,7 @@ enum DeviceCapability {
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
DEVICE_CAPABILITY_PROFILES_V2 = 8;
DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE = 9;
}
message ZkCredential {
@@ -75,6 +75,7 @@ import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptio
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.registration.RegistrationFraudException;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
@@ -1079,7 +1080,8 @@ class VerificationControllerTest {
@CartesianTest
void requestVerificationCodeSuccess(@CartesianTest.Values(booleans = {true, false}) final boolean accountExistsWithNumber,
@CartesianTest.Values(booleans = {true, false}) final boolean enrolledInExperiment) {
@CartesianTest.Values(booleans = {true, false}) final boolean enrolledInExperiment)
throws NotPushRegisteredException {
final String encodedSessionId = encodeSessionId(SESSION_ID);
final RegistrationServiceSession registrationServiceSession = new RegistrationServiceSession(SESSION_ID, NUMBER,
false, null, null,
@@ -1118,9 +1120,9 @@ class VerificationControllerTest {
assertTrue(verificationSessionResponse.requestedInformation().isEmpty());
if (accountExistsWithNumber && enrolledInExperiment) {
verify(pushNotificationManager).trySendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
verify(pushNotificationManager).sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
} else {
verify(pushNotificationManager, never()).trySendVerificationCodeRequestedNotifications(any(), any());
verify(pushNotificationManager, never()).sendVerificationCodeRequestedNotifications(any(), any());
}
}
}
@@ -26,6 +26,7 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -55,6 +56,7 @@ import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
@@ -708,21 +710,29 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
void setZkCredentialKey(final boolean matchesCurrentZkCredentialKey) {
final byte[] publicKey = TestRandomUtil.nextBytes(33);
final long rotationId = ThreadLocalRandom.current().nextLong(1, Long.MAX_VALUE);
final Account account = mock(Account.class);
if (matchesCurrentZkCredentialKey) {
when(account.getZkCredentialKey()).thenReturn(publicKey);
when(account.getZkCredentialKeyRotationId()).thenReturn(rotationId);
}
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
assertDoesNotThrow(() ->
final SetZkCredentialKeyResponse response = assertDoesNotThrow(() ->
authenticatedServiceStub().setZkCredentialKey(SetZkCredentialKeyRequest.newBuilder()
.setPublicKey(ByteString.copyFrom(publicKey))
.build()));
if (matchesCurrentZkCredentialKey) {
assertEquals(rotationId, response.getRotationId());
} else {
assertTrue(response.getRotationId() != 0);
}
final int updateMethodCalls = matchesCurrentZkCredentialKey ? 0 : 1;
verify(accountsManager, times(updateMethodCalls)).update(eq(AUTHENTICATED_ACI), any());
@@ -426,9 +426,9 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@CartesianTest.Values(bytes = {Device.PRIMARY_ID, Device.PRIMARY_ID + 1}) final byte deviceId,
@CartesianTest.Values(booleans = {true, false}) final boolean storage,
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
@CartesianTest.Values(booleans = {true, false}) final boolean deleteSync,
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill,
@CartesianTest.Values(booleans = {true, false}) final boolean spqr) {
@CartesianTest.Values(booleans = {true, false}) final boolean spqr,
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage) {
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
@@ -453,6 +453,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET);
}
if (usernameChangeSyncMessage) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE);
}
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
final Set<DeviceCapability> expectedCapabilities = new HashSet<>();
@@ -474,6 +478,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
expectedCapabilities.add(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET);
}
if (usernameChangeSyncMessage) {
expectedCapabilities.add(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE);
}
verify(device).setCapabilities(expectedCapabilities);
}
}
@@ -67,6 +67,7 @@ class CallQualitySurveyManagerTest {
final String asnRegion = "US";
final byte[] telemetryBytes = TestRandomUtil.nextBytes(32);
final byte[] callIdHashBytes = TestRandomUtil.nextBytes(16);
final float connectionRttMedian = ThreadLocalRandom.current().nextFloat();
final float audioRttMedian = ThreadLocalRandom.current().nextFloat();
@@ -105,6 +106,7 @@ class CallQualitySurveyManagerTest {
.setAudioSendPacketLossFraction(audioSendPacketLossFraction)
.setVideoSendPacketLossFraction(videoSendPacketLossFraction)
.setCallTelemetry(ByteString.copyFrom(telemetryBytes))
.setCallIdHash(ByteString.copyFrom(callIdHashBytes))
.build();
//noinspection unchecked
@@ -145,6 +147,7 @@ class CallQualitySurveyManagerTest {
assertEquals(audioSendPacketLossFraction, callQualitySurveyResponsePubSubMessage.getAudioSendPacketLossFraction());
assertEquals(videoSendPacketLossFraction, callQualitySurveyResponsePubSubMessage.getVideoSendPacketLossFraction());
assertArrayEquals(telemetryBytes, callQualitySurveyResponsePubSubMessage.getCallTelemetry().toByteArray());
assertArrayEquals(callIdHashBytes, callQualitySurveyResponsePubSubMessage.getCallIdHash().toByteArray());
}
@ParameterizedTest
@@ -409,7 +409,7 @@ class FoundationDbMessageStoreTest {
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize,
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device, batchSize, numMessages,
Util.NOOP);
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
@@ -462,20 +462,19 @@ class FoundationDbMessageStoreTest {
final CountDownLatch latch = new CountDownLatch(1);
final MessageProtos.Envelope message3 = generateRandomMessage(false);
final AtomicReference<Versionstamp> versionstamp3 = new AtomicReference<>();
final CompletableFuture<Versionstamp> versionstamp3 = new CompletableFuture<>();
Thread.ofVirtual().start(() -> {
try {
// Wait until queue is empty
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
// Then publish more messages
synchronized (versionstamp3) {
versionstamp3.set(foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message3)).join()
.get(Device.PRIMARY_ID)
.versionstamp()
.orElseThrow());
versionstamp3.notifyAll();
}
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, message3))
.thenAccept(result -> {
result.get(Device.PRIMARY_ID)
.versionstamp()
.ifPresentOrElse(versionstamp3::complete,
() -> versionstamp3.completeExceptionally(new RuntimeException("versionstamp absent")));
});
} catch (final InterruptedException e) {
fail(e);
}
@@ -494,24 +493,11 @@ class FoundationDbMessageStoreTest {
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp2)))
.build()))
.expectNext(new MessageStreamEntry.QueueEmpty())
.then(() -> {
// Trigger insertion of another message
latch.countDown();
// …but then wait for its versionstamp so we can verify that we have the right payload
synchronized (versionstamp3) {
while (versionstamp3.get() == null) {
try {
versionstamp3.wait();
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
}
}
})
// Trigger insertion of another message
.then(latch::countDown)
.expectNextMatches(entry -> entry.equals(new MessageStreamEntry.Envelope(message3
.toBuilder()
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp3.get())))
.setServerGuidBinary(UUIDUtil.toByteString(messageGuidCodec.encodeMessageGuid(versionstamp3.join())))
.build())))
.verifyTimeout(Duration.ofSeconds(3));
}
@@ -578,6 +564,7 @@ class FoundationDbMessageStoreTest {
final CountDownLatch latch = new CountDownLatch(1);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
latch::countDown);
final List<CompletableFuture<Void>> acknowledgeFutures = new ArrayList<>();
final AtomicInteger messageCounter = new AtomicInteger(0);
@@ -632,6 +619,35 @@ class FoundationDbMessageStoreTest {
);
}
@Test
void outstandingUnacknowledgedMessages() {
final int numMessages = 5;
final int maxUnacknowledgedMessages = 3;
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
writePresenceKey(aci, Device.PRIMARY_ID, 1, 5L);
final List<Versionstamp> versionstamps = IntStream.range(0, numMessages)
.mapToObj(
_ -> foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join()
.get(Device.PRIMARY_ID)
.versionstamp()
.orElseThrow())
.toList();
final Device device = new Device();
device.setId(Device.PRIMARY_ID);
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device,
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
maxUnacknowledgedMessages,
Util.NOOP);
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), numMessages)
.expectNextCount(maxUnacknowledgedMessages)
.expectError(TooManyUnacknowledgedMessagesException.class)
.verify();
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
return generateRandomMessage(ephemeral, 16);
}
@@ -29,6 +29,7 @@ class FoundationDbMessageStreamTest {
mock(Database.class),
mock(MessageGuidCodec.class),
100,
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
Util.NOOP
);