mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:56:47 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
569f4f31e8 | ||
|
|
06519ce9d1 | ||
|
|
024fa9ce5f | ||
|
|
7c9e3d029b | ||
|
|
cc6ef53f91 | ||
|
|
4c0f454209 | ||
|
|
9c393972e9 | ||
|
|
31c1bb8940 | ||
|
|
c3b2b43813 | ||
|
|
19f2574799 |
No files matched your search
@@ -400,7 +400,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
@Override
|
||||
public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
|
||||
final Clock clock = Clock.systemUTC();
|
||||
final int availableProcessors = Runtime.getRuntime().availableProcessors();
|
||||
|
||||
final AwsCredentialsProvider awsCredentialsProvider = config.getAwsCredentialsConfiguration().build();
|
||||
|
||||
|
||||
+3
-3
@@ -86,7 +86,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
public CompletionStage<Void> copy(
|
||||
final int sourceCdn,
|
||||
final String sourceKey,
|
||||
final int expectedSourceLength,
|
||||
final long expectedSourceLength,
|
||||
final MediaEncryptionParameters encryptionParameters,
|
||||
final String destinationKey) {
|
||||
final String sourceScheme = this.sourceSchemes.get(sourceCdn);
|
||||
@@ -132,10 +132,10 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
|
||||
*/
|
||||
record Cdn3CopyRequest(
|
||||
String encryptionKey, String hmacKey,
|
||||
SourceDescriptor source, int expectedSourceLength,
|
||||
SourceDescriptor source, long expectedSourceLength,
|
||||
String dst) {
|
||||
|
||||
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, int expectedSourceLength,
|
||||
Cdn3CopyRequest(MediaEncryptionParameters parameters, SourceDescriptor source, long expectedSourceLength,
|
||||
String dst) {
|
||||
this(Base64.getEncoder().encodeToString(parameters.aesEncryptionKey().getEncoded()),
|
||||
Base64.getEncoder().encodeToString(parameters.hmacSHA256Key().getEncoded()),
|
||||
|
||||
@@ -18,7 +18,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
public record CopyParameters(
|
||||
int sourceCdn,
|
||||
String sourceKey,
|
||||
int sourceLength,
|
||||
long sourceLength,
|
||||
MediaEncryptionParameters encryptionParameters,
|
||||
byte[] destinationMediaId) {
|
||||
|
||||
@@ -35,16 +35,17 @@ public record CopyParameters(
|
||||
///
|
||||
/// @return the size, in bytes, of the ciphertext of a media object with the given `inputSize`
|
||||
@VisibleForTesting
|
||||
static long destinationObjectSize(final int inputSize) {
|
||||
static long destinationObjectSize(final long inputSize) {
|
||||
if (inputSize < 0) {
|
||||
throw new IllegalArgumentException("Size must be non-negative, but was " + inputSize);
|
||||
}
|
||||
|
||||
// AES-256 has 16-byte block size, and always adds a block if the plaintext is a multiple of the block size
|
||||
final long numBlocks = ((long) inputSize + 16) / 16;
|
||||
final long numBlocks = Math.addExact(inputSize, 16L) / 16;
|
||||
final long cipherTextLength = Math.multiplyExact(numBlocks, 16);
|
||||
|
||||
// 16-byte IV will be generated and prepended to the ciphertext
|
||||
// 16-byte IV will be generated and prepended to the ciphertext.
|
||||
// IV + AES-256 encrypted data + HmacSHA256
|
||||
return 16 + (numBlocks * 16) + 32;
|
||||
return Math.addExact(cipherTextLength, 16L + 32);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -35,7 +35,7 @@ public interface RemoteStorageManager {
|
||||
CompletionStage<Void> copy(
|
||||
int sourceCdn,
|
||||
String sourceKey,
|
||||
int expectedSourceLength,
|
||||
long expectedSourceLength,
|
||||
MediaEncryptionParameters encryptionParameters,
|
||||
String dstKey);
|
||||
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public record FoundationDbClusterConfiguration(@Nullable String clusterFileUrl,
|
||||
@Nullable String clusterFileContents) {
|
||||
|
||||
@AssertTrue
|
||||
public boolean isSingleClusterFileSourceSpecified() {
|
||||
return StringUtils.isBlank(clusterFileUrl) ^ StringUtils.isBlank(clusterFileContents);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
|
||||
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbClusterConfiguration> clusters,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
|
||||
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch) {
|
||||
|
||||
@AssertTrue
|
||||
boolean isEveryEpochClusterConfigured() {
|
||||
for (final List<String> clustersInEpoch : epochs().values()) {
|
||||
for (final String cluster : clustersInEpoch) {
|
||||
if (!clusters.containsKey(cluster)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
boolean isEveryEpochFreeOfDuplicates() {
|
||||
for (final List<String> clustersInEpoch : epochs().values()) {
|
||||
if (new HashSet<>(clustersInEpoch).size() != clustersInEpoch.size()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
boolean isActiveEpochConfigured() {
|
||||
return epochs().containsKey(activeEpoch());
|
||||
}
|
||||
}
|
||||
+14
-21
@@ -8,6 +8,7 @@ import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.signal.chat.backup.BackupStreamClosed;
|
||||
import org.signal.chat.backup.CopyMediaRequest;
|
||||
import org.signal.chat.backup.CopyMediaResponse;
|
||||
import org.signal.chat.backup.DeleteAllRequest;
|
||||
@@ -223,15 +224,16 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
copyQuota = backupManager.getCopyQuota(backupUser,
|
||||
request.getItemsList().stream().map(item -> new CopyParameters(
|
||||
item.getSourceAttachmentCdn(), item.getSourceKey(),
|
||||
// uint32 in proto, make sure it fits in a signed int
|
||||
fromUnsignedExact(item.getObjectLength()),
|
||||
item.getObjectLength(),
|
||||
new MediaEncryptionParameters(item.getEncryptionKey().toByteArray(), item.getHmacKey().toByteArray()),
|
||||
item.getMediaId().toByteArray())).toList(), maxAttachmentSize);
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
|
||||
.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build()));
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
|
||||
.setDescription(e.getMessage())
|
||||
.build())
|
||||
.build())));
|
||||
}
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(
|
||||
@@ -308,10 +310,12 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
|
||||
.toList());
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
|
||||
.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build()));
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
Mono.error(GrpcExceptions.streamClosed(BackupStreamClosed.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder()
|
||||
.setDescription(e.getMessage())
|
||||
.build())
|
||||
.build())));
|
||||
}
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
|
||||
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
|
||||
@@ -346,17 +350,6 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
|
||||
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
|
||||
*/
|
||||
private static int fromUnsignedExact(final int i) {
|
||||
if (i < 0) {
|
||||
throw GrpcExceptions.invalidArguments("integer length too large");
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
T deserialize(byte[] bytes) throws InvalidInputException, InvalidKeyException;
|
||||
|
||||
+32
@@ -8,8 +8,12 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.credentials.ExternalServiceType;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
|
||||
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
|
||||
@@ -19,8 +23,10 @@ import org.signal.chat.credentials.GetGroupCredentialsResponse;
|
||||
import org.signal.chat.credentials.SimpleCredentialsGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -133,4 +139,30 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
|
||||
rateLimiters.getCreateCallLinkLimiter().validate(accountIdentifier);
|
||||
|
||||
final Instant truncatedDayTimestamp = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
try {
|
||||
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
|
||||
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
|
||||
|
||||
return GetCreateCallLinkCredentialsResponse.newBuilder()
|
||||
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
|
||||
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
|
||||
new ServiceId.Aci(accountIdentifier),
|
||||
truncatedDayTimestamp,
|
||||
serverSecretParams)
|
||||
.serialize()))
|
||||
.build();
|
||||
} catch (final InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("Invalid 'create call link credential' request");
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class ErrorConformanceInterceptor implements ServerInterceptor {
|
||||
}
|
||||
|
||||
switch (status.getCode()) {
|
||||
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED -> {
|
||||
case UNAUTHENTICATED, UNAVAILABLE, INVALID_ARGUMENT, RESOURCE_EXHAUSTED, ABORTED -> {
|
||||
}
|
||||
default -> {
|
||||
log.error("Intercepted call {} returned illegal application status {}: {}",
|
||||
|
||||
@@ -39,6 +39,11 @@ public class GrpcExceptions {
|
||||
.setReason("BAD_AUTHENTICATION")
|
||||
.build());
|
||||
|
||||
private static final Any ERROR_INFO_STREAM_CLOSED = Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("STREAM_CLOSED")
|
||||
.build());
|
||||
|
||||
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage("Upgrade required")
|
||||
@@ -144,6 +149,20 @@ public class GrpcExceptions {
|
||||
return StatusProto.toStatusRuntimeException(builder.build());
|
||||
}
|
||||
|
||||
/// The server terminated the stream non-successfully for a reason specific to the RPC. The server must provide
|
||||
/// additional information about the stream closure reason via the `streamClosedMessage`.
|
||||
///
|
||||
/// @param streamClosedMessage The additional domain-specific proto message that indicates the closure reason
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static <T extends com.google.protobuf.Message> StatusRuntimeException streamClosed(
|
||||
final T streamClosedMessage) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.ABORTED.value())
|
||||
.addDetails(ERROR_INFO_STREAM_CLOSED)
|
||||
.addDetails(Any.pack(streamClosedMessage))
|
||||
.build());
|
||||
}
|
||||
|
||||
public static StatusRuntimeException unavailable() {
|
||||
return unavailable(null);
|
||||
}
|
||||
|
||||
+21
-26
@@ -6,11 +6,13 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
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.signal.chat.messages.GetMessagesStreamClosed;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
@@ -54,14 +56,10 @@ public class MessageDispatcher {
|
||||
|
||||
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 StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
|
||||
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
|
||||
.setConflictingStream(Empty.getDefaultInstance())
|
||||
.build());
|
||||
|
||||
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(MessageDispatcher.class, "sendMessages");
|
||||
|
||||
@@ -99,8 +97,8 @@ public class MessageDispatcher {
|
||||
/// 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.
|
||||
/// The returned flux will error with a [GrpcExceptions#streamClosed] non-ok status exception 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
|
||||
@@ -167,7 +165,11 @@ public class MessageDispatcher {
|
||||
pendingAcknowledgementTracker.markEndOfQueue();
|
||||
yield Mono.empty();
|
||||
}
|
||||
}, MAX_UNACKED_MESSAGES);
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
|
||||
return CONFLICTING_STREAM_EXCEPTION;
|
||||
});
|
||||
|
||||
// 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.
|
||||
@@ -204,18 +206,8 @@ public class MessageDispatcher {
|
||||
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");
|
||||
})
|
||||
// Emit an invalid credentials error if we receive a disconnection request
|
||||
disconnectionSignal(account, device, userAgent))
|
||||
.doFinally(_ -> maybeSchedulePush(account, device));
|
||||
}
|
||||
|
||||
@@ -232,11 +224,14 @@ public class MessageDispatcher {
|
||||
|
||||
/// Watch for a disconnection signal from the [DisconnectionRequestManager]
|
||||
///
|
||||
/// @return Mono that completes with a [org.signal.chat.messages.GetMessagesResponse.Terminated] response if the
|
||||
/// @return Mono that completes with an `InvalidCredentials` status if the
|
||||
/// device receives a disconnection request
|
||||
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device) {
|
||||
private Mono<GetMessagesResponse> disconnectionSignal(final Account account, final Device device, final UserAgent userAgent) {
|
||||
return Mono.create(sink -> {
|
||||
final DisconnectionRequestListener listener = () -> sink.success(REAUTHENTICATION_REQUIRED_RESPONSE);
|
||||
final DisconnectionRequestListener listener = () -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
|
||||
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
|
||||
};
|
||||
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
|
||||
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
|
||||
});
|
||||
|
||||
+1
-1
@@ -350,7 +350,7 @@ public class MessagePersister implements Managed {
|
||||
cachedMessageBytes.set(estimatedPersistedQueueSize);
|
||||
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
|
||||
|
||||
return Flux.from(messagesManager.getMessagesForDeviceReactive(aci, device, false))
|
||||
return Flux.from(messagesManager.getMessagesForDevice(aci, device))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
|
||||
+4
-27
@@ -23,7 +23,6 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.slf4j.Logger;
|
||||
@@ -33,7 +32,6 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -41,7 +39,6 @@ import reactor.core.publisher.Mono;
|
||||
|
||||
public class MessagesManager {
|
||||
|
||||
private static final int RESULT_SET_CHUNK_SIZE = 100;
|
||||
final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = name(MessagesManager.class, "getMessagesForDevice");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);
|
||||
@@ -217,34 +214,14 @@ public class MessagesManager {
|
||||
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
|
||||
}
|
||||
|
||||
public Mono<Pair<List<Envelope>, Boolean>> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
boolean cachedMessagesOnly) {
|
||||
|
||||
return Flux.from(
|
||||
getMessagesForDevice(destinationUuid, destinationDevice, RESULT_SET_CHUNK_SIZE, cachedMessagesOnly))
|
||||
.take(RESULT_SET_CHUNK_SIZE)
|
||||
.collectList()
|
||||
.map(envelopes -> new Pair<>(envelopes, envelopes.size() >= RESULT_SET_CHUNK_SIZE));
|
||||
}
|
||||
|
||||
public Publisher<Envelope> getMessagesForDeviceReactive(UUID destinationUuid, Device destinationDevice,
|
||||
final boolean cachedMessagesOnly) {
|
||||
|
||||
return getMessagesForDevice(destinationUuid, destinationDevice, null, cachedMessagesOnly);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, destinationUuid, destinationDevice);
|
||||
}
|
||||
|
||||
private Publisher<Envelope> getMessagesForDevice(UUID destinationUuid, Device destinationDevice,
|
||||
@Nullable Integer limit, final boolean cachedMessagesOnly) {
|
||||
|
||||
final Publisher<Envelope> dynamoPublisher =
|
||||
cachedMessagesOnly ? Flux.empty() : messagesDynamoDb.load(destinationUuid, destinationDevice, limit);
|
||||
final Publisher<Envelope> cachePublisher = messagesCache.get(destinationUuid, destinationDevice.getId());
|
||||
|
||||
return Flux.concat(dynamoPublisher, cachePublisher)
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return Flux.concat(
|
||||
messagesDynamoDb.load(destinationUuid, destinationDevice, null),
|
||||
messagesCache.get(destinationUuid, destinationDevice.getId()))
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
+97
-20
@@ -17,7 +17,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -40,7 +39,8 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[] databases;
|
||||
private final Database[][] databasesByEpoch;
|
||||
private final int activeEpoch;
|
||||
private final VersionstampUUIDCipher versionstampUUIDCipher;
|
||||
private final Clock clock;
|
||||
|
||||
@@ -53,6 +53,11 @@ public class FoundationDbMessageStore {
|
||||
/// suggest a limit of 1MB to avoid performance issues, although the hard limit is 10MB
|
||||
private static final long MAX_MESSAGE_CHUNK_SIZE = DataSize.megabytes(1).toBytes();
|
||||
|
||||
// We pack the current configuration epoch and shard ID into a single byte of "user data" in each message
|
||||
// versionstamp. We use two bits for the epoch and six for the shard ID.
|
||||
public static final int MAX_EPOCHS = 4;
|
||||
public static final int MAX_SHARDS = 64;
|
||||
|
||||
/// Result of inserting a message for a particular device
|
||||
///
|
||||
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
|
||||
@@ -61,11 +66,18 @@ public class FoundationDbMessageStore {
|
||||
public record InsertResult(Optional<Versionstamp> versionstamp, boolean present) {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases,
|
||||
public FoundationDbMessageStore(final Map<Integer, List<Database>> databasesByEpoch,
|
||||
final int activeEpoch,
|
||||
final VersionstampUUIDCipher versionstampUUIDCipher,
|
||||
final Clock clock) {
|
||||
|
||||
this.databases = databases;
|
||||
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
|
||||
|
||||
databasesByEpoch.forEach((epoch, databases) ->
|
||||
databasesByEpochArray[epoch] = databases.toArray(Database[]::new));
|
||||
|
||||
this.databasesByEpoch = databasesByEpochArray;
|
||||
this.activeEpoch = activeEpoch;
|
||||
this.versionstampUUIDCipher = versionstampUUIDCipher;
|
||||
this.clock = clock;
|
||||
}
|
||||
@@ -79,7 +91,15 @@ public class FoundationDbMessageStore {
|
||||
public CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
|
||||
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId))
|
||||
return insert(aciServiceIdentifier, messagesByDeviceId, activeEpoch);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Map<Byte, InsertResult>> insert(final AciServiceIdentifier aciServiceIdentifier,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final int epoch) {
|
||||
|
||||
return insert(Map.of(aciServiceIdentifier, messagesByDeviceId), epoch)
|
||||
.thenApply(resultsByServiceIdentifier -> {
|
||||
assert resultsByServiceIdentifier.size() == 1;
|
||||
|
||||
@@ -101,6 +121,14 @@ public class FoundationDbMessageStore {
|
||||
public CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier) {
|
||||
|
||||
return insert(messagesByServiceIdentifier, activeEpoch);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insert(
|
||||
final Map<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>> messagesByServiceIdentifier,
|
||||
final int epoch) {
|
||||
|
||||
if (messagesByServiceIdentifier.entrySet()
|
||||
.stream()
|
||||
.anyMatch(entry -> entry.getValue().isEmpty())) {
|
||||
@@ -117,7 +145,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
final Map<Integer, List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>>> messagesByShardId =
|
||||
messagesByServiceIdentifier.entrySet().stream()
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey())));
|
||||
.collect(Collectors.groupingBy(entry -> hashAciToShardNumber(entry.getKey(), epoch)));
|
||||
|
||||
final List<CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>>> chunkFutures =
|
||||
new ArrayList<>();
|
||||
@@ -133,7 +161,7 @@ public class FoundationDbMessageStore {
|
||||
.sum();
|
||||
|
||||
if (estimatedTransactionSize > MAX_MESSAGE_CHUNK_SIZE) {
|
||||
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, current)));
|
||||
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, current)));
|
||||
|
||||
start = current;
|
||||
estimatedTransactionSize = 0;
|
||||
@@ -143,7 +171,7 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
assert start < messagesForShard.size();
|
||||
chunkFutures.add(insertChunk(shardId, messagesForShard.subList(start, messagesForShard.size())));
|
||||
chunkFutures.add(insertChunk(shardId, epoch, messagesForShard.subList(start, messagesForShard.size())));
|
||||
});
|
||||
|
||||
return CompletableFuture.allOf(chunkFutures.toArray(CompletableFuture[]::new))
|
||||
@@ -157,6 +185,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
private CompletableFuture<Map<AciServiceIdentifier, Map<Byte, InsertResult>>> insertChunk(
|
||||
final int shardId,
|
||||
final int epoch,
|
||||
final List<Map.Entry<AciServiceIdentifier, Map<Byte, MessageProtos.Envelope>>> messagesByAccountIdentifier) {
|
||||
|
||||
final Map<AciServiceIdentifier, CompletableFuture<Map<Byte, Boolean>>> insertFuturesByAci = new HashMap<>();
|
||||
@@ -168,9 +197,9 @@ public class FoundationDbMessageStore {
|
||||
.map(MessageProtos.Envelope::getEphemeral)
|
||||
.orElseThrow(() -> new IllegalStateException("One or more bundles is empty"));
|
||||
|
||||
return databases[shardId].runAsync(transaction -> {
|
||||
return getDatabases(epoch)[shardId].runAsync(transaction -> {
|
||||
messagesByAccountIdentifier.forEach(entry ->
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), transaction)));
|
||||
insertFuturesByAci.put(entry.getKey(), insert(entry.getKey(), entry.getValue(), epoch, shardId, transaction)));
|
||||
|
||||
return CompletableFuture.allOf(insertFuturesByAci.values().toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
@@ -181,7 +210,8 @@ public class FoundationDbMessageStore {
|
||||
.anyMatch(isPresent -> isPresent);
|
||||
if (anyClientPresent || !ephemeral) {
|
||||
return transaction.getVersionstamp()
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes, shardId)));
|
||||
.thenApply(versionstampBytes -> Optional.of(Versionstamp.complete(versionstampBytes,
|
||||
packUserData(epoch, shardId))));
|
||||
}
|
||||
return CompletableFuture.completedFuture(Optional.<Versionstamp>empty());
|
||||
});
|
||||
@@ -217,6 +247,8 @@ public class FoundationDbMessageStore {
|
||||
/// @return a future that yields the presence state of each destination device
|
||||
private CompletableFuture<Map<Byte, Boolean>> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final int epoch,
|
||||
final int shardId,
|
||||
final Transaction transaction) {
|
||||
|
||||
final Map<Byte, CompletableFuture<Boolean>> messageInsertFuturesByDeviceId = messagesByDeviceId.entrySet()
|
||||
@@ -232,7 +264,7 @@ public class FoundationDbMessageStore {
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
getDeviceQueueSubspace(aci, deviceId)
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci)))), message.toByteArray());
|
||||
.packWithVersionstamp(Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId)))), message.toByteArray());
|
||||
}
|
||||
|
||||
return isPresent;
|
||||
@@ -251,7 +283,7 @@ public class FoundationDbMessageStore {
|
||||
|
||||
if (anyClientPresent) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete(hashAciToShardNumber(aci))).packWithVersionstamp());
|
||||
Tuple.from(Versionstamp.incomplete(packUserData(epoch, shardId))).packWithVersionstamp());
|
||||
}
|
||||
|
||||
return presenceByDeviceId;
|
||||
@@ -264,11 +296,24 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessageStream getMessages(final AciServiceIdentifier aci, final Device destinationDevice,
|
||||
final int maxMessagesPerScan, final int maxUnacknowledgedMessages, final Runnable doAfterCleanup) {
|
||||
MessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final Device destinationDevice,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
|
||||
|
||||
for (int epoch = 0; epoch < databasesByEpoch.length; epoch++) {
|
||||
databasesForQueueByEpoch[epoch] = databasesByEpoch[epoch] != null
|
||||
? getDatabases(epoch)[hashAciToShardNumber(aci, epoch)]
|
||||
: null;
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, destinationDevice.getId()),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
getShardForAci(aci),
|
||||
databasesForQueueByEpoch,
|
||||
new MessageGuidCodec(aci.uuid(), destinationDevice.getId(), versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
@@ -280,14 +325,46 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
Database getShardForAci(final AciServiceIdentifier aci, final int epoch) {
|
||||
return getDatabases(epoch)[hashAciToShardNumber(aci, epoch)];
|
||||
}
|
||||
|
||||
private Database[] getDatabases(final int epoch) {
|
||||
if (databasesByEpoch[epoch] == null) {
|
||||
throw new IllegalStateException("Epoch (%d) not in static configuration".formatted(epoch));
|
||||
}
|
||||
|
||||
return databasesByEpoch[epoch];
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
int hashAciToShardNumber(final AciServiceIdentifier aci, final int epoch) {
|
||||
// We use a consistent hash here to reduce the number of key remappings if we increase the number of shards
|
||||
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), databases.length);
|
||||
return Hashing.consistentHash(aci.uuid().getLeastSignificantBits(), getDatabases(epoch).length);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int packUserData(final int epoch, final int shardId) {
|
||||
if (epoch < 0 || epoch >= MAX_EPOCHS) {
|
||||
throw new IllegalArgumentException("Epoch (%d) outside of allowable range (0 to %d, exclusive)".formatted(
|
||||
epoch, MAX_EPOCHS));
|
||||
}
|
||||
|
||||
if (shardId < 0 || shardId >= MAX_SHARDS) {
|
||||
throw new IllegalArgumentException("Shard ID (%d) outside of allowable range (0 to %d, exclusive)".formatted(
|
||||
epoch, MAX_SHARDS));
|
||||
}
|
||||
|
||||
return epoch << 6 | shardId;
|
||||
}
|
||||
|
||||
static int getConfigurationEpoch(final Versionstamp versionstamp) {
|
||||
return versionstamp.getUserVersion() >> 6 & 0x03;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static int getShardId(final Versionstamp versionstamp) {
|
||||
return versionstamp.getUserVersion() & 0x3f;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+132
-46
@@ -13,12 +13,18 @@ import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
@@ -27,43 +33,62 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
|
||||
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
private final Database database;
|
||||
private final Database[] databasesByEpoch;
|
||||
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;
|
||||
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
|
||||
private final Runnable doAfterCleanup;
|
||||
private final AcknowledgedMessageBuffer acknowledgedMessageBuffer;
|
||||
|
||||
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
|
||||
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 1024;
|
||||
@VisibleForTesting
|
||||
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
|
||||
|
||||
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
|
||||
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Database database,
|
||||
final Database[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.database = database;
|
||||
this.databasesByEpoch = databasesByEpoch;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
|
||||
this.acknowledgedMessageBuffer = new AcknowledgedMessageBuffer(maxUnacknowledgedMessages);
|
||||
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
|
||||
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
|
||||
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
|
||||
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toMap(database -> database,
|
||||
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
|
||||
(_, _) -> {
|
||||
throw new AssertionError("Duplicate database in distinct stream");
|
||||
},
|
||||
IdentityHashMap::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -81,7 +106,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
|
||||
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
|
||||
try {
|
||||
acknowledgedMessageBuffer.addUnacknowledgedMessage(message.versionstamp());
|
||||
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
|
||||
} catch (final TooManyUnacknowledgedMessagesException e) {
|
||||
sink.error(e);
|
||||
return;
|
||||
@@ -107,34 +132,75 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
|
||||
/// See [FoundationDbMessageStore] for more details on the message insert process.
|
||||
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
|
||||
return Mono.fromFuture(this::getEndOfQueueKeyExclusive)
|
||||
.flatMapMany(maybeEndOfQueueKeyExclusive -> {
|
||||
final Flux<FoundationDbMessageStreamEntry.Message> finitePublisher = maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive, database, maxMessagesPerScan, this::clearAcknowledgedMessages).getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
// Ephemeral messages from the finite stream are considered stale and automatically discarded
|
||||
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
|
||||
acknowledgedMessageBuffer.acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
|
||||
staleEphemeralMessagesCounter.increment();
|
||||
return;
|
||||
}
|
||||
sink.next(fdbMessageStreamEntry);
|
||||
});
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive.orElseGet(
|
||||
() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
final Flux<FoundationDbMessageStreamEntry.Message> infinitePublisher = FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
infinitePublisherBeginKey, KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database, maxMessagesPerScan, messagesAvailableWatchKey, this::clearAcknowledgedMessages).getMessages();
|
||||
return Flux.concat(
|
||||
finitePublisher,
|
||||
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
|
||||
infinitePublisher
|
||||
);
|
||||
});
|
||||
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
|
||||
// `Flux#fromArray` cannot handle `null` elements
|
||||
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
return Flux.fromIterable(databases)
|
||||
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
|
||||
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.flatMapMany(endOfQueueKeysByDatabase -> {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
() -> this.clearAcknowledgedMessages(database))
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
// Ephemeral messages from the finite stream are considered stale and automatically discarded
|
||||
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
|
||||
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
|
||||
staleEphemeralMessagesCounter.increment();
|
||||
return;
|
||||
}
|
||||
sink.next(fdbMessageStreamEntry);
|
||||
});
|
||||
})
|
||||
.toArray(Flux[]::new);
|
||||
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] infinitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
final KeySelector infinitePublisherBeginKey = maybeEndOfQueueKeyExclusive
|
||||
.orElseGet(() -> KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin));
|
||||
|
||||
return FoundationDbMessagePublisher.createInfinitePublisher(
|
||||
infinitePublisherBeginKey,
|
||||
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
database,
|
||||
maxMessagesPerScan,
|
||||
messagesAvailableWatchKey,
|
||||
() -> clearAcknowledgedMessages(database)).getMessages();
|
||||
})
|
||||
.toArray(Flux[]::new);
|
||||
|
||||
return Flux.concat(
|
||||
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers),
|
||||
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
|
||||
|
||||
// Note that we use `mergePriority` instead of `mergeComparing` for the "live"/non-terminating publishers
|
||||
// because `mergePriority` sorts messages _as they arrive._ If we used `mergeComparing` for the live
|
||||
// streams and one of the streams had no new messages (which will be true most of the time), then the
|
||||
// merged publisher would never emit any signals because it'd be waiting to have something to compare
|
||||
// against. This does mean that we risk some slightly out-of-order messages in the exceedingly rare cases
|
||||
// where messages arrive at different servers while somebody is connected and a migration is in progress,
|
||||
// but that should be (again) exceedingly rare and also minimally-disruptive (i.e. it would self-correct
|
||||
// so quickly that end users would likely never even notice).
|
||||
Flux.mergePriority(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, infinitePublishers));
|
||||
});
|
||||
}
|
||||
|
||||
/// Gets a [KeySelector] for the first key greater than the current greatest key in the device queue. This allows us
|
||||
@@ -142,7 +208,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// subsequent scan.
|
||||
///
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive() {
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
|
||||
return database.runAsync(
|
||||
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
|
||||
.thenApply(items -> {
|
||||
@@ -156,7 +222,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
acknowledgedMessageBuffer.acknowledgeMessage(messageGuidCodec.decodeMessageGuid(messageGuid));
|
||||
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
|
||||
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
@@ -174,20 +241,39 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
/// Clear all outstanding acknowledged messages. Called when the stream ends
|
||||
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
|
||||
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages();
|
||||
return database.runAsync(transaction -> {
|
||||
clearAllAcknowlegedMessagedConsumer.accept(transaction);
|
||||
return CompletableFuture.completedFuture((Void) null);
|
||||
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.map(database -> {
|
||||
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
clearAllAcknowlegedMessagedConsumer.accept(transaction);
|
||||
return CompletableFuture.completedFuture((Void) null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear acknowledged messages", throwable);
|
||||
}
|
||||
});
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear acknowledged messages", throwable);
|
||||
}
|
||||
});
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
private synchronized Consumer<Transaction> clearAcknowledgedMessages() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = acknowledgedMessageBuffer.takeFlushableRanges();
|
||||
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
|
||||
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
|
||||
final Database database = databasesByEpoch[epoch];
|
||||
|
||||
if (database == null) {
|
||||
throw new IllegalStateException("Read message for unrecognized epoch");
|
||||
}
|
||||
|
||||
return acknowledgedMessageBuffersByDatabase.get(database);
|
||||
}
|
||||
|
||||
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
|
||||
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
|
||||
|
||||
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
|
||||
}
|
||||
|
||||
@@ -34,14 +34,15 @@ The server may set the `reason` to match the enum string for the `Status.Code` i
|
||||
|
||||
The chat server may return the following errors from any RPC
|
||||
|
||||
| Status Code | Reason | Description |
|
||||
| :---- | :---- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `INVALID_ARGUMENT` | `UPGRADE_REQUIRED` | The client version provided in the `User-Agent` is no longer supported. The client must upgrade to use the service. |
|
||||
| `INVALID_ARGUMENT` | `CONSTRAINT_VIOLATED` | The RPC argument violated a constraint that was annotated or documented in the service definition. It is always possible to check this constraint without communicating with the chat server. This always represents a client bug or out of date client. <br><br> The `details` may include a [`BadRequest` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L236) that indicates additional information about the invalid field. |
|
||||
| `INVALID_ARGUMENT` | `BAD_AUTHENTICATION` | The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the authorization mode is not correct for the RPC. For example, <br><br> The RPC was for an anonymous service, but included an Authentication header in the RPC metadata. <br><br>The RPC should only be made by the primary device, but the request had linked device credentials. |
|
||||
| `UNAUTHENTICATED` | `INVALID_CREDENTIALS` | The account credentials provided in the authorization header are not valid. |
|
||||
| `RESOURCE_EXHAUSTED` | `RESOURCE_EXHAUSTED` | A server-side resource was exhausted. The `details` field may include a [`RetryInfo` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L92) that includes the amount of time in seconds the client should wait before retrying the request. <br><br> If a `RetryInfo` is present, the client must wait the indicated time before retrying the request. If absent, the client should retry with an exponential backoff. |
|
||||
| `UNAVAILABLE` | `UNAVAILABLE` | There was an internal error processing the RPC. The client should retry the request with exponential backoff. |
|
||||
| Status Code | Reason | Description |
|
||||
|:---------------------|:----------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `INVALID_ARGUMENT` | `UPGRADE_REQUIRED` | The client version provided in the `User-Agent` is no longer supported. The client must upgrade to use the service. |
|
||||
| `INVALID_ARGUMENT` | `CONSTRAINT_VIOLATED` | The RPC argument violated a constraint that was annotated or documented in the service definition. It is always possible to check this constraint without communicating with the chat server. This always represents a client bug or out of date client. <br><br> The `details` may include a [`BadRequest` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L236) that indicates additional information about the invalid field. |
|
||||
| `INVALID_ARGUMENT` | `BAD_AUTHENTICATION` | The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the authorization mode is not correct for the RPC. For example, <br><br> The RPC was for an anonymous service, but included an Authentication header in the RPC metadata. <br><br>The RPC should only be made by the primary device, but the request had linked device credentials. |
|
||||
| `UNAUTHENTICATED` | `INVALID_CREDENTIALS` | The account credentials provided in the authorization header are not valid. |
|
||||
| `RESOURCE_EXHAUSTED` | `RESOURCE_EXHAUSTED` | A server-side resource was exhausted. The `details` field may include a [`RetryInfo` message](https://github.com/googleapis/googleapis/blob/8c06c1e04ae562f49f411357577c700e9142f33c/google/rpc/error_details.proto#L92) that includes the amount of time in seconds the client should wait before retrying the request. <br><br> If a `RetryInfo` is present, the client must wait the indicated time before retrying the request. If absent, the client should retry with an exponential backoff. |
|
||||
| `ABORTED` | `STREAM_CLOSED` | The server terminated a streaming RPC for some domain specific reason. The `details` field must include a message with additional information about why the stream was closed. This message must be defined in the corresponding service proto for the streaming RPC. This status must only be returned from server-side streaming RPCs. Clients must handle a STREAM_CLOSED status even if no corresponding message is defined in the version of the proto they are targeting. Unless otherwise noted, if a stream termination message is defined, clients must handle the error at any point in the message stream. |
|
||||
| `UNAVAILABLE` | `UNAVAILABLE` | There was an internal error processing the RPC. The client should retry the request with exponential backoff. |
|
||||
|
||||
### Logging Errors
|
||||
|
||||
|
||||
@@ -183,6 +183,9 @@ service BackupsAnonymous {
|
||||
//
|
||||
// On retries, a particular destination media id must not be reused with a
|
||||
// different source media id or different encryption parameters.
|
||||
//
|
||||
// The response stream may be closed with STREAM_CLOSED error reason. In this
|
||||
// case, a BackupStreamClosed message will be present in the error details.
|
||||
rpc CopyMedia(CopyMediaRequest) returns (stream CopyMediaResponse) {}
|
||||
|
||||
// Retrieve a page of media objects stored for this backup-id. A client may
|
||||
@@ -194,6 +197,9 @@ service BackupsAnonymous {
|
||||
|
||||
// Delete media objects stored with this backup-id. Streams the locations of
|
||||
// media items back when the item has successfully been removed.
|
||||
//
|
||||
// The response stream may be closed with STREAM_CLOSED error reason. In this
|
||||
// case, a BackupStreamClosed message will be present in the error details.
|
||||
rpc DeleteMedia(DeleteMediaRequest) returns (stream DeleteMediaResponse) {}
|
||||
|
||||
// Delete all backup metadata, objects, and stored public key. To use
|
||||
@@ -404,7 +410,7 @@ message CopyMediaItem {
|
||||
|
||||
// The length of the source attachment before the encryption applied by the
|
||||
// copy operation
|
||||
uint32 object_length = 3;
|
||||
uint64 object_length = 3;
|
||||
|
||||
// media_id to copy on to the backup CDN
|
||||
bytes media_id = 4 [(require.exactlySize) = 15];
|
||||
@@ -439,20 +445,25 @@ message CopyMediaResponse {
|
||||
// The media item was successfully copied into the backup
|
||||
CopySuccess success = 2;
|
||||
|
||||
// The source object was not found
|
||||
SourceNotFound source_not_found = 3 [(tag.reason) = "source_not_found"];
|
||||
|
||||
// The provided object length was incorrect
|
||||
WrongSourceLength wrong_source_length = 4 [(tag.reason) = "wrong_source_length"];
|
||||
|
||||
// All media capacity has been consumed. Free some space to continue.
|
||||
OutOfSpace out_of_space = 5 [(tag.reason) = "out_of_space"];
|
||||
}
|
||||
}
|
||||
|
||||
// The reason why a media stream RPC is being prematurely closed by the server.
|
||||
message BackupStreamClosed {
|
||||
oneof reason {
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 3 [(tag.reason) = "failed_authentication"];
|
||||
|
||||
// The source object was not found
|
||||
SourceNotFound source_not_found = 4 [(tag.reason) = "source_not_found"];
|
||||
|
||||
// The provided object length was incorrect
|
||||
WrongSourceLength wrong_source_length = 5 [(tag.reason) = "wrong_source_length"];
|
||||
|
||||
// All media capacity has been consumed. Free some space to continue.
|
||||
OutOfSpace out_of_space = 6 [(tag.reason) = "out_of_space"];
|
||||
errors.FailedZkAuthentication failed_authentication = 1 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -537,13 +548,5 @@ message DeleteMediaRequest {
|
||||
}
|
||||
|
||||
message DeleteMediaResponse {
|
||||
oneof response {
|
||||
DeleteMediaItem deleted_item = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
DeleteMediaItem deleted_item = 1;
|
||||
}
|
||||
@@ -30,6 +30,10 @@ service Credentials {
|
||||
// actions.
|
||||
rpc GetGroupCredentials(GetGroupCredentialsRequest)
|
||||
returns (GetGroupCredentialsResponse) {}
|
||||
|
||||
// Generates zero-knowledge credentials for creating call links.
|
||||
rpc GetCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest)
|
||||
returns (GetCreateCallLinkCredentialsResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for working with previously-generated credentials without
|
||||
@@ -142,3 +146,18 @@ message GetGroupCredentialsResponse {
|
||||
// generated
|
||||
bytes pni = 3;
|
||||
}
|
||||
|
||||
message GetCreateCallLinkCredentialsRequest {
|
||||
// A zero-knowledge credential request
|
||||
bytes credential_request = 1;
|
||||
}
|
||||
|
||||
message GetCreateCallLinkCredentialsResponse {
|
||||
// A zero-knowledge credential that may be redeemed at or up to one day after
|
||||
// the given redemption time
|
||||
bytes credential = 1;
|
||||
|
||||
// The earliest time, in seconds since the epoch, at which the associated
|
||||
// credential may be redeemed
|
||||
uint64 redemption_time_seconds = 2;
|
||||
}
|
||||
@@ -43,8 +43,11 @@ service Messages {
|
||||
// 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.
|
||||
// The server will keep the stream open until the client disconnects. Only
|
||||
// one GetMessages stream may be open per device. If a second GetMessages
|
||||
// stream is opened, the server may terminate any of the streams with
|
||||
// a STREAM_CLOSED error reason. A GetMessagesStreamClosed message will be
|
||||
// present in the error details.
|
||||
rpc GetMessages(stream GetMessagesRequest) returns (stream GetMessagesResponse) {}
|
||||
}
|
||||
|
||||
@@ -68,19 +71,15 @@ message GetMessagesRequest {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
// The reason why a GetMessages RPC is being closed by the server.
|
||||
message GetMessagesStreamClosed {
|
||||
oneof reason {
|
||||
// Another caller has opened a GetMessages stream for the same device.
|
||||
google.protobuf.Empty conflicting_stream = 1;
|
||||
}
|
||||
}
|
||||
|
||||
message GetMessagesResponse {
|
||||
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
|
||||
@@ -92,9 +91,6 @@ message GetMessagesResponse {
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -525,11 +525,11 @@ public class BackupManagerTest {
|
||||
|
||||
when(tusCredentialGenerator.generateUpload(any(), anyLong()))
|
||||
.thenReturn(new BackupUploadDescriptor(3, "", Collections.emptyMap(), ""));
|
||||
when(remoteStorageManager.copy(eq(3), eq("success"), eq(100), any(), any()))
|
||||
when(remoteStorageManager.copy(eq(3), eq("success"), eq(100L), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(remoteStorageManager.copy(eq(3), eq("missing"), eq(200), any(), any()))
|
||||
when(remoteStorageManager.copy(eq(3), eq("missing"), eq(200L), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new SourceObjectNotFoundException()));
|
||||
when(remoteStorageManager.copy(eq(3), eq("badlength"), eq(300), any(), any()))
|
||||
when(remoteStorageManager.copy(eq(3), eq("badlength"), eq(300L), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new InvalidLengthException("")));
|
||||
|
||||
final List<CopyResult> results = backupManager
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class FoundationDbClusterConfigurationTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isSingleClusterFileSourceSpecified(final FoundationDbClusterConfiguration clusterConfiguration,
|
||||
final boolean expectSingleClusterFileSourceSpecified) {
|
||||
|
||||
assertEquals(expectSingleClusterFileSourceSpecified, clusterConfiguration.isSingleClusterFileSourceSpecified());
|
||||
}
|
||||
|
||||
private static List<Arguments> isSingleClusterFileSourceSpecified() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Cluster file URL only",
|
||||
new FoundationDbClusterConfiguration("test-url", null), true),
|
||||
|
||||
Arguments.argumentSet("Cluster file contents only",
|
||||
new FoundationDbClusterConfiguration(null, "test-contents"), true),
|
||||
|
||||
Arguments.argumentSet("Both",
|
||||
new FoundationDbClusterConfiguration("test-url", "test-contents"), false),
|
||||
|
||||
Arguments.argumentSet("Neither",
|
||||
new FoundationDbClusterConfiguration(null, null), false)
|
||||
);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class FoundationDbMessagesConfigurationTest {
|
||||
|
||||
@Test
|
||||
void isEveryEpochClusterConfigured() {
|
||||
assertTrue(new FoundationDbMessagesConfiguration(
|
||||
Map.of("messages-0", new FoundationDbClusterConfiguration("test-url", null)),
|
||||
Map.of(0, List.of("messages-0")),
|
||||
0
|
||||
).isEveryEpochClusterConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
Map.of("messages-0", new FoundationDbClusterConfiguration("test-url", null)),
|
||||
Map.of(0, List.of("messages-0", "unconfigured-cluster")),
|
||||
0
|
||||
).isEveryEpochClusterConfigured());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isEveryEpochFreeOfDuplicates() {
|
||||
assertTrue(new FoundationDbMessagesConfiguration(
|
||||
Map.of("messages-0", new FoundationDbClusterConfiguration("test-url", null)),
|
||||
Map.of(0, List.of("messages-0")),
|
||||
0
|
||||
).isEveryEpochFreeOfDuplicates());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
Map.of("messages-0", new FoundationDbClusterConfiguration("test-url", null)),
|
||||
Map.of(0, List.of("messages-0", "messages-0")),
|
||||
0
|
||||
).isEveryEpochFreeOfDuplicates());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isActiveEpochConfigured() {
|
||||
assertTrue(new FoundationDbMessagesConfiguration(
|
||||
Map.of("messages-0", new FoundationDbClusterConfiguration("test-url", null)),
|
||||
Map.of(0, List.of("messages-0")),
|
||||
0
|
||||
).isActiveEpochConfigured());
|
||||
|
||||
assertFalse(new FoundationDbMessagesConfiguration(
|
||||
Map.of("messages-0", new FoundationDbClusterConfiguration("test-url", null)),
|
||||
Map.of(0, List.of("messages-0")),
|
||||
1
|
||||
).isActiveEpochConfigured());
|
||||
}
|
||||
}
|
||||
+52
-2
@@ -8,9 +8,12 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertRateLimitExceeded;
|
||||
@@ -46,6 +49,8 @@ import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.signal.chat.credentials.CredentialsGrpc;
|
||||
import org.signal.chat.credentials.ExternalServiceType;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
|
||||
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
|
||||
@@ -63,10 +68,12 @@ import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
import org.signal.libsignal.zkgroup.auth.ClientZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequestContext;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
@@ -190,7 +197,7 @@ public class CredentialsGrpcServiceTest
|
||||
@MethodSource
|
||||
public void testSuccess(
|
||||
final ExternalServiceType externalServiceType,
|
||||
final ExternalServiceCredentialsGenerator credentialsGenerator) throws Exception {
|
||||
final ExternalServiceCredentialsGenerator credentialsGenerator) {
|
||||
final RateLimiter limiter = mock(RateLimiter.class);
|
||||
doReturn(limiter).when(rateLimiters).forDescriptor(eq(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS));
|
||||
doReturn(Mono.fromFuture(CompletableFuture.completedFuture(null))).when(limiter).validateReactive(eq(AUTHENTICATED_ACI));
|
||||
@@ -220,7 +227,7 @@ public class CredentialsGrpcServiceTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRateLimitExceeded() throws Exception {
|
||||
public void testRateLimitExceeded() {
|
||||
final Duration retryAfter = MockUtils.updateRateLimiterResponseToFail(
|
||||
rateLimiters, RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS, AUTHENTICATED_ACI, Duration.ofSeconds(100));
|
||||
Mockito.reset(DIRECTORY_CREDENTIALS_GENERATOR);
|
||||
@@ -354,4 +361,47 @@ public class CredentialsGrpcServiceTest
|
||||
Arguments.argumentSet("End is not at a day boundary", startOfDay, startOfDay.plusSeconds(17))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCreateCallLinkCredentials() {
|
||||
when(rateLimiters.getCreateCallLinkLimiter()).thenReturn(mock(RateLimiter.class));
|
||||
|
||||
final byte[] roomId = TestRandomUtil.nextBytes(32);
|
||||
|
||||
final GetCreateCallLinkCredentialsResponse response =
|
||||
authenticatedServiceStub().getCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest.newBuilder()
|
||||
.setCredentialRequest(
|
||||
ByteString.copyFrom(CreateCallLinkCredentialRequestContext.forRoom(roomId).getRequest().serialize()))
|
||||
.build());
|
||||
|
||||
assertFalse(response.getCredential().isEmpty());
|
||||
assertEquals(CLOCK.instant().truncatedTo(ChronoUnit.DAYS).getEpochSecond(), response.getRedemptionTimeSeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCreateCallLinkCredentialsRateLimited() throws RateLimitExceededException {
|
||||
final Duration retryAfter = Duration.ofSeconds(71);
|
||||
|
||||
final RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
doThrow(new RateLimitExceededException(retryAfter)).when(rateLimiter).validate(any(UUID.class));
|
||||
|
||||
when(rateLimiters.getCreateCallLinkLimiter()).thenReturn(rateLimiter);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertRateLimitExceeded(retryAfter,
|
||||
() -> authenticatedServiceStub().getCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest.newBuilder()
|
||||
.setCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCreateCallLinkCredentialsInvalidRequest() {
|
||||
when(rateLimiters.getCreateCallLinkLimiter()).thenReturn(mock(RateLimiter.class));
|
||||
|
||||
//noinspection ThrowableNotThrown,ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> authenticatedServiceStub().getCreateCallLinkCredentials(GetCreateCallLinkCredentialsRequest.newBuilder()
|
||||
.setCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.build()));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
@@ -33,6 +34,12 @@ public final class GrpcTestUtils {
|
||||
return exception;
|
||||
}
|
||||
|
||||
public static void assertStatusException(final Status expected, final String expectedReason, final Throwable throwable) {
|
||||
final StatusRuntimeException exception = Assertions.assertInstanceOf(StatusRuntimeException.class, throwable);
|
||||
assertEquals(expected.getCode(), exception.getStatus().getCode());
|
||||
assertEquals(expectedReason, extractErrorInfo(exception).getReason());
|
||||
}
|
||||
|
||||
public static void assertStatusException(final Status expected, final String expectedReason, final Executable serviceCall) {
|
||||
final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall);
|
||||
assertEquals(expected.getCode(), exception.getStatus().getCode());
|
||||
@@ -43,14 +50,6 @@ public final class GrpcTestUtils {
|
||||
return assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
|
||||
}
|
||||
|
||||
public static StatusRuntimeException assertStatusUnauthenticated(final Executable serviceCall) {
|
||||
return assertStatusException(Status.UNAUTHENTICATED, serviceCall);
|
||||
}
|
||||
|
||||
public static StatusRuntimeException assertStatusPermissionDenied(final Executable serviceCall) {
|
||||
return assertStatusException(Status.PERMISSION_DENIED, serviceCall);
|
||||
}
|
||||
|
||||
public static void assertRateLimitExceeded(
|
||||
final Duration expectedRetryAfter,
|
||||
final Executable serviceCall,
|
||||
@@ -71,6 +70,13 @@ public final class GrpcTestUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends Message> T assertStreamClosed(final Class<T> streamClosedMessageClass, final Throwable exception) {
|
||||
final StatusRuntimeException statusRuntimeException = assertInstanceOf(StatusRuntimeException.class, exception);
|
||||
final ErrorInfo errorInfo = extractErrorInfo(statusRuntimeException);
|
||||
assertEquals("STREAM_CLOSED", errorInfo.getReason());
|
||||
return extractDetail(streamClosedMessageClass, statusRuntimeException);
|
||||
}
|
||||
|
||||
public static ErrorInfo extractErrorInfo(final StatusRuntimeException exception) {
|
||||
return extractDetail(ErrorInfo.class, exception);
|
||||
}
|
||||
|
||||
+18
-16
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -17,6 +18,7 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.Status;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
@@ -30,6 +32,7 @@ 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.signal.chat.messages.GetMessagesStreamClosed;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -59,16 +62,6 @@ 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;
|
||||
@@ -296,8 +289,17 @@ class MessageDispatcherTest {
|
||||
verify(disconnectionRequestManager).addListener(eq(ACI), eq(DEVICE_ID), listener.capture());
|
||||
listener.getValue().handleDisconnectionRequest();
|
||||
})
|
||||
.expectNext(REQUIRES_REAUTH)
|
||||
.verifyComplete();
|
||||
.expectErrorSatisfies(MessageDispatcherTest::assertReauthError)
|
||||
.verify();
|
||||
}
|
||||
|
||||
private static void assertReauthError(final Throwable e) {
|
||||
GrpcTestUtils.assertStatusException(Status.UNAUTHENTICATED, "INVALID_CREDENTIALS", e);
|
||||
}
|
||||
|
||||
private static void assertConflictError(final Throwable e) {
|
||||
final GetMessagesStreamClosed reason = GrpcTestUtils.assertStreamClosed(GetMessagesStreamClosed.class, e);
|
||||
assertEquals(GetMessagesStreamClosed.ReasonCase.CONFLICTING_STREAM, reason.getReasonCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -306,8 +308,8 @@ class MessageDispatcherTest {
|
||||
final Flux<GetMessagesResponse> responses =
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, Flux.never());
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(CONFLICTING_STREAM)
|
||||
.verifyComplete();
|
||||
.expectErrorSatisfies(MessageDispatcherTest::assertConflictError)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -329,8 +331,8 @@ class MessageDispatcherTest {
|
||||
.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();
|
||||
.expectErrorSatisfies(MessageDispatcherTest::assertConflictError)
|
||||
.verify();
|
||||
}
|
||||
|
||||
/// Set envelopes to return when a message stream is created. A [MessageStreamEntry.QueueEmpty] will be emitted after
|
||||
|
||||
+1
-1
@@ -504,7 +504,7 @@ class MessagePersisterTest {
|
||||
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), anyList()))
|
||||
.thenThrow(ItemCollectionSizeLimitExceededException.builder().build());
|
||||
when(messagesManager.getMessagesForDeviceReactive(DESTINATION_ACCOUNT_UUID, primary, false))
|
||||
when(messagesManager.getMessagesForDevice(DESTINATION_ACCOUNT_UUID, primary))
|
||||
.thenReturn(Flux.concat(
|
||||
Flux.fromIterable(persistedMessages),
|
||||
Flux.fromIterable(cachedMessages)));
|
||||
|
||||
+270
-17
@@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
@@ -23,6 +24,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -36,7 +38,9 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
@@ -49,6 +53,8 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.junitpioneer.jupiter.params.IntRangeSource;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -73,6 +79,9 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.ofEpochSecond(500), ZoneId.of("UTC"));
|
||||
|
||||
private static final int DEFAULT_EPOCH = 0;
|
||||
private static final int FUTURE_EPOCH = 2;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
@@ -80,8 +89,17 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
versionstampUUIDCipher = new VersionstampUUIDCipher(0, versionstampCipherKey);
|
||||
|
||||
final List<Database> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
FOUNDATION_DB_EXTENSION.getDatabases(),
|
||||
// Simulate a topology change by reversing the order of the (two) databases in the group in a second epoch. This
|
||||
// construction ensures that queues will land in different databases in different epochs, and defining
|
||||
// non-contiguous epochs forces us to deal with "holes" and null values in the epoch list.
|
||||
Map.of(
|
||||
DEFAULT_EPOCH, databases,
|
||||
FUTURE_EPOCH, databases.reversed()
|
||||
),
|
||||
DEFAULT_EPOCH,
|
||||
versionstampUUIDCipher,
|
||||
CLOCK);
|
||||
}
|
||||
@@ -157,6 +175,49 @@ class FoundationDbMessageStoreTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertEpochChange() throws InvalidProtocolBufferException {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final MessageProtos.Envelope defaultEpochMessage = generateRandomMessage(false);
|
||||
final MessageProtos.Envelope futureEpochMessage = generateRandomMessage(false);
|
||||
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> defaultEpochInsertResult =
|
||||
foundationDbMessageStore.insert(aci, Map.of(deviceId, defaultEpochMessage), DEFAULT_EPOCH).join();
|
||||
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> futureEpochInsertResult =
|
||||
foundationDbMessageStore.insert(aci, Map.of(deviceId, futureEpochMessage), FUTURE_EPOCH).join();
|
||||
|
||||
for (int epoch : new int[] { DEFAULT_EPOCH, FUTURE_EPOCH }) {
|
||||
final List<KeyValue> itemsInDeviceQueue = getItemsInDeviceQueue(aci, deviceId, epoch);
|
||||
assertEquals(1, itemsInDeviceQueue.size());
|
||||
|
||||
final Versionstamp expectedVersionstamp = switch (epoch) {
|
||||
case DEFAULT_EPOCH -> defaultEpochInsertResult.get(deviceId).versionstamp().orElseThrow();
|
||||
case FUTURE_EPOCH -> futureEpochInsertResult.get(deviceId).versionstamp().orElseThrow();
|
||||
default -> throw new AssertionError("Unexpected epoch");
|
||||
};
|
||||
|
||||
final Versionstamp retrievedVersionstamp =
|
||||
FoundationDbMessageStore.getVersionstamp(itemsInDeviceQueue.getFirst().getKey());
|
||||
|
||||
assertEquals(expectedVersionstamp, retrievedVersionstamp);
|
||||
assertEquals(epoch, FoundationDbMessageStore.getConfigurationEpoch(retrievedVersionstamp));
|
||||
|
||||
final MessageProtos.Envelope expectedEnvelope = switch (epoch) {
|
||||
case DEFAULT_EPOCH -> defaultEpochMessage;
|
||||
case FUTURE_EPOCH -> futureEpochMessage;
|
||||
default -> throw new AssertionError("Unexpected epoch");
|
||||
};
|
||||
|
||||
final MessageProtos.Envelope retrievedEnvelope =
|
||||
MessageProtos.Envelope.parseFrom(itemsInDeviceQueue.getFirst().getValue());
|
||||
|
||||
assertEquals(expectedEnvelope, retrievedEnvelope);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
@@ -286,7 +347,7 @@ class FoundationDbMessageStoreTest {
|
||||
// assert that each shard has the expected number of committed transactions.
|
||||
final Map<Integer, Set<Versionstamp>> returnedVersionstampsByShard = new HashMap<>();
|
||||
result.forEach((aci, deviceResults) -> {
|
||||
final int shardNum = foundationDbMessageStore.hashAciToShardNumber(aci);
|
||||
final int shardNum = foundationDbMessageStore.hashAciToShardNumber(aci, DEFAULT_EPOCH);
|
||||
final Set<Versionstamp> versionstampSet = returnedVersionstampsByShard.computeIfAbsent(shardNum, _ -> new HashSet<>());
|
||||
deviceResults.forEach((_, deviceResult) -> deviceResult.versionstamp().ifPresent(versionstampSet::add));
|
||||
});
|
||||
@@ -438,6 +499,69 @@ class FoundationDbMessageStoreTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMessagesEpochChange() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(deviceId);
|
||||
|
||||
final int messagesPerBatch = 8;
|
||||
|
||||
final AtomicLong serialTimestamp = new AtomicLong();
|
||||
|
||||
final List<MessageProtos.Envelope> existingDefaultEpochMessages =
|
||||
generateAndInsertMessages(aci, deviceId, DEFAULT_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement);
|
||||
|
||||
final List<MessageProtos.Envelope> existingFutureEpochMessages =
|
||||
generateAndInsertMessages(aci, deviceId, FUTURE_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement);
|
||||
|
||||
final List<MessageProtos.Envelope> liveDefaultEpochMessages = new ArrayList<>();
|
||||
final List<MessageProtos.Envelope> liveFutureEpochMessages = new ArrayList<>();
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
final CountDownLatch queueEmptyLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
// Wait until queue is empty
|
||||
assertTrue(queueEmptyLatch.await(1000, TimeUnit.MILLISECONDS));
|
||||
|
||||
// Then publish more messages
|
||||
liveDefaultEpochMessages.addAll(generateAndInsertMessages(aci, deviceId, DEFAULT_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement));
|
||||
liveFutureEpochMessages.addAll(generateAndInsertMessages(aci, deviceId, FUTURE_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement));
|
||||
} catch (final InterruptedException e) {
|
||||
fail(e);
|
||||
}
|
||||
});
|
||||
|
||||
writePresenceKey(aci, deviceId, 1, 5L, DEFAULT_EPOCH);
|
||||
writePresenceKey(aci, deviceId, 1, 5L, FUTURE_EPOCH);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(existingDefaultEpochMessages.size() + existingFutureEpochMessages.size())
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(queueEmptyLatch::countDown)
|
||||
.expectNextCount(2 * messagesPerBatch)
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
|
||||
final List<MessageProtos.Envelope> retrievedMessages = retrievedEntries.stream()
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.map(messageStreamEntry -> ((MessageStreamEntry.Envelope) messageStreamEntry).message())
|
||||
.toList();
|
||||
|
||||
assertEquals(4 * messagesPerBatch, retrievedMessages.size());
|
||||
assertEquals(existingDefaultEpochMessages, retrievedMessages.subList(0, existingDefaultEpochMessages.size()));
|
||||
assertEquals(existingFutureEpochMessages, retrievedMessages.subList(existingDefaultEpochMessages.size(), existingDefaultEpochMessages.size() + existingFutureEpochMessages.size()));
|
||||
|
||||
// Order is not strictly defined for "competing" live messages
|
||||
assertTrue(retrievedMessages.containsAll(liveDefaultEpochMessages));
|
||||
assertTrue(retrievedMessages.containsAll(liveFutureEpochMessages));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMessagesPublishMoreAfterQueueEmpty() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
@@ -616,6 +740,68 @@ class FoundationDbMessageStoreTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgeMessagesEpochChange() throws InterruptedException {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(deviceId);
|
||||
|
||||
final int messagesPerBatch = 8;
|
||||
|
||||
final AtomicLong serialTimestamp = new AtomicLong();
|
||||
|
||||
generateAndInsertMessages(aci, deviceId, DEFAULT_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement);
|
||||
generateAndInsertMessages(aci, deviceId, FUTURE_EPOCH, messagesPerBatch, serialTimestamp::getAndIncrement);
|
||||
|
||||
{
|
||||
final CountDownLatch cleanupLatch = new CountDownLatch(1);
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci,
|
||||
device,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanupLatch::countDown);
|
||||
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(2 * messagesPerBatch)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.then(() -> retrievedEntries.stream()
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.map(messageStreamEntry -> ((MessageStreamEntry.Envelope) messageStreamEntry).message())
|
||||
// Acknowledge messages with even-numbered timestamps; this will spread acknowledgements across both epochs
|
||||
.filter(message -> message.getServerTimestamp() % 2 == 0)
|
||||
.forEach(message -> messageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()), message.getServerTimestamp()).join()))
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
|
||||
cleanupLatch.await();
|
||||
}
|
||||
|
||||
{
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, device);
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
.recordWith(() -> retrievedEntries)
|
||||
.expectNextCount(messagesPerBatch)
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofSeconds(1));
|
||||
|
||||
final List<MessageProtos.Envelope> retrievedMessages = retrievedEntries.stream()
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.map(messageStreamEntry -> ((MessageStreamEntry.Envelope) messageStreamEntry).message())
|
||||
.toList();
|
||||
|
||||
assertEquals(messagesPerBatch, retrievedMessages.size());
|
||||
assertTrue(retrievedMessages.stream().noneMatch(message -> message.getServerTimestamp() % 2 == 0),
|
||||
"All messages with even-numbered timestamps should be acknowledged and removed");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void outstandingUnacknowledgedMessages() {
|
||||
final int numMessages = 5;
|
||||
@@ -624,13 +810,9 @@ class FoundationDbMessageStoreTest {
|
||||
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();
|
||||
for (int i = 0; i < numMessages; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final Device device = new Device();
|
||||
device.setId(Device.PRIMARY_ID);
|
||||
@@ -701,6 +883,17 @@ class FoundationDbMessageStoreTest {
|
||||
assertNotNull(getMessageByVersionstamp(aci, Device.PRIMARY_ID, deliveredUnacknowledgedVersionstamp.join()));
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void packUserVersion(@IntRangeSource(from = 0, to = FoundationDbMessageStore.MAX_EPOCHS) final int epoch,
|
||||
@IntRangeSource(from = 0, to = FoundationDbMessageStore.MAX_SHARDS) final int shardId) {
|
||||
|
||||
final Versionstamp versionstamp =
|
||||
Versionstamp.complete(new byte[10], FoundationDbMessageStore.packUserData(epoch, shardId));
|
||||
|
||||
assertEquals(epoch, FoundationDbMessageStore.getConfigurationEpoch(versionstamp));
|
||||
assertEquals(shardId, FoundationDbMessageStore.getShardId(versionstamp));
|
||||
}
|
||||
|
||||
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
|
||||
return generateRandomMessage(ephemeral, contentSize, CLOCK.millis());
|
||||
}
|
||||
@@ -718,10 +911,46 @@ class FoundationDbMessageStoreTest {
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<MessageProtos.Envelope> generateAndInsertMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int epoch,
|
||||
final int messageCount,
|
||||
final Supplier<Long> timestampSupplier) {
|
||||
|
||||
final MessageGuidCodec messageGuidCodec =
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher);
|
||||
|
||||
return IntStream.range(0, messageCount)
|
||||
.mapToObj(_ -> {
|
||||
final MessageProtos.Envelope message =
|
||||
generateRandomMessage(false, 16, timestampSupplier.get());
|
||||
|
||||
final FoundationDbMessageStore.InsertResult insertResult =
|
||||
foundationDbMessageStore.insert(aci, Map.of(deviceId, message), epoch).join().get(deviceId);
|
||||
|
||||
final Versionstamp versionstamp = insertResult.versionstamp().orElseThrow();
|
||||
final UUID messageGuid = messageGuidCodec.encodeMessageGuid(versionstamp);
|
||||
|
||||
return message.toBuilder().setServerGuid(UUIDUtil.toByteString(messageGuid)).build();
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final Versionstamp versionstamp) {
|
||||
return foundationDbMessageStore.getShardForAci(aci).read(transaction -> {
|
||||
|
||||
return getMessageByVersionstamp(aci, deviceId, versionstamp, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final Versionstamp versionstamp,
|
||||
final int epoch) {
|
||||
|
||||
return foundationDbMessageStore.getShardForAci(aci, epoch).read(transaction -> {
|
||||
final byte[] key = FoundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
.pack(Tuple.from(versionstamp));
|
||||
return transaction.get(key);
|
||||
@@ -729,16 +958,32 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
|
||||
private Optional<Versionstamp> getMessagesAvailableWatch(final AciServiceIdentifier aci) {
|
||||
return foundationDbMessageStore.getShardForAci(aci)
|
||||
return getMessagesAvailableWatch(aci, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
private Optional<Versionstamp> getMessagesAvailableWatch(final AciServiceIdentifier aci, final int epoch) {
|
||||
return foundationDbMessageStore.getShardForAci(aci, epoch)
|
||||
.read(transaction -> transaction.get(FoundationDbMessageStore.getMessagesAvailableWatchKey(aci))
|
||||
.thenApply(value -> value == null ? null : Tuple.fromBytes(value).getVersionstamp(0))
|
||||
.thenApply(Optional::ofNullable))
|
||||
.join();
|
||||
}
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci, final byte deviceId, final int serverId,
|
||||
private void writePresenceKey(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int serverId,
|
||||
final long secondsBeforeCurrentTime) {
|
||||
foundationDbMessageStore.getShardForAci(aci).run(transaction -> {
|
||||
|
||||
writePresenceKey(aci, deviceId, serverId, secondsBeforeCurrentTime, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int serverId,
|
||||
final long secondsBeforeCurrentTime,
|
||||
final int epoch) {
|
||||
|
||||
foundationDbMessageStore.getShardForAci(aci, epoch).run(transaction -> {
|
||||
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
|
||||
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
|
||||
@@ -756,18 +1001,26 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
|
||||
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber) {
|
||||
return generateRandomAciForShard(shardNumber, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
private AciServiceIdentifier generateRandomAciForShard(final int shardNumber, final int epoch) {
|
||||
assert shardNumber < FOUNDATION_DB_EXTENSION.getDatabases().length;
|
||||
while (true) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
if (foundationDbMessageStore.hashAciToShardNumber(aci) == shardNumber) {
|
||||
if (foundationDbMessageStore.hashAciToShardNumber(aci, epoch) == shardNumber) {
|
||||
return aci;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<KeyValue> getItemsInDeviceQueue(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return foundationDbMessageStore.getShardForAci(aci).readAsync(transaction -> AsyncUtil.collect(transaction.getRange(
|
||||
FoundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId).range()))).join();
|
||||
return getItemsInDeviceQueue(aci, deviceId, DEFAULT_EPOCH);
|
||||
}
|
||||
|
||||
private List<KeyValue> getItemsInDeviceQueue(final AciServiceIdentifier aci, final byte deviceId, final int epoch) {
|
||||
return foundationDbMessageStore.getShardForAci(aci, epoch).readAsync(transaction ->
|
||||
AsyncUtil.collect(transaction.getRange(FoundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId).range())))
|
||||
.join();
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule spam-filter updated: 8545e8fe4d...57b87bf038.
Reference in new issue
Block a user