mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 08:06:47 +00:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
470e17963a | ||
|
|
4c5dc118aa | ||
|
|
ad84cd848a | ||
|
|
127bd56f73 | ||
|
|
ad3721acf1 | ||
|
|
085127326b | ||
|
|
2e32ab3282 | ||
|
|
8bb125597b | ||
|
|
8ca7f85bf0 | ||
|
|
9d4d36939c | ||
|
|
dabe1c157b | ||
|
|
36d0c4422e | ||
|
|
1429efd573 | ||
|
|
93c03c5676 | ||
|
|
bd1bd007c0 | ||
|
|
f485406c4d | ||
|
|
d96c360016 | ||
|
|
6d71f43b6c | ||
|
|
d6824fcaf6 | ||
|
|
61f388f5f4 |
No files matched your search
@@ -272,7 +272,6 @@ import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.EncryptDeviceCreationTimestampCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
@@ -347,7 +346,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new IdleDeviceNotificationSchedulerFactory()));
|
||||
|
||||
bootstrap.addCommand(new RegenerateSecondaryDynamoDbTableDataCommand());
|
||||
bootstrap.addCommand(new EncryptDeviceCreationTimestampCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -635,8 +633,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Clock.systemUTC());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager,
|
||||
messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
ClientPublicKeysManager clientPublicKeysManager =
|
||||
@@ -653,8 +653,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
apnSender, fcmSender, accountsManager, 0, 0);
|
||||
PushNotificationManager pushNotificationManager =
|
||||
new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler);
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster);
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
@@ -970,7 +968,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final MetricsHttpChannelListener metricsHttpChannelListener = new MetricsHttpChannelListener(clientReleaseManager,
|
||||
Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
|
||||
metricsHttpChannelListener.configure(environment);
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageMetrics messageMetrics = new MessageMetrics(config.getDynamoDbTables().getMessages().getExpiration());
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
|
||||
@@ -996,8 +994,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, redisMessageAvailabilityManager, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager));
|
||||
pushNotificationScheduler, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
|
||||
));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
|
||||
-15
@@ -6,8 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -26,7 +24,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
@@ -34,9 +31,6 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CloudflareTurnCredentialsManager.class);
|
||||
|
||||
private static final String CREDENTIAL_FETCH_TIMER_NAME = MetricsUtil.name(CloudflareTurnCredentialsManager.class,
|
||||
"credentialFetchLatency");
|
||||
|
||||
private final List<String> cloudflareTurnUrls;
|
||||
private final List<String> cloudflareTurnUrlsWithIps;
|
||||
private final String cloudflareTurnHostname;
|
||||
@@ -119,20 +113,11 @@ public class CloudflareTurnCredentialsManager {
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "success")
|
||||
.register(Metrics.globalRegistry));
|
||||
} catch (CompletionException e) {
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
sample.stop(Timer.builder(CREDENTIAL_FETCH_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags("outcome", "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
}
|
||||
|
||||
|
||||
-7
@@ -8,8 +8,6 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
import com.fasterxml.jackson.annotation.JsonAnyGetter;
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.micrometer.registry.otlp.HistogramFlavor;
|
||||
import io.micrometer.registry.otlp.OtlpConfig;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
@@ -35,11 +33,6 @@ public record OpenTelemetryConfiguration(
|
||||
return maxBucketsPerMeter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HistogramFlavor histogramFlavor() {
|
||||
return HistogramFlavor.BASE2_EXPONENTIAL_BUCKET_HISTOGRAM;
|
||||
}
|
||||
|
||||
public Duration shutdownWaitDuration() {
|
||||
if (shutdownWaitDuration == null) {
|
||||
return step().plus(step().dividedBy(2));
|
||||
|
||||
+8
-2
@@ -394,6 +394,8 @@ public class DeviceController {
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
accountAndSample.second().stop(Timer.builder(WAIT_FOR_LINKED_DEVICE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(100))
|
||||
.maximumExpectedValue(Duration.ofMinutes(1))
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry));
|
||||
}
|
||||
@@ -448,6 +450,8 @@ public class DeviceController {
|
||||
|
||||
private static boolean isCapabilityDowngrade(final Account account, final Set<DeviceCapability> capabilities) {
|
||||
final Set<DeviceCapability> requiredCapabilities = Arrays.stream(DeviceCapability.values())
|
||||
// `ALWAYS_CAPABLE` capabilities are always assumed to be present, so we don't require callers to specify them
|
||||
.filter(capability -> capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE)
|
||||
.filter(DeviceCapability::preventDowngrade)
|
||||
.filter(account::hasCapability)
|
||||
.collect(Collectors.toSet());
|
||||
@@ -541,7 +545,7 @@ public class DeviceController {
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
io.micrometer.core.instrument.Tag.of(
|
||||
HAS_REGISTRATION_ID_TAG_NAME,
|
||||
String.valueOf(transferArchiveUploadedRequest.registrationId().isPresent()))
|
||||
String.valueOf(transferArchiveUploadedRequest.destinationDeviceRegistrationId().isPresent()))
|
||||
)).increment();
|
||||
return rateLimiters.getUploadTransferArchiveLimiter()
|
||||
.validateAsync(authenticatedDevice.accountIdentifier())
|
||||
@@ -553,7 +557,7 @@ public class DeviceController {
|
||||
return accounts.recordTransferArchiveUpload(account,
|
||||
transferArchiveUploadedRequest.destinationDeviceId(),
|
||||
transferArchiveUploadedRequest.destinationDeviceCreated().map(Instant::ofEpochMilli),
|
||||
transferArchiveUploadedRequest.registrationId(),
|
||||
transferArchiveUploadedRequest.destinationDeviceRegistrationId(),
|
||||
transferArchiveUploadedRequest.transferArchive());
|
||||
});
|
||||
}
|
||||
@@ -612,6 +616,8 @@ public class DeviceController {
|
||||
if (response != null && response.getStatus() == Response.Status.OK.getStatusCode()) {
|
||||
accountAndSample.second().stop(Timer.builder(WAIT_FOR_TRANSFER_ARCHIVE_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(250))
|
||||
.maximumExpectedValue(Duration.ofMinutes(5))
|
||||
.tags(Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
primaryPlatformTag(accountAndSample.first())))
|
||||
|
||||
+2
@@ -61,6 +61,8 @@ public class KeepAliveController {
|
||||
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(50))
|
||||
.maximumExpectedValue(Duration.ofMinutes(2))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(age);
|
||||
}
|
||||
|
||||
-14
@@ -91,8 +91,6 @@ public class KeysController {
|
||||
private final Clock clock;
|
||||
|
||||
private static final String STORE_KEYS_COUNTER_NAME = MetricsUtil.name(KeysController.class, "storeKeys");
|
||||
private static final String STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME =
|
||||
MetricsUtil.name(KeysController.class, "storeKeyBundleSize");
|
||||
private static final String PRIMARY_DEVICE_TAG_NAME = "isPrimary";
|
||||
private static final String IDENTITY_TYPE_TAG_NAME = "identityType";
|
||||
private static final String KEY_TYPE_TAG_NAME = "keyType";
|
||||
@@ -173,12 +171,6 @@ public class KeysController {
|
||||
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
|
||||
|
||||
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(setKeysRequest.preKeys().size());
|
||||
|
||||
storeFutures.add(keysManager.storeEcOneTimePreKeys(identifier, device.getId(), setKeysRequest.preKeys()));
|
||||
}
|
||||
|
||||
@@ -194,12 +186,6 @@ public class KeysController {
|
||||
final Tags tags = Tags.of(platformTag, primaryDeviceTag, identityTypeTag, Tag.of(KEY_TYPE_TAG_NAME, "kyber"));
|
||||
Metrics.counter(STORE_KEYS_COUNTER_NAME, tags).increment();
|
||||
|
||||
DistributionSummary.builder(STORE_KEY_BUNDLE_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(setKeysRequest.pqPreKeys().size());
|
||||
|
||||
storeFutures.add(keysManager.storeKemOneTimePreKeys(identifier, device.getId(), setKeysRequest.pqPreKeys()));
|
||||
}
|
||||
|
||||
|
||||
+14
-9
@@ -110,7 +110,6 @@ import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.websocket.WebsocketHeaders;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
@@ -153,14 +152,21 @@ public class MessageController {
|
||||
INDIVIDUAL_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
|
||||
.tags(multiRecipientTagName, "false")
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(1))
|
||||
.minimumExpectedValue(Duration.ofSeconds(10))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
MULTI_RECIPIENT_MESSAGE_LATENCY_TIMER = Timer.builder(timerName)
|
||||
.tags(multiRecipientTagName, "true")
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(1))
|
||||
.minimumExpectedValue(Duration.ofSeconds(10))
|
||||
.register(Metrics.globalRegistry);
|
||||
}
|
||||
|
||||
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
|
||||
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
|
||||
|
||||
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
|
||||
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
// for additional details.
|
||||
@@ -452,6 +458,12 @@ public class MessageController {
|
||||
userAgent);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
if (messageType == MessageType.SYNC) {
|
||||
Metrics.counter(INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
}
|
||||
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevicesResponse(e.getMismatchedDevices().staleDeviceIds()))
|
||||
@@ -841,15 +853,8 @@ public class MessageController {
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
return messagesManager.delete(
|
||||
auth.accountIdentifier(),
|
||||
device,
|
||||
uuid,
|
||||
null)
|
||||
return messagesManager.delete(auth.accountIdentifier(), device, uuid, null)
|
||||
.thenAccept(maybeRemovedMessage -> maybeRemovedMessage.ifPresent(removedMessage -> {
|
||||
|
||||
WebSocketConnection.recordMessageDeliveryDuration(removedMessage.serverTimestamp(), device);
|
||||
|
||||
if (removedMessage.sourceServiceId().isPresent()
|
||||
&& removedMessage.envelopeType() != Type.SERVER_DELIVERY_RECEIPT) {
|
||||
if (removedMessage.sourceServiceId().get() instanceof AciServiceIdentifier aciServiceIdentifier) {
|
||||
|
||||
+3
-3
@@ -24,13 +24,13 @@ public record TransferArchiveUploadedRequest(
|
||||
|
||||
@Schema(description = """
|
||||
The timestamp, in milliseconds since the epoch, at which the destination device was created.
|
||||
Deprecated in favor of registrationId.
|
||||
Deprecated in favor of `destinationDeviceRegistrationId`.
|
||||
""", deprecated = true)
|
||||
@Deprecated
|
||||
Optional<@Positive Long> destinationDeviceCreated,
|
||||
|
||||
@Schema(description = "The registration ID of the destination device")
|
||||
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> registrationId,
|
||||
Optional<@Min(0) @Max(Device.MAX_REGISTRATION_ID) Integer> destinationDeviceRegistrationId,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -42,6 +42,6 @@ public record TransferArchiveUploadedRequest(
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isExactlyOneDisambiguatorProvided() {
|
||||
return destinationDeviceCreated.isPresent() ^ registrationId.isPresent();
|
||||
return destinationDeviceCreated.isPresent() ^ destinationDeviceRegistrationId.isPresent();
|
||||
}
|
||||
}
|
||||
@@ -32,15 +32,17 @@ public final class MessageMetrics {
|
||||
"mismatchedAccountEnvelopeUuid");
|
||||
|
||||
public static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
|
||||
private final Duration messageTtl;
|
||||
private final MeterRegistry metricRegistry;
|
||||
|
||||
@VisibleForTesting
|
||||
MessageMetrics(final MeterRegistry metricRegistry) {
|
||||
MessageMetrics(final MeterRegistry metricRegistry, final Duration messageTtl) {
|
||||
this.metricRegistry = metricRegistry;
|
||||
this.messageTtl = messageTtl;
|
||||
}
|
||||
|
||||
public MessageMetrics() {
|
||||
this(Metrics.globalRegistry);
|
||||
public MessageMetrics(final Duration messageTtl) {
|
||||
this(Metrics.globalRegistry, messageTtl);
|
||||
}
|
||||
|
||||
public void measureAccountOutgoingMessageUuidMismatches(final Account account,
|
||||
@@ -83,10 +85,13 @@ public final class MessageMetrics {
|
||||
tags.add(Tag.of("isUrgent", String.valueOf(isUrgent)));
|
||||
tags.add(Tag.of("isEphemeral", String.valueOf(isEphemeral)));
|
||||
|
||||
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
|
||||
// This tag makes the metric extremely expensive on some platforms
|
||||
// UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
|
||||
|
||||
Timer.builder(DELIVERY_LATENCY_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofSeconds(1))
|
||||
.maximumExpectedValue(messageTtl)
|
||||
.tags(tags)
|
||||
.register(metricRegistry)
|
||||
.record(Duration.between(Instant.ofEpochMilli(serverTimestamp), Instant.now()));
|
||||
|
||||
@@ -19,19 +19,25 @@ import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
|
||||
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.registry.otlp.HistogramFlavor;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
import io.micrometer.statsd.StatsdMeterRegistry;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.stream.IntStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
public class MetricsUtil {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MetricsUtil.class);
|
||||
|
||||
public static final String PREFIX = "chat";
|
||||
|
||||
private static volatile boolean registeredMetrics = false;
|
||||
@@ -86,6 +92,7 @@ public class MetricsUtil {
|
||||
config.getOpenTelemetryConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
configureMeterFilters(otlpMeterRegistry.config(), dynamicConfigurationManager);
|
||||
configureHistogramFilters(otlpMeterRegistry.config(), config.getOpenTelemetryConfiguration());
|
||||
Metrics.addRegistry(otlpMeterRegistry);
|
||||
|
||||
if (config.getOpenTelemetryConfiguration().shutdownWaitDuration().compareTo(shutdownWaitDuration) > 0) {
|
||||
@@ -113,7 +120,7 @@ public class MetricsUtil {
|
||||
config.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
return Optional.ofNullable(config.isPercentileHistogram()).orElse(false) ? config : defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
})
|
||||
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
|
||||
@@ -137,6 +144,54 @@ public class MetricsUtil {
|
||||
&& id.getName().startsWith(awsSdkMetricNamePrefix)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static void configureHistogramFilters(MeterRegistry.Config config, OpenTelemetryConfiguration openTelemetryConfig) {
|
||||
if (openTelemetryConfig.histogramFlavor() != HistogramFlavor.EXPLICIT_BUCKET_HISTOGRAM) {
|
||||
// This workaround for Micrometer's awful defaults is only required for explicit bucket histograms.
|
||||
return;
|
||||
}
|
||||
|
||||
config.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
if (config.isPercentileHistogram() == null || !config.isPercentileHistogram()) {
|
||||
return config;
|
||||
}
|
||||
|
||||
if (config.getMinimumExpectedValueAsDouble() == null || config.getMaximumExpectedValueAsDouble() == null) {
|
||||
log.error("Distribution {} does not specify lower or upper bounds, not exporting histograms", id.getName());
|
||||
return DistributionStatisticConfig.builder()
|
||||
.percentilesHistogram(false)
|
||||
.build()
|
||||
.merge(config);
|
||||
}
|
||||
|
||||
final double lowerBound = config.getMinimumExpectedValueAsDouble();
|
||||
final double upperBound = config.getMaximumExpectedValueAsDouble();
|
||||
|
||||
final int numBuckets = Optional.ofNullable(openTelemetryConfig.maxBucketsPerMeter().get(id.getName()))
|
||||
.orElse(openTelemetryConfig.maxBucketCount());
|
||||
|
||||
// Bucket i covers values from (buckets[i-1], buckets[i]] except the first one which covers (-inf, buckets[0]].
|
||||
// A final bucket will automatically be added at positive infinity, so if we want numBuckets total buckets, we
|
||||
// need numBuckets - 1 explicit ones; if we want those to have equal ratios between values, and want an explicit
|
||||
// bucket for (-inf, lowerBound] as well as an implicit one for (upperBound, inf], the ratio between buckets will be
|
||||
// r = (upperBound/lowerBound)^(1/(numBuckets - 2)), so that we have values at lowerBound * r^i
|
||||
// for i in [0, numBuckets-2] i.e. numBuckets - 1 values, plus the one at infinity
|
||||
final double scale = Math.pow(upperBound / lowerBound, 1.0 / (numBuckets - 2));
|
||||
final double[] buckets = IntStream.range(0, numBuckets - 1).mapToDouble(i -> lowerBound * Math.pow(scale, i)).toArray();
|
||||
|
||||
// yes, percentilesHistogram(false)! Otherwise, Micrometer will add its own non-configurable buckets based on an
|
||||
// inferior selection algorithm that produces 69(!) buckets for a range from 1ms to 30s and still yields ±25% relative error
|
||||
return DistributionStatisticConfig.builder()
|
||||
.percentilesHistogram(false)
|
||||
.serviceLevelObjectives(buckets)
|
||||
.build()
|
||||
.merge(config);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
new ProcessorMetrics().bindTo(Metrics.globalRegistry);
|
||||
new FileDescriptorMetrics().bindTo(Metrics.globalRegistry);
|
||||
|
||||
+11
-3
@@ -6,6 +6,8 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
@@ -20,6 +22,7 @@ public class OpenWebSocketCounter {
|
||||
|
||||
private final String newConnectionCounterName;
|
||||
private final String durationTimerName;
|
||||
private final Duration longestExpectedConnectionDuration;
|
||||
|
||||
private final Tags tags;
|
||||
|
||||
@@ -28,18 +31,21 @@ public class OpenWebSocketCounter {
|
||||
|
||||
public OpenWebSocketCounter(final String openWebSocketGaugeName,
|
||||
final String newConnectionCounterName,
|
||||
final String durationTimerName) {
|
||||
final String durationTimerName,
|
||||
final Duration longestExpectedConnectionDuration) {
|
||||
|
||||
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, Tags.empty());
|
||||
this(openWebSocketGaugeName, newConnectionCounterName, durationTimerName, longestExpectedConnectionDuration, Tags.empty());
|
||||
}
|
||||
|
||||
public OpenWebSocketCounter(final String openWebSocketGaugeName,
|
||||
final String newConnectionCounterName,
|
||||
final String durationTimerName,
|
||||
final Duration longestExpectedConnectionDuration,
|
||||
final Tags tags) {
|
||||
|
||||
this.newConnectionCounterName = newConnectionCounterName;
|
||||
this.durationTimerName = durationTimerName;
|
||||
this.longestExpectedConnectionDuration = longestExpectedConnectionDuration;
|
||||
|
||||
this.tags = tags;
|
||||
|
||||
@@ -83,9 +89,11 @@ public class OpenWebSocketCounter {
|
||||
|
||||
Metrics.counter(newConnectionCounterName, tagsWithClientPlatform).increment();
|
||||
|
||||
context.addWebsocketClosedListener((context1, statusCode, reason) -> {
|
||||
context.addWebsocketClosedListener((_, statusCode, _) -> {
|
||||
sample.stop(Timer.builder(durationTimerName)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofSeconds(1))
|
||||
.maximumExpectedValue(longestExpectedConnectionDuration)
|
||||
.tags(tagsWithClientPlatform)
|
||||
.register(Metrics.globalRegistry));
|
||||
|
||||
|
||||
+2
@@ -37,6 +37,8 @@ public class MultiRecipientMessageProvider implements MessageBodyReader<SealedSe
|
||||
private static final DistributionSummary RECIPIENT_COUNT_DISTRIBUTION = DistributionSummary
|
||||
.builder(name(MultiRecipientMessageProvider.class, "recipients"))
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(1.0)
|
||||
.maximumExpectedValue((double) MAX_RECIPIENT_COUNT)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -29,5 +29,5 @@ public interface MessageAvailabilityListener {
|
||||
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
|
||||
* underlying network connection.
|
||||
*/
|
||||
void handleConflictingMessageReader();
|
||||
void handleConflictingMessageConsumer();
|
||||
}
|
||||
@@ -313,26 +313,23 @@ public class MessageSender {
|
||||
final boolean isStory,
|
||||
final Tag platformTag) throws MessageTooLargeException {
|
||||
|
||||
final boolean oversize = contentLength > MAX_MESSAGE_SIZE;
|
||||
final Tags tags = Tags.of(platformTag,
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory)));
|
||||
|
||||
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(platformTag,
|
||||
Tag.of("oversize", String.valueOf(oversize)),
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory))))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(contentLength);
|
||||
|
||||
if (oversize) {
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, Tags.of(platformTag,
|
||||
Tag.of("multiRecipientMessage", String.valueOf(isMultiRecipientMessage)),
|
||||
Tag.of("syncMessage", String.valueOf(isSyncMessage)),
|
||||
Tag.of("story", String.valueOf(isStory))))
|
||||
.increment();
|
||||
if (contentLength > MAX_MESSAGE_SIZE) {
|
||||
Metrics.counter(REJECT_OVERSIZE_MESSAGE_COUNTER_NAME, tags).increment();
|
||||
|
||||
throw new MessageTooLargeException();
|
||||
} else {
|
||||
DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(256.0)
|
||||
.maximumExpectedValue((double) MAX_MESSAGE_SIZE)
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(contentLength);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -132,7 +132,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
|
||||
/**
|
||||
* Marks the given device as "present" for message delivery and registers a listener for new messages and conflicting
|
||||
* connections. If the given device already has a presence registered with this manager, that presence is displaced
|
||||
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageReader()} method is called.
|
||||
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageConsumer()} method is called.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for the newly-connected device
|
||||
* @param deviceId the ID of the newly-connected device within the given account
|
||||
@@ -176,7 +176,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
|
||||
});
|
||||
|
||||
if (displacedListener.get() != null) {
|
||||
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageReader());
|
||||
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageConsumer());
|
||||
}
|
||||
|
||||
return subscribeFuture.get()
|
||||
@@ -318,7 +318,7 @@ public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<b
|
||||
// Only act on new connections to other event manager instances; we'll learn about displacements in THIS
|
||||
// instance when we update the listener map in `handleClientConnected`
|
||||
if (!this.serverId.equals(UUIDUtil.fromByteString(clientEvent.getClientConnected().getServerId()))) {
|
||||
listenerEventExecutor.execute(listener::handleConflictingMessageReader);
|
||||
listenerEventExecutor.execute(listener::handleConflictingMessageConsumer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-12
@@ -9,7 +9,6 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.zone.ZoneRules;
|
||||
import java.util.Comparator;
|
||||
@@ -19,19 +18,21 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public class SchedulingUtil {
|
||||
private static final String PARSED_TIMEZONE_COUNTER_NAME = MetricsUtil.name(SchedulingUtil.class, "parsedTimezone");
|
||||
private static final String HAS_TIMEZONE_TAG_NAME = "hasTimezone";
|
||||
|
||||
/**
|
||||
* Gets a present or future time at which to send a notification to a device associated with the given account. This
|
||||
* is mainly intended to facilitate scheduling notifications such that they arrive during a recipient's waking hours.
|
||||
* <p/>
|
||||
* This method will attempt to use a timezone derived from the account's phone number to choose an appropriate time
|
||||
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will use
|
||||
* the account's creation time as a hint. As an example, if the account was created at 07:17 in the server's local
|
||||
* time, we can assume that the account holder was awake at that time of day, and it's likely a safe time to send a
|
||||
* notification in the absence of other hints.
|
||||
* to send a notification. If a timezone cannot be derived from the account's phone number, then this method will
|
||||
* default to the preferred time in the server's timezone.
|
||||
*
|
||||
* @param account the account that will receive the notification
|
||||
* @param preferredTime the preferred local time (e.g. "noon") at which to deliver the notification
|
||||
@@ -44,14 +45,13 @@ public class SchedulingUtil {
|
||||
final Clock clock) {
|
||||
|
||||
final ZonedDateTime candidateNotificationTime = getZoneId(account, clock)
|
||||
.map(zoneId -> ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime))
|
||||
.map(zoneId -> {
|
||||
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
|
||||
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
|
||||
})
|
||||
.orElseGet(() -> {
|
||||
// We couldn't find a reasonable timezone for the account for some reason, so make an educated guess at a
|
||||
// reasonable time to send a notification based on the account's creation time.
|
||||
final Instant accountCreation = Instant.ofEpochMilli(account.getPrimaryDevice().getCreated());
|
||||
final LocalTime accountCreationLocalTime = LocalTime.ofInstant(accountCreation, ZoneId.systemDefault());
|
||||
|
||||
return ZonedDateTime.now(ZoneId.systemDefault()).with(accountCreationLocalTime);
|
||||
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
|
||||
return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime);
|
||||
});
|
||||
|
||||
if (candidateNotificationTime.toInstant().isBefore(clock.instant())) {
|
||||
|
||||
@@ -271,6 +271,7 @@ public class Account {
|
||||
case PRIMARY_DEVICE -> getPrimaryDevice().hasCapability(capability);
|
||||
case ANY_DEVICE -> devices.stream().anyMatch(device -> device.hasCapability(capability));
|
||||
case ALL_DEVICES -> devices.stream().allMatch(device -> device.hasCapability(capability));
|
||||
case ALWAYS_CAPABLE -> true;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
/// Indicates that more than one consumer is trying to read a specific message queue at the same time.
|
||||
public class ConflictingMessageConsumerException extends NoStackTraceException {
|
||||
}
|
||||
+9
-2
@@ -10,8 +10,10 @@ import java.util.Optional;
|
||||
public enum DeviceCapability {
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false),
|
||||
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALL_DEVICES, true, true),
|
||||
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALL_DEVICES, true, true),
|
||||
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
|
||||
DELETE_SYNC("deleteSync", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
|
||||
@Deprecated(forRemoval = true) // Can be removed sometime after 11/10/2025
|
||||
STORAGE_SERVICE_RECORD_KEY_ROTATION("ssre2", AccountCapabilityMode.ALWAYS_CAPABLE, true, true),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true);
|
||||
|
||||
@@ -28,6 +30,11 @@ public enum DeviceCapability {
|
||||
* The account will have the capability iff all devices on the account have the capability
|
||||
*/
|
||||
ALL_DEVICES,
|
||||
/**
|
||||
* The account always has this capability, regardless of the constituent devices' capabilities.
|
||||
* This supports retiring capabilities where older clients still need the field provided.
|
||||
*/
|
||||
ALWAYS_CAPABLE,
|
||||
}
|
||||
|
||||
private final String name;
|
||||
|
||||
+7
-5
@@ -22,6 +22,7 @@ import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.IntStream;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -58,16 +59,17 @@ public class MessagePersister implements Managed {
|
||||
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
|
||||
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
|
||||
name(MessagePersister.class, "queueCount"))
|
||||
.publishPercentileHistogram(true)
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
|
||||
|
||||
static final int QUEUE_BATCH_LIMIT = 100;
|
||||
static final int MESSAGE_BATCH_LIMIT = 100;
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY = DistributionSummary.builder(
|
||||
name(MessagePersister.class, "queueCount"))
|
||||
.publishPercentiles(new double[0])
|
||||
.serviceLevelObjectives(IntStream.range(1, QUEUE_BATCH_LIMIT + 1).mapToDouble(i -> i).toArray())
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
|
||||
|
||||
private static final int CONSECUTIVE_EMPTY_CACHE_REMOVAL_LIMIT = 3;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
|
||||
/// A message stream publishes an ordered stream of Signal messages from a destination device's queue and provides a
|
||||
/// mechanism for consumers to acknowledge receipt of delivered messages.
|
||||
public interface MessageStream {
|
||||
|
||||
/// Publishes a non-terminating stream of [MessageStreamEntry.Envelope] entities and at most one
|
||||
/// [MessageStreamEntry.QueueEmpty].
|
||||
///
|
||||
/// @return a non-terminating stream of message stream entries
|
||||
Flow.Publisher<MessageStreamEntry> getMessages();
|
||||
|
||||
/// Acknowledges receipt of the given message. Implementations may delete the message immediately or defer deletion for
|
||||
/// inclusion in a more efficient batch deletion.
|
||||
///
|
||||
/// @param message the message to acknowledge
|
||||
///
|
||||
/// @return a future that completes when the message stream has processed the acknowledgement
|
||||
CompletableFuture<Void> acknowledgeMessage(MessageProtos.Envelope message);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
|
||||
/// A `MessageStreamEntr` is an entity that can be emitted by the publisher returned by [MessageStream#getMessages()].
|
||||
/// Message stream entries either produce an individual message (see [Envelope]) or that the initial contents of a
|
||||
/// message queue have been drained (see [QueueEmpty]).
|
||||
public sealed interface MessageStreamEntry permits MessageStreamEntry.Envelope, MessageStreamEntry.QueueEmpty {
|
||||
|
||||
/// A message stream entry that carries a single message.
|
||||
///
|
||||
/// @param message the message emitted by the publisher
|
||||
record Envelope(MessageProtos.Envelope message) implements MessageStreamEntry {
|
||||
}
|
||||
|
||||
/// A message stream entry that indicates that the initial contents of a message queue have been emitted by the
|
||||
/// publisher; any [Envelope] entries after a `QueueEmpty` entry arrived after caller started reading
|
||||
/// messages from the queue.
|
||||
record QueueEmpty() implements MessageStreamEntry {
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,7 @@ public class MessagesManager {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
@@ -64,12 +65,14 @@ public class MessagesManager {
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ReportMessageManager reportMessageManager,
|
||||
final ExecutorService messageDeletionExecutor,
|
||||
final Clock clock) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.clock = clock;
|
||||
@@ -221,6 +224,10 @@ public class MessagesManager {
|
||||
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) {
|
||||
|
||||
|
||||
+4
-1
@@ -22,6 +22,8 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -73,7 +75,8 @@ public class PagedSingleUseKEMPreKeyStore {
|
||||
|
||||
final DistributionSummary availableKeyCountDistributionSummary = DistributionSummary
|
||||
.builder(name(getClass(), "availableKeyCount"))
|
||||
.publishPercentileHistogram()
|
||||
.publishPercentiles(new double[0])
|
||||
.serviceLevelObjectives(IntStream.range(1, 102).mapToDouble(i -> i).toArray())
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private final String takeKeyTimerName = name(getClass(), "takeKey");
|
||||
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Flow;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
/// A Redis/DynamoDB message publisher produces a non-terminating stream of messages for a specific device. It listens
|
||||
/// for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its subscriber
|
||||
/// when available.
|
||||
///
|
||||
/// This publisher supports only a single subscriber. It assumes that subscribers acknowledge (delete) messages as they
|
||||
/// read the messages, and may emit duplicate messages if subscribers do not acknowledge messages before requesting more
|
||||
/// messages.
|
||||
class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow.Publisher<MessageStreamEntry> {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
// Indicates which data source(s) we think might contain messages for the destination device. Messages initially land
|
||||
// in Redis, but are eventually "persisted" to DynamoDB. This state changes in response to signals this publisher
|
||||
// receives as a MessageAvailabilityListener. As an initial state, we assume that we have messages in both DynamoDB
|
||||
// and Redis.
|
||||
private StoredMessageState storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
|
||||
// The number of messages the downstream subscriber is ready to receive. This changes in response to new requests from
|
||||
// the downstream subscriber and gets decremented every time we publish a message.
|
||||
private long unmetDemand = 0;
|
||||
|
||||
// Although technically nullable, operation of this publisher really begins once we get a subscriber. This publisher
|
||||
// supports only a single subscriber.
|
||||
@Nullable private Flow.Subscriber<? super MessageStreamEntry> subscriber;
|
||||
|
||||
// If terminated (i.e. by an error or by downstream cancellation), this publisher will stop emitting signals. Once
|
||||
// terminated, a publisher cannot be un-terminated.
|
||||
private boolean terminated = false;
|
||||
|
||||
// This publisher will emit exactly one "queue empty" signal once the initial contents of the message queue have been
|
||||
// drained. Once emitted, this flag is set to `true` and will never change again.
|
||||
private boolean publishedQueueEmptySignal = false;
|
||||
|
||||
// …but we may not be able to send the "queue empty" signal downstream immediately if there's no demand. This flag
|
||||
// tracks whether we're ready to publish a "queue empty" signal, regardless of whether we've actually sent it. Once
|
||||
// this flag is set to `true`, it will never change again.
|
||||
private boolean readyToPublishQueueEmptySignal = false;
|
||||
|
||||
// A message source subscriber subscribes to messages from upstream data sources (i.e. DynamoDB and Redis), and this
|
||||
// publisher relays signals the message source subscriber to the downstream subscriber. The message source subscriber
|
||||
// may be null if we're not actively fetching messages from an upstream source and changes every time an upstream
|
||||
// publisher completes.
|
||||
@Nullable private MessageSourceSubscriber messageSourceSubscriber;
|
||||
|
||||
private static final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME =
|
||||
name(RedisDynamoDbMessagePublisher.class, "getMessagesForDevice");
|
||||
|
||||
private enum StoredMessageState {
|
||||
// Indicates that stored messages are available in at least DynamoDB and possibly also Redis
|
||||
PERSISTED_NEW_MESSAGES_AVAILABLE,
|
||||
|
||||
// Indicates that messages are available in Redis, but have not yet been persisted to DynamoDB
|
||||
CACHED_NEW_MESSAGES_AVAILABLE,
|
||||
|
||||
// Indicates that no new messages are available in either Redis or DynamoDB
|
||||
EMPTY
|
||||
}
|
||||
|
||||
/// A message source subscriber subscribes to upstream message source publishers and relays signals to the downstream
|
||||
/// subscriber via the parent `RedisDynamoDbMessagePublisher`.
|
||||
private static class MessageSourceSubscriber extends BaseSubscriber<MessageProtos.Envelope> {
|
||||
|
||||
private final RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher;
|
||||
|
||||
private MessageSourceSubscriber(RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher) {
|
||||
this.redisDynamoDbMessagePublisher = redisDynamoDbMessagePublisher;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
final long unmetDemand = redisDynamoDbMessagePublisher.getUnmetDemand();
|
||||
|
||||
// If we already have some unmet demand, pass that on to the upstream publisher immediately on subscribing
|
||||
if (unmetDemand > 0) {
|
||||
subscription.request(unmetDemand);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnNext(final MessageProtos.Envelope message) {
|
||||
redisDynamoDbMessagePublisher.handleNextMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnComplete() {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnError(final Throwable throwable) {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
RedisDynamoDbMessagePublisher(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final UUID accountIdentifier,
|
||||
final Device device) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void subscribe(final Flow.Subscriber<? super MessageStreamEntry> subscriber) {
|
||||
if (this.subscriber != null) {
|
||||
subscriber.onError(new IllegalStateException("Redis/DynamoDB message publisher only allows one subscriber"));
|
||||
return;
|
||||
}
|
||||
|
||||
this.subscriber = subscriber;
|
||||
|
||||
// Listen for signals indicating that new messages are available in Redis, that messages have been persisted from
|
||||
// Redis to DynamoDB, or that there's a conflicting message reader connected somewhere else
|
||||
redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this);
|
||||
|
||||
subscriber.onSubscribe(new Flow.Subscription() {
|
||||
@Override
|
||||
public void request(final long n) {
|
||||
addDemand(n);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
terminate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleNewMessageAvailable() {
|
||||
// We only need to take action if we think there aren't already messages to pass downstream. Any other stored
|
||||
// message state implies that we're either actively sending messages downstream or we're waiting for demand from the
|
||||
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
|
||||
// we receive a request for more messages or when the current upstream publisher completes.
|
||||
if (storedMessageState == StoredMessageState.EMPTY) {
|
||||
storedMessageState = StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE;
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleMessagesPersisted() {
|
||||
// We only need to take action if we think there aren't already messages in DynamoDB. If we're already aware of
|
||||
// messages in DynamoDB, then we're either actively sending messages downstream or we're waiting for demand from the
|
||||
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
|
||||
// we receive a request for more messages or when the current upstream publisher completes.
|
||||
if (storedMessageState != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE) {
|
||||
storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleConflictingMessageConsumer() {
|
||||
// We don't register as a listener for conflicting consumer signals until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
subscriber.onError(new ConflictingMessageConsumerException());
|
||||
}
|
||||
|
||||
terminate();
|
||||
}
|
||||
|
||||
private synchronized boolean maybeSendQueueEmptySignal() {
|
||||
// Regardless of any other state, don't do anything if terminated
|
||||
if (terminated) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (readyToPublishQueueEmptySignal && !publishedQueueEmptySignal && getUnmetDemand() > 0) {
|
||||
subscriber.onNext(new MessageStreamEntry.QueueEmpty());
|
||||
unmetDemand -= 1;
|
||||
|
||||
assert unmetDemand >= 0;
|
||||
|
||||
publishedQueueEmptySignal = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private synchronized void maybeGenerateMessageSource() {
|
||||
// Regardless of any other state, don't do anything if terminated
|
||||
if (terminated) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (storedMessageState == StoredMessageState.EMPTY || unmetDemand == 0) {
|
||||
// We don't think there are any messages in either source or there's no demand for messages; either way, wait for
|
||||
// things to change before trying to generate a message source
|
||||
return;
|
||||
}
|
||||
|
||||
// We maybe be able to skip reading from DynamoDB entirely if we think messages are only stored in Redis
|
||||
final Publisher<MessageProtos.Envelope> dynamoPublisher =
|
||||
storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
? messagesDynamoDb.load(accountIdentifier, device, null)
|
||||
: Flux.empty();
|
||||
|
||||
final Publisher<MessageProtos.Envelope> redisPublisher = messagesCache.get(accountIdentifier, device.getId());
|
||||
|
||||
final Flux<MessageProtos.Envelope> messageSource = Flux.concat(dynamoPublisher, redisPublisher)
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
|
||||
messageSourceSubscriber = new MessageSourceSubscriber(this);
|
||||
messageSource.subscribe(messageSourceSubscriber);
|
||||
|
||||
// If nothing else happens before the DynamoDB/Redis publisher completes, then we'll have emptied all stored
|
||||
// messages; new signals about persisted messages or newly-arrived messages will change this state
|
||||
storedMessageState = StoredMessageState.EMPTY;
|
||||
}
|
||||
|
||||
private synchronized void handleNextMessage(final MessageProtos.Envelope message) {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
unmetDemand -= 1;
|
||||
assert unmetDemand >= 0;
|
||||
|
||||
subscriber.onNext(new MessageStreamEntry.Envelope(message));
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceComplete() {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
messageSourceSubscriber = null;
|
||||
|
||||
// Attempt to send a "queue empty" signal if we haven't already
|
||||
readyToPublishQueueEmptySignal = true;
|
||||
maybeSendQueueEmptySignal();
|
||||
|
||||
// New messages may have arrived already; fetch them if possible
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceError(final Throwable throwable) {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
subscriber.onError(throwable);
|
||||
terminate();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void addDemand(final long demand) {
|
||||
if (demand <= 0) {
|
||||
throw new IllegalArgumentException("Demand must be positive");
|
||||
}
|
||||
|
||||
unmetDemand += demand;
|
||||
|
||||
// We may have been waiting for non-zero demand before sending a "queue empty" signal
|
||||
final boolean sentQueueEmptySignal = maybeSendQueueEmptySignal();
|
||||
|
||||
// This is a little tricky; if we already have a subscriber, we only want to request NEW demand, not the total
|
||||
// outstanding demand. On top of that, we may have consumed some demand by sending a "queue empty" message.
|
||||
final long newDemand = demand - (sentQueueEmptySignal ? 1 : 0);
|
||||
|
||||
if (newDemand > 0) {
|
||||
if (messageSourceSubscriber != null) {
|
||||
messageSourceSubscriber.request(newDemand);
|
||||
} else {
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized long getUnmetDemand() {
|
||||
return unmetDemand;
|
||||
}
|
||||
|
||||
private synchronized void terminate() {
|
||||
if (!terminated) {
|
||||
terminated = true;
|
||||
|
||||
// Stop receiving signals about new messages/conflicting consumers
|
||||
redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId());
|
||||
|
||||
if (messageSourceSubscriber != null) {
|
||||
messageSourceSubscriber.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
|
||||
public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
private final RedisDynamoDbMessagePublisher messagePublisher;
|
||||
|
||||
public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final UUID accountIdentifier,
|
||||
final Device device) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
|
||||
this.messagePublisher = new RedisDynamoDbMessagePublisher(messagesDynamoDb,
|
||||
messagesCache,
|
||||
redisMessageAvailabilityManager,
|
||||
accountIdentifier,
|
||||
device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return messagePublisher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final MessageProtos.Envelope message) {
|
||||
final UUID guid = UUID.fromString(message.getServerGuid());
|
||||
|
||||
return messagesCache.remove(accountIdentifier, device.getId(), guid)
|
||||
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
|
||||
.orElseGet(() ->
|
||||
messagesDynamoDb.deleteMessage(accountIdentifier, device, guid, message.getServerTimestamp())
|
||||
.thenRun(Util.NOOP)));
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
///
|
||||
/// @implNote The layout of elements in FoundationDB is as follows:
|
||||
/// * messages
|
||||
/// * {aci}
|
||||
/// * last => versionstamp
|
||||
/// * {deviceId}
|
||||
/// * queue
|
||||
/// * {versionstamp_1} => envelope_1
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[] databases;
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private final Executor executor;
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor) {
|
||||
this.databases = databases;
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a message bundle for a set of devices belonging to a single recipient
|
||||
*
|
||||
* @param aci destination account identifier
|
||||
* @param messagesByDeviceId a map of deviceId => message envelope
|
||||
* @return a future that completes with a {@link Versionstamp} of the committed transaction
|
||||
*/
|
||||
public CompletableFuture<Versionstamp> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
|
||||
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
|
||||
// for details.
|
||||
return getShardForAci(aci).runAsync(transaction -> {
|
||||
insert(aci, messagesByDeviceId, transaction);
|
||||
return CompletableFuture.completedFuture(transaction.getVersionstamp());
|
||||
})
|
||||
.thenComposeAsync(Function.identity(), executor)
|
||||
.thenApply(Versionstamp::complete);
|
||||
}
|
||||
|
||||
private void insert(final AciServiceIdentifier aci, final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
messagesByDeviceId.forEach((deviceId, message) -> {
|
||||
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY, deviceQueueSubspace.packWithVersionstamp(Tuple.from(
|
||||
Versionstamp.incomplete())), message.toByteArray());
|
||||
});
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getLastMessageKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
|
||||
private Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
return databases[hashAciToShardNumber(aci)];
|
||||
}
|
||||
|
||||
private int hashAciToShardNumber(final AciServiceIdentifier aci) {
|
||||
// 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);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).get("Q");
|
||||
}
|
||||
|
||||
private Subspace getDeviceSubspace(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getAccountSubspace(aci).get(deviceId);
|
||||
}
|
||||
|
||||
private Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return MESSAGES_SUBSPACE.get(aci.uuid());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getLastMessageKey(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(aci).pack("l");
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -229,7 +229,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
try {
|
||||
return stripeClient.paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (StripeException e) {
|
||||
final String errorCode = e.getCode().toLowerCase(Locale.ROOT);
|
||||
final String errorCode = StringUtils.lowerCase(e.getCode(), Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionException.InvalidAmount(errorCode));
|
||||
|
||||
+52
-60
@@ -7,8 +7,11 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -21,12 +24,12 @@ import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -43,21 +46,18 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthenticatedConnectListener.class);
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ReceiptSender receiptSender;
|
||||
private final MessagesManager messagesManager;
|
||||
private final MessageMetrics messageMetrics;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final WebSocketConnectionBuilder webSocketConnectionBuilder;
|
||||
|
||||
private final OpenWebSocketCounter openAuthenticatedWebSocketCounter;
|
||||
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
|
||||
|
||||
@VisibleForTesting
|
||||
@FunctionalInterface
|
||||
interface WebSocketConnectionBuilder {
|
||||
WebSocketConnection buildWebSocketConnection(Account account, Device device, WebSocketClient client);
|
||||
}
|
||||
|
||||
public AuthenticatedConnectListener(
|
||||
final AccountsManager accountsManager,
|
||||
final ReceiptSender receiptSender,
|
||||
@@ -65,47 +65,63 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final MessageMetrics messageMetrics,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this(accountsManager,
|
||||
disconnectionRequestManager,
|
||||
(account, device, client) -> new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
account,
|
||||
device,
|
||||
client,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager),
|
||||
authenticated -> new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME,
|
||||
NEW_CONNECTION_COUNTER_NAME,
|
||||
CONNECTED_DURATION_TIMER_NAME,
|
||||
Duration.ofHours(3),
|
||||
Tags.of(AUTHENTICATED_TAG_NAME, String.valueOf(authenticated)))
|
||||
);
|
||||
}
|
||||
|
||||
@VisibleForTesting AuthenticatedConnectListener(
|
||||
final AccountsManager accountsManager,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final WebSocketConnectionBuilder webSocketConnectionBuilder,
|
||||
final Function<Boolean, OpenWebSocketCounter> openWebSocketCounterBuilder) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageMetrics = messageMetrics;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.webSocketConnectionBuilder = webSocketConnectionBuilder;
|
||||
|
||||
openAuthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "true"));
|
||||
|
||||
openUnauthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Tags.of(AUTHENTICATED_TAG_NAME, "false"));
|
||||
openAuthenticatedWebSocketCounter = openWebSocketCounterBuilder.apply(true);
|
||||
openUnauthenticatedWebSocketCounter = openWebSocketCounterBuilder.apply(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWebSocketConnect(final WebSocketSessionContext context) {
|
||||
|
||||
final boolean authenticated = (context.getAuthenticated() != null);
|
||||
final OpenWebSocketCounter openWebSocketCounter =
|
||||
authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter;
|
||||
|
||||
openWebSocketCounter.countOpenWebSocket(context);
|
||||
(authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter).countOpenWebSocket(context);
|
||||
|
||||
if (authenticated) {
|
||||
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
|
||||
|
||||
final Optional<Account> maybeAuthenticatedAccount = accountsManager.getByAccountIdentifier(auth.accountIdentifier());
|
||||
final Optional<Device> maybeAuthenticatedDevice = maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
|
||||
final Optional<Account> maybeAuthenticatedAccount =
|
||||
accountsManager.getByAccountIdentifier(auth.accountIdentifier());
|
||||
|
||||
final Optional<Device> maybeAuthenticatedDevice =
|
||||
maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
|
||||
|
||||
if (maybeAuthenticatedAccount.isEmpty() || maybeAuthenticatedDevice.isEmpty()) {
|
||||
log.warn("{}:{} not found when opening authenticated WebSocket", auth.accountIdentifier(), auth.deviceId());
|
||||
@@ -114,18 +130,10 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
return;
|
||||
}
|
||||
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
maybeAuthenticatedAccount.get(),
|
||||
maybeAuthenticatedDevice.get(),
|
||||
context.getClient(),
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager);
|
||||
final WebSocketConnection connection =
|
||||
webSocketConnectionBuilder.buildWebSocketConnection(maybeAuthenticatedAccount.get(),
|
||||
maybeAuthenticatedDevice.get(),
|
||||
context.getClient());
|
||||
|
||||
disconnectionRequestManager.addListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
|
||||
maybeAuthenticatedDevice.get().getId(),
|
||||
@@ -136,27 +144,11 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
maybeAuthenticatedDevice.get().getId(),
|
||||
connection);
|
||||
|
||||
// We begin the shutdown process by removing this client's "presence," which means it will again begin to
|
||||
// receive push notifications for inbound messages. We should do this first because, at this point, the
|
||||
// connection has already closed and attempts to actually deliver a message via the connection will not succeed.
|
||||
// It's preferable to start sending push notifications as soon as possible.
|
||||
redisMessageAvailabilityManager.handleClientDisconnected(auth.accountIdentifier(), auth.deviceId());
|
||||
|
||||
// Finally, stop trying to deliver messages and send a push notification if the connection is aware of any
|
||||
// undelivered messages.
|
||||
connection.stop();
|
||||
});
|
||||
|
||||
try {
|
||||
// Once we "start" the websocket connection, we'll cancel any scheduled "you may have new messages" push
|
||||
// notifications and begin delivering any stored messages for the connected device. We have not yet declared the
|
||||
// client as "present" yet. If a message arrives at this point, we will update the message availability state
|
||||
// correctly, but we may also send a spurious push notification.
|
||||
connection.start();
|
||||
|
||||
// Finally, we register this client's presence, which suppresses push notifications. We do this last because
|
||||
// receiving extra push notifications is generally preferable to missing out on a push notification.
|
||||
redisMessageAvailabilityManager.handleClientConnected(auth.accountIdentifier(), auth.deviceId(), connection);
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
|
||||
+2
-1
@@ -55,7 +55,8 @@ public class ProvisioningConnectListener implements WebSocketConnectListener {
|
||||
this.timeout = timeout;
|
||||
this.openWebSocketCounter = new OpenWebSocketCounter(MetricsUtil.name(getClass(), "openWebsockets"),
|
||||
MetricsUtil.name(getClass(), "newConnections"),
|
||||
MetricsUtil.name(getClass(), "sessionDuration"));
|
||||
MetricsUtil.name(getClass(), "sessionDuration"),
|
||||
Duration.ofSeconds(90));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+152
-220
@@ -9,32 +9,25 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.eclipse.jetty.util.StaticException;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
@@ -44,31 +37,29 @@ import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.WebSocketResourceProvider;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, DisconnectionRequestListener {
|
||||
public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
|
||||
private static final DistributionSummary messageTime = Metrics.summary(
|
||||
name(MessageController.class, "messageDeliveryDuration"));
|
||||
private static final DistributionSummary primaryDeviceMessageTime = Metrics.summary(
|
||||
name(MessageController.class, "primaryDeviceMessageDeliveryDuration"));
|
||||
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
|
||||
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
|
||||
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
|
||||
@@ -84,17 +75,15 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
"sendMessages");
|
||||
private static final String SEND_MESSAGE_ERROR_COUNTER = MetricsUtil.name(WebSocketConnection.class,
|
||||
"sendMessageError");
|
||||
private static final String MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class, "messagesAvailable");
|
||||
private static final String MESSAGES_PERSISTED_COUNTER_NAME = name(WebSocketConnection.class, "messagesPersisted");
|
||||
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
|
||||
|
||||
private static final String PRESENCE_MANAGER_TAG = "presenceManager";
|
||||
private static final String STATUS_CODE_TAG = "status";
|
||||
private static final String STATUS_MESSAGE_TAG = "message";
|
||||
private static final String ERROR_TYPE_TAG = "errorType";
|
||||
private static final String EXCEPTION_TYPE_TAG = "exceptionType";
|
||||
private static final String CONNECTED_ELSEWHERE_TAG = "connectedElsewhere";
|
||||
|
||||
private static final long SLOW_DRAIN_THRESHOLD = 10_000;
|
||||
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
|
||||
@@ -114,28 +103,21 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final Retry retrySpec;
|
||||
|
||||
private final Account authenticatedAccount;
|
||||
private final Device authenticatedDevice;
|
||||
private final MessageStream messageStream;
|
||||
private final WebSocketClient client;
|
||||
private final Tags platformTag;
|
||||
|
||||
private final Semaphore processStoredMessagesSemaphore = new Semaphore(1);
|
||||
private final AtomicReference<StoredMessageState> storedMessageState = new AtomicReference<>(
|
||||
StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
private final AtomicBoolean sentInitialQueueEmptyMessage = new AtomicBoolean(false);
|
||||
private final LongAdder sentMessageCounter = new LongAdder();
|
||||
private final AtomicLong queueDrainStartTime = new AtomicLong();
|
||||
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
|
||||
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private enum StoredMessageState {
|
||||
EMPTY,
|
||||
CACHED_NEW_MESSAGES_AVAILABLE,
|
||||
PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
}
|
||||
|
||||
public WebSocketConnection(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
final MessageMetrics messageMetrics,
|
||||
@@ -149,6 +131,38 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
client,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager,
|
||||
Retry.backoff(4, Duration.ofSeconds(1))
|
||||
.maxBackoff(Duration.ofSeconds(2))
|
||||
.filter(throwable -> !isConnectionClosedException(throwable)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
WebSocketConnection(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
final MessageMetrics messageMetrics,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final Account authenticatedAccount,
|
||||
final Device authenticatedDevice,
|
||||
final WebSocketClient client,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final Retry retrySpec) {
|
||||
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageMetrics = messageMetrics;
|
||||
@@ -161,12 +175,79 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.retrySpec = retrySpec;
|
||||
|
||||
this.messageStream =
|
||||
messagesManager.getMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice);
|
||||
|
||||
this.platformTag = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
}
|
||||
|
||||
public void start() {
|
||||
pushNotificationManager.handleMessagesRetrieved(authenticatedAccount, authenticatedDevice, client.getUserAgent());
|
||||
queueDrainStartTime.set(System.currentTimeMillis());
|
||||
processStoredMessages();
|
||||
|
||||
final long queueDrainStartNanos = System.nanoTime();
|
||||
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
|
||||
|
||||
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
// We want to handle conflicting connections as soon as possible, and so do this before we start processing
|
||||
// messages in the `flatMapSequential` stage below. If we didn't do this first, then we'd wait for clients to
|
||||
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
|
||||
// it's also not ideal.
|
||||
.doOnError(ConflictingMessageConsumerException.class, _ -> {
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, platformTag.and(CONNECTED_ELSEWHERE_TAG, "true")).increment();
|
||||
client.close(4409, "Connected elsewhere");
|
||||
})
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.Envelope(final Envelope message)) {
|
||||
if (hasSentFirstMessage.compareAndSet(false, true)) {
|
||||
messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI),
|
||||
authenticatedDevice.getId(),
|
||||
UUID.fromString(message.getServerGuid()),
|
||||
client.getUserAgent(),
|
||||
"websocket");
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope envelope -> Mono.fromFuture(() -> sendMessage(envelope.message()))
|
||||
.retryWhen(retrySpec)
|
||||
.thenReturn(entry);
|
||||
case MessageStreamEntry.QueueEmpty _ -> Mono.just(entry);
|
||||
}, MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
// `ConflictingMessageConsumerException` is handled before processing messages
|
||||
.doOnError(throwable -> !(throwable instanceof ConflictingMessageConsumerException), throwable -> {
|
||||
measureSendMessageErrors(throwable);
|
||||
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
})
|
||||
// Make sure we process message acknowledgements before sending the "queue clear" signal
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
final Duration drainDuration = Duration.ofNanos(System.nanoTime() - queueDrainStartNanos);
|
||||
|
||||
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, platformTag).record(sentMessageCounter.sum());
|
||||
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, platformTag).record(drainDuration);
|
||||
|
||||
if (drainDuration.compareTo(SLOW_DRAIN_THRESHOLD) > 0) {
|
||||
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, platformTag).increment();
|
||||
}
|
||||
|
||||
client.sendRequest("PUT", "/api/v1/queue/empty",
|
||||
Collections.singletonList(HeaderUtils.getTimestampHeader()), Optional.empty());
|
||||
}
|
||||
})
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe());
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
@@ -177,16 +258,22 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
|
||||
client.close(1000, "OK");
|
||||
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
}
|
||||
messagesManager.mayHaveMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice)
|
||||
.thenAccept(mayHaveMessages -> {
|
||||
if (mayHaveMessages) {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessage(final Envelope message, StoredMessageInfo storedMessageInfo) {
|
||||
// clear ephemeral field from the envelope
|
||||
final Optional<byte[]> body = Optional.ofNullable(message.toBuilder().clearEphemeral().build().toByteArray());
|
||||
private CompletableFuture<Void> sendMessage(final Envelope message) {
|
||||
if (message.getStory() && !client.shouldDeliverStories()) {
|
||||
return messageStream.acknowledgeMessage(message);
|
||||
}
|
||||
|
||||
final Optional<byte[]> body = Optional.of(serializeMessage(message));
|
||||
|
||||
sendMessageCounter.increment();
|
||||
sentMessageCounter.increment();
|
||||
@@ -214,45 +301,37 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
final CompletableFuture<Void> result;
|
||||
if (isSuccessResponse(response)) {
|
||||
|
||||
result = messagesManager.delete(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice,
|
||||
storedMessageInfo.guid(), storedMessageInfo.serverTimestamp())
|
||||
.thenApply(ignored -> null);
|
||||
result = messageStream.acknowledgeMessage(message);
|
||||
|
||||
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
recordMessageDeliveryDuration(message.getServerTimestamp(), authenticatedDevice);
|
||||
sendDeliveryReceiptFor(message);
|
||||
}
|
||||
} else {
|
||||
final List<Tag> tags = new ArrayList<>(
|
||||
List.of(
|
||||
Tag.of(STATUS_CODE_TAG, String.valueOf(response.getStatus())),
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent())
|
||||
));
|
||||
Tags tags = platformTag.and(STATUS_CODE_TAG, String.valueOf(response.getStatus()));
|
||||
|
||||
// TODO Remove this once we've identified the cause of message rejections from desktop clients
|
||||
if (StringUtils.isNotBlank(response.getMessage())) {
|
||||
tags.add(Tag.of(STATUS_MESSAGE_TAG, response.getMessage()));
|
||||
}
|
||||
|
||||
Metrics.counter(NON_SUCCESS_RESPONSE_COUNTER_NAME, tags).increment();
|
||||
|
||||
result = CompletableFuture.completedFuture(null);
|
||||
// TODO Remove this once we've identified the cause of message rejections from desktop clients
|
||||
if (StringUtils.isNotBlank(response.getMessage())) {
|
||||
tags = tags.and(Tag.of(STATUS_MESSAGE_TAG, response.getMessage()));
|
||||
}
|
||||
|
||||
Metrics.counter(NON_SUCCESS_RESPONSE_COUNTER_NAME, tags).increment();
|
||||
|
||||
result = CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
return result;
|
||||
})
|
||||
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent())))
|
||||
.minimumExpectedValue(Duration.ofMillis(100))
|
||||
.maximumExpectedValue(Duration.ofDays(1))
|
||||
.tags(platformTag)
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
public static void recordMessageDeliveryDuration(long timestamp, Device messageDestinationDevice) {
|
||||
final long messageDeliveryDuration = System.currentTimeMillis() - timestamp;
|
||||
messageTime.record(messageDeliveryDuration);
|
||||
if (messageDestinationDevice.isPrimary()) {
|
||||
primaryDeviceMessageTime.record(messageDeliveryDuration);
|
||||
}
|
||||
@VisibleForTesting
|
||||
static byte[] serializeMessage(final Envelope message) {
|
||||
return message.toBuilder().clearEphemeral().build().toByteArray();
|
||||
}
|
||||
|
||||
private void sendDeliveryReceiptFor(Envelope message) {
|
||||
@@ -264,110 +343,17 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
receiptSender.sendReceipt(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
authenticatedDevice.getId(), AciServiceIdentifier.valueOf(message.getSourceServiceId()),
|
||||
message.getClientTimestamp());
|
||||
} catch (IllegalArgumentException e) {
|
||||
} catch (final IllegalArgumentException e) {
|
||||
logger.error("Could not parse UUID: {}", message.getSourceServiceId());
|
||||
} catch (Exception e) {
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to send receipt", e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSuccessResponse(WebSocketResponseMessage response) {
|
||||
private static boolean isSuccessResponse(final WebSocketResponseMessage response) {
|
||||
return response != null && response.getStatus() >= 200 && response.getStatus() < 300;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void processStoredMessages() {
|
||||
if (processStoredMessagesSemaphore.tryAcquire()) {
|
||||
final StoredMessageState state = storedMessageState.getAndSet(StoredMessageState.EMPTY);
|
||||
final boolean cachedMessagesOnly = state != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
sendMessages(cachedMessagesOnly)
|
||||
// Update our state with the outcome, send the empty queue message if we need to, and release the semaphore
|
||||
.whenComplete((ignored, cause) -> {
|
||||
try {
|
||||
if (cause != null) {
|
||||
// We failed, if the state is currently EMPTY, set it to what it was before we tried
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, state);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cleared the queue! Send a queue empty message if we need to
|
||||
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
|
||||
|
||||
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
|
||||
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDuration, TimeUnit.MILLISECONDS);
|
||||
|
||||
if (drainDuration > SLOW_DRAIN_THRESHOLD) {
|
||||
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
|
||||
client.sendRequest("PUT", "/api/v1/queue/empty",
|
||||
Collections.singletonList(HeaderUtils.getTimestampHeader()), Optional.empty());
|
||||
}
|
||||
} finally {
|
||||
processStoredMessagesSemaphore.release();
|
||||
}
|
||||
})
|
||||
// Potentially kick off more work, must happen after we release the semaphore
|
||||
.whenComplete((ignored, cause) -> {
|
||||
if (cause != null) {
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
return;
|
||||
}
|
||||
|
||||
// Success, but check if more messages came in while we were processing
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
processStoredMessages();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessages(final boolean cachedMessagesOnly) {
|
||||
final CompletableFuture<Void> queueCleared = new CompletableFuture<>();
|
||||
|
||||
final Publisher<Envelope> messages =
|
||||
messagesManager.getMessagesForDeviceReactive(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice, cachedMessagesOnly);
|
||||
|
||||
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
|
||||
|
||||
final Disposable subscription = Flux.from(messages)
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
.doOnNext(envelope -> {
|
||||
if (hasSentFirstMessage.compareAndSet(false, true)) {
|
||||
messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI),
|
||||
authenticatedDevice.getId(),
|
||||
UUID.fromString(envelope.getServerGuid()),
|
||||
client.getUserAgent(),
|
||||
"websocket");
|
||||
}
|
||||
})
|
||||
.flatMapSequential(envelope -> Mono.fromFuture(() -> sendMessage(envelope))
|
||||
.retryWhen(Retry.backoff(4, Duration.ofSeconds(1)).filter(throwable -> !isConnectionClosedException(throwable))),
|
||||
MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
.doOnError(this::measureSendMessageErrors)
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
// no additional consumer of values - it is Flux<Void> by now
|
||||
null,
|
||||
// this first error will terminate the stream, but we may get multiple errors from in-flight messages
|
||||
queueCleared::completeExceptionally,
|
||||
// completion
|
||||
() -> queueCleared.complete(null)
|
||||
);
|
||||
|
||||
messageSubscription.set(subscription);
|
||||
return queueCleared;
|
||||
}
|
||||
|
||||
private void measureSendMessageErrors(final Throwable e) {
|
||||
final String errorType;
|
||||
|
||||
@@ -380,76 +366,22 @@ public class WebSocketConnection implements MessageAvailabilityListener, Disconn
|
||||
errorType = "other";
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of(ERROR_TYPE_TAG, errorType),
|
||||
Tag.of(EXCEPTION_TYPE_TAG, e.getClass().getSimpleName())))
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER,
|
||||
platformTag.and(ERROR_TYPE_TAG, errorType, EXCEPTION_TYPE_TAG, e.getClass().getSimpleName()))
|
||||
.increment();
|
||||
}
|
||||
|
||||
private static boolean isConnectionClosedException(final Throwable throwable) {
|
||||
@VisibleForTesting
|
||||
static boolean isConnectionClosedException(final Throwable throwable) {
|
||||
return throwable instanceof java.nio.channels.ClosedChannelException ||
|
||||
throwable == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
|
||||
throwable instanceof org.eclipse.jetty.io.EofException ||
|
||||
(throwable instanceof StaticException staticException && "Closed".equals(staticException.getMessage()));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessage(Envelope envelope) {
|
||||
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
|
||||
|
||||
if (envelope.getStory() && !client.shouldDeliverStories()) {
|
||||
messagesManager.delete(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice, messageGuid, envelope.getServerTimestamp());
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
} else {
|
||||
return sendMessage(envelope, new StoredMessageInfo(messageGuid, envelope.getServerTimestamp()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleNewMessageAvailable() {
|
||||
Metrics.counter(MESSAGE_AVAILABLE_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessagesPersisted() {
|
||||
Metrics.counter(MESSAGES_PERSISTED_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.set(StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConflictingMessageReader() {
|
||||
closeConnection(4409, "Connected elsewhere");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisconnectionRequest() {
|
||||
closeConnection(4401, "Reauthentication required");
|
||||
}
|
||||
|
||||
private void closeConnection(final int code, final String message) {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
// TODO We should probably just use the status code directly
|
||||
Tag.of("connectedElsewhere", String.valueOf(code == 4409)));
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
|
||||
|
||||
client.close(code, message);
|
||||
}
|
||||
|
||||
private record StoredMessageInfo(UUID guid, long serverTimestamp) {
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, platformTag.and(CONNECTED_ELSEWHERE_TAG, "false")).increment();
|
||||
client.close(4401, "Reauthentication required");
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -266,7 +266,9 @@ record CommandDependencies(
|
||||
configuration.getReportMessageConfiguration().getReportTtl());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
configuration.getReportMessageConfiguration().getCounterTtl());
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionExecutor, Clock.systemUTC());
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
configuration.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
@@ -321,9 +323,6 @@ record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(),
|
||||
Clock.systemUTC());
|
||||
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
|
||||
final DynamoDbRecoveryManager dynamoDbRecoveryManager =
|
||||
new DynamoDbRecoveryManager(accounts, phoneNumberIdentifiers);
|
||||
|
||||
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class EncryptDeviceCreationTimestampCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String BUFFER_ARGUMENT = "buffer";
|
||||
|
||||
private static final int MAX_CONCURRENCY = 16;
|
||||
|
||||
private static final String PROCESSED_ACCOUNT_COUNTER_NAME =
|
||||
name(EncryptDeviceCreationTimestampCommand.class, "processedAccount");
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EncryptDeviceCreationTimestampCommand.class);
|
||||
|
||||
public EncryptDeviceCreationTimestampCommand() {
|
||||
super("encrypt-device-creation-timestamps", "Encrypts the creation timestamp of devices on accounts");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually update device records");
|
||||
|
||||
subparser.addArgument("--buffer")
|
||||
.type(Integer.class)
|
||||
.dest(BUFFER_ARGUMENT)
|
||||
.setDefault(16_384)
|
||||
.help("Records to buffer");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final boolean isDryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int bufferSize = getNamespace().getInt(BUFFER_ARGUMENT);
|
||||
|
||||
final Counter processedAccountCounter =
|
||||
Metrics.counter(PROCESSED_ACCOUNT_COUNTER_NAME, "dryRun", String.valueOf(isDryRun));
|
||||
|
||||
accounts
|
||||
// We've partially processed enough accounts now that this should speed up the crawler
|
||||
.filter(a -> a.getDevices().stream().anyMatch(d -> d.getCreatedAtCiphertext() == null || d.getCreatedAtCiphertext().length == 0))
|
||||
.buffer(bufferSize)
|
||||
.map(source -> {
|
||||
final List<Account> shuffled = new ArrayList<>(source);
|
||||
Collections.shuffle(shuffled);
|
||||
return shuffled;
|
||||
})
|
||||
.limitRate(2)
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(account -> {
|
||||
Mono<Void> encryptTimestampMono = isDryRun
|
||||
? Mono.empty()
|
||||
: Mono.fromFuture(
|
||||
() -> getCommandDependencies().accountsManager().updateAsync(account, a -> {
|
||||
final IdentityKey aciIdentityKey = account.getIdentityKey(IdentityType.ACI);
|
||||
for (final Device device : a.getDevices()) {
|
||||
final byte[] createdAtCiphertext = EncryptDeviceCreationTimestampUtil.encrypt(
|
||||
device.getCreated(), aciIdentityKey,
|
||||
device.getId(), device.getRegistrationId(IdentityType.ACI));
|
||||
device.setCreatedAtCiphertext(createdAtCiphertext);
|
||||
}
|
||||
}).thenRun(Util.NOOP));
|
||||
return encryptTimestampMono
|
||||
.doOnSuccess(_ -> processedAccountCounter.increment())
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
|
||||
.onErrorResume(throwable -> {
|
||||
log.warn("Failed to encrypt creation timestamps on account {}", account.getUuid(), throwable);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, MAX_CONCURRENCY)
|
||||
.then()
|
||||
.block();
|
||||
|
||||
log.info("Finished encrypting device timestamps");
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -348,7 +348,8 @@ class DeviceControllerTest {
|
||||
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
|
||||
|
||||
final int expectedStatus =
|
||||
capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
|
||||
capability.getAccountCapabilityMode() != DeviceCapability.AccountCapabilityMode.ALWAYS_CAPABLE
|
||||
&& capability.preventDowngrade() && accountHasCapability && !requestHasCapability ? 409 : 200;
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/devices/link")
|
||||
|
||||
+1
-1
@@ -195,7 +195,7 @@ class MessageControllerTest {
|
||||
new MessageController(rateLimiters, cardinalityEstimator, messageSender, receiptSender, accountsManager,
|
||||
messagesManager, phoneNumberIdentifiers, pushNotificationManager, pushNotificationScheduler,
|
||||
reportMessageManager, messageDeliveryScheduler, mock(ClientReleaseManager.class),
|
||||
serverSecretParams, SpamChecker.noop(), new MessageMetrics(), mock(MessageDeliveryLoopMonitor.class),
|
||||
serverSecretParams, SpamChecker.noop(), new MessageMetrics(Duration.ofDays(30)), mock(MessageDeliveryLoopMonitor.class),
|
||||
clock))
|
||||
.build();
|
||||
|
||||
|
||||
-3
@@ -442,9 +442,7 @@ class ProfileControllerTest {
|
||||
|
||||
@CartesianTest
|
||||
void testProfileCapabilities(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean isDeleteSyncSupported,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean isAttachmentBackfillSupported) {
|
||||
when(capabilitiesAccount.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(isDeleteSyncSupported);
|
||||
when(capabilitiesAccount.hasCapability(DeviceCapability.ATTACHMENT_BACKFILL)).thenReturn(isAttachmentBackfillSupported);
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID)
|
||||
@@ -452,7 +450,6 @@ class ProfileControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(BaseProfileResponse.class);
|
||||
|
||||
assertEquals(isDeleteSyncSupported, profile.getCapabilities().get("deleteSync"));
|
||||
assertEquals(isAttachmentBackfillSupported, profile.getCapabilities().get("attachmentBackfill"));
|
||||
}
|
||||
|
||||
|
||||
-3
@@ -100,7 +100,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
@@ -451,7 +450,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
when(account.hasCapability(any())).thenReturn(false);
|
||||
when(account.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
|
||||
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
|
||||
@@ -462,7 +460,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(true)
|
||||
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_DELETE_SYNC)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.build();
|
||||
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -42,7 +43,7 @@ class MessageMetricsTest {
|
||||
when(account.isIdentifiedBy(new AciServiceIdentifier(aci))).thenReturn(true);
|
||||
when(account.isIdentifiedBy(new PniServiceIdentifier(pni))).thenReturn(true);
|
||||
simpleMeterRegistry = new SimpleMeterRegistry();
|
||||
messageMetrics = new MessageMetrics(simpleMeterRegistry);
|
||||
messageMetrics = new MessageMetrics(simpleMeterRegistry, Duration.ofDays(30));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -10,14 +10,26 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.micrometer.core.instrument.Clock;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.cumulative.CumulativeDistributionSummary;
|
||||
import io.micrometer.core.instrument.distribution.CountAtBucket;
|
||||
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import io.micrometer.registry.otlp.OtlpMeterRegistry;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.assertj.core.api.AbstractStringAssert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMetricsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
@@ -81,4 +93,34 @@ class MetricsUtilTest {
|
||||
|
||||
assertThat(registry.getMeters()).hasSize(enableAwsSdkMetrics ? 1 : 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exponentialHistogramBuckets() {
|
||||
final OpenTelemetryConfiguration openTelemetryConfig =
|
||||
new OpenTelemetryConfiguration(true, Duration.ZERO, 8, Map.of(), Map.of());
|
||||
|
||||
// Yes, this has to be OtlpMeterRegistry—its histograms behave differently than SimpleMeterRegistry's
|
||||
final MeterRegistry registry = new OtlpMeterRegistry(openTelemetryConfig, Clock.SYSTEM);
|
||||
|
||||
MetricsUtil.configureHistogramFilters(registry.config(), openTelemetryConfig);
|
||||
final DistributionSummary summary = DistributionSummary.builder("test.distribution")
|
||||
.publishPercentileHistogram()
|
||||
.minimumExpectedValue(1.0)
|
||||
.maximumExpectedValue(64.0)
|
||||
.register(registry);
|
||||
|
||||
IntStream.range(1, 128).forEach(summary::record);
|
||||
|
||||
final CountAtBucket[] counts = summary.takeSnapshot().histogramCounts();
|
||||
assertThat(counts).containsExactly(
|
||||
new CountAtBucket(1.0, 1),
|
||||
new CountAtBucket(2.0, 1),
|
||||
new CountAtBucket(4.0, 2),
|
||||
new CountAtBucket(8.0, 4),
|
||||
new CountAtBucket(16.0, 8),
|
||||
new CountAtBucket(32.0, 16),
|
||||
new CountAtBucket(64.0, 32),
|
||||
new CountAtBucket(Double.POSITIVE_INFINITY, 63));
|
||||
}
|
||||
|
||||
}
|
||||
+3
-3
@@ -62,7 +62,7 @@ class RedisMessageAvailabilityManagerTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConflictingMessageReader() {
|
||||
public void handleConflictingMessageConsumer() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ class RedisMessageAvailabilityManagerTest {
|
||||
|
||||
localEventManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() {
|
||||
@Override
|
||||
public void handleConflictingMessageReader() {
|
||||
public void handleConflictingMessageConsumer() {
|
||||
synchronized (firstListenerDisplaced) {
|
||||
firstListenerDisplaced.set(true);
|
||||
firstListenerDisplaced.notifyAll();
|
||||
@@ -126,7 +126,7 @@ class RedisMessageAvailabilityManagerTest {
|
||||
|
||||
displacingManager.handleClientConnected(accountIdentifier, deviceId, new MessageAvailabilityAdapter() {
|
||||
@Override
|
||||
public void handleConflictingMessageReader() {
|
||||
public void handleConflictingMessageConsumer() {
|
||||
secondListenerDisplaced.set(true);
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class FaultTolerantRedisClusterClientTest {
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofMillis(50);
|
||||
private static final Duration TIMEOUT = Duration.ofMillis(200);
|
||||
|
||||
private static final RetryConfiguration RETRY_CONFIGURATION = new RetryConfiguration();
|
||||
|
||||
|
||||
+7
-15
@@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberToTimeZonesMapper;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -13,13 +12,9 @@ import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
class SchedulingUtilTest {
|
||||
@@ -51,26 +46,23 @@ class SchedulingUtilTest {
|
||||
|
||||
{
|
||||
final Account account = mock(Account.class);
|
||||
final Device primaryDevice = mock(Device.class);
|
||||
|
||||
// The account does not have a phone number that can be connected to a region/time zone
|
||||
when(account.getNumber()).thenReturn("Not a parseable number");
|
||||
when(account.getPrimaryDevice()).thenReturn(primaryDevice);
|
||||
when(primaryDevice.getCreated())
|
||||
.thenReturn(ZonedDateTime.of(2024, 7, 10, 9, 53, 12, 0, ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
|
||||
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(9, 0));
|
||||
final ZonedDateTime beforeNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(13, 59));
|
||||
final LocalTime preferredNotificationTime = LocalTime.of(14, 0);
|
||||
|
||||
assertEquals(
|
||||
beforeNotificationTime.with(LocalTime.of(9, 53, 12)).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
|
||||
beforeNotificationTime.with(preferredNotificationTime).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, preferredNotificationTime,
|
||||
Clock.fixed(beforeNotificationTime.toInstant(), ZoneId.systemDefault())));
|
||||
|
||||
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(10, 0));
|
||||
final ZonedDateTime afterNotificationTime = ZonedDateTime.now(ZoneId.systemDefault()).with(LocalTime.of(14, 1));
|
||||
|
||||
assertEquals(
|
||||
afterNotificationTime.with(LocalTime.of(9, 53, 12)).plusDays(1).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, LocalTime.of(14, 0),
|
||||
afterNotificationTime.with(preferredNotificationTime).plusDays(1).toInstant(),
|
||||
SchedulingUtil.getNextRecommendedNotificationTime(account, preferredNotificationTime,
|
||||
Clock.fixed(afterNotificationTime.toInstant(), ZoneId.systemDefault())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,6 @@ class AccountTest {
|
||||
private final Device agingSecondaryDevice = mock(Device.class);
|
||||
private final Device recentSecondaryDevice = mock(Device.class);
|
||||
private final Device oldSecondaryDevice = mock(Device.class);
|
||||
private final Device deleteSyncCapableDevice = mock(Device.class);
|
||||
private final Device deleteSyncIncapableDevice = mock(Device.class);
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@@ -58,12 +56,6 @@ class AccountTest {
|
||||
|
||||
when(oldSecondaryDevice.getLastSeen()).thenReturn(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(366));
|
||||
when(oldSecondaryDevice.getId()).thenReturn(deviceId2);
|
||||
|
||||
when(deleteSyncCapableDevice.getId()).thenReturn((byte) 1);
|
||||
when(deleteSyncCapableDevice.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(true);
|
||||
|
||||
when(deleteSyncIncapableDevice.getId()).thenReturn((byte) 2);
|
||||
when(deleteSyncIncapableDevice.hasCapability(DeviceCapability.DELETE_SYNC)).thenReturn(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -121,13 +113,21 @@ class AccountTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void isDeleteSyncSupported() {
|
||||
void hardcodedCapabilities() {
|
||||
final Device mockDevice = mock(Device.class);
|
||||
when(mockDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(deleteSyncCapableDevice),
|
||||
List.of(mockDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.DELETE_SYNC));
|
||||
|
||||
assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(mockDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.STORAGE_SERVICE_RECORD_KEY_ROTATION));
|
||||
|
||||
assertFalse(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(deleteSyncIncapableDevice, deleteSyncCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.DELETE_SYNC));
|
||||
List.of(mockDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).hasCapability(DeviceCapability.TRANSFER));
|
||||
}
|
||||
|
||||
void stale() {
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import java.io.IOException;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
public class FoundationDbExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
|
||||
|
||||
private static FoundationDbDatabaseLifecycleManager databaseLifecycleManager;
|
||||
|
||||
|
||||
+3
-3
@@ -82,8 +82,8 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService, Clock.systemUTC());
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(RedisMessageAvailabilityManager.class),
|
||||
mock(ReportMessageManager.class), messageDeletionExecutorService, Clock.systemUTC());
|
||||
|
||||
websocketConnectionEventExecutor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
asyncOperationQueueingExecutor = Executors.newSingleThreadExecutor();
|
||||
@@ -165,7 +165,7 @@ class MessagePersisterIntegrationTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConflictingMessageReader() {
|
||||
public void handleConflictingMessageConsumer() {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+2
-1
@@ -40,6 +40,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MultiRecipientMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestRecipient;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
@@ -54,7 +55,7 @@ class MessagesManagerTest {
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.now());
|
||||
|
||||
private final MessagesManager messagesManager = new MessagesManager(messagesDynamoDb, messagesCache,
|
||||
reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK);
|
||||
mock(RedisMessageAvailabilityManager.class), reportMessageManager, Executors.newSingleThreadExecutor(), CLOCK);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class RedisDynamoDbMessagePublisherTest {
|
||||
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private static ExecutorService sharedExecutorService;
|
||||
private static Scheduler messageDeliveryScheduler;
|
||||
|
||||
private Device destinationDevice;
|
||||
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.MESSAGES);
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private static final AtomicLong SERIAL_TIMESTAMP = new AtomicLong(0);
|
||||
|
||||
private static final ServiceIdentifier DESTINATION_SERVICE_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
sharedExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.MESSAGES.tableName(),
|
||||
Duration.ofDays(14),
|
||||
sharedExecutorService);
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
|
||||
redisMessageAvailabilityManager = mock(RedisMessageAvailabilityManager.class);
|
||||
|
||||
destinationDevice = mock(Device.class);
|
||||
when(destinationDevice.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
when(destinationDevice.getCreated()).thenReturn(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() {
|
||||
sharedExecutorService.shutdown();
|
||||
messageDeliveryScheduler.dispose();
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscribeDispose() {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
when(device.getCreated()).thenReturn(System.currentTimeMillis());
|
||||
|
||||
{
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final RedisDynamoDbMessagePublisher _ =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
|
||||
|
||||
verify(redisMessageAvailabilityManager, never()).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
|
||||
verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId));
|
||||
}
|
||||
|
||||
{
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe();
|
||||
|
||||
verify(redisMessageAvailabilityManager).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
|
||||
verify(redisMessageAvailabilityManager, never()).handleClientDisconnected(eq(accountIdentifier), eq(deviceId));
|
||||
}
|
||||
|
||||
{
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, accountIdentifier, device);
|
||||
|
||||
final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher).subscribe();
|
||||
disposable.dispose();
|
||||
|
||||
verify(redisMessageAvailabilityManager).handleClientConnected(eq(accountIdentifier), eq(deviceId), any());
|
||||
verify(redisMessageAvailabilityManager).handleClientDisconnected(eq(accountIdentifier), eq(deviceId));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessages() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesDynamoDbOnly() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesRedisOnly() {
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesTailNewRedisMessages() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final MessageProtos.Envelope newArrivalRedisMessage = generateRandomMessage();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
queueEmptyCountDownLatch.await();
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
deleteRedisMessage(redisMessage);
|
||||
deleteDynamoDbMessage(dynamoDbMessage);
|
||||
|
||||
insertRedisMessage(newArrivalRedisMessage);
|
||||
messagePublisher.handleNewMessageAvailable();
|
||||
});
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
queueEmptyCountDownLatch.countDown();
|
||||
}
|
||||
}))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.expectNext(new MessageStreamEntry.Envelope(newArrivalRedisMessage))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesTailNewPersistedMessages() {
|
||||
final MessageProtos.Envelope dynamoDbMessage = insertDynamoDbMessage(generateRandomMessage());
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
final MessageProtos.Envelope persistedMessage = generateRandomMessage();
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final CountDownLatch queueEmptyCountDownLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
queueEmptyCountDownLatch.await();
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
deleteRedisMessage(redisMessage);
|
||||
deleteDynamoDbMessage(dynamoDbMessage);
|
||||
|
||||
insertDynamoDbMessage(persistedMessage);
|
||||
messagePublisher.handleMessagesPersisted();
|
||||
});
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
queueEmptyCountDownLatch.countDown();
|
||||
}
|
||||
}))
|
||||
.expectNext(new MessageStreamEntry.Envelope(dynamoDbMessage))
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.expectNext(new MessageStreamEntry.Envelope(persistedMessage))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMessagesConsumerConflict() {
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final CountDownLatch countDownLatch = new CountDownLatch(1);
|
||||
|
||||
Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
countDownLatch.await();
|
||||
} catch (final InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
messagePublisher.handleConflictingMessageConsumer();
|
||||
});
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnSubscribe(_ -> countDownLatch.countDown()))
|
||||
.expectError(ConflictingMessageConsumerException.class)
|
||||
.verify();
|
||||
|
||||
verify(redisMessageAvailabilityManager, timeout(1_000)).handleClientConnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), messagePublisher);
|
||||
verify(redisMessageAvailabilityManager, timeout(1_000)).handleClientDisconnected(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"207, 173",
|
||||
"323, 0",
|
||||
"0, 221",
|
||||
})
|
||||
void publishMessagesMultipleRequests(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
|
||||
for (int i = 0; i < persistedMessageCount; i++) {
|
||||
expectedMessages.add(insertDynamoDbMessage(generateRandomMessage()));
|
||||
}
|
||||
|
||||
for (int i = 0; i < cachedMessageCount; i++) {
|
||||
expectedMessages.add(insertRedisMessage(generateRandomMessage()));
|
||||
}
|
||||
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
final List<MessageProtos.Envelope> publishedMessages = new ArrayList<>(expectedMessages.size());
|
||||
|
||||
final CompletableFuture<Void> queueEmptyFuture = new CompletableFuture<>();
|
||||
|
||||
final Disposable disposable = JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.limitRate(20)
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
|
||||
publishedMessages.add(message);
|
||||
} else if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
queueEmptyFuture.complete(null);
|
||||
}
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
queueEmptyFuture.thenRun(disposable::dispose).join();
|
||||
|
||||
assertEquals(expectedMessages, publishedMessages);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishQueueEmptySignalDeferred() {
|
||||
final MessageProtos.Envelope redisMessage = insertRedisMessage(generateRandomMessage());
|
||||
|
||||
{
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 1)
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
|
||||
{
|
||||
final RedisDynamoDbMessagePublisher messagePublisher =
|
||||
new RedisDynamoDbMessagePublisher(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messagePublisher), 2)
|
||||
.expectNext(new MessageStreamEntry.Envelope(redisMessage))
|
||||
.expectNext(new MessageStreamEntry.QueueEmpty())
|
||||
.verifyTimeout(Duration.ofMillis(500));
|
||||
}
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope insertRedisMessage(final MessageProtos.Envelope message) {
|
||||
messagesCache.insert(UUID.fromString(message.getServerGuid()),
|
||||
DESTINATION_SERVICE_IDENTIFIER.uuid(),
|
||||
destinationDevice.getId(),
|
||||
message)
|
||||
.join();
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private void deleteRedisMessage(final MessageProtos.Envelope message) {
|
||||
messagesCache.remove(DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice.getId(), UUID.fromString(message.getServerGuid())).join();
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope insertDynamoDbMessage(final MessageProtos.Envelope message) {
|
||||
messagesDynamoDb.store(List.of(message), DESTINATION_SERVICE_IDENTIFIER.uuid(), destinationDevice);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private void deleteDynamoDbMessage(final MessageProtos.Envelope message) {
|
||||
messagesDynamoDb.deleteMessage(DESTINATION_SERVICE_IDENTIFIER.uuid(),
|
||||
destinationDevice,
|
||||
UUID.fromString(message.getServerGuid()),
|
||||
message.getServerTimestamp())
|
||||
.join();
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage() {
|
||||
|
||||
final long timestamp = SERIAL_TIMESTAMP.incrementAndGet();
|
||||
|
||||
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(timestamp)
|
||||
.setServerTimestamp(timestamp)
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.secure().nextAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.setDestinationServiceId(DESTINATION_SERVICE_IDENTIFIER.toServiceIdentifierString());
|
||||
|
||||
return envelopeBuilder.build();
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
|
||||
class RedisDynamoDbMessageStreamTest {
|
||||
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
|
||||
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
|
||||
private Device device;
|
||||
|
||||
private static final UUID ACCOUNT_IDENTIFIER = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
messagesDynamoDb = mock(MessagesDynamoDb.class);
|
||||
messagesCache = mock(MessagesCache.class);
|
||||
|
||||
device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
|
||||
redisDynamoDbMessageStream = new RedisDynamoDbMessageStream(messagesDynamoDb,
|
||||
messagesCache,
|
||||
mock(RedisMessageAvailabilityManager.class),
|
||||
ACCOUNT_IDENTIFIER,
|
||||
device);
|
||||
|
||||
when(messagesDynamoDb.deleteMessage(any(), any(), any(), anyLong()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
when(messagesCache.remove(any(), anyByte(), any(UUID.class)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgeMessageDynamoDb() {
|
||||
final MessageProtos.Envelope message = generateMessage();
|
||||
final UUID messageGuid = UUID.fromString(message.getServerGuid());
|
||||
final long serverTimestamp = message.getServerTimestamp();
|
||||
|
||||
when(messagesDynamoDb.deleteMessage(ACCOUNT_IDENTIFIER, device, messageGuid, serverTimestamp))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(message)));
|
||||
|
||||
redisDynamoDbMessageStream.acknowledgeMessage(message).join();
|
||||
|
||||
verify(messagesCache).remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
|
||||
verify(messagesDynamoDb).deleteMessage(ACCOUNT_IDENTIFIER, device, messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acknowledgeMessageRedis() {
|
||||
final MessageProtos.Envelope message = generateMessage();
|
||||
final UUID messageGuid = UUID.fromString(message.getServerGuid());
|
||||
final long serverTimestamp = message.getServerTimestamp();
|
||||
|
||||
when(messagesCache.remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(RemovedMessage.fromEnvelope(message))));
|
||||
|
||||
redisDynamoDbMessageStream.acknowledgeMessage(message).join();
|
||||
|
||||
verify(messagesCache).remove(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
|
||||
verify(messagesDynamoDb, never()).deleteMessage(any(), any(), any(), anyLong());
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateMessage() {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.setDestinationServiceId(new AciServiceIdentifier(ACCOUNT_IDENTIFIER).toServiceIdentifierString())
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setClientTimestamp(System.currentTimeMillis())
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbExtension;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class FoundationDbMessageStoreTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbExtension FOUNDATION_DB_EXTENSION = new FoundationDbExtension();
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
new Database[]{FOUNDATION_DB_EXTENSION.getDatabase()},
|
||||
Executors.newVirtualThreadPerTaskExecutor());
|
||||
}
|
||||
|
||||
@Test
|
||||
void insert() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage()));
|
||||
final Versionstamp versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
|
||||
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), deviceId -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
|
||||
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
|
||||
assertEquals(versionstamp, getLastMessageVersionstamp(aci),
|
||||
"last message versionstamp should be the versionstamp of the last insert transaction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
final Versionstamp secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
assertEquals(secondMessageVersionstamp, getLastMessageVersionstamp(aci));
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage() {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.build();
|
||||
}
|
||||
|
||||
private byte[] getMessageByVersionstamp(final AciServiceIdentifier aci, final byte deviceId,
|
||||
final Versionstamp versionstamp) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase().read(transaction -> {
|
||||
final byte[] key = foundationDbMessageStore.getDeviceQueueSubspace(aci, deviceId)
|
||||
.pack(Tuple.from(versionstamp));
|
||||
return transaction.get(key);
|
||||
}).join();
|
||||
}
|
||||
|
||||
private Versionstamp getLastMessageVersionstamp(final AciServiceIdentifier aci) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase()
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getLastMessageKey(aci))
|
||||
.thenApply(Tuple::fromBytes)
|
||||
.thenApply(t -> t.getVersionstamp(0)))
|
||||
.join();
|
||||
}
|
||||
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
class AuthenticatedConnectListenerTest {
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private DisconnectionRequestManager disconnectionRequestManager;
|
||||
|
||||
private WebSocketConnection authenticatedWebSocketConnection;
|
||||
private AuthenticatedConnectListener authenticatedConnectListener;
|
||||
|
||||
private Account authenticatedAccount;
|
||||
private WebSocketClient webSocketClient;
|
||||
private WebSocketSessionContext webSocketSessionContext;
|
||||
|
||||
private static final UUID ACCOUNT_IDENTIFIER = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUpBeforeEach() {
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
|
||||
authenticatedWebSocketConnection = mock(WebSocketConnection.class);
|
||||
|
||||
authenticatedConnectListener = new AuthenticatedConnectListener(accountsManager,
|
||||
disconnectionRequestManager,
|
||||
(_, _, _) -> authenticatedWebSocketConnection,
|
||||
_ -> mock(OpenWebSocketCounter.class));
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
|
||||
authenticatedAccount = mock(Account.class);
|
||||
when(authenticatedAccount.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER);
|
||||
when(authenticatedAccount.getDevice(DEVICE_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
webSocketClient = mock(WebSocketClient.class);
|
||||
|
||||
webSocketSessionContext = mock(WebSocketSessionContext.class);
|
||||
when(webSocketSessionContext.getClient()).thenReturn(webSocketClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectAuthenticated() {
|
||||
when(webSocketSessionContext.getAuthenticated()).thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
when(webSocketSessionContext.getAuthenticated(AuthenticatedDevice.class))
|
||||
.thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER)).thenReturn(Optional.of(authenticatedAccount));
|
||||
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(disconnectionRequestManager).addListener(ACCOUNT_IDENTIFIER, DEVICE_ID, authenticatedWebSocketConnection);
|
||||
verify(webSocketSessionContext).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectAuthenticatedAccountNotFound() {
|
||||
when(webSocketSessionContext.getAuthenticated()).thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
when(webSocketSessionContext.getAuthenticated(AuthenticatedDevice.class))
|
||||
.thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER)).thenReturn(Optional.empty());
|
||||
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(webSocketClient).close(eq(1011), anyString());
|
||||
|
||||
verify(disconnectionRequestManager, never()).addListener(any(), anyByte(), any());
|
||||
verify(webSocketSessionContext, never()).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection, never()).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectAuthenticatedStartException() {
|
||||
when(webSocketSessionContext.getAuthenticated()).thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
when(webSocketSessionContext.getAuthenticated(AuthenticatedDevice.class))
|
||||
.thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER)).thenReturn(Optional.of(authenticatedAccount));
|
||||
doThrow(new RuntimeException()).when(authenticatedWebSocketConnection).start();
|
||||
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(disconnectionRequestManager).addListener(ACCOUNT_IDENTIFIER, DEVICE_ID, authenticatedWebSocketConnection);
|
||||
verify(webSocketSessionContext).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection).start();
|
||||
|
||||
verify(webSocketClient).close(eq(1011), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectUnauthenticated() {
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(disconnectionRequestManager, never()).addListener(any(), anyByte(), any());
|
||||
verify(webSocketSessionContext, never()).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection, never()).start();
|
||||
}
|
||||
}
|
||||
+31
-36
@@ -15,6 +15,7 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atMost;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -32,7 +33,6 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -42,7 +42,6 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
@@ -53,6 +52,7 @@ import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
@@ -81,6 +81,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
private ExecutorService sharedExecutorService;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private ReportMessageManager reportMessageManager;
|
||||
private Account account;
|
||||
private Device device;
|
||||
@@ -88,21 +89,24 @@ class WebSocketConnectionIntegrationTest {
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
|
||||
sharedExecutorService);
|
||||
redisMessageAvailabilityManager = new RedisMessageAvailabilityManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService, sharedExecutorService);
|
||||
reportMessageManager = mock(ReportMessageManager.class);
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
@@ -112,10 +116,14 @@ class WebSocketConnectionIntegrationTest {
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
redisMessageAvailabilityManager.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
redisMessageAvailabilityManager.stop();
|
||||
|
||||
sharedExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
@@ -130,8 +138,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessages(final int persistedMessageCount, final int cachedMessageCount) {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(Duration.ofDays(30)),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
account,
|
||||
@@ -140,7 +148,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
mock(ExperimentEnrollmentManager.class)
|
||||
);
|
||||
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
|
||||
@@ -168,36 +177,21 @@ class WebSocketConnectionIntegrationTest {
|
||||
}
|
||||
|
||||
final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class);
|
||||
final AtomicBoolean queueCleared = new AtomicBoolean(false);
|
||||
|
||||
when(successResponse.getStatus()).thenReturn(200);
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(successResponse));
|
||||
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), any())).thenAnswer(
|
||||
(Answer<CompletableFuture<WebSocketResponseMessage>>) invocation -> {
|
||||
synchronized (queueCleared) {
|
||||
queueCleared.set(true);
|
||||
queueCleared.notifyAll();
|
||||
}
|
||||
webSocketConnection.start();
|
||||
|
||||
return CompletableFuture.completedFuture(successResponse);
|
||||
});
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Optional<byte[]>> messageBodyCaptor =
|
||||
ArgumentCaptor.forClass(Optional.class);
|
||||
|
||||
webSocketConnection.processStoredMessages();
|
||||
verify(webSocketClient, timeout(10_000))
|
||||
.sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty()));
|
||||
|
||||
synchronized (queueCleared) {
|
||||
while (!queueCleared.get()) {
|
||||
queueCleared.wait();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(
|
||||
Optional.class);
|
||||
|
||||
verify(webSocketClient, times(persistedMessageCount + cachedMessageCount)).sendRequest(eq("PUT"),
|
||||
eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
verify(webSocketClient).sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty()));
|
||||
verify(webSocketClient, times(persistedMessageCount + cachedMessageCount))
|
||||
.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
|
||||
final List<MessageProtos.Envelope> sentMessages = new ArrayList<>();
|
||||
|
||||
@@ -219,8 +213,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
void testProcessStoredMessagesClientClosed() {
|
||||
final WebSocketConnection webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(),
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager, reportMessageManager, sharedExecutorService, Clock.systemUTC()),
|
||||
new MessageMetrics(Duration.ofDays(30)),
|
||||
mock(PushNotificationManager.class),
|
||||
mock(PushNotificationScheduler.class),
|
||||
account,
|
||||
@@ -229,7 +223,8 @@ class WebSocketConnectionIntegrationTest {
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
mock(ExperimentEnrollmentManager.class)
|
||||
);
|
||||
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
@@ -261,10 +256,10 @@ class WebSocketConnectionIntegrationTest {
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any())).thenReturn(
|
||||
CompletableFuture.failedFuture(new IOException("Connection closed")));
|
||||
|
||||
webSocketConnection.processStoredMessages();
|
||||
webSocketConnection.start();
|
||||
|
||||
//noinspection unchecked
|
||||
ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(Optional.class);
|
||||
final ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(Optional.class);
|
||||
|
||||
verify(webSocketClient, atMost(persistedMessageCount + cachedMessageCount)).sendRequest(eq("PUT"),
|
||||
eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
@@ -272,7 +267,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
eq(Optional.empty()));
|
||||
|
||||
final List<MessageProtos.Envelope> sentMessages = messageBodyCaptor.getAllValues().stream()
|
||||
.map(Optional::get)
|
||||
.map(Optional::orElseThrow)
|
||||
.map(messageBytes -> {
|
||||
try {
|
||||
return Envelope.parseFrom(messageBytes);
|
||||
|
||||
+386
-704
File diff suppressed because it is too large.
Load diff
-139
@@ -1,139 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class EncryptDeviceCreationTimestampCommandTest {
|
||||
|
||||
private static class TestEncryptDeviceCreationTimestampCommand extends EncryptDeviceCreationTimestampCommand {
|
||||
|
||||
private final CommandDependencies commandDependencies;
|
||||
private final Namespace namespace;
|
||||
|
||||
public TestEncryptDeviceCreationTimestampCommand(final AccountsManager accountsManager, final boolean isDryRun) {
|
||||
super();
|
||||
|
||||
commandDependencies = mock(CommandDependencies.class);
|
||||
when(commandDependencies.accountsManager()).thenReturn(accountsManager);
|
||||
|
||||
namespace = mock(Namespace.class);
|
||||
when(namespace.getBoolean(EncryptDeviceCreationTimestampCommand.DRY_RUN_ARGUMENT)).thenReturn(isDryRun);
|
||||
when(namespace.getInt(EncryptDeviceCreationTimestampCommand.BUFFER_ARGUMENT)).thenReturn(5);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CommandDependencies getCommandDependencies() {
|
||||
return commandDependencies;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Namespace getNamespace() {
|
||||
return namespace;
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void crawlAccounts(final boolean isDryRun) {
|
||||
final String number = "+14152222222";
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
|
||||
final Account testAccount = AccountsHelper.generateTestAccount(number, uuid, UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
testAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.updateAsync(any(), any())).thenAnswer(invocation -> {
|
||||
final Account account = invocation.getArgument(0);
|
||||
final Consumer<Account> updater = invocation.getArgument(1);
|
||||
updater.accept(account);
|
||||
return CompletableFuture.completedFuture(account);
|
||||
});
|
||||
|
||||
final EncryptDeviceCreationTimestampCommand encryptDeviceCreationTimestampCommand =
|
||||
new TestEncryptDeviceCreationTimestampCommand(accountsManager, isDryRun);
|
||||
|
||||
encryptDeviceCreationTimestampCommand.crawlAccounts(Flux.just(testAccount));
|
||||
|
||||
if (isDryRun) {
|
||||
verify(accountsManager, never()).updateAsync(any(), any());
|
||||
assertNull(testAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
} else {
|
||||
verify(accountsManager).updateAsync(eq(testAccount), any());
|
||||
assertNotNull(testAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void crawlAccountsWithEncryptedTimestamps() {
|
||||
final Account unencryptedTimestampAccount = AccountsHelper.generateTestAccount("+14152222222", UUID.randomUUID(), UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
unencryptedTimestampAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
|
||||
final Account encryptedTimestampAccount = AccountsHelper.generateTestAccount("+14152222223", UUID.randomUUID(), UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
encryptedTimestampAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
encryptedTimestampAccount.getDevices().getFirst().setCreatedAtCiphertext(TestRandomUtil.nextBytes(56));
|
||||
|
||||
final Account halfEncryptedTimestampAccount = AccountsHelper.generateTestAccount("+14152222224", UUID.randomUUID(), UUID.randomUUID(), List.of(
|
||||
DevicesHelper.createDevice(Device.PRIMARY_ID), DevicesHelper.createDevice((byte) 2)), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
|
||||
halfEncryptedTimestampAccount.setIdentityKey(new IdentityKey(ECKeyPair.generate().getPublicKey()));
|
||||
halfEncryptedTimestampAccount.getDevices().getFirst().setCreatedAtCiphertext(TestRandomUtil.nextBytes(56));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.updateAsync(any(), any())).thenAnswer(invocation -> {
|
||||
final Account account = invocation.getArgument(0);
|
||||
final Consumer<Account> updater = invocation.getArgument(1);
|
||||
updater.accept(account);
|
||||
return CompletableFuture.completedFuture(account);
|
||||
});
|
||||
|
||||
final EncryptDeviceCreationTimestampCommand encryptDeviceCreationTimestampCommand =
|
||||
new TestEncryptDeviceCreationTimestampCommand(accountsManager, false);
|
||||
|
||||
assertNull(unencryptedTimestampAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
assertNull(halfEncryptedTimestampAccount.getDevices().get(1).getCreatedAtCiphertext());
|
||||
|
||||
encryptDeviceCreationTimestampCommand.crawlAccounts(Flux.just(unencryptedTimestampAccount,
|
||||
encryptedTimestampAccount,
|
||||
halfEncryptedTimestampAccount));
|
||||
|
||||
verify(accountsManager, times(1)).updateAsync(eq(unencryptedTimestampAccount), any());
|
||||
verify(accountsManager, never()).updateAsync(eq(encryptedTimestampAccount), any());
|
||||
verify(accountsManager, times(1)).updateAsync(eq(halfEncryptedTimestampAccount), any());
|
||||
|
||||
assertNotNull(unencryptedTimestampAccount.getDevices().getFirst().getCreatedAtCiphertext());
|
||||
assertNotNull(halfEncryptedTimestampAccount.getDevices().get(1).getCreatedAtCiphertext());
|
||||
}
|
||||
}
|
||||
@@ -303,6 +303,9 @@ openTelemetry:
|
||||
environment: dev
|
||||
shutdownWaitDuration: PT0S
|
||||
url: http://127.0.0.1:4318/
|
||||
maxBucketCount: 16
|
||||
maxBucketsPerMeter:
|
||||
chat.SomeClass.someMetric: 64
|
||||
|
||||
unidentifiedDelivery:
|
||||
certificate: CgIIAQ==
|
||||
|
||||
+1
-1
Submodule spam-filter updated: ac649619ec...6ef5efd1e1.
Reference in new issue
Block a user