mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:26:47 +00:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2f5815316 | ||
|
|
2da00e162a | ||
|
|
e53a9f3f1a | ||
|
|
767f6a90e0 | ||
|
|
562b495a18 | ||
|
|
084607f359 | ||
|
|
eeeb565313 | ||
|
|
1fa31b3974 | ||
|
|
7158a504fa | ||
|
|
3ccd7508ac | ||
|
|
fc6075f19c | ||
|
|
776c147ea4 | ||
|
|
5d9641ae86 | ||
|
|
88a1f951c2 | ||
|
|
1726a1d5f4 | ||
|
|
6c563a3f13 | ||
|
|
6a1f4906c5 | ||
|
|
ef716aacc2 | ||
|
|
c91242ed60 | ||
|
|
e536a40740 | ||
|
|
5aaf4cad20 | ||
|
|
1c167ec150 | ||
|
|
9898e18ae2 | ||
|
|
b182c3d86d | ||
|
|
96a4d4c8ac | ||
|
|
9d19fc9ecc | ||
|
|
aad12670b2 | ||
|
|
7ca7fe7c13 | ||
|
|
ca7e7c288e | ||
|
|
3a604464b5 | ||
|
|
e277281d18 | ||
|
|
3d339696dc | ||
|
|
3e36a49142 | ||
|
|
d8f53954d0 | ||
|
|
8c984cbf42 | ||
|
|
60cdcf5f0c | ||
|
|
5afcd634b6 | ||
|
|
00ca58ec13 | ||
|
|
bbb6d448db |
No files matched your search
@@ -28,7 +28,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**</exclude>
|
||||
@@ -39,7 +38,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<additionalClasspathElements>
|
||||
<additionalClasspathElement>${project.basedir}/.libs/software.amazon.awssdk-sso.jar</additionalClasspathElement>
|
||||
|
||||
@@ -37,41 +37,41 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.23.8</aws.sdk2.version>
|
||||
<braintree.version>3.34.0</braintree.version>
|
||||
<commons-csv.version>1.11.0</commons-csv.version>
|
||||
<commons-io.version>2.16.1</commons-io.version>
|
||||
<dropwizard.version>3.0.7</dropwizard.version>
|
||||
<aws.sdk2.version>2.29.7</aws.sdk2.version>
|
||||
<braintree.version>3.37.0</braintree.version>
|
||||
<commons-csv.version>1.12.0</commons-csv.version>
|
||||
<commons-io.version>2.17.0</commons-io.version>
|
||||
<dropwizard.version>3.0.10</dropwizard.version>
|
||||
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
|
||||
<dynamodblocal.version>1.23.0</dynamodblocal.version>
|
||||
<google-cloud-libraries.version>26.33.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.50.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.61.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.11.0</gson.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.17.2</jackson.version>
|
||||
<jackson.version>2.18.1</jackson.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<junit-pioneer.version>2.2.0</junit-pioneer.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>1.9.24</kotlin.version>
|
||||
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
|
||||
<lettuce.version>6.3.2.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.13.40</libphonenumber.version>
|
||||
<lettuce.version>6.4.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>8.13.49</libphonenumber.version>
|
||||
<logstash.logback.version>7.3</logstash.logback.version>
|
||||
<log4j-bom.version>2.23.1</log4j-bom.version>
|
||||
<luajava.version>3.4.0</luajava.version>
|
||||
<micrometer.version>1.13.2</micrometer.version>
|
||||
<micrometer.version>1.13.6</micrometer.version>
|
||||
<netty.version>4.1.111.Final</netty.version>
|
||||
<protobuf.version>3.25.5</protobuf.version> <!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2023.0.8</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2023.0.11</reactor-bom.version> <!-- 3.6.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.2.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<slf4j.version>2.0.13</slf4j.version>
|
||||
<stripe.version>23.10.0</stripe.version>
|
||||
<swagger.version>2.2.22</swagger.version>
|
||||
<swagger.version>2.2.25</swagger.version>
|
||||
|
||||
<!-- 21.0.4_7-jre-jammy (note: always use the multi-arch manifest *LIST* here) -->
|
||||
<docker.image.sha256>870aae69d4521fdaf26e952f8026f75b37cb721e6302d4d4d7100f6b09823057</docker.image.sha256>
|
||||
@@ -383,7 +383,42 @@
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>3.4.3</version>
|
||||
<version>3.4.4</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.7.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -466,7 +501,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<property>
|
||||
@@ -501,7 +535,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-install-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<version>3.1.3</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
@@ -510,7 +544,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<version>3.1.3</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
|
||||
@@ -160,9 +160,6 @@ dynamoDbTables:
|
||||
cacheCluster: # Redis server configuration for cache cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
clientPresenceCluster: # Redis server configuration for client presence cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
uri: redis://redis.example.com:6379/
|
||||
|
||||
|
||||
+16
-26
@@ -11,11 +11,11 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<firebase-admin.version>9.2.0</firebase-admin.version>
|
||||
<firebase-admin.version>9.4.1</firebase-admin.version>
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<sqlite4java.version>1.0.392</sqlite4java.version>
|
||||
<google-androidpublisher.version>v3-rev20240820-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.1.0</storekit.version>
|
||||
<google-androidpublisher.version>v3-rev20241016-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.2.0</storekit.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -236,24 +236,27 @@
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-pubsub</artifactId>
|
||||
<exclusions>
|
||||
<!-- Conflicts with our direct Guava dependency -->
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.firebase</groupId>
|
||||
<artifactId>firebase-admin</artifactId>
|
||||
<version>${firebase-admin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
<version>1.25.0-alpha</version>
|
||||
</dependency>
|
||||
<!-- resolve opentelemetry-semconv conflict from lower in firebase-admin dependency tree -->
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<version>3.28.0</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<!-- fix dependency convergence from older 1.0.1 -->
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
<groupId>io.opentelemetry.semconv</groupId>
|
||||
<artifactId>opentelemetry-semconv</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
@@ -279,13 +282,6 @@
|
||||
<dependency>
|
||||
<groupId>io.grpc</groupId>
|
||||
<artifactId>grpc-netty</artifactId>
|
||||
<exclusions>
|
||||
<!-- fix dependency convergence from older 0.26.0 -->
|
||||
<exclusion>
|
||||
<groupId>io.perfmark</groupId>
|
||||
<artifactId>perfmark-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.grpc</groupId>
|
||||
@@ -530,7 +526,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>true</createDependencyReducedPom>
|
||||
<filters>
|
||||
@@ -565,7 +560,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.7.1</version>
|
||||
<configuration>
|
||||
<descriptors>
|
||||
<descriptor>assembly.xml</descriptor>
|
||||
@@ -585,7 +579,6 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>read-deploy-configuration</id>
|
||||
@@ -680,7 +673,6 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-test-server</id>
|
||||
@@ -720,7 +712,6 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<configuration>
|
||||
<!-- work around PATCH not being a supported method on HttpUrlConnection -->
|
||||
<argLine>--add-opens=java.base/java.net=ALL-UNNAMED</argLine>
|
||||
@@ -742,7 +733,6 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>check-all-service-config</id>
|
||||
|
||||
@@ -165,11 +165,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private MessageCacheConfiguration messageCache;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private FaultTolerantRedisClusterFactory clientPresenceCluster;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -411,10 +406,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return messageCache;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getClientPresenceClusterConfiguration() {
|
||||
return clientPresenceCluster;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getPushSchedulerCluster() {
|
||||
return pushSchedulerCluster;
|
||||
}
|
||||
|
||||
@@ -50,7 +50,6 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.ServiceLoader;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
@@ -95,7 +94,6 @@ import org.whispersystems.textsecuregcm.backup.BackupsDb;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3BackupCredentialGenerator;
|
||||
import org.whispersystems.textsecuregcm.backup.Cdn3RemoteStorageManager;
|
||||
import org.whispersystems.textsecuregcm.badges.ConfiguredProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.badges.ResourceBundleLevelTranslator;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.CallDnsRecordsManager;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.CallRoutingTableManager;
|
||||
import org.whispersystems.textsecuregcm.calls.routing.DynamicConfigTurnRouter;
|
||||
@@ -192,10 +190,10 @@ import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
@@ -373,8 +371,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new HeaderControlledResourceBundleLookup();
|
||||
ConfiguredProfileBadgeConverter profileBadgeConverter = new ConfiguredProfileBadgeConverter(
|
||||
clock, config.getBadges(), headerControlledResourceBundleLookup);
|
||||
ResourceBundleLevelTranslator resourceBundleLevelTranslator = new ResourceBundleLevelTranslator(
|
||||
headerControlledResourceBundleLookup);
|
||||
BankMandateTranslator bankMandateTranslator = new BankMandateTranslator(headerControlledResourceBundleLookup);
|
||||
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
@@ -454,8 +450,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient clientPresenceCluster = config.getClientPresenceClusterConfiguration()
|
||||
.build("client_presence", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -464,9 +458,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantRedisClient pubsubClient =
|
||||
config.getRedisPubSubConfiguration().build("pubsub", sharedClientResources);
|
||||
|
||||
final BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(100_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(),
|
||||
keyspaceNotificationDispatchQueue);
|
||||
final BlockingQueue<Runnable> receiptSenderQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "receiptSenderQueue"), Collections.emptyList(), receiptSenderQueue);
|
||||
final BlockingQueue<Runnable> fcmSenderQueue = new LinkedBlockingQueue<>();
|
||||
@@ -479,14 +470,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.scheduledExecutorService(name(getClass(), "recurringJob-%d")).threads(6).build();
|
||||
ScheduledExecutorService websocketScheduledExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "websocket-%d")).threads(8).build();
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = ExecutorServiceMetrics.monitor(Metrics.globalRegistry,
|
||||
environment.lifecycle()
|
||||
.executorService(name(getClass(), "keyspaceNotification-%d"))
|
||||
.maxThreads(16)
|
||||
.workQueue(keyspaceNotificationDispatchQueue)
|
||||
.build(),
|
||||
MetricsUtil.name(getClass(), "keyspaceNotificationExecutor"),
|
||||
MetricsUtil.PREFIX);
|
||||
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(getClass(), "apnSender-%d"))
|
||||
.maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "fcmSender-%d"))
|
||||
@@ -545,11 +528,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
.build();
|
||||
ExecutorService clientPresenceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "clientPresence-%d"))
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
.build();
|
||||
// unbounded executor (same as cachedThreadPool)
|
||||
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "remoteStorage-%d"))
|
||||
@@ -569,6 +547,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
|
||||
ExecutorService appleAppStoreExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
|
||||
ExecutorService clientEventExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "clientEvent-%d"));
|
||||
|
||||
ScheduledExecutorService appleAppStoreRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "appleAppStoreRetry-%d")).threads(1).build();
|
||||
@@ -617,11 +597,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor,
|
||||
keyspaceNotificationDispatchExecutor);
|
||||
PubSubClientEventManager pubSubClientEventManager = new PubSubClientEventManager(messagesCluster, clientEventExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, keyspaceNotificationDispatchExecutor,
|
||||
messageDeliveryScheduler, messageDeletionAsyncExecutor, clock, dynamicConfigurationManager);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, clock, dynamicConfigurationManager);
|
||||
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
|
||||
recurringJobExecutor,
|
||||
config.getClientReleaseConfiguration().refreshInterval(),
|
||||
@@ -636,9 +615,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client,
|
||||
clientPresenceManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
secureStorageClient, secureValueRecovery2Client, pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor,
|
||||
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
|
||||
@@ -667,7 +645,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new MessageDeliveryLoopMonitor(rateLimitersCluster);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, clientPresenceManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
accountsManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
|
||||
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
|
||||
@@ -676,8 +654,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final AccountAuthenticator accountAuthenticator = new AccountAuthenticator(accountsManager);
|
||||
|
||||
final MessageSender messageSender =
|
||||
new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
|
||||
final MessageSender messageSender = new MessageSender(messagesManager, pushNotificationManager);
|
||||
final ReceiptSender receiptSender = new ReceiptSender(accountsManager, messageSender, receiptSenderExecutor);
|
||||
final TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(dynamicConfigurationManager,
|
||||
config.getTurnConfiguration().secret().value());
|
||||
@@ -743,8 +720,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
environment.lifecycle().manage(pubSubClientEventManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
@@ -996,7 +972,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
|
||||
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class));
|
||||
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager));
|
||||
environment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
///
|
||||
@@ -1006,15 +982,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, clientPresenceManager, websocketScheduledExecutor, messageDeliveryScheduler,
|
||||
clientReleaseManager, messageDeliveryLoopMonitor));
|
||||
pushNotificationScheduler, pubSubClientEventManager, websocketScheduledExecutor,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor));
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(pubSubClientEventManager));
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
@@ -1139,7 +1115,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
zkReceiptOperations, issuedReceiptsManager);
|
||||
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, resourceBundleLevelTranslator, bankMandateTranslator));
|
||||
profileBadgeConverter, bankMandateTranslator));
|
||||
commonControllers.add(new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager));
|
||||
}
|
||||
@@ -1151,10 +1127,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
WebSocketEnvironment<AuthenticatedDevice> provisioningEnvironment = new WebSocketEnvironment<>(environment,
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(pubSubClientEventManager));
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
registerCorsFilter(environment);
|
||||
|
||||
+6
-5
@@ -25,8 +25,8 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -54,7 +54,7 @@ public class RegistrationLockVerificationManager {
|
||||
private static final String PHONE_VERIFICATION_TYPE_TAG_NAME = "phoneVerificationType";
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator svr3CredentialGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
@@ -62,14 +62,15 @@ public class RegistrationLockVerificationManager {
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
|
||||
public RegistrationLockVerificationManager(
|
||||
final AccountsManager accounts, final ClientPresenceManager clientPresenceManager,
|
||||
final AccountsManager accounts,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
|
||||
final ExternalServiceCredentialsGenerator svr3CredentialGenerator,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.accounts = accounts;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.svr2CredentialGenerator = svr2CredentialGenerator;
|
||||
this.svr3CredentialGenerator = svr3CredentialGenerator;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
@@ -160,7 +161,7 @@ public class RegistrationLockVerificationManager {
|
||||
}
|
||||
|
||||
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
clientPresenceManager.disconnectAllPresences(updatedAccount.getUuid(), deviceIds);
|
||||
pubSubClientEventManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
|
||||
|
||||
try {
|
||||
// Send a push notification that prompts the client to attempt login and fail due to locked credentials
|
||||
|
||||
+3
-3
@@ -9,7 +9,7 @@ import org.glassfish.jersey.server.monitoring.ApplicationEvent;
|
||||
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
|
||||
/**
|
||||
@@ -20,9 +20,9 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
|
||||
private final WebsocketRefreshRequestEventListener websocketRefreshRequestEventListener;
|
||||
|
||||
public WebsocketRefreshApplicationEventListener(final AccountsManager accountsManager,
|
||||
final ClientPresenceManager clientPresenceManager) {
|
||||
final PubSubClientEventManager pubSubClientEventManager) {
|
||||
|
||||
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
|
||||
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(pubSubClientEventManager,
|
||||
new LinkedDeviceRefreshRequirementProvider(accountsManager),
|
||||
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
|
||||
}
|
||||
|
||||
+6
-5
@@ -10,6 +10,7 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.ws.rs.container.ResourceInfo;
|
||||
import javax.ws.rs.core.Context;
|
||||
@@ -18,11 +19,11 @@ import org.glassfish.jersey.server.monitoring.RequestEvent.Type;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
|
||||
public class WebsocketRefreshRequestEventListener implements RequestEventListener {
|
||||
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final WebsocketRefreshRequirementProvider[] providers;
|
||||
|
||||
private static final Counter DISPLACED_ACCOUNTS = Metrics.counter(
|
||||
@@ -34,10 +35,10 @@ public class WebsocketRefreshRequestEventListener implements RequestEventListene
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebsocketRefreshRequestEventListener.class);
|
||||
|
||||
public WebsocketRefreshRequestEventListener(
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final WebsocketRefreshRequirementProvider... providers) {
|
||||
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.providers = providers;
|
||||
}
|
||||
|
||||
@@ -59,7 +60,7 @@ public class WebsocketRefreshRequestEventListener implements RequestEventListene
|
||||
.forEach(pair -> {
|
||||
try {
|
||||
displacedDevices.incrementAndGet();
|
||||
clientPresenceManager.disconnectPresence(pair.first(), pair.second());
|
||||
pubSubClientEventManager.requestDisconnection(pair.first(), List.of(pair.second()));
|
||||
} catch (final Exception e) {
|
||||
logger.error("Could not displace device presence", e);
|
||||
}
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.badges;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.ResourceBundle;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.signal.i18n.HeaderControlledResourceBundleLookup;
|
||||
|
||||
public class ResourceBundleLevelTranslator implements LevelTranslator {
|
||||
|
||||
private static final String BASE_NAME = "org.signal.subscriptions.Subscriptions";
|
||||
|
||||
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
|
||||
|
||||
public ResourceBundleLevelTranslator(
|
||||
@Nonnull final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup) {
|
||||
this.headerControlledResourceBundleLookup = Objects.requireNonNull(headerControlledResourceBundleLookup);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String translate(final List<Locale> acceptableLanguages, final String badgeId) {
|
||||
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
|
||||
acceptableLanguages);
|
||||
return resourceBundle.getString(badgeId);
|
||||
}
|
||||
}
|
||||
+2
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
@@ -30,6 +31,7 @@ public sealed interface SubscriptionLevelConfiguration permits
|
||||
|
||||
record Backup(
|
||||
@JsonProperty("playProductId") @NotEmpty String playProductId,
|
||||
@JsonProperty("mediaTtl") @NotNull Duration mediaTtl,
|
||||
@JsonProperty("prices") @Valid Map<@NotEmpty String, @NotNull @Valid SubscriptionPriceConfiguration> prices)
|
||||
implements SubscriptionLevelConfiguration {}
|
||||
|
||||
|
||||
+3
-2
@@ -5,9 +5,10 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicMessagesConfiguration(boolean storeSharedMrmData, boolean mrmViewExperimentEnabled) {
|
||||
public record DynamicMessagesConfiguration(boolean storeSharedMrmData, boolean fetchSharedMrmData,
|
||||
boolean useSharedMrmData) {
|
||||
|
||||
public DynamicMessagesConfiguration() {
|
||||
this(false, false);
|
||||
this(false, false, false);
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -22,7 +22,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
@@ -34,14 +34,14 @@ public class KeepAliveController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final ClientPresenceManager clientPresenceManager) {
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
public KeepAliveController(final PubSubClientEventManager pubSubClientEventManager) {
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -49,7 +49,7 @@ public class KeepAliveController {
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!clientPresenceManager.isLocallyPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())) {
|
||||
if (!pubSubClientEventManager.isLocallyPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
|
||||
+27
-43
@@ -15,10 +15,7 @@ import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -37,8 +34,10 @@ import javax.ws.rs.ServerErrorException;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.signal.keytransparency.client.AciMonitorRequest;
|
||||
import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.MonitorKey;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -60,12 +59,6 @@ public class KeyTransparencyController {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(KeyTransparencyController.class);
|
||||
@VisibleForTesting
|
||||
static final Duration KEY_TRANSPARENCY_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
@VisibleForTesting
|
||||
static final byte USERNAME_PREFIX = (byte) 'u';
|
||||
@VisibleForTesting
|
||||
static final byte E164_PREFIX = (byte) 'n';
|
||||
@VisibleForTesting
|
||||
static final byte ACI_PREFIX = (byte) 'a';
|
||||
private final KeyTransparencyServiceClient keyTransparencyServiceClient;
|
||||
|
||||
public KeyTransparencyController(
|
||||
@@ -139,9 +132,10 @@ public class KeyTransparencyController {
|
||||
identifiers. Enforced unauthenticated endpoint.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "All search keys exist in the log", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "200", description = "All identifiers exist in the log", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
|
||||
@ApiResponse(responseCode = "404", description = "At least one search key lookup did not find the key")
|
||||
@ApiResponse(responseCode = "403", description = "One or more of the provided commitment indexes did not match")
|
||||
@ApiResponse(responseCode = "404", description = "At least one identifier was not found")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@POST
|
||||
@@ -156,26 +150,34 @@ public class KeyTransparencyController {
|
||||
requireNotAuthenticated(authenticatedAccount);
|
||||
|
||||
try {
|
||||
final List<MonitorKey> monitorKeys = new ArrayList<>(List.of(
|
||||
createMonitorKey(getFullSearchKeyByteString(ACI_PREFIX, request.aci().value().toCompactByteArray()),
|
||||
request.aci().positions(),
|
||||
ByteString.copyFrom(request.aci().commitmentIndex()))
|
||||
));
|
||||
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
|
||||
.setAci(ByteString.copyFrom(request.aci().value().toCompactByteArray()))
|
||||
.addAllEntries(request.aci().positions())
|
||||
.setCommitmentIndex(ByteString.copyFrom(request.aci().commitmentIndex()))
|
||||
.build();
|
||||
|
||||
request.usernameHash().ifPresent(usernameHash ->
|
||||
monitorKeys.add(createMonitorKey(getFullSearchKeyByteString(USERNAME_PREFIX, usernameHash.value()),
|
||||
usernameHash.positions(), ByteString.copyFrom(usernameHash.commitmentIndex()))));
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest = request.usernameHash().map(usernameHash ->
|
||||
UsernameHashMonitorRequest.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash.value()))
|
||||
.addAllEntries(usernameHash.positions())
|
||||
.setCommitmentIndex(ByteString.copyFrom(usernameHash.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
request.e164().ifPresent(e164 ->
|
||||
monitorKeys.add(
|
||||
createMonitorKey(getFullSearchKeyByteString(E164_PREFIX, e164.value().getBytes(StandardCharsets.UTF_8)),
|
||||
e164.positions(), ByteString.copyFrom(e164.commitmentIndex()))));
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest = request.e164().map(e164 ->
|
||||
E164MonitorRequest.newBuilder()
|
||||
.setE164(e164.value())
|
||||
.addAllEntries(e164.positions())
|
||||
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor(
|
||||
monitorKeys,
|
||||
aciMonitorRequest,
|
||||
usernameHashMonitorRequest,
|
||||
e164MonitorRequest,
|
||||
request.lastNonDistinguishedTreeHeadSize(),
|
||||
request.lastDistinguishedTreeHeadSize(),
|
||||
KEY_TRANSPARENCY_RPC_TIMEOUT).join());
|
||||
|
||||
} catch (final CancellationException exception) {
|
||||
LOGGER.error("Unexpected cancellation from key transparency service", exception);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, exception);
|
||||
@@ -242,28 +244,10 @@ public class KeyTransparencyController {
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, unwrapped);
|
||||
}
|
||||
|
||||
private static MonitorKey createMonitorKey(final ByteString fullSearchKey, final List<Long> positions,
|
||||
final ByteString commitmentIndex) {
|
||||
return MonitorKey.newBuilder()
|
||||
.setSearchKey(fullSearchKey)
|
||||
.addAllEntries(positions)
|
||||
.setCommitmentIndex(commitmentIndex)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void requireNotAuthenticated(final Optional<AuthenticatedDevice> authenticatedAccount) {
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new BadRequestException("Endpoint requires unauthenticated access");
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static ByteString getFullSearchKeyByteString(final byte prefix, final byte[] searchKeyBytes) {
|
||||
final ByteBuffer fullSearchKeyBuffer = ByteBuffer.allocate(searchKeyBytes.length + 1);
|
||||
fullSearchKeyBuffer.put(prefix);
|
||||
fullSearchKeyBuffer.put(searchKeyBytes);
|
||||
fullSearchKeyBuffer.flip();
|
||||
|
||||
return ByteString.copyFrom(fullSearchKeyBuffer.array());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -957,7 +957,7 @@ public class MessageController {
|
||||
if (sharedMrmKey != null) {
|
||||
messageBuilder.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey));
|
||||
}
|
||||
// mrm views phase 1: always set content
|
||||
// mrm views phase 2: always set content
|
||||
messageBuilder.setContent(ByteString.copyFrom(payload));
|
||||
|
||||
messageSender.sendMessage(destinationAccount, destinationDevice, messageBuilder.build(), online);
|
||||
|
||||
+11
-9
@@ -60,7 +60,6 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.badges.LevelTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
@@ -104,7 +103,6 @@ public class SubscriptionController {
|
||||
private final GooglePlayBillingManager googlePlayBillingManager;
|
||||
private final AppleAppStoreManager appleAppStoreManager;
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final LevelTranslator levelTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
|
||||
static final String PROCESSOR_TAG_NAME = "processor";
|
||||
@@ -121,7 +119,6 @@ public class SubscriptionController {
|
||||
@Nonnull GooglePlayBillingManager googlePlayBillingManager,
|
||||
@Nonnull AppleAppStoreManager appleAppStoreManager,
|
||||
@Nonnull BadgeTranslator badgeTranslator,
|
||||
@Nonnull LevelTranslator levelTranslator,
|
||||
@Nonnull BankMandateTranslator bankMandateTranslator) {
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
@@ -132,7 +129,6 @@ public class SubscriptionController {
|
||||
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
|
||||
this.levelTranslator = Objects.requireNonNull(levelTranslator);
|
||||
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
|
||||
}
|
||||
|
||||
@@ -183,7 +179,7 @@ public class SubscriptionController {
|
||||
|
||||
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
|
||||
final LevelConfiguration levelConfiguration = new LevelConfiguration(
|
||||
levelTranslator.translate(acceptableLanguages, levelConfig.badge()),
|
||||
"" /* deprecated and unused */,
|
||||
badgeTranslator.translate(acceptableLanguages, levelConfig.badge()));
|
||||
donationLevels.put(String.valueOf(levelId), levelConfiguration);
|
||||
});
|
||||
@@ -192,7 +188,7 @@ public class SubscriptionController {
|
||||
oneTimeDonationConfiguration.boost().badge());
|
||||
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()),
|
||||
new LevelConfiguration(
|
||||
boostBadge.getName(),
|
||||
"" /* deprecated and unused */,
|
||||
// NB: the one-time badges are PurchasableBadge, which has a `duration` field
|
||||
new PurchasableBadge(
|
||||
boostBadge,
|
||||
@@ -201,7 +197,7 @@ public class SubscriptionController {
|
||||
final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge());
|
||||
donationLevels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()),
|
||||
new LevelConfiguration(
|
||||
giftBadge.getName(),
|
||||
"" /* deprecated and unused */,
|
||||
new PurchasableBadge(
|
||||
giftBadge,
|
||||
oneTimeDonationConfiguration.gift().expiration())));
|
||||
@@ -210,7 +206,10 @@ public class SubscriptionController {
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
e -> String.valueOf(e.getKey()),
|
||||
e -> new BackupLevelConfiguration(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES, e.getValue().playProductId())));
|
||||
e -> new BackupLevelConfiguration(
|
||||
BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES,
|
||||
e.getValue().playProductId(),
|
||||
e.getValue().mediaTtl().toDays())));
|
||||
|
||||
return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(), donationLevels,
|
||||
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
|
||||
@@ -504,6 +503,7 @@ public class SubscriptionController {
|
||||
|
||||
@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces")
|
||||
public record LevelConfiguration(
|
||||
@Deprecated(forRemoval = true) // may be removed after 2025-01-28
|
||||
@Schema(description = "The localized name for the level")
|
||||
String name,
|
||||
@Schema(description = "The displayable badge associated with the level")
|
||||
@@ -520,7 +520,9 @@ public class SubscriptionController {
|
||||
@Schema(description = "The amount of media storage in bytes that a paying subscriber may store")
|
||||
long storageAllowanceBytes,
|
||||
@Schema(description = "The play billing productID associated with this backup level")
|
||||
String playProductId) {}
|
||||
String playProductId,
|
||||
@Schema(description = "The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential")
|
||||
long mediaTtlDays) {}
|
||||
|
||||
@GET
|
||||
@Path("/configuration")
|
||||
|
||||
+1
-1
@@ -16,5 +16,5 @@ public record KeyTransparencyDistinguishedKeyResponse(
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Schema(description = "The serialized `DistinguishedResponse` encoded in standard un-padded base64")
|
||||
byte[] distinguishedKeyResponse
|
||||
byte[] serializedResponse
|
||||
) {}
|
||||
+2
-2
@@ -16,6 +16,6 @@ public record KeyTransparencyMonitorResponse(
|
||||
@NotNull
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Schema(description = "The monitor response encoded in standard un-padded base64")
|
||||
byte[] monitorResponse
|
||||
@Schema(description = "The serialized `MonitorResponse` encoded in standard un-padded base64")
|
||||
byte[] serializedResponse
|
||||
) {}
|
||||
+14
-10
@@ -19,18 +19,19 @@ import java.security.cert.X509Certificate;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.signal.keytransparency.client.AciMonitorRequest;
|
||||
import org.signal.keytransparency.client.ConsistencyParameters;
|
||||
import org.signal.keytransparency.client.DistinguishedRequest;
|
||||
import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
|
||||
import org.signal.keytransparency.client.MonitorKey;
|
||||
import org.signal.keytransparency.client.MonitorRequest;
|
||||
import org.signal.keytransparency.client.SearchRequest;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
@@ -138,19 +139,22 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
.thenApply(AbstractMessageLite::toByteArray);
|
||||
}
|
||||
|
||||
public CompletableFuture<byte[]> monitor(final List<MonitorKey> monitorKeys,
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public CompletableFuture<byte[]> monitor(final AciMonitorRequest aciMonitorRequest,
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest,
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest,
|
||||
final long lastTreeHeadSize,
|
||||
final long distinguishedTreeHeadSize,
|
||||
final Duration timeout) {
|
||||
final MonitorRequest.Builder monitorRequestBuilder = MonitorRequest.newBuilder()
|
||||
.addAllContactKeys(monitorKeys);
|
||||
.setAci(aciMonitorRequest)
|
||||
.setConsistency(ConsistencyParameters.newBuilder()
|
||||
.setLast(lastTreeHeadSize)
|
||||
.setDistinguished(distinguishedTreeHeadSize)
|
||||
.build());
|
||||
|
||||
final ConsistencyParameters consistency = ConsistencyParameters.newBuilder()
|
||||
.setLast(lastTreeHeadSize)
|
||||
.setDistinguished(distinguishedTreeHeadSize)
|
||||
.build();
|
||||
|
||||
monitorRequestBuilder.setConsistency(consistency);
|
||||
usernameHashMonitorRequest.ifPresent(monitorRequestBuilder::setUsernameHash);
|
||||
e164MonitorRequest.ifPresent(monitorRequestBuilder::setE164);
|
||||
|
||||
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
.monitor(monitorRequestBuilder.build()), callbackExecutor)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
/**
|
||||
* A client event listener handles events related to a client's message-retrieval presence. Handler methods are run on
|
||||
* dedicated threads and may safely perform blocking operations.
|
||||
*/
|
||||
public interface ClientEventListener {
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available in the connected client's message queue.
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersisted();
|
||||
|
||||
/**
|
||||
* Indicates that the client's presence has been displaced and the listener should close the client's underlying
|
||||
* network connection.
|
||||
*
|
||||
* @param connectedElsewhere if {@code true}, indicates that the client's presence has been displaced by another
|
||||
* connection from the same client
|
||||
*/
|
||||
void handleConnectionDisplaced(boolean connectedElsewhere);
|
||||
}
|
||||
-389
@@ -1,389 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.LettuceFutures;
|
||||
import io.lettuce.core.RedisFuture;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
/**
|
||||
* The client presence manager keeps track of which clients are actively connected and "present" to receive messages.
|
||||
* Only one client per account/device may be present at a time; if a second client for the same account/device declares
|
||||
* its presence, the previous client is displaced.
|
||||
* <p/>
|
||||
* The client presence manager depends on Redis keyspace notifications and requires that the Redis instance support at
|
||||
* least the following notification types: {@code K$z}.
|
||||
*/
|
||||
public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, String> implements Managed {
|
||||
|
||||
private final String managerId = UUID.randomUUID().toString();
|
||||
private final String connectedClientSetKey = getConnectedClientSetKey(managerId);
|
||||
|
||||
private final FaultTolerantRedisClusterClient presenceCluster;
|
||||
private final FaultTolerantPubSubClusterConnection<String, String> pubSubConnection;
|
||||
|
||||
private final ClusterLuaScript clearPresenceScript;
|
||||
private final ClusterLuaScript renewPresenceScript;
|
||||
|
||||
private final ExecutorService keyspaceNotificationExecutorService;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private ScheduledFuture<?> pruneMissingPeersFuture;
|
||||
|
||||
private final Map<String, DisplacedPresenceListener> displacementListenersByPresenceKey = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletionStage<?>> pendingPresenceSetsByPresenceKey = new ConcurrentHashMap<>();
|
||||
|
||||
private final Timer checkPresenceTimer;
|
||||
private final Timer setPresenceTimer;
|
||||
private final Timer clearPresenceTimer;
|
||||
private final Timer prunePeersTimer;
|
||||
private final Counter pruneClientMeter;
|
||||
private final Counter remoteDisplacementMeter;
|
||||
private final Counter pubSubMessageMeter;
|
||||
private final Counter displacementListenerAlreadyRemovedCounter;
|
||||
|
||||
private static final int PRUNE_PEERS_INTERVAL_SECONDS = (int) Duration.ofSeconds(30).toSeconds();
|
||||
private static final int PRESENCE_EXPIRATION_SECONDS = (int) Duration.ofMinutes(11).toSeconds();
|
||||
|
||||
static final String MANAGER_SET_KEY = "presence::managers";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClientPresenceManager.class);
|
||||
|
||||
public ClientPresenceManager(final FaultTolerantRedisClusterClient presenceCluster,
|
||||
final ScheduledExecutorService scheduledExecutorService,
|
||||
final ExecutorService keyspaceNotificationExecutorService) throws IOException {
|
||||
this.presenceCluster = presenceCluster;
|
||||
this.pubSubConnection = this.presenceCluster.createPubSubConnection();
|
||||
this.clearPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/clear_presence.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
this.renewPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/renew_presence.lua",
|
||||
ScriptOutputType.VALUE);
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.keyspaceNotificationExecutorService = keyspaceNotificationExecutorService;
|
||||
|
||||
Metrics.gauge(name(getClass(), "localClientCount"), this, ignored -> displacementListenersByPresenceKey.size());
|
||||
|
||||
this.checkPresenceTimer = Metrics.timer(name(getClass(), "checkPresence"));
|
||||
this.setPresenceTimer = Metrics.timer(name(getClass(), "setPresence"));
|
||||
this.clearPresenceTimer = Metrics.timer(name(getClass(), "clearPresence"));
|
||||
this.prunePeersTimer = Metrics.timer(name(getClass(), "prunePeers"));
|
||||
this.pruneClientMeter = Metrics.counter(name(getClass(), "pruneClient"));
|
||||
this.remoteDisplacementMeter = Metrics.counter(name(getClass(), "remoteDisplacement"));
|
||||
this.pubSubMessageMeter = Metrics.counter(name(getClass(), "pubSubMessage"));
|
||||
this.displacementListenerAlreadyRemovedCounter = Metrics.counter(
|
||||
name(getClass(), "displacementListenerAlreadyRemoved"));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FaultTolerantPubSubClusterConnection<String, String> getPubSubConnection() {
|
||||
return pubSubConnection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
connection.addListener(this);
|
||||
|
||||
final String presenceChannel = getManagerPresenceChannel(managerId);
|
||||
final int slot = SlotHash.getSlot(presenceChannel);
|
||||
|
||||
connection.sync().nodes(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM) && node.hasSlot(slot))
|
||||
.commands()
|
||||
.subscribe(presenceChannel);
|
||||
});
|
||||
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribeAll);
|
||||
|
||||
presenceCluster.useCluster(connection -> connection.sync().sadd(MANAGER_SET_KEY, managerId));
|
||||
|
||||
pruneMissingPeersFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
pruneMissingPeers();
|
||||
} catch (final Throwable t) {
|
||||
log.warn("Failed to prune missing peers", t);
|
||||
}
|
||||
}, new Random().nextInt(PRUNE_PEERS_INTERVAL_SECONDS), PRUNE_PEERS_INTERVAL_SECONDS, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.removeListener(this));
|
||||
|
||||
if (pruneMissingPeersFuture != null) {
|
||||
pruneMissingPeersFuture.cancel(false);
|
||||
}
|
||||
|
||||
for (final String presenceKey : displacementListenersByPresenceKey.keySet()) {
|
||||
clearPresence(presenceKey);
|
||||
}
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
connection.sync().srem(MANAGER_SET_KEY, managerId);
|
||||
connection.sync().del(getConnectedClientSetKey(managerId));
|
||||
});
|
||||
|
||||
pubSubConnection.usePubSubConnection(
|
||||
connection -> connection.sync().upstream().commands().unsubscribe(getManagerPresenceChannel(managerId)));
|
||||
}
|
||||
|
||||
public void setPresent(final UUID accountUuid, final byte deviceId,
|
||||
final DisplacedPresenceListener displacementListener) {
|
||||
|
||||
setPresenceTimer.record(() -> {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
displacePresence(presenceKey, true);
|
||||
|
||||
displacementListenersByPresenceKey.put(presenceKey, displacementListener);
|
||||
|
||||
final CompletableFuture<Void> presenceFuture = new CompletableFuture<>();
|
||||
final CompletionStage<?> previousFuture = pendingPresenceSetsByPresenceKey.put(presenceKey, presenceFuture);
|
||||
if (previousFuture != null) {
|
||||
log.debug("Another presence is already pending for {}:{}", accountUuid, deviceId);
|
||||
}
|
||||
|
||||
subscribeForRemotePresenceChanges(presenceKey);
|
||||
|
||||
presenceCluster.withCluster(connection -> {
|
||||
final RedisAdvancedClusterAsyncCommands<String, String> commands = connection.async();
|
||||
|
||||
commands.sadd(connectedClientSetKey, presenceKey);
|
||||
return commands.setex(presenceKey, PRESENCE_EXPIRATION_SECONDS, managerId);
|
||||
}).whenComplete((result, throwable) -> {
|
||||
if (throwable != null) {
|
||||
presenceFuture.completeExceptionally(throwable);
|
||||
} else {
|
||||
presenceFuture.complete(null);
|
||||
}
|
||||
});
|
||||
|
||||
presenceFuture.whenComplete(
|
||||
(ignored, throwable) -> pendingPresenceSetsByPresenceKey.remove(presenceKey, presenceFuture));
|
||||
});
|
||||
}
|
||||
|
||||
public void renewPresence(final UUID accountUuid, final byte deviceId) {
|
||||
renewPresenceScript.execute(List.of(getPresenceKey(accountUuid, deviceId)),
|
||||
List.of(managerId, String.valueOf(PRESENCE_EXPIRATION_SECONDS)));
|
||||
}
|
||||
|
||||
public void disconnectAllPresences(final UUID accountUuid, final List<Byte> deviceIds) {
|
||||
|
||||
List<String> presenceKeys = new ArrayList<>();
|
||||
deviceIds.forEach(deviceId -> {
|
||||
String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
if (isLocallyPresent(accountUuid, deviceId)) {
|
||||
displacePresence(presenceKey, false);
|
||||
}
|
||||
presenceKeys.add(presenceKey);
|
||||
});
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
List<RedisFuture<Long>> futures = presenceKeys.stream().map(key -> connection.async().del(key)).toList();
|
||||
LettuceFutures.awaitAll(connection.getTimeout(), futures.toArray(new RedisFuture[0]));
|
||||
});
|
||||
}
|
||||
|
||||
public void disconnectAllPresencesForUuid(final UUID accountUuid) {
|
||||
disconnectAllPresences(accountUuid, Device.ALL_POSSIBLE_DEVICE_IDS);
|
||||
}
|
||||
|
||||
public void disconnectPresence(final UUID accountUuid, final byte deviceId) {
|
||||
disconnectAllPresences(accountUuid, List.of(deviceId));
|
||||
}
|
||||
|
||||
private void displacePresence(final String presenceKey, final boolean connectedElsewhere) {
|
||||
final DisplacedPresenceListener displacementListener = displacementListenersByPresenceKey.get(presenceKey);
|
||||
|
||||
if (displacementListener != null) {
|
||||
displacementListener.handleDisplacement(connectedElsewhere);
|
||||
}
|
||||
|
||||
clearPresence(presenceKey);
|
||||
}
|
||||
|
||||
public boolean isPresent(final UUID accountUuid, final byte deviceId) {
|
||||
return checkPresenceTimer.record(() ->
|
||||
presenceCluster.withCluster(connection ->
|
||||
connection.sync().exists(getPresenceKey(accountUuid, deviceId))) == 1);
|
||||
}
|
||||
|
||||
public boolean isLocallyPresent(final UUID accountUuid, final byte deviceId) {
|
||||
return displacementListenersByPresenceKey.containsKey(getPresenceKey(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
public boolean clearPresence(final UUID accountUuid, final byte deviceId, final DisplacedPresenceListener listener) {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
if (displacementListenersByPresenceKey.remove(presenceKey, listener)) {
|
||||
return clearPresence(presenceKey);
|
||||
} else {
|
||||
displacementListenerAlreadyRemovedCounter.increment();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean clearPresence(final String presenceKey) {
|
||||
return clearPresenceTimer.record(() -> {
|
||||
displacementListenersByPresenceKey.remove(presenceKey);
|
||||
unsubscribeFromRemotePresenceChanges(presenceKey);
|
||||
|
||||
final boolean removed = clearPresenceScript.execute(List.of(presenceKey), List.of(managerId)) != null;
|
||||
presenceCluster.useCluster(connection -> connection.sync().srem(connectedClientSetKey, presenceKey));
|
||||
|
||||
return removed;
|
||||
});
|
||||
}
|
||||
|
||||
private void subscribeForRemotePresenceChanges(final String presenceKey) {
|
||||
final int slot = SlotHash.getSlot(presenceKey);
|
||||
|
||||
pubSubConnection.usePubSubConnection(
|
||||
connection -> connection.sync().nodes(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM) && node.hasSlot(slot))
|
||||
.commands()
|
||||
.subscribe(getKeyspaceNotificationChannel(presenceKey)));
|
||||
}
|
||||
|
||||
private void resubscribeAll() {
|
||||
for (final String presenceKey : displacementListenersByPresenceKey.keySet()) {
|
||||
subscribeForRemotePresenceChanges(presenceKey);
|
||||
}
|
||||
}
|
||||
|
||||
private void unsubscribeFromRemotePresenceChanges(final String presenceKey) {
|
||||
pubSubConnection.usePubSubConnection(
|
||||
connection -> connection.sync().upstream().commands().unsubscribe(getKeyspaceNotificationChannel(presenceKey)));
|
||||
}
|
||||
|
||||
void pruneMissingPeers() {
|
||||
prunePeersTimer.record(() -> {
|
||||
final Set<String> peerIds = presenceCluster.withCluster(
|
||||
connection -> connection.sync().smembers(MANAGER_SET_KEY));
|
||||
peerIds.remove(managerId);
|
||||
|
||||
for (final String peerId : peerIds) {
|
||||
final boolean peerMissing = presenceCluster.withCluster(
|
||||
connection -> connection.sync().publish(getManagerPresenceChannel(peerId), "ping") == 0);
|
||||
|
||||
if (peerMissing) {
|
||||
log.debug("Presence manager {} did not respond to ping", peerId);
|
||||
|
||||
final String connectedClientsKey = getConnectedClientSetKey(peerId);
|
||||
|
||||
String presenceKey;
|
||||
|
||||
while ((presenceKey = presenceCluster.withCluster(connection -> connection.sync().spop(connectedClientsKey)))
|
||||
!= null) {
|
||||
clearPresenceScript.execute(List.of(presenceKey), List.of(peerId));
|
||||
pruneClientMeter.increment();
|
||||
}
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
connection.sync().del(connectedClientsKey);
|
||||
connection.sync().srem(MANAGER_SET_KEY, peerId);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void message(final RedisClusterNode node, final String channel, final String message) {
|
||||
pubSubMessageMeter.increment();
|
||||
|
||||
if (channel.startsWith("__keyspace@0__:presence::{")) {
|
||||
if ("set".equals(message) || "del".equals(message)) {
|
||||
// "set" might mean the client has connected to another host, although it might just be our own `set`,
|
||||
// because we subscribe for changes before setting the key.
|
||||
// for "del", another process has indicated the client should be disconnected
|
||||
final boolean maybeConnectedElsewhere = "set".equals(message);
|
||||
|
||||
// At this point, we're on a Lettuce IO thread and need to dispatch to a separate thread before making
|
||||
// synchronous Lettuce calls to avoid deadlocking.
|
||||
keyspaceNotificationExecutorService.execute(() -> {
|
||||
final String clientPresenceKey = channel.substring("__keyspace@0__:".length());
|
||||
|
||||
final CompletionStage<?> pendingConnection = pendingPresenceSetsByPresenceKey.getOrDefault(clientPresenceKey,
|
||||
CompletableFuture.completedFuture(null));
|
||||
|
||||
pendingConnection.thenCompose(ignored -> {
|
||||
if (maybeConnectedElsewhere) {
|
||||
return presenceCluster.withCluster(connection -> connection.async().get(clientPresenceKey))
|
||||
.thenApply(currentManagerId -> !managerId.equals(currentManagerId));
|
||||
}
|
||||
|
||||
return CompletableFuture.completedFuture(true);
|
||||
})
|
||||
.exceptionally(ignored -> true)
|
||||
.thenAcceptAsync(shouldDisplace -> {
|
||||
if (shouldDisplace) {
|
||||
try {
|
||||
displacePresence(clientPresenceKey, maybeConnectedElsewhere);
|
||||
remoteDisplacementMeter.increment();
|
||||
} catch (final Exception e) {
|
||||
log.warn("Error displacing presence", e);
|
||||
}
|
||||
}
|
||||
}, keyspaceNotificationExecutorService);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getManagerId() {
|
||||
return managerId;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getPresenceKey(final UUID accountUuid, final byte deviceId) {
|
||||
return "presence::{" + accountUuid.toString() + "::" + deviceId + "}";
|
||||
}
|
||||
|
||||
private static String getKeyspaceNotificationChannel(final String presenceKey) {
|
||||
return "__keyspace@0__:" + presenceKey;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getConnectedClientSetKey(final String managerId) {
|
||||
return "presence::clients::" + managerId;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getManagerPresenceChannel(final String managerId) {
|
||||
return "presence::manager::" + managerId;
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
/**
|
||||
* A displaced presence listener is notified when a specific client's presence has been displaced because the same
|
||||
* client opened a newer connection to the Signal service.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface DisplacedPresenceListener {
|
||||
|
||||
void handleDisplacement(boolean connectedElsewhere);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.push;
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -21,13 +22,10 @@ import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
* for "online" delivery only and will not be delivered (and clients will not be notified) if the destination device
|
||||
* isn't actively connected to a Signal server.
|
||||
*
|
||||
* @see ClientPresenceManager
|
||||
* @see org.whispersystems.textsecuregcm.storage.MessageAvailabilityListener
|
||||
* @see ReceiptSender
|
||||
*/
|
||||
public class MessageSender {
|
||||
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final MessagesManager messagesManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
|
||||
@@ -39,62 +37,43 @@ public class MessageSender {
|
||||
private static final String STORY_TAG_NAME = "story";
|
||||
private static final String SEALED_SENDER_TAG_NAME = "sealedSender";
|
||||
|
||||
public MessageSender(final ClientPresenceManager clientPresenceManager,
|
||||
final MessagesManager messagesManager,
|
||||
final PushNotificationManager pushNotificationManager) {
|
||||
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
public MessageSender(final MessagesManager messagesManager, final PushNotificationManager pushNotificationManager) {
|
||||
this.messagesManager = messagesManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
}
|
||||
|
||||
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
|
||||
final boolean destinationPresent = messagesManager.insert(account.getUuid(),
|
||||
device.getId(),
|
||||
online ? message.toBuilder().setEphemeral(true).build() : message);
|
||||
|
||||
final String channel;
|
||||
|
||||
if (device.getGcmId() != null) {
|
||||
channel = "gcm";
|
||||
} else if (device.getApnId() != null) {
|
||||
channel = "apn";
|
||||
} else if (device.getFetchesMessages()) {
|
||||
channel = "websocket";
|
||||
} else {
|
||||
channel = "none";
|
||||
}
|
||||
|
||||
final boolean clientPresent;
|
||||
|
||||
if (online) {
|
||||
clientPresent = clientPresenceManager.isPresent(account.getUuid(), device.getId());
|
||||
|
||||
if (clientPresent) {
|
||||
messagesManager.insert(account.getUuid(), device.getId(), message.toBuilder().setEphemeral(true).build());
|
||||
} else {
|
||||
messagesManager.removeRecipientViewFromMrmData(device.getId(), message);
|
||||
}
|
||||
} else {
|
||||
messagesManager.insert(account.getUuid(), device.getId(), message);
|
||||
|
||||
// We check for client presence after inserting the message to take a conservative view of notifications. If the
|
||||
// client wasn't present at the time of insertion but is now, they'll retrieve the message. If they were present
|
||||
// but disconnected before the message was delivered, we should send a notification.
|
||||
clientPresent = clientPresenceManager.isPresent(account.getUuid(), device.getId());
|
||||
|
||||
if (!clientPresent) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
if (!destinationPresent && !online) {
|
||||
try {
|
||||
pushNotificationManager.sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
} catch (final NotPushRegisteredException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME,
|
||||
CHANNEL_TAG_NAME, channel,
|
||||
CHANNEL_TAG_NAME, getDeliveryChannelName(device),
|
||||
EPHEMERAL_TAG_NAME, String.valueOf(online),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(clientPresent),
|
||||
CLIENT_ONLINE_TAG_NAME, String.valueOf(destinationPresent),
|
||||
URGENT_TAG_NAME, String.valueOf(message.getUrgent()),
|
||||
STORY_TAG_NAME, String.valueOf(message.getStory()),
|
||||
SEALED_SENDER_TAG_NAME, String.valueOf(!message.hasSourceServiceId()))
|
||||
.increment();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getDeliveryChannelName(final Device device) {
|
||||
if (device.getGcmId() != null) {
|
||||
return "gcm";
|
||||
} else if (device.getApnId() != null) {
|
||||
return "apn";
|
||||
} else if (device.getFetchesMessages()) {
|
||||
return "websocket";
|
||||
} else {
|
||||
return "none";
|
||||
}
|
||||
}
|
||||
}
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* The pub/sub-based client presence manager uses the Redis 7 sharded pub/sub system to notify connected clients that
|
||||
* new messages are available for retrieval and report to senders whether a client was present to receive a message when
|
||||
* sent. This system makes a best effort to ensure that a given client has only a single open connection across the
|
||||
* fleet of servers, but cannot guarantee at-most-one behavior.
|
||||
*/
|
||||
public class PubSubClientEventManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed {
|
||||
|
||||
private final FaultTolerantRedisClusterClient clusterClient;
|
||||
private final Executor listenerEventExecutor;
|
||||
|
||||
private final UUID serverId = UUID.randomUUID();
|
||||
|
||||
private final byte[] CLIENT_CONNECTED_EVENT_BYTES = ClientEvent.newBuilder()
|
||||
.setClientConnected(ClientConnectedEvent.newBuilder()
|
||||
.setServerId(UUIDUtil.toByteString(serverId))
|
||||
.build())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
@Nullable
|
||||
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
|
||||
|
||||
private final Map<AccountAndDeviceIdentifier, ClientEventListener> listenersByAccountAndDeviceIdentifier;
|
||||
|
||||
private static final byte[] DISCONNECT_REQUESTED_EVENT_BYTES = ClientEvent.newBuilder()
|
||||
.setDisconnectRequested(DisconnectRequested.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
private static final Counter PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(PubSubClientEventManager.class, "publishClientConnectionEventError"));
|
||||
|
||||
private static final Counter UNSUBSCRIBE_ERROR_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(PubSubClientEventManager.class, "unsubscribeError"));
|
||||
|
||||
private static final Counter MESSAGE_WITHOUT_LISTENER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(PubSubClientEventManager.class, "messageWithoutListener"));
|
||||
|
||||
private static final String LISTENER_GAUGE_NAME =
|
||||
MetricsUtil.name(PubSubClientEventManager.class, "listeners");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PubSubClientEventManager.class);
|
||||
|
||||
@VisibleForTesting
|
||||
record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {
|
||||
}
|
||||
|
||||
public PubSubClientEventManager(final FaultTolerantRedisClusterClient clusterClient,
|
||||
final Executor listenerEventExecutor) {
|
||||
|
||||
this.clusterClient = clusterClient;
|
||||
this.listenerEventExecutor = listenerEventExecutor;
|
||||
|
||||
this.listenersByAccountAndDeviceIdentifier =
|
||||
Metrics.gaugeMapSize(LISTENER_GAUGE_NAME, Tags.empty(), new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start() {
|
||||
this.pubSubConnection = clusterClient.createBinaryPubSubConnection();
|
||||
this.pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
|
||||
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
if (pubSubConnection != null) {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
connection.removeListener(this);
|
||||
connection.close();
|
||||
});
|
||||
}
|
||||
|
||||
pubSubConnection = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the given device as "present" and registers a listener for new messages and conflicting connections. If the
|
||||
* given device already has a presence registered with this presence manager instance, that presence is displaced
|
||||
* immediately and the listener's {@link ClientEventListener#handleConnectionDisplaced(boolean)} 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
|
||||
* @param listener the listener to notify when new messages or conflicting connections arrive for the newly-conencted
|
||||
* device
|
||||
*
|
||||
* @return a future that yields a connection identifier when the new device's presence has been registered; the future
|
||||
* may fail if a pub/sub subscription could not be established, in which case callers should close the client's
|
||||
* connection to the server
|
||||
*/
|
||||
public CompletionStage<UUID> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final ClientEventListener listener) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("Presence manager not started");
|
||||
}
|
||||
|
||||
final UUID connectionId = UUID.randomUUID();
|
||||
final byte[] clientPresenceKey = getClientEventChannel(accountIdentifier, deviceId);
|
||||
final AtomicReference<ClientEventListener> displacedListener = new AtomicReference<>();
|
||||
final AtomicReference<CompletionStage<Void>> subscribeFuture = new AtomicReference<>();
|
||||
|
||||
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
|
||||
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
|
||||
//
|
||||
// > The entire method invocation is performed atomically. The supplied function is invoked exactly once per
|
||||
// > invocation of this method. Some attempted update operations on this map by other threads may be blocked while
|
||||
// > computation is in progress, so the computation should be short and simple.
|
||||
//
|
||||
// This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order
|
||||
// as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued
|
||||
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
|
||||
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
|
||||
(key, existingListener) -> {
|
||||
subscribeFuture.set(pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().ssubscribe(clientPresenceKey)));
|
||||
|
||||
if (existingListener != null) {
|
||||
displacedListener.set(existingListener);
|
||||
}
|
||||
|
||||
return listener;
|
||||
});
|
||||
|
||||
if (displacedListener.get() != null) {
|
||||
listenerEventExecutor.execute(() -> displacedListener.get().handleConnectionDisplaced(true));
|
||||
}
|
||||
|
||||
return subscribeFuture.get()
|
||||
.thenCompose(ignored -> clusterClient.withBinaryCluster(connection -> connection.async()
|
||||
.spublish(clientPresenceKey, CLIENT_CONNECTED_EVENT_BYTES)))
|
||||
.handle((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER.increment();
|
||||
}
|
||||
|
||||
return connectionId;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the "presence" for the given device. Callers should call this method when they have been notified that
|
||||
* the client's underlying network connection has been closed.
|
||||
*
|
||||
* @param accountIdentifier the identifier of the account for the disconnected device
|
||||
* @param deviceId the ID of the disconnected device within the given account
|
||||
*
|
||||
* @return a future that completes when the presence has been removed
|
||||
*/
|
||||
public CompletionStage<Void> handleClientDisconnected(final UUID accountIdentifier, final byte deviceId) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("Presence manager not started");
|
||||
}
|
||||
|
||||
final AtomicReference<CompletionStage<Void>> unsubscribeFuture = new AtomicReference<>();
|
||||
|
||||
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
|
||||
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
|
||||
//
|
||||
// > The entire method invocation is performed atomically. The supplied function is invoked exactly once per
|
||||
// > invocation of this method. Some attempted update operations on this map by other threads may be blocked while
|
||||
// > computation is in progress, so the computation should be short and simple.
|
||||
//
|
||||
// This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order
|
||||
// as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued
|
||||
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
|
||||
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
|
||||
(ignored, existingListener) -> {
|
||||
unsubscribeFuture.set(pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountIdentifier, deviceId)))
|
||||
.thenRun(Util.NOOP));
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return unsubscribeFuture.get().whenComplete((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
UNSUBSCRIBE_ERROR_COUNTER.increment();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether a client with the given account/device is connected to this presence manager instance.
|
||||
*
|
||||
* @param accountUuid the account identifier for the client to check
|
||||
* @param deviceId the ID of the device within the given account
|
||||
*
|
||||
* @return {@code true} if a client with the given account/device is connected to this presence manager instance or
|
||||
* {@code false} if the client is not connected at all or is connected to a different presence manager instance
|
||||
*/
|
||||
public boolean isLocallyPresent(final UUID accountUuid, final byte deviceId) {
|
||||
return listenersByAccountAndDeviceIdentifier.containsKey(new AccountAndDeviceIdentifier(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts a request that all devices associated with the identified account and connected to any client presence
|
||||
* instance close their network connections.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for which to request disconnection
|
||||
*
|
||||
* @return a future that completes when the request has been sent
|
||||
*/
|
||||
public CompletableFuture<Void> requestDisconnection(final UUID accountIdentifier) {
|
||||
return requestDisconnection(accountIdentifier, Device.ALL_POSSIBLE_DEVICE_IDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts a request that the specified devices associated with the identified account and connected to any client
|
||||
* presence instance close their network connections.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for which to request disconnection
|
||||
* @param deviceIds the IDs of the devices for which to request disconnection
|
||||
*
|
||||
* @return a future that completes when the request has been sent
|
||||
*/
|
||||
public CompletableFuture<Void> requestDisconnection(final UUID accountIdentifier, final Collection<Byte> deviceIds) {
|
||||
return CompletableFuture.allOf(deviceIds.stream()
|
||||
.map(deviceId -> {
|
||||
final byte[] clientPresenceKey = getClientEventChannel(accountIdentifier, deviceId);
|
||||
|
||||
return clusterClient.withBinaryCluster(connection -> connection.async()
|
||||
.spublish(clientPresenceKey, DISCONNECT_REQUESTED_EVENT_BYTES))
|
||||
.toCompletableFuture();
|
||||
})
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void resubscribe(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
|
||||
final boolean[] changedSlots = RedisClusterUtil.getChangedSlots(clusterTopologyChangedEvent);
|
||||
|
||||
final Map<Integer, List<byte[]>> clientPresenceKeysBySlot = new HashMap<>();
|
||||
|
||||
// Organize subscriptions by slot so we can issue a smaller number of larger resubscription commands
|
||||
listenersByAccountAndDeviceIdentifier.keySet()
|
||||
.stream()
|
||||
.map(accountAndDeviceIdentifier -> getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId()))
|
||||
.forEach(clientEventChannel -> {
|
||||
final int slot = SlotHash.getSlot(clientEventChannel);
|
||||
|
||||
if (changedSlots[slot]) {
|
||||
clientPresenceKeysBySlot.computeIfAbsent(slot, ignored -> new ArrayList<>()).add(clientEventChannel);
|
||||
}
|
||||
});
|
||||
|
||||
// Issue one resubscription command per affected slot
|
||||
clientPresenceKeysBySlot.forEach((slot, clientPresenceKeys) -> {
|
||||
if (pubSubConnection != null) {
|
||||
final byte[][] clientPresenceKeyArray = clientPresenceKeys.toArray(byte[][]::new);
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().ssubscribe(clientPresenceKeyArray));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribes for notifications for the given account and device identifier if and only if no listener is registered
|
||||
* for that account and device identifier.
|
||||
*
|
||||
* @param accountAndDeviceIdentifier the account and device identifier for which to stop receiving notifications
|
||||
*/
|
||||
void unsubscribeIfMissingListener(final AccountAndDeviceIdentifier accountAndDeviceIdentifier) {
|
||||
listenersByAccountAndDeviceIdentifier.compute(accountAndDeviceIdentifier, (ignored, existingListener) -> {
|
||||
if (existingListener == null && pubSubConnection != null) {
|
||||
// Enqueue, but do not block on, an "unsubscribe" operation
|
||||
pubSubConnection.usePubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(),
|
||||
accountAndDeviceIdentifier.deviceId())));
|
||||
}
|
||||
|
||||
// Make no change to the existing listener whether present or absent
|
||||
return existingListener;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void smessage(final RedisClusterNode node, final byte[] shardChannel, final byte[] message) {
|
||||
final ClientEvent clientEvent;
|
||||
|
||||
try {
|
||||
clientEvent = ClientEvent.parseFrom(message);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.error("Failed to parse pub/sub event protobuf", e);
|
||||
return;
|
||||
}
|
||||
|
||||
final AccountAndDeviceIdentifier accountAndDeviceIdentifier = parseClientPresenceKey(shardChannel);
|
||||
|
||||
@Nullable final ClientEventListener listener =
|
||||
listenersByAccountAndDeviceIdentifier.get(accountAndDeviceIdentifier);
|
||||
|
||||
if (listener != null) {
|
||||
switch (clientEvent.getEventCase()) {
|
||||
case NEW_MESSAGE_AVAILABLE -> listener.handleNewMessageAvailable();
|
||||
|
||||
case CLIENT_CONNECTED -> {
|
||||
// Only act on new connections to other presence 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.handleConnectionDisplaced(true));
|
||||
}
|
||||
}
|
||||
|
||||
case DISCONNECT_REQUESTED -> listenerEventExecutor.execute(() -> listener.handleConnectionDisplaced(false));
|
||||
|
||||
case MESSAGES_PERSISTED -> listenerEventExecutor.execute(listener::handleMessagesPersisted);
|
||||
|
||||
default -> logger.warn("Unexpected client event type: {}", clientEvent.getClass());
|
||||
}
|
||||
} else {
|
||||
MESSAGE_WITHOUT_LISTENER_COUNTER.increment();
|
||||
listenerEventExecutor.execute(() -> unsubscribeIfMissingListener(accountAndDeviceIdentifier));
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] getClientEventChannel(final UUID accountIdentifier, final byte deviceId) {
|
||||
return ("client_presence::{" + accountIdentifier + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static AccountAndDeviceIdentifier parseClientPresenceKey(final byte[] clientPresenceKeyBytes) {
|
||||
final String clientPresenceKey = new String(clientPresenceKeyBytes, StandardCharsets.UTF_8);
|
||||
final int uuidStart = "client_presence::{".length();
|
||||
|
||||
final UUID accountIdentifier = UUID.fromString(clientPresenceKey.substring(uuidStart, uuidStart + 36));
|
||||
final byte deviceId = Byte.parseByte(clientPresenceKey.substring(uuidStart + 38, clientPresenceKey.length() - 1));
|
||||
|
||||
return new AccountAndDeviceIdentifier(accountIdentifier, deviceId);
|
||||
}
|
||||
}
|
||||
+15
-3
@@ -11,6 +11,7 @@ import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTolerantPubSubConnection<K, V, StatefulRedisClusterPubSubConnection<K, V>> {
|
||||
|
||||
@@ -32,17 +33,28 @@ public class FaultTolerantPubSubClusterConnection<K, V> extends AbstractFaultTol
|
||||
this.topologyChangedEventScheduler = topologyChangedEventScheduler;
|
||||
}
|
||||
|
||||
public void subscribeToClusterTopologyChangedEvents(final Runnable eventHandler) {
|
||||
public void subscribeToClusterTopologyChangedEvents(final Consumer<ClusterTopologyChangedEvent> eventHandler) {
|
||||
|
||||
usePubSubConnection(connection -> connection.getResources().eventBus().get()
|
||||
.filter(event -> event instanceof ClusterTopologyChangedEvent)
|
||||
.filter(event -> {
|
||||
// If we use shared `ClientResources` for multiple clients, we may receive topology change events for clusters
|
||||
// other than our own. Filter for clusters that have at least one node in common with our current view of our
|
||||
// partitions.
|
||||
if (event instanceof ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
|
||||
return withPubSubConnection(c -> c.getPartitions().stream().anyMatch(redisClusterNode ->
|
||||
clusterTopologyChangedEvent.before().contains(redisClusterNode) ||
|
||||
clusterTopologyChangedEvent.after().contains(redisClusterNode)));
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
.subscribeOn(topologyChangedEventScheduler)
|
||||
.subscribe(event -> {
|
||||
logger.info("Got topology change event for {}, resubscribing all keyspace notifications", getName());
|
||||
|
||||
resubscribeRetry.executeRunnable(() -> {
|
||||
try {
|
||||
eventHandler.run();
|
||||
eventHandler.accept((ClusterTopologyChangedEvent) event);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Resubscribe for {} failed", getName(), e);
|
||||
throw e;
|
||||
|
||||
+11
@@ -59,6 +59,17 @@ public class FaultTolerantRedisClient {
|
||||
|
||||
this.name = name;
|
||||
|
||||
// Lettuce will issue a CLIENT SETINFO command unconditionally if these fields are set (and they are by default),
|
||||
// which can generate a bunch of spurious warnings in versions of Redis before 7.2.0.
|
||||
//
|
||||
// See:
|
||||
//
|
||||
// - https://github.com/redis/lettuce/pull/2823
|
||||
// - https://github.com/redis/lettuce/issues/2817
|
||||
redisUri.setClientName(null);
|
||||
redisUri.setLibraryName(null);
|
||||
redisUri.setLibraryVersion(null);
|
||||
|
||||
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
|
||||
circuitBreakerConfiguration.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
|
||||
this.redisClient = RedisClient.create(clientResourcesBuilder.build(), redisUri);
|
||||
|
||||
+20
@@ -75,6 +75,19 @@ public class FaultTolerantRedisClusterClient {
|
||||
|
||||
this.name = name;
|
||||
|
||||
// Lettuce will issue a CLIENT SETINFO command unconditionally if these fields are set (and they are by default),
|
||||
// which can generate a bunch of spurious warnings in versions of Redis before 7.2.0.
|
||||
//
|
||||
// See:
|
||||
//
|
||||
// - https://github.com/redis/lettuce/pull/2823
|
||||
// - https://github.com/redis/lettuce/issues/2817
|
||||
redisUris.forEach(redisUri -> {
|
||||
redisUri.setClientName(null);
|
||||
redisUri.setLibraryName(null);
|
||||
redisUri.setLibraryVersion(null);
|
||||
});
|
||||
|
||||
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker(name,
|
||||
circuitBreakerConfig.toCircuitBreakerConfig(), Schedulers.newSingle("topology-changed-" + name, true));
|
||||
this.clusterClient = RedisClusterClient.create(
|
||||
@@ -202,4 +215,11 @@ public class FaultTolerantRedisClusterClient {
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents", true));
|
||||
}
|
||||
|
||||
public FaultTolerantPubSubClusterConnection<byte[], byte[]> createBinaryPubSubConnection() {
|
||||
final StatefulRedisClusterPubSubConnection<byte[], byte[]> pubSubConnection = clusterClient.connectPubSub(ByteArrayCodec.INSTANCE);
|
||||
pubSubConnections.add(pubSubConnection);
|
||||
|
||||
return new FaultTolerantPubSubClusterConnection<>(name, pubSubConnection, topologyChangedEventRetry,
|
||||
Schedulers.newSingle(name + "-redisPubSubEvents", true));
|
||||
}
|
||||
}
|
||||
+39
-22
@@ -23,6 +23,7 @@ import io.netty.channel.ChannelDuplexHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelPromise;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -195,9 +196,6 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
|
||||
|
||||
logger.trace("Breaker state is {}", breaker.getState());
|
||||
|
||||
// Note: io.lettuce.core.protocol.CommandHandler also supports batches (List/Collection<RedisCommand>),
|
||||
// but we do not use that feature, so we can just check for single commands
|
||||
//
|
||||
// There are two types of RedisCommands that are not CompleteableCommand:
|
||||
// - io.lettuce.core.protocol.Command
|
||||
// - io.lettuce.core.protocol.PristineFallbackCommand
|
||||
@@ -206,36 +204,55 @@ public class LettuceShardCircuitBreaker implements NettyCustomizer {
|
||||
// to consume responses.
|
||||
if (msg instanceof RedisCommand<?, ?, ?> rc && rc instanceof CompleteableCommand<?> command) {
|
||||
try {
|
||||
breaker.acquirePermission();
|
||||
|
||||
// state can change in acquirePermission()
|
||||
logger.trace("Breaker is permitted: {}", breaker.getState());
|
||||
|
||||
final long startNanos = System.nanoTime();
|
||||
|
||||
command.onComplete((ignored, throwable) -> {
|
||||
final long durationNanos = System.nanoTime() - startNanos;
|
||||
|
||||
// RedisNoScriptException doesn’t indicate a fault the breaker can protect
|
||||
if (throwable != null && !(throwable instanceof RedisNoScriptException)) {
|
||||
breaker.onError(durationNanos, TimeUnit.NANOSECONDS, throwable);
|
||||
logger.warn("Command completed with error", throwable);
|
||||
} else {
|
||||
breaker.onSuccess(durationNanos, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
});
|
||||
|
||||
instrumentCommand(command);
|
||||
} catch (final CallNotPermittedException e) {
|
||||
rc.completeExceptionally(e);
|
||||
promise.tryFailure(e);
|
||||
return;
|
||||
}
|
||||
|
||||
} else if (msg instanceof Collection<?> collection &&
|
||||
!collection.isEmpty() &&
|
||||
collection.stream().allMatch(obj -> obj instanceof RedisCommand && obj instanceof CompleteableCommand<?>)) {
|
||||
|
||||
@SuppressWarnings("unchecked") final Collection<RedisCommand<?, ?, ?>> commandCollection =
|
||||
(Collection<RedisCommand<?, ?, ?>>) collection;
|
||||
|
||||
try {
|
||||
// If we have a collection of commands, we only acquire a single permit for the whole batch (since there's
|
||||
// only a single write promise to fail). We choose a single command from the collection to sample for failure.
|
||||
instrumentCommand((CompleteableCommand<?>) commandCollection.iterator().next());
|
||||
} catch (final CallNotPermittedException e) {
|
||||
commandCollection.forEach(redisCommand -> redisCommand.completeExceptionally(e));
|
||||
promise.tryFailure(e);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
logger.warn("Unexpected msg type: {}", msg.getClass());
|
||||
}
|
||||
|
||||
super.write(ctx, msg, promise);
|
||||
}
|
||||
|
||||
private void instrumentCommand(final CompleteableCommand<?> command) throws CallNotPermittedException {
|
||||
breaker.acquirePermission();
|
||||
|
||||
// state can change in acquirePermission()
|
||||
logger.trace("Breaker is permitted: {}", breaker.getState());
|
||||
|
||||
final long startNanos = System.nanoTime();
|
||||
|
||||
command.onComplete((ignored, throwable) -> {
|
||||
final long durationNanos = System.nanoTime() - startNanos;
|
||||
|
||||
// RedisNoScriptException doesn’t indicate a fault the breaker can protect
|
||||
if (throwable != null && !(throwable instanceof RedisNoScriptException)) {
|
||||
breaker.onError(durationNanos, TimeUnit.NANOSECONDS, throwable);
|
||||
logger.warn("Command completed with error", throwable);
|
||||
} else {
|
||||
breaker.onSuccess(durationNanos, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-17
@@ -68,18 +68,17 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
@@ -125,11 +124,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final ProfilesManager profilesManager;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
private final Executor accountLockExecutor;
|
||||
private final Executor clientPresenceExecutor;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
@@ -204,11 +202,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final ProfilesManager profilesManager,
|
||||
final SecureStorageClient secureStorageClient,
|
||||
final SecureValueRecovery2Client secureValueRecovery2Client,
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final Executor accountLockExecutor,
|
||||
final Executor clientPresenceExecutor,
|
||||
final Clock clock,
|
||||
final byte[] linkDeviceSecret,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
@@ -222,11 +219,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
this.profilesManager = profilesManager;
|
||||
this.secureStorageClient = secureStorageClient;
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
this.accountLockExecutor = accountLockExecutor;
|
||||
this.clientPresenceExecutor = clientPresenceExecutor;
|
||||
this.clock = requireNonNull(clock);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
|
||||
@@ -329,7 +325,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
keysManager.deleteSingleUsePreKeys(pni),
|
||||
messagesManager.clear(aci),
|
||||
profilesManager.deleteAll(aci))
|
||||
.thenRunAsync(() -> clientPresenceManager.disconnectAllPresencesForUuid(aci), clientPresenceExecutor)
|
||||
.thenCompose(ignored -> pubSubClientEventManager.requestDisconnection(aci))
|
||||
.thenCompose(ignored -> accounts.reclaimAccount(e.getExistingAccount(), account, additionalWriteItems))
|
||||
.thenCompose(ignored -> {
|
||||
// We should have cleared all messages before overwriting the old account, but more may have arrived
|
||||
@@ -591,11 +587,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
return CompletableFuture.failedFuture(throwable);
|
||||
})
|
||||
.whenCompleteAsync((ignored, throwable) -> {
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
if (throwable == null) {
|
||||
RedisOperation.unchecked(() -> clientPresenceManager.disconnectPresence(accountIdentifier, deviceId));
|
||||
pubSubClientEventManager.requestDisconnection(accountIdentifier, List.of(deviceId));
|
||||
}
|
||||
}, clientPresenceExecutor);
|
||||
});
|
||||
}
|
||||
|
||||
public Account changeNumber(final Account account,
|
||||
@@ -1240,9 +1236,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber()))
|
||||
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
|
||||
.thenCompose(ignored -> redisDeleteAsync(account))
|
||||
.thenRunAsync(() -> RedisOperation.unchecked(() ->
|
||||
account.getDevices().forEach(device ->
|
||||
clientPresenceManager.disconnectPresence(account.getUuid(), device.getId()))), clientPresenceExecutor);
|
||||
.thenRun(() -> pubSubClientEventManager.requestDisconnection(account.getUuid()));
|
||||
}
|
||||
|
||||
private String getAccountMapKey(String key) {
|
||||
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
/**
|
||||
* A message availability listener is notified when new messages are available for a specific device for a specific
|
||||
* account. Availability listeners are also notified when messages are moved from the message cache to long-term storage
|
||||
* as an optimization hint to implementing classes.
|
||||
*/
|
||||
public interface MessageAvailabilityListener {
|
||||
|
||||
/**
|
||||
* @return whether the listener is still active. {@code false} indicates the listener can no longer handle messages
|
||||
* and may be discarded
|
||||
*/
|
||||
boolean handleNewMessagesAvailable();
|
||||
|
||||
/**
|
||||
* @return whether the listener is still active. {@code false} indicates the listener can no longer handle messages
|
||||
* and may be discarded
|
||||
*/
|
||||
boolean handleMessagesPersisted();
|
||||
}
|
||||
+4
-2
@@ -61,9 +61,11 @@ public class MessagePersister implements Managed {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache, final MessagesManager messagesManager,
|
||||
public MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager, final Duration persistDelay,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Duration persistDelay,
|
||||
final int dedicatedProcessWorkerThreadCount
|
||||
) {
|
||||
|
||||
|
||||
+64
-240
@@ -10,11 +10,8 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.ZAddArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
@@ -27,18 +24,13 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -50,11 +42,9 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -64,8 +54,7 @@ import reactor.core.scheduler.Schedulers;
|
||||
/**
|
||||
* Manages short-term storage of messages in Redis. Messages are frequently delivered to their destination and deleted
|
||||
* shortly after they reach the server, and this cache acts as a low-latency holding area for new messages, reducing
|
||||
* load on higher-latency, longer-term storage systems. Redis in particular provides keyspace notifications, which act
|
||||
* as a form of pub-sub notifications to alert listeners when new messages arrive.
|
||||
* load on higher-latency, longer-term storage systems.
|
||||
* <p>
|
||||
* The following structures are used:
|
||||
* <dl>
|
||||
@@ -117,13 +106,11 @@ import reactor.core.scheduler.Schedulers;
|
||||
* @see MessagesCacheRemoveRecipientViewFromMrmDataScript
|
||||
* @see MessagesCacheRemoveQueueScript
|
||||
*/
|
||||
public class MessagesCache extends RedisClusterPubSubAdapter<String, String> implements Managed {
|
||||
public class MessagesCache {
|
||||
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
private final FaultTolerantPubSubClusterConnection<String, String> pubSubConnection;
|
||||
private final Clock clock;
|
||||
|
||||
private final ExecutorService notificationExecutorService;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ExecutorService messageDeletionExecutorService;
|
||||
// messageDeletionExecutorService wrapped into a reactor Scheduler
|
||||
@@ -138,10 +125,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
private final MessagesCacheRemoveQueueScript removeQueueScript;
|
||||
private final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript;
|
||||
private final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript;
|
||||
|
||||
private final ReentrantLock messageListenersLock = new ReentrantLock();
|
||||
private final Map<String, MessageAvailabilityListener> messageListenersByQueueName = new HashMap<>();
|
||||
private final Map<MessageAvailabilityListener, String> queueNamesByMessageListener = new IdentityHashMap<>();
|
||||
private final MessagesCacheUnlockQueueScript unlockQueueScript;
|
||||
|
||||
private final Timer insertTimer = Metrics.timer(name(MessagesCache.class, "insert"));
|
||||
private final Timer insertSharedMrmPayloadTimer = Metrics.timer(name(MessagesCache.class, "insertSharedMrmPayload"));
|
||||
@@ -150,27 +134,18 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
|
||||
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
|
||||
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
|
||||
private final Counter pubSubMessageCounter = Metrics.counter(name(MessagesCache.class, "pubSubMessage"));
|
||||
private final Counter newMessageNotificationCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "newMessageNotification"));
|
||||
private final Counter queuePersistedNotificationCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "queuePersisted"));
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "staleEphemeralMessages"));
|
||||
private final Counter messageAvailabilityListenerRemovedAfterAddCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "messageAvailabilityListenerRemovedAfterAdd"));
|
||||
private final Counter prunedStaleSubscriptionCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "prunedStaleSubscription"));
|
||||
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
|
||||
private final Counter mrmRetrievalErrorCounter = Metrics.counter(name(MessagesCache.class, "mrmRetrievalError"));
|
||||
private final Counter mrmPhaseTwoMissingContentCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "mrmPhaseTwoMissingContent"));
|
||||
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "sharedMrmKeyRemoved"));
|
||||
|
||||
static final String NEXT_SLOT_TO_PERSIST_KEY = "user_queue_persist_slot";
|
||||
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final String QUEUE_KEYSPACE_PREFIX = "__keyspace@0__:user_queue::";
|
||||
private static final String PERSISTING_KEYSPACE_PREFIX = "__keyspace@0__:user_queue_persisting::";
|
||||
|
||||
private static final String MRM_VIEWS_EXPERIMENT_NAME = "mrmViews";
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -183,13 +158,15 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class);
|
||||
|
||||
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster, final ExecutorService notificationExecutorService,
|
||||
final Scheduler messageDeliveryScheduler, final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
|
||||
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager)
|
||||
throws IOException {
|
||||
|
||||
this(
|
||||
redisCluster,
|
||||
notificationExecutorService,
|
||||
messageDeliveryScheduler,
|
||||
messageDeletionExecutorService,
|
||||
clock,
|
||||
@@ -200,27 +177,27 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
new MessagesCacheRemoveByGuidScript(redisCluster),
|
||||
new MessagesCacheRemoveQueueScript(redisCluster),
|
||||
new MessagesCacheGetQueuesToPersistScript(redisCluster),
|
||||
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster)
|
||||
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster),
|
||||
new MessagesCacheUnlockQueueScript(redisCluster)
|
||||
);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessagesCache(final FaultTolerantRedisClusterClient redisCluster, final ExecutorService notificationExecutorService,
|
||||
final Scheduler messageDeliveryScheduler, final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript, final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheGetQueuesToPersistScript getQueuesToPersistScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript)
|
||||
throws IOException {
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript,
|
||||
final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException {
|
||||
|
||||
this.redisCluster = redisCluster;
|
||||
this.pubSubConnection = redisCluster.createPubSubConnection();
|
||||
this.clock = clock;
|
||||
|
||||
this.notificationExecutorService = notificationExecutorService;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.messageDeletionExecutorService = messageDeletionExecutorService;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
|
||||
@@ -234,40 +211,16 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
this.removeQueueScript = removeQueueScript;
|
||||
this.getQueuesToPersistScript = getQueuesToPersistScript;
|
||||
this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript;
|
||||
this.unlockQueueScript = unlockQueueScript;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribeAll);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.sync().upstream().commands().unsubscribe());
|
||||
}
|
||||
|
||||
private void resubscribeAll() {
|
||||
|
||||
final Set<String> queueNames;
|
||||
|
||||
messageListenersLock.lock();
|
||||
try {
|
||||
queueNames = new HashSet<>(messageListenersByQueueName.keySet());
|
||||
} finally {
|
||||
messageListenersLock.unlock();
|
||||
}
|
||||
|
||||
for (final String queueName : queueNames) {
|
||||
// avoid overwhelming a newly recovered node by processing synchronously, rather than using CompletableFuture.allOf()
|
||||
subscribeForKeyspaceNotifications(queueName).join();
|
||||
}
|
||||
}
|
||||
|
||||
public long insert(final UUID guid, final UUID destinationUuid, final byte destinationDevice,
|
||||
public boolean insert(final UUID messageGuid,
|
||||
final UUID destinationAccountIdentifier,
|
||||
final byte destinationDeviceId,
|
||||
final MessageProtos.Envelope message) {
|
||||
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(guid.toString()).build();
|
||||
return insertTimer.record(() -> insertScript.execute(destinationUuid, destinationDevice, messageWithGuid));
|
||||
|
||||
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(messageGuid.toString()).build();
|
||||
return insertTimer.record(() -> insertScript.execute(destinationAccountIdentifier, destinationDeviceId, messageWithGuid));
|
||||
}
|
||||
|
||||
public byte[] insertSharedMultiRecipientMessagePayload(
|
||||
@@ -404,19 +357,15 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
final Mono<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
|
||||
final Mono<?> experimentMono;
|
||||
if (isStaleEphemeralMessage(message, earliestAllowableEphemeralTimestamp)) {
|
||||
// skip fetching content for message that will be discarded
|
||||
experimentMono = Mono.empty();
|
||||
messageMono = Mono.just(message.toBuilder().clearSharedMrmKey().build());
|
||||
} else {
|
||||
experimentMono = maybeRunMrmViewExperiment(message, destinationUuid, destinationDevice);
|
||||
// mrm views phase 2: fetch shared MRM data -- internally depends on dynamic config that
|
||||
// enables fetching and using it (the stored messages still always have `content` set upstream)
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
}
|
||||
|
||||
// mrm views phase 1: messageMono for sharedMrmKey is always Mono.just(), because messages always have content
|
||||
// To avoid races, wait for the experiment to run, but ignore any errors
|
||||
messageMono = experimentMono
|
||||
.onErrorComplete()
|
||||
.then(Mono.just(message.toBuilder().clearSharedMrmKey().build()));
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
}
|
||||
@@ -433,14 +382,23 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the fetch and compare logic for the MRM view experiment, if it is enabled.
|
||||
* Returns the given message with its shared MRM data.
|
||||
*
|
||||
* @see DynamicMessagesConfiguration#mrmViewExperimentEnabled()
|
||||
* @see DynamicMessagesConfiguration#fetchSharedMrmData()
|
||||
* @see DynamicMessagesConfiguration#useSharedMrmData()
|
||||
*/
|
||||
private Mono<?> maybeRunMrmViewExperiment(final MessageProtos.Envelope mrmMessage, final UUID destinationUuid,
|
||||
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
|
||||
final byte destinationDevice) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration()
|
||||
.mrmViewExperimentEnabled()) {
|
||||
|
||||
assert mrmMessage.hasSharedMrmKey();
|
||||
|
||||
// mrm views phase 2: messages have content
|
||||
if (!mrmMessage.hasContent()) {
|
||||
mrmPhaseTwoMissingContentCounter.increment();
|
||||
}
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().fetchSharedMrmData()
|
||||
|| !mrmMessage.hasContent()) {
|
||||
|
||||
final Experiment experiment = new Experiment(MRM_VIEWS_EXPERIMENT_NAME);
|
||||
|
||||
@@ -449,7 +407,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
// the message might be addressed to the account's PNI, so use the service ID from the envelope
|
||||
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
|
||||
final Mono<MessageProtos.Envelope> mrmMessageMono = Mono.from(redisCluster.withBinaryClusterReactive(
|
||||
final Mono<MessageProtos.Envelope> messageFromRedisMono = Mono.from(redisCluster.withBinaryClusterReactive(
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
.collectList()
|
||||
.publishOn(messageDeliveryScheduler)))
|
||||
@@ -471,14 +429,25 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
sink.error(e);
|
||||
}
|
||||
})
|
||||
.onErrorResume(throwable -> {
|
||||
logger.warn("Failed to retrieve shared mrm data", throwable);
|
||||
mrmRetrievalErrorCounter.increment();
|
||||
return Mono.empty();
|
||||
})
|
||||
.share();
|
||||
|
||||
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), mrmMessageMono);
|
||||
if (mrmMessage.hasContent()) {
|
||||
experiment.compareMonoResult(mrmMessage.toBuilder().clearSharedMrmKey().build(), messageFromRedisMono);
|
||||
}
|
||||
|
||||
return mrmMessageMono;
|
||||
} else {
|
||||
return Mono.empty();
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagesConfiguration().useSharedMrmData()
|
||||
|| !mrmMessage.hasContent()) {
|
||||
return messageFromRedisMono;
|
||||
}
|
||||
}
|
||||
|
||||
// if fetching or using shared data is disabled, fallback to just() with the existing message
|
||||
return Mono.just(mrmMessage.toBuilder().clearSharedMrmKey().build());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -552,13 +521,9 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
.concatMap(message -> {
|
||||
final Mono<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
final Mono<?> experimentMono = maybeRunMrmViewExperiment(message, accountUuid, destinationDevice);
|
||||
|
||||
// mrm views phase 1: messageMono for sharedMrmKey is always Mono.just(), because messages always have content
|
||||
// To avoid races, wait for the experiment to run, but ignore any errors
|
||||
messageMono = experimentMono
|
||||
.onErrorComplete()
|
||||
.then(Mono.just(message.toBuilder().clearSharedMrmKey().build()));
|
||||
// mrm views phase 2: fetch shared MRM data -- internally depends on dynamic config that
|
||||
// enables fetching and using it (the stored messages still always have `content` set upstream)
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
}
|
||||
@@ -637,148 +602,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
void unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
redisCluster.useBinaryCluster(
|
||||
connection -> connection.sync().del(getPersistInProgressKey(accountUuid, deviceId)));
|
||||
}
|
||||
|
||||
public void addMessageAvailabilityListener(final UUID destinationUuid, final byte deviceId,
|
||||
final MessageAvailabilityListener listener) {
|
||||
final String queueName = getQueueName(destinationUuid, deviceId);
|
||||
|
||||
final CompletableFuture<Void> subscribeFuture;
|
||||
messageListenersLock.lock();
|
||||
try {
|
||||
messageListenersByQueueName.put(queueName, listener);
|
||||
queueNamesByMessageListener.put(listener, queueName);
|
||||
// Submit to the Redis queue while holding the lock, but don’t wait until exiting
|
||||
subscribeFuture = subscribeForKeyspaceNotifications(queueName);
|
||||
} finally {
|
||||
messageListenersLock.unlock();
|
||||
}
|
||||
|
||||
subscribeFuture.join();
|
||||
}
|
||||
|
||||
public void removeMessageAvailabilityListener(final MessageAvailabilityListener listener) {
|
||||
@Nullable final String queueName;
|
||||
messageListenersLock.lock();
|
||||
try {
|
||||
queueName = queueNamesByMessageListener.get(listener);
|
||||
} finally {
|
||||
messageListenersLock.unlock();
|
||||
}
|
||||
|
||||
if (queueName != null) {
|
||||
|
||||
final CompletableFuture<Void> unsubscribeFuture;
|
||||
messageListenersLock.lock();
|
||||
try {
|
||||
queueNamesByMessageListener.remove(listener);
|
||||
if (messageListenersByQueueName.remove(queueName, listener)) {
|
||||
// Submit to the Redis queue holding the lock, but don’t wait until exiting
|
||||
unsubscribeFuture = unsubscribeFromKeyspaceNotifications(queueName);
|
||||
} else {
|
||||
messageAvailabilityListenerRemovedAfterAddCounter.increment();
|
||||
unsubscribeFuture = CompletableFuture.completedFuture(null);
|
||||
}
|
||||
} finally {
|
||||
messageListenersLock.unlock();
|
||||
}
|
||||
|
||||
unsubscribeFuture.join();
|
||||
}
|
||||
}
|
||||
|
||||
private void pruneStaleSubscription(final String channel) {
|
||||
unsubscribeFromKeyspaceNotifications(getQueueNameFromKeyspaceChannel(channel))
|
||||
.thenRun(prunedStaleSubscriptionCounter::increment);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> subscribeForKeyspaceNotifications(final String queueName) {
|
||||
final int slot = SlotHash.getSlot(queueName);
|
||||
|
||||
return pubSubConnection.withPubSubConnection(
|
||||
connection -> connection.async()
|
||||
.nodes(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM) && node.hasSlot(slot))
|
||||
.commands()
|
||||
.subscribe(getKeyspaceChannels(queueName))).toCompletableFuture()
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> unsubscribeFromKeyspaceNotifications(final String queueName) {
|
||||
final int slot = SlotHash.getSlot(queueName);
|
||||
|
||||
return pubSubConnection.withPubSubConnection(
|
||||
connection -> connection.async()
|
||||
.nodes(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM) && node.hasSlot(slot))
|
||||
.commands()
|
||||
.unsubscribe(getKeyspaceChannels(queueName)))
|
||||
.toCompletableFuture()
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
private static String[] getKeyspaceChannels(final String queueName) {
|
||||
return new String[]{
|
||||
QUEUE_KEYSPACE_PREFIX + "{" + queueName + "}",
|
||||
PERSISTING_KEYSPACE_PREFIX + "{" + queueName + "}"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void message(final RedisClusterNode node, final String channel, final String message) {
|
||||
pubSubMessageCounter.increment();
|
||||
|
||||
if (channel.startsWith(QUEUE_KEYSPACE_PREFIX) && "zadd".equals(message)) {
|
||||
newMessageNotificationCounter.increment();
|
||||
notificationExecutorService.execute(() -> {
|
||||
try {
|
||||
findListener(channel).ifPresentOrElse(listener -> {
|
||||
if (!listener.handleNewMessagesAvailable()) {
|
||||
removeMessageAvailabilityListener(listener);
|
||||
}
|
||||
}, () -> pruneStaleSubscription(channel));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Unexpected error handling new message", e);
|
||||
}
|
||||
});
|
||||
} else if (channel.startsWith(PERSISTING_KEYSPACE_PREFIX) && "del".equals(message)) {
|
||||
queuePersistedNotificationCounter.increment();
|
||||
notificationExecutorService.execute(() -> {
|
||||
try {
|
||||
findListener(channel).ifPresentOrElse(listener -> {
|
||||
if (!listener.handleMessagesPersisted()) {
|
||||
removeMessageAvailabilityListener(listener);
|
||||
}
|
||||
}, () -> pruneStaleSubscription(channel));
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Unexpected error handling messages persisted", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<MessageAvailabilityListener> findListener(final String keyspaceChannel) {
|
||||
final String queueName = getQueueNameFromKeyspaceChannel(keyspaceChannel);
|
||||
|
||||
messageListenersLock.lock();
|
||||
try {
|
||||
return Optional.ofNullable(messageListenersByQueueName.get(queueName));
|
||||
} finally {
|
||||
messageListenersLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getQueueName(final UUID accountUuid, final byte deviceId) {
|
||||
return accountUuid + "::" + deviceId;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getQueueNameFromKeyspaceChannel(final String channel) {
|
||||
final int startOfHashTag = channel.indexOf('{');
|
||||
final int endOfHashTag = channel.lastIndexOf('}');
|
||||
|
||||
return channel.substring(startOfHashTag + 1, endOfHashTag);
|
||||
unlockQueueScript.execute(accountUuid, deviceId);
|
||||
}
|
||||
|
||||
static byte[] getMessageQueueKey(final UUID accountUuid, final byte deviceId) {
|
||||
|
||||
+25
-6
@@ -13,36 +13,55 @@ import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
/**
|
||||
* Inserts an envelope into the message queue for a destination device.
|
||||
* Inserts an envelope into the message queue for a destination device and publishes a "new message available" event.
|
||||
*/
|
||||
class MessagesCacheInsertScript {
|
||||
|
||||
private final ClusterLuaScript insertScript;
|
||||
|
||||
private static final byte[] NEW_MESSAGE_EVENT_BYTES = ClientEvent.newBuilder()
|
||||
.setNewMessageAvailable(NewMessageAvailableEvent.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
MessagesCacheInsertScript(FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.insertScript = ClusterLuaScript.fromResource(redisCluster, "lua/insert_item.lua", ScriptOutputType.INTEGER);
|
||||
this.insertScript = ClusterLuaScript.fromResource(redisCluster, "lua/insert_item.lua", ScriptOutputType.BOOLEAN);
|
||||
}
|
||||
|
||||
long execute(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
|
||||
/**
|
||||
* Inserts a message into the given device's message queue and publishes a "new message available" event.
|
||||
*
|
||||
* @param destinationUuid the account identifier for the receiving account
|
||||
* @param destinationDevice the ID of the receiving device within the given account
|
||||
* @param envelope the message to insert
|
||||
* @return {@code true} if the destination device had a registered "presence"/event subscriber or {@code false}
|
||||
* otherwise
|
||||
*/
|
||||
boolean execute(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
|
||||
assert envelope.hasServerGuid();
|
||||
assert envelope.hasServerTimestamp();
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice) // queueTotalIndexKey
|
||||
MessagesCache.getQueueIndexKey(destinationUuid, destinationDevice), // queueTotalIndexKey
|
||||
PubSubClientEventManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>(Arrays.asList(
|
||||
envelope.toByteArray(), // message
|
||||
String.valueOf(envelope.getServerTimestamp()).getBytes(StandardCharsets.UTF_8), // currentTime
|
||||
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8) // guid
|
||||
envelope.getServerGuid().getBytes(StandardCharsets.UTF_8), // guid
|
||||
NEW_MESSAGE_EVENT_BYTES // eventPayload
|
||||
));
|
||||
|
||||
return (long) insertScript.executeBinary(keys, args);
|
||||
return (boolean) insertScript.executeBinary(keys, args);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Unlocks a message queue for persistence/message retrieval.
|
||||
*/
|
||||
class MessagesCacheUnlockQueueScript {
|
||||
|
||||
private final ClusterLuaScript unlockQueueScript;
|
||||
|
||||
private final List<byte[]> MESSAGES_PERSISTED_EVENT_ARGS = List.of(ClientEvent.newBuilder()
|
||||
.setMessagesPersisted(MessagesPersistedEvent.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray()); // eventPayload
|
||||
|
||||
MessagesCacheUnlockQueueScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.unlockQueueScript =
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/unlock_queue.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
void execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
|
||||
PubSubClientEventManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
|
||||
);
|
||||
|
||||
unlockQueueScript.executeBinary(keys, MESSAGES_PERSISTED_EVENT_ARGS);
|
||||
}
|
||||
}
|
||||
+4
-29
@@ -24,7 +24,6 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
@@ -60,14 +59,16 @@ public class MessagesManager {
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
}
|
||||
|
||||
public void insert(UUID destinationUuid, byte destinationDevice, Envelope message) {
|
||||
public boolean insert(UUID destinationUuid, byte destinationDevice, Envelope message) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
|
||||
messagesCache.insert(messageGuid, destinationUuid, destinationDevice, message);
|
||||
final boolean destinationPresent = messagesCache.insert(messageGuid, destinationUuid, destinationDevice, message);
|
||||
|
||||
if (message.hasSourceServiceId() && !destinationUuid.toString().equals(message.getSourceServiceId())) {
|
||||
reportMessageManager.store(message.getSourceServiceId(), messageGuid);
|
||||
}
|
||||
|
||||
return destinationPresent;
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@@ -128,10 +129,6 @@ public class MessagesManager {
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public Mono<Long> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, Device destinationDevice) {
|
||||
return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid) {
|
||||
return messagesCache.clear(destinationUuid);
|
||||
}
|
||||
@@ -190,17 +187,6 @@ public class MessagesManager {
|
||||
return messagesRemovedFromCache;
|
||||
}
|
||||
|
||||
public void addMessageAvailabilityListener(
|
||||
final UUID destinationUuid,
|
||||
final byte destinationDeviceId,
|
||||
final MessageAvailabilityListener listener) {
|
||||
messagesCache.addMessageAvailabilityListener(destinationUuid, destinationDeviceId, listener);
|
||||
}
|
||||
|
||||
public void removeMessageAvailabilityListener(final MessageAvailabilityListener listener) {
|
||||
messagesCache.removeMessageAvailabilityListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the shared multi-recipient message payload to storage.
|
||||
*
|
||||
@@ -211,15 +197,4 @@ public class MessagesManager {
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the recipient's view from shared MRM data if necessary
|
||||
*/
|
||||
public void removeRecipientViewFromMrmData(final byte destinationDeviceId, final Envelope message) {
|
||||
if (message.hasSharedMrmKey()) {
|
||||
messagesCache.removeRecipientViewFromMrmData(List.of(message.getSharedMrmKey().toByteArray()),
|
||||
ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
destinationDeviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,12 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class RedisClusterUtil {
|
||||
|
||||
@@ -38,4 +44,51 @@ public class RedisClusterUtil {
|
||||
public static String getMinimalHashTag(final int slot) {
|
||||
return HASHES_BY_SLOT[slot];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array indicating which slots have moved as part of a {@link ClusterTopologyChangedEvent}. The elements
|
||||
* of the array map to slots in the cluster; for example, if slot 1234 has changed, then element 1234 of the returned
|
||||
* array will be {@code true}.
|
||||
*
|
||||
* @param clusterTopologyChangedEvent the event from which to derive an array of changed slots
|
||||
*
|
||||
* @return an array indicating which slots of changed
|
||||
*/
|
||||
public static boolean[] getChangedSlots(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
|
||||
final Map<String, RedisClusterNode> beforeNodesById = clusterTopologyChangedEvent.before().stream()
|
||||
.collect(Collectors.toMap(RedisClusterNode::getNodeId, node -> node));
|
||||
|
||||
final Map<String, RedisClusterNode> afterNodesById = clusterTopologyChangedEvent.after().stream()
|
||||
.collect(Collectors.toMap(RedisClusterNode::getNodeId, node -> node));
|
||||
|
||||
final Set<String> nodeIds = new HashSet<>(beforeNodesById.keySet());
|
||||
nodeIds.addAll(afterNodesById.keySet());
|
||||
|
||||
final boolean[] changedSlots = new boolean[SlotHash.SLOT_COUNT];
|
||||
|
||||
for (final String nodeId : nodeIds) {
|
||||
if (beforeNodesById.containsKey(nodeId) && afterNodesById.containsKey(nodeId)) {
|
||||
// This node was present before and after the topology change, but its slots may have changed
|
||||
final boolean[] beforeSlots = new boolean[SlotHash.SLOT_COUNT];
|
||||
beforeNodesById.get(nodeId).getSlots().forEach(slot -> beforeSlots[slot] = true);
|
||||
|
||||
final boolean[] afterSlots = new boolean[SlotHash.SLOT_COUNT];
|
||||
afterNodesById.get(nodeId).getSlots().forEach(slot -> afterSlots[slot] = true);
|
||||
|
||||
for (int slot = 0; slot < SlotHash.SLOT_COUNT; slot++) {
|
||||
changedSlots[slot] |= beforeSlots[slot] ^ afterSlots[slot];
|
||||
}
|
||||
} else if (beforeNodesById.containsKey(nodeId)) {
|
||||
// The node was present before the topology change, but is gone now; all of its slots should be considered
|
||||
// changed
|
||||
beforeNodesById.get(nodeId).getSlots().forEach(slot -> changedSlots[slot] = true);
|
||||
} else {
|
||||
// The node was present after the change, but wasn't there before; all of its slots should be considered
|
||||
// changed
|
||||
afterNodesById.get(nodeId).getSlots().forEach(slot -> changedSlots[slot] = true);
|
||||
}
|
||||
}
|
||||
|
||||
return changedSlots;
|
||||
}
|
||||
}
|
||||
+7
-37
@@ -9,20 +9,16 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
@@ -37,8 +33,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
private static final String AUTHENTICATED_TAG_NAME = "authenticated";
|
||||
|
||||
private static final long RENEW_PRESENCE_INTERVAL_MINUTES = 5;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthenticatedConnectListener.class);
|
||||
|
||||
private final ReceiptSender receiptSender;
|
||||
@@ -46,7 +40,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final MessageMetrics messageMetrics;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
@@ -60,7 +54,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
MessageMetrics messageMetrics,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationScheduler pushNotificationScheduler,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
PubSubClientEventManager pubSubClientEventManager,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
ClientReleaseManager clientReleaseManager,
|
||||
@@ -70,7 +64,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
this.messageMetrics = messageMetrics;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
@@ -106,25 +100,13 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor);
|
||||
|
||||
final AtomicReference<ScheduledFuture<?>> renewPresenceFutureReference = new AtomicReference<>();
|
||||
|
||||
context.addWebsocketClosedListener((closingContext, statusCode, reason) -> {
|
||||
final ScheduledFuture<?> renewPresenceFuture = renewPresenceFutureReference.get();
|
||||
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(false);
|
||||
}
|
||||
|
||||
// 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.
|
||||
RedisOperation.unchecked(() -> clientPresenceManager.clearPresence(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection));
|
||||
|
||||
// Next, we stop listening for inbound messages. If a message arrives after this call, the websocket connection
|
||||
// will not be notified and will not change its state, but that's okay because it has already closed and
|
||||
// attempts to deliver mesages via this connection will not succeed.
|
||||
RedisOperation.unchecked(() -> messagesManager.removeMessageAvailabilityListener(connection));
|
||||
pubSubClientEventManager.handleClientDisconnected(auth.getAccount().getUuid(),
|
||||
auth.getAuthenticatedDevice().getId());
|
||||
|
||||
// Finally, stop trying to deliver messages and send a push notification if the connection is aware of any
|
||||
// undelivered messages.
|
||||
@@ -132,12 +114,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
});
|
||||
|
||||
try {
|
||||
// Once we add this connection as a message availability listener, it will be notified any time a new message
|
||||
// arrives in the message cache. This updates the connection's "may have messages" state. It's important that
|
||||
// we do this first because we want to make sure we're accurately tracking message availability in the
|
||||
// connection's internal state.
|
||||
messagesManager.addMessageAvailabilityListener(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
|
||||
|
||||
// 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
|
||||
@@ -146,13 +122,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
// 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.
|
||||
clientPresenceManager.setPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
|
||||
|
||||
renewPresenceFutureReference.set(scheduledExecutorService.scheduleAtFixedRate(() -> RedisOperation.unchecked(() ->
|
||||
clientPresenceManager.renewPresence(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())),
|
||||
RENEW_PRESENCE_INTERVAL_MINUTES,
|
||||
RENEW_PRESENCE_INTERVAL_MINUTES,
|
||||
TimeUnit.MINUTES));
|
||||
pubSubClientEventManager.handleClientConnected(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
|
||||
+78
-89
@@ -45,13 +45,12 @@ 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.DisplacedPresenceListener;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEventListener;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
@@ -62,18 +61,15 @@ import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, DisplacedPresenceListener {
|
||||
public class WebSocketConnection implements ClientEventListener {
|
||||
|
||||
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 messageAvailableCounter = Metrics.counter(
|
||||
name(WebSocketConnection.class, "messagesAvailable"));
|
||||
private static final Counter messagesPersistedCounter = Metrics.counter(
|
||||
name(WebSocketConnection.class, "messagesPersisted"));
|
||||
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
|
||||
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
|
||||
|
||||
@@ -85,12 +81,14 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
|
||||
private static final String NON_SUCCESS_RESPONSE_COUNTER_NAME = name(WebSocketConnection.class,
|
||||
"clientNonSuccessResponse");
|
||||
private static final String CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class,
|
||||
"messageAvailableAfterClientClosed");
|
||||
private static final String SEND_MESSAGES_FLUX_NAME = MetricsUtil.name(WebSocketConnection.class,
|
||||
"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 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";
|
||||
@@ -317,70 +315,78 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
void processStoredMessages() {
|
||||
if (processStoredMessagesSemaphore.tryAcquire()) {
|
||||
final StoredMessageState state = storedMessageState.getAndSet(StoredMessageState.EMPTY);
|
||||
final CompletableFuture<Void> queueCleared = new CompletableFuture<>();
|
||||
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;
|
||||
}
|
||||
|
||||
sendMessages(state != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE, queueCleared);
|
||||
// Cleared the queue! Send a queue empty message if we need to
|
||||
consecutiveRetries.set(0);
|
||||
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
final long drainDuration = System.currentTimeMillis() - queueDrainStartTime.get();
|
||||
|
||||
setQueueClearedHandler(state, queueCleared);
|
||||
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) -> processMoreIfRequested(cause));
|
||||
}
|
||||
}
|
||||
|
||||
private void setQueueClearedHandler(final StoredMessageState state, final CompletableFuture<Void> queueCleared) {
|
||||
|
||||
queueCleared.whenComplete((v, cause) -> {
|
||||
if (cause == null) {
|
||||
consecutiveRetries.set(0);
|
||||
|
||||
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
|
||||
final List<Tag> tags = List.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());
|
||||
}
|
||||
} else {
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, state);
|
||||
/**
|
||||
* After processing messages, kick off another processing job if more messages came in or if there was an error
|
||||
*
|
||||
* @param cause An error that was encountered when processing the message queue, if there was one
|
||||
*/
|
||||
private void processMoreIfRequested(final @Nullable Throwable cause) {
|
||||
if (cause == null) {
|
||||
// Success, but check if more messages came in while we were processing
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
processStoredMessages();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
processStoredMessagesSemaphore.release();
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
if (cause == null) {
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
processStoredMessages();
|
||||
}
|
||||
} else {
|
||||
if (client.isOpen()) {
|
||||
if (consecutiveRetries.incrementAndGet() > MAX_CONSECUTIVE_RETRIES) {
|
||||
logger.warn("Max consecutive retries exceeded", cause);
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
return;
|
||||
}
|
||||
|
||||
if (consecutiveRetries.incrementAndGet() > MAX_CONSECUTIVE_RETRIES) {
|
||||
logger.warn("Max consecutive retries exceeded", cause);
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
} else {
|
||||
logger.debug("Failed to clear queue", cause);
|
||||
final List<Tag> tags = List.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
logger.debug("Failed to clear queue", cause);
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
|
||||
Metrics.counter(QUEUE_DRAIN_RETRY_COUNTER_NAME, tags).increment();
|
||||
Metrics.counter(QUEUE_DRAIN_RETRY_COUNTER_NAME, tags).increment();
|
||||
|
||||
final long delay = RETRY_DELAY_MILLIS + random.nextInt(RETRY_DELAY_JITTER_MILLIS);
|
||||
retryFuture
|
||||
.set(scheduledExecutorService.schedule(this::processStoredMessages, delay, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
} else {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
}
|
||||
}
|
||||
});
|
||||
final long delay = RETRY_DELAY_MILLIS + random.nextInt(RETRY_DELAY_JITTER_MILLIS);
|
||||
retryFuture.set(scheduledExecutorService.schedule(this::processStoredMessages, delay, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
private void sendMessages(final boolean cachedMessagesOnly, final CompletableFuture<Void> queueCleared) {
|
||||
private CompletableFuture<Void> sendMessages(final boolean cachedMessagesOnly) {
|
||||
final CompletableFuture<Void> queueCleared = new CompletableFuture<>();
|
||||
|
||||
final Publisher<Envelope> messages =
|
||||
messagesManager.getMessagesForDeviceReactive(auth.getAccount().getUuid(), auth.getAuthenticatedDevice(), cachedMessagesOnly);
|
||||
@@ -426,6 +432,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
);
|
||||
|
||||
messageSubscription.set(subscription);
|
||||
return queueCleared;
|
||||
}
|
||||
|
||||
private void measureSendMessageErrors(Throwable e, final boolean terminal) {
|
||||
@@ -461,44 +468,32 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleNewMessagesAvailable() {
|
||||
if (!client.isOpen()) {
|
||||
// The client may become closed without successful removal of references to the `MessageAvailabilityListener`
|
||||
Metrics.counter(CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME).increment();
|
||||
return false;
|
||||
}
|
||||
|
||||
messageAvailableCounter.increment();
|
||||
public void handleNewMessageAvailable() {
|
||||
Metrics.counter(MESSAGE_AVAILABLE_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMessagesPersisted() {
|
||||
if (!client.isOpen()) {
|
||||
// The client may become without successful removal of references to the `MessageAvailabilityListener`
|
||||
Metrics.counter(CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME).increment();
|
||||
return false;
|
||||
}
|
||||
messagesPersistedCounter.increment();
|
||||
public void handleMessagesPersisted() {
|
||||
Metrics.counter(MESSAGES_PERSISTED_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.set(StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisplacement(final boolean connectedElsewhere) {
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere))
|
||||
);
|
||||
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)));
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
|
||||
|
||||
@@ -513,13 +508,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
message = "OK";
|
||||
}
|
||||
|
||||
try {
|
||||
client.close(code, message);
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Orderly close failed", e);
|
||||
|
||||
client.hardDisconnectQuietly();
|
||||
}
|
||||
client.close(code, message);
|
||||
}
|
||||
|
||||
private record StoredMessageInfo(UUID guid, long serverTimestamp) {
|
||||
|
||||
+10
-20
@@ -35,12 +35,12 @@ import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSam
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountLockManager;
|
||||
@@ -76,7 +76,6 @@ record CommandDependencies(
|
||||
ReportMessageManager reportMessageManager,
|
||||
MessagesCache messagesCache,
|
||||
MessagesManager messagesManager,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
KeysManager keysManager,
|
||||
APNSender apnSender,
|
||||
FcmSender fcmSender,
|
||||
@@ -117,12 +116,8 @@ record CommandDependencies(
|
||||
FaultTolerantRedisClient pubsubClient =
|
||||
configuration.getRedisPubSubConfiguration().build("pubsub", redisClientResourcesBuilder.build());
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "recurringJob-%d")).threads(2).build();
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
environment.lifecycle().executorService("messageDelivery").minThreads(4).maxThreads(4).build());
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "keyspaceNotification-%d")).minThreads(4).maxThreads(4).build();
|
||||
ExecutorService messageDeletionExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "messageDeletion-%d")).minThreads(4).maxThreads(4).build();
|
||||
ExecutorService secureValueRecoveryServiceExecutor = environment.lifecycle()
|
||||
@@ -131,8 +126,6 @@ record CommandDependencies(
|
||||
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(8).build();
|
||||
ExecutorService accountLockExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "accountLock-%d")).minThreads(8).maxThreads(8).build();
|
||||
ExecutorService clientPresenceExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "clientPresence-%d")).minThreads(8).maxThreads(8).build();
|
||||
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "remoteStorage-%d"))
|
||||
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
|
||||
@@ -141,6 +134,8 @@ record CommandDependencies(
|
||||
.maxThreads(1).minThreads(1).build();
|
||||
ExecutorService fcmSenderExecutor = environment.lifecycle().executorService(name(name, "fcmSender-%d"))
|
||||
.maxThreads(16).minThreads(16).build();
|
||||
ExecutorService clientEventExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(name, "clientEvent-%d"));
|
||||
|
||||
ScheduledExecutorService secureValueRecoveryServiceRetryExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "secureValueRecoveryServiceRetry-%d")).threads(1).build();
|
||||
@@ -202,8 +197,6 @@ record CommandDependencies(
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration()
|
||||
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisClusterClient clientPresenceCluster = configuration.getClientPresenceClusterConfiguration()
|
||||
.build("client_presence", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
|
||||
redisClientResourcesBuilder);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
@@ -212,9 +205,8 @@ record CommandDependencies(
|
||||
configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, keyspaceNotificationDispatchExecutor,
|
||||
PubSubClientEventManager pubSubClientEventManager = new PubSubClientEventManager(messagesCluster, clientEventExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient,
|
||||
@@ -230,8 +222,8 @@ record CommandDependencies(
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
secureStorageClient, secureValueRecovery2Client, pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor,
|
||||
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
@@ -267,8 +259,7 @@ record CommandDependencies(
|
||||
Clock.systemUTC());
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
environment.lifecycle().manage(pubSubClientEventManager);
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
|
||||
return new CommandDependencies(
|
||||
@@ -277,7 +268,6 @@ record CommandDependencies(
|
||||
reportMessageManager,
|
||||
messagesCache,
|
||||
messagesManager,
|
||||
clientPresenceManager,
|
||||
keys,
|
||||
apnSender,
|
||||
fcmSender,
|
||||
|
||||
+4
-3
@@ -60,12 +60,13 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
});
|
||||
}
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(), deps.messagesManager(),
|
||||
deps.accountsManager(), deps.dynamicConfigurationManager(),
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(),
|
||||
deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
|
||||
environment.lifecycle().manage(deps.messagesCache());
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
|
||||
MetricsUtil.registerSystemResourceMetrics(environment);
|
||||
|
||||
+2
-2
@@ -42,10 +42,10 @@ public class NotifyIdleDevicesCommand extends AbstractSinglePassCrawlAccountsCom
|
||||
static final Duration MAX_SHORT_IDLE_DURATION = Duration.ofDays(30);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(30);
|
||||
static final Duration MIN_LONG_IDLE_DURATION = Duration.ofDays(60);
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(45);
|
||||
static final Duration MAX_LONG_IDLE_DURATION = Duration.ofDays(75);
|
||||
|
||||
private static final Counter DEVICE_INSPECTED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(NotifyIdleDevicesCommand.class, "deviceInspected"));
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
syntax = "proto3";
|
||||
|
||||
package org.signal.chat.presence;
|
||||
|
||||
option java_package = "org.whispersystems.textsecuregcm.push";
|
||||
option java_multiple_files = true;
|
||||
|
||||
message ClientEvent {
|
||||
oneof event {
|
||||
NewMessageAvailableEvent new_message_available = 1;
|
||||
ClientConnectedEvent client_connected = 2;
|
||||
DisconnectRequested disconnect_requested = 3;
|
||||
MessagesPersistedEvent messages_persisted = 4;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available for the client to retrieve.
|
||||
*/
|
||||
message NewMessageAvailableEvent {
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates that a client has connected to the presence system.
|
||||
*/
|
||||
message ClientConnectedEvent {
|
||||
bytes server_id = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates that the server has requested that the client disconnect due to
|
||||
* (for example) account lifecycle events.
|
||||
*/
|
||||
message DisconnectRequested {
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term
|
||||
* storage to long-term storage.
|
||||
*/
|
||||
message MessagesPersistedEvent {
|
||||
}
|
||||
@@ -34,7 +34,7 @@ service KeyTransparencyQueryService {
|
||||
*/
|
||||
rpc Search(SearchRequest) returns (SearchResponse) {}
|
||||
/**
|
||||
* An endpoint that allows users to monitor a set of identifiers by returning proof that the log continues to be
|
||||
* An endpoint that allows users to monitor a group of identifiers by returning proof that the log continues to be
|
||||
* constructed correctly in later entries for those identifiers.
|
||||
*/
|
||||
rpc Monitor(MonitorRequest) returns (MonitorResponse) {}
|
||||
@@ -141,7 +141,7 @@ message DistinguishedRequest {
|
||||
|
||||
/**
|
||||
* DistinguishedResponse contains the tree head and search proof for the most
|
||||
* recent `distinguished` key in the log.
|
||||
* recent `distinguished` key in the log.
|
||||
*/
|
||||
message DistinguishedResponse {
|
||||
/**
|
||||
@@ -182,14 +182,14 @@ message FullTreeHead {
|
||||
* A representation of the log tree's current state signed by the key transparency service.
|
||||
*/
|
||||
TreeHead tree_head = 1;
|
||||
/**
|
||||
* A consistency proof between the current tree size and the requested distinguished tree size.
|
||||
*/
|
||||
repeated bytes distinguished = 2;
|
||||
/**
|
||||
* A consistency proof between the current tree size and the requested tree size.
|
||||
*/
|
||||
repeated bytes consistency = 3;
|
||||
repeated bytes last = 2;
|
||||
/**
|
||||
* A consistency proof between the current tree size and the requested distinguished tree size.
|
||||
*/
|
||||
repeated bytes distinguished = 3;
|
||||
/**
|
||||
* A tree head signed by a third-party auditor.
|
||||
*/
|
||||
@@ -286,46 +286,34 @@ message PrefixSearchResult {
|
||||
uint32 counter = 2;
|
||||
}
|
||||
|
||||
message MonitorKey {
|
||||
/**
|
||||
* The key to search for in the log tree.
|
||||
*/
|
||||
bytes search_key = 1;
|
||||
/**
|
||||
* A list of log tree positions maintained by a client for the identifier being monitored.
|
||||
* Each position is in the direct path to a key version and corresponds to a tree head
|
||||
* that has been verified to contain that version or greater.
|
||||
* The key transparency server uses this list to compute which log entries to return
|
||||
* in the corresponding MonitorProof.
|
||||
*/
|
||||
message MonitorRequest {
|
||||
AciMonitorRequest aci = 1;
|
||||
optional UsernameHashMonitorRequest username_hash = 2;
|
||||
optional E164MonitorRequest e164 = 3;
|
||||
ConsistencyParameters consistency = 4;
|
||||
}
|
||||
|
||||
message AciMonitorRequest {
|
||||
bytes aci = 1;
|
||||
repeated uint64 entries = 2;
|
||||
/**
|
||||
* The commitment index for the identifier. This is derived from vrf_proof in
|
||||
* the SearchResponse.
|
||||
*/
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message UsernameHashMonitorRequest {
|
||||
bytes username_hash = 1;
|
||||
repeated uint64 entries = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message MonitorRequest {
|
||||
/**
|
||||
* TODO: Remove this protobuf field in the KT server
|
||||
*/
|
||||
repeated MonitorKey owned_keys = 1;
|
||||
/**
|
||||
* The list of identifiers that the client would like to monitor.
|
||||
* All identifiers *must* belong to the same user.
|
||||
*/
|
||||
repeated MonitorKey contact_keys = 2;
|
||||
/**
|
||||
* The tree head size(s) to prove consistency against.
|
||||
*/
|
||||
ConsistencyParameters consistency = 3;
|
||||
message E164MonitorRequest {
|
||||
string e164 = 1;
|
||||
repeated uint64 entries = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message MonitorProof {
|
||||
/**
|
||||
* Generated based on the monitored entries provided in MonitorKey.entries. Each ProofStep
|
||||
* Generated based on the monitored entry provided in MonitorRequest.entries. Each ProofStep
|
||||
* corresponds to a log tree entry that exists in the search path to each monitored entry
|
||||
* and that came *after* that monitored entry. It proves that the log tree has been constructed
|
||||
* correctly at that later entry. This list also includes any remaining entries
|
||||
@@ -342,17 +330,22 @@ message MonitorResponse {
|
||||
*/
|
||||
FullTreeHead tree_head = 1;
|
||||
/**
|
||||
* TODO: Remove this protobuf field in the KT server
|
||||
* A proof that the MonitorRequest's ACI continues to be constructed correctly in later entries of the log tree.
|
||||
*/
|
||||
repeated MonitorProof owned_proofs = 2;
|
||||
MonitorProof aci = 2;
|
||||
/**
|
||||
* A list of proofs, one for each identifier in MonitorRequest.contact_keys, each proving that the given identifier
|
||||
* continues to be constructed correctly in later entries of the log tree.
|
||||
* A proof that the username hash continues to be constructed correctly in later entries of the log tree.
|
||||
* Will be absent if the request did not include a UsernameHashMonitorRequest.
|
||||
*/
|
||||
repeated MonitorProof contact_proofs = 3;
|
||||
optional MonitorProof username_hash = 3;
|
||||
/**
|
||||
* A proof that the e164 continues to be constructed correctly in later entries of the log tree.
|
||||
* Will be absent if the request did not include a E164MonitorRequest.
|
||||
*/
|
||||
optional MonitorProof e164 = 4;
|
||||
/**
|
||||
* A batch inclusion proof that the log entries involved in the binary search for each of the entries
|
||||
* being monitored in MonitorKey.entries are included in the current log tree.
|
||||
* being monitored in the request are included in the current log tree.
|
||||
*/
|
||||
repeated bytes inclusion = 4;
|
||||
repeated bytes inclusion = 5;
|
||||
}
|
||||
@@ -4,9 +4,11 @@
|
||||
local queueKey = KEYS[1] -- sorted set of Envelopes for a device, by queue-local ID
|
||||
local queueMetadataKey = KEYS[2] -- hash of message GUID to queue-local IDs
|
||||
local queueTotalIndexKey = KEYS[3] -- sorted set of all queues in the shard, by timestamp of oldest message
|
||||
local eventChannelKey = KEYS[4] -- pub/sub channel for message availability events
|
||||
local message = ARGV[1] -- [bytes] the Envelope to insert
|
||||
local currentTime = ARGV[2] -- [number] the message timestamp, to sort the queue in the queueTotalIndex
|
||||
local guid = ARGV[3] -- [string] the message GUID
|
||||
local eventPayload = ARGV[4] -- [bytes] a protobuf payload for a "message available" pub/sub event
|
||||
|
||||
if redis.call("HEXISTS", queueMetadataKey, guid) == 1 then
|
||||
return tonumber(redis.call("HGET", queueMetadataKey, guid))
|
||||
@@ -21,4 +23,5 @@ redis.call("EXPIRE", queueKey, 3974400) -- 46 days
|
||||
redis.call("EXPIRE", queueMetadataKey, 3974400) -- 46 days
|
||||
|
||||
redis.call("ZADD", queueTotalIndexKey, "NX", currentTime, queueKey)
|
||||
return messageId
|
||||
|
||||
return redis.call("SPUBLISH", eventChannelKey, eventPayload) > 0
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Unlocks a message queue when a persist-to-DynamoDB run has finished and publishes an event notifying listeners that
|
||||
-- messages have been persisted
|
||||
|
||||
local persistInProgressKey = KEYS[1] -- simple string key whose presence indicates a lock
|
||||
local eventChannelKey = KEYS[2] -- the channel on which to publish the "messages persisted" event
|
||||
local eventPayload = ARGV[1] -- [bytes] a protobuf payload for a "message persisted" pub/sub event
|
||||
|
||||
redis.call("DEL", persistInProgressKey)
|
||||
redis.call("SPUBLISH", eventChannelKey, eventPayload)
|
||||
@@ -1,13 +0,0 @@
|
||||
#
|
||||
# Copyright 2021 Signal Messenger, LLC
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
#
|
||||
# These are deprecated, will be unused by clients in a future update, and can be removed in ~April 2023.
|
||||
# First subscription level
|
||||
R_LOW = Sustainer 1
|
||||
|
||||
# Second subscription level
|
||||
R_MED = Sustainer 2
|
||||
|
||||
# Third subscription level
|
||||
R_HIGH = Sustainer 3
|
||||
Whitespace-only changes.
+11
-14
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -60,7 +59,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -96,19 +95,19 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
.build();
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
|
||||
private LinkedDeviceRefreshRequirementProvider provider;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
|
||||
provider = new LinkedDeviceRefreshRequirementProvider(accountsManager);
|
||||
|
||||
final WebsocketRefreshRequestEventListener listener =
|
||||
new WebsocketRefreshRequestEventListener(clientPresenceManager, provider);
|
||||
new WebsocketRefreshRequestEventListener(pubSubClientEventManager, provider);
|
||||
|
||||
when(applicationEventListener.onRequest(any())).thenReturn(listener);
|
||||
|
||||
@@ -119,9 +118,6 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
.forEach(deviceId -> account.addDevice(DevicesHelper.createDevice((byte) deviceId)));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
|
||||
account.getDevices()
|
||||
.forEach(device -> when(clientPresenceManager.isPresent(uuid, device.getId())).thenReturn(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,9 +139,9 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
|
||||
assertEquals(initialDeviceCount + addedDeviceNames.size(), account.getDevices().size());
|
||||
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 1);
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 2);
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 3);
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 1));
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 2));
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 3));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -173,10 +169,11 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
initialDeviceIds.forEach(deviceId ->
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), deviceId));
|
||||
initialDeviceIds.forEach(deviceId -> {
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(deviceId));
|
||||
});
|
||||
|
||||
verifyNoMoreInteractions(clientPresenceManager);
|
||||
verifyNoMoreInteractions(pubSubClientEventManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+13
-14
@@ -28,6 +28,7 @@ import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.servlet.DispatcherType;
|
||||
@@ -46,7 +47,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -73,7 +74,7 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
private static final AccountAuthenticator AUTHENTICATOR = mock(AccountAuthenticator.class);
|
||||
private static final AccountsManager ACCOUNTS_MANAGER = mock(AccountsManager.class);
|
||||
private static final ClientPresenceManager CLIENT_PRESENCE = mock(ClientPresenceManager.class);
|
||||
private static final PubSubClientEventManager PUBSUB_CLIENT_PRESENCE = mock(PubSubClientEventManager.class);
|
||||
|
||||
private WebSocketClient client;
|
||||
private final Account account1 = new Account();
|
||||
@@ -83,7 +84,7 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
reset(AUTHENTICATOR, CLIENT_PRESENCE, ACCOUNTS_MANAGER);
|
||||
reset(AUTHENTICATOR, ACCOUNTS_MANAGER, PUBSUB_CLIENT_PRESENCE);
|
||||
client = new WebSocketClient();
|
||||
client.start();
|
||||
|
||||
@@ -122,9 +123,9 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
|
||||
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE));
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, PUBSUB_CLIENT_PRESENCE));
|
||||
environment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE));
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, PUBSUB_CLIENT_PRESENCE));
|
||||
webSocketEnvironment.setConnectListener(webSocketSessionContext -> {
|
||||
});
|
||||
|
||||
@@ -198,7 +199,7 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Event listeners can fire after responses are sent
|
||||
verify(ACCOUNTS_MANAGER, timeout(5000).times(1)).getByAccountIdentifier(eq(account1.getUuid()));
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
|
||||
verifyNoMoreInteractions(ACCOUNTS_MANAGER);
|
||||
}
|
||||
|
||||
@@ -212,9 +213,9 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Make sure we disconnect the account if the account has changed numbers. Event listeners can fire after responses
|
||||
// are sent, so use a timeout.
|
||||
verify(CLIENT_PRESENCE, timeout(5000))
|
||||
.disconnectPresence(eq(account1.getUuid()), eq(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
verify(PUBSUB_CLIENT_PRESENCE, timeout(5000))
|
||||
.requestDisconnection(account1.getUuid(), List.of(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -228,9 +229,9 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Make sure we disconnect the account if the account has changed numbers. Event listeners can fire after responses
|
||||
// are sent, so use a timeout.
|
||||
verify(CLIENT_PRESENCE, timeout(5000))
|
||||
.disconnectPresence(eq(account1.getUuid()), eq(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
verify(PUBSUB_CLIENT_PRESENCE, timeout(5000))
|
||||
.requestDisconnection(account1.getUuid(), List.of(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -244,7 +245,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Shouldn't even read the account if the method has not been annotated
|
||||
verifyNoMoreInteractions(ACCOUNTS_MANAGER);
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -258,7 +258,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Shouldn't even read the account if the method has not been annotated
|
||||
verifyNoMoreInteractions(ACCOUNTS_MANAGER);
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+6
-6
@@ -33,8 +33,8 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -46,7 +46,7 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
class RegistrationLockVerificationManagerTest {
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
private final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialsGenerator = mock(
|
||||
ExternalServiceCredentialsGenerator.class);
|
||||
private final ExternalServiceCredentialsGenerator svr3CredentialsGenerator = mock(
|
||||
@@ -56,7 +56,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
private static PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, clientPresenceManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
accountsManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
|
||||
private final RateLimiter pinLimiter = mock(RateLimiter.class);
|
||||
@@ -107,7 +107,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
} else {
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
}
|
||||
verify(clientPresenceManager).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
try {
|
||||
verify(pushNotificationManager).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
|
||||
} catch (NotPushRegisteredException npre) {}
|
||||
@@ -130,7 +130,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
verify(pushNotificationManager, never()).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
|
||||
} catch (NotPushRegisteredException npre) {}
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
verify(clientPresenceManager, never()).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -168,7 +168,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
|
||||
verify(account, never()).lockAuthTokenHash();
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
verify(clientPresenceManager, never()).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
|
||||
}
|
||||
|
||||
static Stream<Arguments> testSuccess() {
|
||||
|
||||
-3
@@ -22,9 +22,6 @@ public class LocalFaultTolerantRedisClusterFactory implements FaultTolerantRedis
|
||||
try {
|
||||
redisClusterExtension.beforeAll(null);
|
||||
redisClusterExtension.beforeEach(null);
|
||||
|
||||
redisClusterExtension.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz"));
|
||||
} catch (final Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
+4
-5
@@ -79,7 +79,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientPublicKeysManager;
|
||||
@@ -110,7 +110,7 @@ class DeviceControllerTest {
|
||||
private static final Account account = mock(Account.class);
|
||||
private static final Account maxedAccount = mock(Account.class);
|
||||
private static final Device primaryDevice = mock(Device.class);
|
||||
private static final ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
private static final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
private static final Map<String, Integer> deviceConfiguration = new HashMap<>();
|
||||
private static final TestClock testClock = TestClock.now();
|
||||
|
||||
@@ -131,7 +131,7 @@ class DeviceControllerTest {
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager))
|
||||
.addProvider(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager))
|
||||
.addProvider(new DeviceLimitExceededExceptionMapper())
|
||||
.addResource(deviceController)
|
||||
.build();
|
||||
@@ -171,8 +171,7 @@ class DeviceControllerTest {
|
||||
asyncCommands,
|
||||
account,
|
||||
maxedAccount,
|
||||
primaryDevice,
|
||||
clientPresenceManager
|
||||
primaryDevice
|
||||
);
|
||||
|
||||
testClock.unpin();
|
||||
|
||||
+6
-20
@@ -18,8 +18,6 @@ import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.controllers.KeyTransparencyController.ACI_PREFIX;
|
||||
import static org.whispersystems.textsecuregcm.controllers.KeyTransparencyController.getFullSearchKeyByteString;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
@@ -124,18 +122,6 @@ public class KeyTransparencyControllerTest {
|
||||
monitorRatelimiter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFullSearchKey() {
|
||||
final byte[] charBytes = new byte[]{ACI_PREFIX};
|
||||
final byte[] aci = ACI.toCompactByteArray();
|
||||
|
||||
final byte[] expectedFullSearchKey = new byte[aci.length + 1];
|
||||
System.arraycopy(charBytes, 0, expectedFullSearchKey, 0, charBytes.length);
|
||||
System.arraycopy(aci, 0, expectedFullSearchKey, charBytes.length, aci.length);
|
||||
|
||||
assertArrayEquals(expectedFullSearchKey, getFullSearchKeyByteString(ACI_PREFIX, aci).toByteArray());
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@@ -309,7 +295,7 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
@Test
|
||||
void monitorSuccess() {
|
||||
when(keyTransparencyServiceClient.monitor(any(), anyLong(), anyLong(), any()))
|
||||
when(keyTransparencyServiceClient.monitor(any(), any(), any(), anyLong(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(TestRandomUtil.nextBytes(16)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -325,10 +311,10 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
final KeyTransparencyMonitorResponse keyTransparencyMonitorResponse = response.readEntity(
|
||||
KeyTransparencyMonitorResponse.class);
|
||||
assertNotNull(keyTransparencyMonitorResponse.monitorResponse());
|
||||
assertNotNull(keyTransparencyMonitorResponse.serializedResponse());
|
||||
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(
|
||||
any(), eq(3L), eq(4L), eq(KeyTransparencyController.KEY_TRANSPARENCY_RPC_TIMEOUT));
|
||||
any(), any(), any(), eq(3L), eq(4L), eq(KeyTransparencyController.KEY_TRANSPARENCY_RPC_TIMEOUT));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,7 +337,7 @@ public class KeyTransparencyControllerTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void monitorGrpcErrors(final Status grpcStatus, final int httpStatus) {
|
||||
when(keyTransparencyServiceClient.monitor(any(), anyLong(), anyLong(), any()))
|
||||
when(keyTransparencyServiceClient.monitor(any(), any(), any(), anyLong(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new CompletionException(new StatusRuntimeException(grpcStatus))));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -363,7 +349,7 @@ public class KeyTransparencyControllerTest {
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))))) {
|
||||
assertEquals(httpStatus, response.getStatus());
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(any(), anyLong(), anyLong(), any());
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(any(), any(), any(), anyLong(), anyLong(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,7 +529,7 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
final KeyTransparencyDistinguishedKeyResponse distinguishedKeyResponse = response.readEntity(
|
||||
KeyTransparencyDistinguishedKeyResponse.class);
|
||||
assertNotNull(distinguishedKeyResponse.distinguishedKeyResponse());
|
||||
assertNotNull(distinguishedKeyResponse.serializedResponse());
|
||||
|
||||
verify(keyTransparencyServiceClient, times(1))
|
||||
.getDistinguishedKey(eq(Optional.ofNullable(lastTreeHeadSize)),
|
||||
|
||||
+2
-1
@@ -252,7 +252,8 @@ class MessageControllerTest {
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getInboundMessageByteLimitConfiguration()).thenReturn(inboundMessageByteLimitConfiguration);
|
||||
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(new DynamicMessagesConfiguration(true, true));
|
||||
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(
|
||||
new DynamicMessagesConfiguration(true, true, true));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
|
||||
+52
-68
@@ -67,7 +67,6 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.badges.LevelTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.SubscriptionController.GetBankMandateResponse;
|
||||
@@ -87,14 +86,14 @@ import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager.PayPalOneTimePaymentApprovalDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.MockUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -123,15 +122,12 @@ class SubscriptionControllerTest {
|
||||
private static final IssuedReceiptsManager ISSUED_RECEIPTS_MANAGER = mock(IssuedReceiptsManager.class);
|
||||
private static final OneTimeDonationsManager ONE_TIME_DONATIONS_MANAGER = mock(OneTimeDonationsManager.class);
|
||||
private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class);
|
||||
private static final LevelTranslator LEVEL_TRANSLATOR = mock(LevelTranslator.class);
|
||||
private static final BankMandateTranslator BANK_MANDATE_TRANSLATOR = mock(BankMandateTranslator.class);
|
||||
private final static SubscriptionController SUBSCRIPTION_CONTROLLER = new SubscriptionController(CLOCK,
|
||||
SUBSCRIPTION_CONFIG, ONETIME_CONFIG,
|
||||
new SubscriptionManager(SUBSCRIPTIONS,
|
||||
List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
|
||||
ZK_OPS, ISSUED_RECEIPTS_MANAGER),
|
||||
STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER,
|
||||
BADGE_TRANSLATOR, LEVEL_TRANSLATOR, BANK_MANDATE_TRANSLATOR);
|
||||
new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER),
|
||||
ZK_OPS, ISSUED_RECEIPTS_MANAGER), STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER,
|
||||
BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR);
|
||||
private static final OneTimeDonationController ONE_TIME_CONTROLLER = new OneTimeDonationController(CLOCK,
|
||||
ONETIME_CONFIG, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, ONE_TIME_DONATIONS_MANAGER);
|
||||
private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder()
|
||||
@@ -148,17 +144,14 @@ class SubscriptionControllerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
reset(CLOCK, SUBSCRIPTIONS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER,
|
||||
BADGE_TRANSLATOR, LEVEL_TRANSLATOR);
|
||||
reset(CLOCK, SUBSCRIPTIONS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, BADGE_TRANSLATOR);
|
||||
|
||||
when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE);
|
||||
when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE);
|
||||
|
||||
List.of(STRIPE_MANAGER, BRAINTREE_MANAGER)
|
||||
.forEach(manager -> {
|
||||
when(manager.supportsPaymentMethod(any()))
|
||||
.thenCallRealMethod();
|
||||
});
|
||||
.forEach(manager -> when(manager.supportsPaymentMethod(any()))
|
||||
.thenCallRealMethod());
|
||||
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
|
||||
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
|
||||
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.SEPA_DEBIT))
|
||||
@@ -512,13 +505,12 @@ class SubscriptionControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(400);
|
||||
|
||||
assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class))
|
||||
.satisfies(errorResponse -> {
|
||||
assertThat(errorResponse.errors())
|
||||
.anySatisfy(error -> {
|
||||
assertThat(error.type()).isEqualTo(
|
||||
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION);
|
||||
});
|
||||
});
|
||||
.satisfies(errorResponse ->
|
||||
assertThat(errorResponse.errors())
|
||||
.anySatisfy(error ->
|
||||
assertThat(error.type())
|
||||
.isEqualTo(
|
||||
SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1087,9 +1079,6 @@ class SubscriptionControllerTest {
|
||||
when(BADGE_TRANSLATOR.translate(any(), eq("GIFT"))).thenReturn(new Badge("GIFT", "gift1", "gift1", "gift1",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))));
|
||||
when(LEVEL_TRANSLATOR.translate(any(), eq("B1"))).thenReturn("Z1");
|
||||
when(LEVEL_TRANSLATOR.translate(any(), eq("B2"))).thenReturn("Z2");
|
||||
when(LEVEL_TRANSLATOR.translate(any(), eq("B3"))).thenReturn("Z3");
|
||||
|
||||
GetSubscriptionConfigurationResponse response = RESOURCE_EXTENSION.target("/v1/subscription/configuration")
|
||||
.request()
|
||||
@@ -1159,50 +1148,48 @@ class SubscriptionControllerTest {
|
||||
});
|
||||
|
||||
assertThat(response.levels()).containsKeys("1", "5", "15", "35", "100").satisfies(levelsMap -> {
|
||||
assertThat(levelsMap).extractingByKey("1").satisfies(level -> {
|
||||
assertThat(level.name()).isEqualTo("boost1"); // level name is the same as badge name
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge).satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("BOOST");
|
||||
assertThat(badge.getName()).isEqualTo("boost1");
|
||||
});
|
||||
});
|
||||
assertThat(levelsMap).extractingByKey("1").satisfies(
|
||||
level -> assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge)
|
||||
.satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("BOOST");
|
||||
assertThat(badge.getName()).isEqualTo("boost1");
|
||||
}));
|
||||
|
||||
assertThat(levelsMap).extractingByKey("100").satisfies(level -> {
|
||||
assertThat(level.name()).isEqualTo("gift1"); // level name is the same as badge name
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge).satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("GIFT");
|
||||
assertThat(badge.getName()).isEqualTo("gift1");
|
||||
});
|
||||
});
|
||||
assertThat(levelsMap).extractingByKey("100").satisfies(
|
||||
level -> assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge)
|
||||
.satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("GIFT");
|
||||
assertThat(badge.getName()).isEqualTo("gift1");
|
||||
}));
|
||||
|
||||
assertThat(levelsMap).extractingByKey("5").satisfies(level -> {
|
||||
assertThat(level.name()).isEqualTo("Z1");
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge).satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("B1");
|
||||
assertThat(badge.getName()).isEqualTo("name1");
|
||||
});
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge)
|
||||
.satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("B1");
|
||||
assertThat(badge.getName()).isEqualTo("name1");
|
||||
});
|
||||
});
|
||||
|
||||
assertThat(levelsMap).extractingByKey("15").satisfies(level -> {
|
||||
assertThat(level.name()).isEqualTo("Z2");
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge).satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("B2");
|
||||
assertThat(badge.getName()).isEqualTo("name2");
|
||||
});
|
||||
});
|
||||
assertThat(levelsMap).extractingByKey("15").satisfies(level ->
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge)
|
||||
.satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("B2");
|
||||
assertThat(badge.getName()).isEqualTo("name2");
|
||||
}));
|
||||
|
||||
assertThat(levelsMap).extractingByKey("35").satisfies(level -> {
|
||||
assertThat(level.name()).isEqualTo("Z3");
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge).satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("B3");
|
||||
assertThat(badge.getName()).isEqualTo("name3");
|
||||
});
|
||||
assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge)
|
||||
.satisfies(badge -> {
|
||||
assertThat(badge.getId()).isEqualTo("B3");
|
||||
assertThat(badge.getName()).isEqualTo("name3");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
assertThat(response.backup().levels()).containsOnlyKeys("201").extractingByKey("201").satisfies(configuration -> {
|
||||
assertThat(configuration.storageAllowanceBytes()).isEqualTo(BackupManager.MAX_TOTAL_BACKUP_MEDIA_BYTES);
|
||||
assertThat(configuration.playProductId()).isEqualTo("testPlayProductId");
|
||||
assertThat(configuration.mediaTtlDays()).isEqualTo(40);
|
||||
});
|
||||
assertThat(response.backup().freeTierMediaDays()).isEqualTo(30);
|
||||
|
||||
@@ -1214,21 +1201,17 @@ class SubscriptionControllerTest {
|
||||
|
||||
assertThat(genericResponse.get("levels")).satisfies(levels -> {
|
||||
final Set<String> oneTimeLevels = Set.of("1", "100");
|
||||
oneTimeLevels.forEach(oneTimeLevel -> {
|
||||
assertThat((Map<String, Map<String, Map<String, Object>>>) levels).extractingByKey(oneTimeLevel)
|
||||
.satisfies(level -> {
|
||||
assertThat(level.get("badge")).containsKeys("duration");
|
||||
});
|
||||
});
|
||||
oneTimeLevels.forEach(
|
||||
oneTimeLevel -> assertThat((Map<String, Map<String, Map<String, Object>>>) levels)
|
||||
.extractingByKey(oneTimeLevel)
|
||||
.satisfies(level -> assertThat(level.get("badge")).containsKeys("duration")));
|
||||
|
||||
((Map<String, ?>) levels).keySet().stream()
|
||||
.filter(Predicate.not(oneTimeLevels::contains))
|
||||
.forEach(subscriptionLevel -> {
|
||||
assertThat((Map<String, Map<String, Map<String, Object>>>) levels).extractingByKey(subscriptionLevel)
|
||||
.satisfies(level -> {
|
||||
assertThat(level.get("badge")).doesNotContainKeys("duration");
|
||||
});
|
||||
});
|
||||
.forEach(subscriptionLevel ->
|
||||
assertThat((Map<String, Map<String, Map<String, Object>>>) levels)
|
||||
.extractingByKey(subscriptionLevel)
|
||||
.satisfies(level -> assertThat(level.get("badge")).doesNotContainKeys("duration")));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1262,6 +1245,7 @@ class SubscriptionControllerTest {
|
||||
backupLevels:
|
||||
201:
|
||||
playProductId: testPlayProductId
|
||||
mediaTtl: P40D
|
||||
prices:
|
||||
usd:
|
||||
amount: '5'
|
||||
|
||||
-413
@@ -1,413 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class ClientPresenceManagerTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
|
||||
private static final DisplacedPresenceListener NO_OP = connectedElsewhere -> {
|
||||
};
|
||||
|
||||
private boolean expectExceptionOnClientPresenceManagerStop = false;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().flushall();
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
clientPresenceManager = new ClientPresenceManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
presenceRenewalExecutorService,
|
||||
presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void tearDown() throws Exception {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||
|
||||
try {
|
||||
clientPresenceManager.stop();
|
||||
} catch (final Exception e) {
|
||||
if (!expectExceptionOnClientPresenceManagerStop) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsPresent() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
assertTrue(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsLocallyPresent() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
assertFalse(clientPresenceManager.isLocallyPresent(accountUuid, deviceId));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> connection.sync().flushall());
|
||||
|
||||
assertTrue(clientPresenceManager.isLocallyPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLocalDisplacement() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final AtomicInteger displacementCounter = new AtomicInteger(0);
|
||||
final DisplacedPresenceListener displacementListener = connectedElsewhere -> displacementCounter.incrementAndGet();
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, displacementListener);
|
||||
|
||||
assertEquals(0, displacementCounter.get());
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, displacementListener);
|
||||
|
||||
assertEquals(1, displacementCounter.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemoteDisplacement() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
|
||||
clientPresenceManager.start();
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, connectedElsewhere -> displaced.complete(null));
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(ClientPresenceManager.getPresenceKey(accountUuid, deviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemoteDisplacementAfterTopologyChange() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
|
||||
clientPresenceManager.start();
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, connectedElsewhere -> displaced.complete(null));
|
||||
|
||||
clientPresenceManager.getPubSubConnection()
|
||||
.usePubSubConnection(connection -> connection.getResources().eventBus()
|
||||
.publish(new ClusterTopologyChangedEvent(List.of(), List.of())));
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(ClientPresenceManager.getPresenceKey(accountUuid, deviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
assertFalse(clientPresenceManager.clearPresence(accountUuid, deviceId,
|
||||
ignored -> fail("this listener should never be called")));
|
||||
assertTrue(clientPresenceManager.clearPresence(accountUuid, deviceId, NO_OP));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(ClientPresenceManager.getPresenceKey(accountUuid, deviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
assertFalse(clientPresenceManager.clearPresence(accountUuid, deviceId, NO_OP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPruneMissingPeers() {
|
||||
final String presentPeerId = UUID.randomUUID().toString();
|
||||
final String missingPeerId = UUID.randomUUID().toString();
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().sadd(ClientPresenceManager.MANAGER_SET_KEY, presentPeerId);
|
||||
connection.sync().sadd(ClientPresenceManager.MANAGER_SET_KEY, missingPeerId);
|
||||
});
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
addClientPresence(presentPeerId);
|
||||
addClientPresence(missingPeerId);
|
||||
}
|
||||
|
||||
clientPresenceManager.getPubSubConnection().usePubSubConnection(
|
||||
connection -> connection.sync().upstream().commands()
|
||||
.subscribe(ClientPresenceManager.getManagerPresenceChannel(presentPeerId)));
|
||||
clientPresenceManager.pruneMissingPeers();
|
||||
|
||||
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
connection -> connection.sync().exists(ClientPresenceManager.getConnectedClientSetKey(presentPeerId))));
|
||||
assertTrue(REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
(Function<StatefulRedisClusterConnection<String, String>, Boolean>) connection -> connection.sync()
|
||||
.sismember(ClientPresenceManager.MANAGER_SET_KEY, presentPeerId)));
|
||||
|
||||
assertEquals(0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
connection -> connection.sync().exists(ClientPresenceManager.getConnectedClientSetKey(missingPeerId))));
|
||||
assertFalse(REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
(Function<StatefulRedisClusterConnection<String, String>, Boolean>) connection -> connection.sync()
|
||||
.sismember(ClientPresenceManager.MANAGER_SET_KEY, missingPeerId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInitialPresenceExpiration() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(ClientPresenceManager.getPresenceKey(accountUuid, deviceId)).intValue());
|
||||
|
||||
assertTrue(ttl > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRenewPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final String presenceKey = ClientPresenceManager.getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().set(presenceKey, clientPresenceManager.getManagerId()));
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(presenceKey).intValue());
|
||||
|
||||
assertEquals(-1, ttl);
|
||||
}
|
||||
|
||||
clientPresenceManager.renewPresence(accountUuid, deviceId);
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(presenceKey).intValue());
|
||||
|
||||
assertTrue(ttl > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExpiredPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
|
||||
assertTrue(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
// Hackily set this key to expire immediately
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().expire(ClientPresenceManager.getPresenceKey(accountUuid, deviceId), 0));
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
private void addClientPresence(final String managerId) {
|
||||
final String clientPresenceKey = ClientPresenceManager.getPresenceKey(UUID.randomUUID(), (byte) 7);
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().set(clientPresenceKey, managerId);
|
||||
connection.sync().sadd(ClientPresenceManager.getConnectedClientSetKey(managerId), clientPresenceKey);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearAllOnStop() {
|
||||
final int localAccounts = 10;
|
||||
final UUID[] localUuids = new UUID[localAccounts];
|
||||
final byte[] localDeviceIds = new byte[localAccounts];
|
||||
|
||||
for (int i = 0; i < localAccounts; i++) {
|
||||
localUuids[i] = UUID.randomUUID();
|
||||
localDeviceIds[i] = (byte) i;
|
||||
|
||||
clientPresenceManager.setPresent(localUuids[i], localDeviceIds[i], NO_OP);
|
||||
}
|
||||
|
||||
final UUID displacedAccountUuid = UUID.randomUUID();
|
||||
final byte displacedAccountDeviceId = 7;
|
||||
|
||||
clientPresenceManager.setPresent(displacedAccountUuid, displacedAccountDeviceId, NO_OP);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> connection.sync()
|
||||
.set(ClientPresenceManager.getPresenceKey(displacedAccountUuid, displacedAccountDeviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
clientPresenceManager.stop();
|
||||
|
||||
for (int i = 0; i < localAccounts; i++) {
|
||||
localUuids[i] = UUID.randomUUID();
|
||||
localDeviceIds[i] = (byte) i;
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(localUuids[i], localDeviceIds[i]));
|
||||
}
|
||||
|
||||
assertTrue(clientPresenceManager.isPresent(displacedAccountUuid, displacedAccountDeviceId));
|
||||
|
||||
expectExceptionOnClientPresenceManagerStop = true;
|
||||
}
|
||||
|
||||
@Nested
|
||||
class MultiServerTest {
|
||||
|
||||
private ClientPresenceManager server1;
|
||||
private ClientPresenceManager server2;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().flushall();
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
final ScheduledExecutorService scheduledExecutorService1 = mock(ScheduledExecutorService.class);
|
||||
final ExecutorService keyspaceNotificationExecutorService1 = Executors.newSingleThreadExecutor();
|
||||
server1 = new ClientPresenceManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
scheduledExecutorService1, keyspaceNotificationExecutorService1);
|
||||
|
||||
final ScheduledExecutorService scheduledExecutorService2 = mock(ScheduledExecutorService.class);
|
||||
final ExecutorService keyspaceNotificationExecutorService2 = Executors.newSingleThreadExecutor();
|
||||
server2 = new ClientPresenceManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
scheduledExecutorService2, keyspaceNotificationExecutorService2);
|
||||
|
||||
server1.start();
|
||||
server2.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
server2.stop();
|
||||
server1.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetPresentRemotely() {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
server1.setPresent(uuid1, deviceId, listener1);
|
||||
|
||||
server2.setPresent(uuid1, deviceId, connectedElsewhere -> {});
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDisconnectPresenceLocally() {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
server1.setPresent(uuid1, deviceId, listener1);
|
||||
|
||||
server1.disconnectPresence(uuid1, deviceId);
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDisconnectPresenceRemotely() {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
server1.setPresent(uuid1, deviceId, listener1);
|
||||
|
||||
server2.disconnectPresence(uuid1, deviceId);
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 100)
|
||||
void testConcurrentConnection() throws Exception {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
|
||||
final Thread server1Thread = new Thread(() -> server1.setPresent(uuid1, deviceId, listener1));
|
||||
final Thread server2Thread = new Thread(() -> server2.setPresent(uuid1, deviceId, listener1));
|
||||
|
||||
server1Thread.start();
|
||||
server2Thread.start();
|
||||
|
||||
displaced.join();
|
||||
server2Thread.join();
|
||||
server1Thread.join();
|
||||
|
||||
while (server1.isLocallyPresent(uuid1, deviceId) == server2.isLocallyPresent(uuid1, deviceId)) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+66
-103
@@ -7,158 +7,121 @@ package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
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.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
|
||||
class MessageSenderTest {
|
||||
|
||||
private Account account;
|
||||
private Device device;
|
||||
private MessageProtos.Envelope message;
|
||||
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private MessagesManager messagesManager;
|
||||
private PushNotificationManager pushNotificationManager;
|
||||
private MessageSender messageSender;
|
||||
|
||||
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = 1;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
message = generateRandomMessage();
|
||||
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
pushNotificationManager = mock(PushNotificationManager.class);
|
||||
messageSender = new MessageSender(clientPresenceManager, messagesManager, pushNotificationManager);
|
||||
|
||||
when(account.getUuid()).thenReturn(ACCOUNT_UUID);
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
messageSender = new MessageSender(messagesManager, pushNotificationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendOnlineMessageClientPresent() throws Exception {
|
||||
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(true);
|
||||
when(device.getGcmId()).thenReturn("gcm-id");
|
||||
@CartesianTest
|
||||
void sendMessage(@CartesianTest.Values(booleans = {true, false}) final boolean clientPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean onlineMessage,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean hasPushToken) throws NotPushRegisteredException {
|
||||
|
||||
messageSender.sendMessage(account, device, message, true);
|
||||
final boolean expectPushNotificationAttempt = !clientPresent && !onlineMessage;
|
||||
|
||||
ArgumentCaptor<MessageProtos.Envelope> envelopeArgumentCaptor = ArgumentCaptor.forClass(
|
||||
MessageProtos.Envelope.class);
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
verify(messagesManager).insert(any(), anyByte(), envelopeArgumentCaptor.capture());
|
||||
verify(messagesManager, never()).removeRecipientViewFromMrmData(anyByte(), any(MessageProtos.Envelope.class));
|
||||
final Account account = mock(Account.class);
|
||||
final Device device = mock(Device.class);
|
||||
final MessageProtos.Envelope message = generateRandomMessage();
|
||||
|
||||
assertTrue(envelopeArgumentCaptor.getValue().getEphemeral());
|
||||
when(account.getUuid()).thenReturn(accountIdentifier);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(device.getId()).thenReturn(deviceId);
|
||||
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
if (hasPushToken) {
|
||||
when(device.getApnId()).thenReturn("apns-token");
|
||||
} else {
|
||||
doThrow(NotPushRegisteredException.class)
|
||||
.when(pushNotificationManager).sendNewMessageNotification(any(), anyByte(), anyBoolean());
|
||||
}
|
||||
|
||||
when(messagesManager.insert(eq(accountIdentifier), eq(deviceId), any())).thenReturn(clientPresent);
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMessage(account, device, message, onlineMessage));
|
||||
|
||||
final MessageProtos.Envelope expectedMessage = onlineMessage
|
||||
? message.toBuilder().setEphemeral(true).build()
|
||||
: message.toBuilder().build();
|
||||
|
||||
verify(messagesManager).insert(accountIdentifier, deviceId, expectedMessage);
|
||||
|
||||
if (expectPushNotificationAttempt) {
|
||||
verify(pushNotificationManager).sendNewMessageNotification(account, deviceId, expectedMessage.getUrgent());
|
||||
} else {
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testSendOnlineMessageClientNotPresent(final boolean hasSharedMrmKey) throws Exception {
|
||||
@MethodSource
|
||||
void getDeliveryChannelName(final Device device, final String expectedChannelName) {
|
||||
assertEquals(expectedChannelName, MessageSender.getDeliveryChannelName(device));
|
||||
}
|
||||
|
||||
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(false);
|
||||
when(device.getGcmId()).thenReturn("gcm-id");
|
||||
private static List<Arguments> getDeliveryChannelName() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
if (hasSharedMrmKey) {
|
||||
messageSender.sendMessage(account, device,
|
||||
message.toBuilder().setSharedMrmKey(ByteString.copyFromUtf8("sharedMrmKey")).build(), true);
|
||||
} else {
|
||||
messageSender.sendMessage(account, device, message, true);
|
||||
{
|
||||
final Device apnDevice = mock(Device.class);
|
||||
when(apnDevice.getApnId()).thenReturn("apns-token");
|
||||
|
||||
arguments.add(Arguments.of(apnDevice, "apn"));
|
||||
}
|
||||
|
||||
verify(messagesManager, never()).insert(any(), anyByte(), any());
|
||||
verify(messagesManager).removeRecipientViewFromMrmData(anyByte(), any(MessageProtos.Envelope.class));
|
||||
{
|
||||
final Device fcmDevice = mock(Device.class);
|
||||
when(fcmDevice.getGcmId()).thenReturn("fcm-token");
|
||||
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
arguments.add(Arguments.of(fcmDevice, "gcm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendMessageClientPresent() throws Exception {
|
||||
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(true);
|
||||
when(device.getGcmId()).thenReturn("gcm-id");
|
||||
{
|
||||
final Device fetchesMessagesDevice = mock(Device.class);
|
||||
when(fetchesMessagesDevice.getFetchesMessages()).thenReturn(true);
|
||||
|
||||
messageSender.sendMessage(account, device, message, false);
|
||||
arguments.add(Arguments.of(fetchesMessagesDevice, "websocket"));
|
||||
}
|
||||
|
||||
final ArgumentCaptor<MessageProtos.Envelope> envelopeArgumentCaptor = ArgumentCaptor.forClass(
|
||||
MessageProtos.Envelope.class);
|
||||
arguments.add(Arguments.of(mock(Device.class), "none"));
|
||||
|
||||
verify(messagesManager).insert(eq(ACCOUNT_UUID), eq(DEVICE_ID), envelopeArgumentCaptor.capture());
|
||||
|
||||
assertFalse(envelopeArgumentCaptor.getValue().getEphemeral());
|
||||
assertEquals(message, envelopeArgumentCaptor.getValue());
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendMessageGcmClientNotPresent() throws Exception {
|
||||
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(false);
|
||||
when(device.getGcmId()).thenReturn("gcm-id");
|
||||
|
||||
messageSender.sendMessage(account, device, message, false);
|
||||
|
||||
verify(messagesManager).insert(ACCOUNT_UUID, DEVICE_ID, message);
|
||||
verify(pushNotificationManager).sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendMessageApnClientNotPresent() throws Exception {
|
||||
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(false);
|
||||
when(device.getApnId()).thenReturn("apn-id");
|
||||
|
||||
messageSender.sendMessage(account, device, message, false);
|
||||
|
||||
verify(messagesManager).insert(ACCOUNT_UUID, DEVICE_ID, message);
|
||||
verify(pushNotificationManager).sendNewMessageNotification(account, device.getId(), message.getUrgent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendMessageFetchClientNotPresent() throws Exception {
|
||||
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(false);
|
||||
when(device.getFetchesMessages()).thenReturn(true);
|
||||
|
||||
doThrow(NotPushRegisteredException.class)
|
||||
.when(pushNotificationManager).sendNewMessageNotification(account, DEVICE_ID, message.getUrgent());
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMessage(account, device, message, false));
|
||||
verify(messagesManager).insert(ACCOUNT_UUID, DEVICE_ID, message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendMessageNoChannel() {
|
||||
when(device.getGcmId()).thenReturn(null);
|
||||
when(device.getApnId()).thenReturn(null);
|
||||
when(device.getFetchesMessages()).thenReturn(false);
|
||||
|
||||
assertDoesNotThrow(() -> messageSender.sendMessage(account, device, message, false));
|
||||
verify(messagesManager).insert(ACCOUNT_UUID, DEVICE_ID, message);
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage() {
|
||||
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.api.async.RedisClusterPubSubAsyncCommands;
|
||||
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class PubSubClientEventManagerTest {
|
||||
|
||||
private PubSubClientEventManager localPresenceManager;
|
||||
private PubSubClientEventManager remotePresenceManager;
|
||||
|
||||
private static ExecutorService clientEventExecutor;
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private static class ClientEventAdapter implements ClientEventListener {
|
||||
|
||||
@Override
|
||||
public void handleNewMessageAvailable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessagesPersisted() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeAll() {
|
||||
clientEventExecutor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
localPresenceManager = new PubSubClientEventManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), clientEventExecutor);
|
||||
remotePresenceManager = new PubSubClientEventManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), clientEventExecutor);
|
||||
|
||||
localPresenceManager.start();
|
||||
remotePresenceManager.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
localPresenceManager.stop();
|
||||
remotePresenceManager.stop();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownAfterAll() {
|
||||
clientEventExecutor.shutdown();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void handleClientConnected(final boolean displaceRemotely) throws InterruptedException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
|
||||
|
||||
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
|
||||
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, deviceId, new ClientEventAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
synchronized (firstListenerDisplaced) {
|
||||
firstListenerDisplaced.set(true);
|
||||
firstListenerConnectedElsewhere.set(connectedElsewhere);
|
||||
|
||||
firstListenerDisplaced.notifyAll();
|
||||
}
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
assertFalse(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
final PubSubClientEventManager displacingManager =
|
||||
displaceRemotely ? remotePresenceManager : localPresenceManager;
|
||||
|
||||
displacingManager.handleClientConnected(accountIdentifier, deviceId, new ClientEventAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
secondListenerDisplaced.set(true);
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
synchronized (firstListenerDisplaced) {
|
||||
while (!firstListenerDisplaced.get()) {
|
||||
firstListenerDisplaced.wait();
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
assertTrue(firstListenerConnectedElsewhere.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isLocallyPresent() {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
assertFalse(localPresenceManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
assertFalse(remotePresenceManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, deviceId, new ClientEventAdapter())
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
assertTrue(localPresenceManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
assertFalse(remotePresenceManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
|
||||
localPresenceManager.handleClientDisconnected(accountIdentifier, deviceId)
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
assertFalse(localPresenceManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
assertFalse(remotePresenceManager.isLocallyPresent(accountIdentifier, deviceId));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void requestDisconnection(final boolean requestDisconnectionRemotely) throws InterruptedException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte firstDeviceId = Device.PRIMARY_ID;
|
||||
final byte secondDeviceId = firstDeviceId + 1;
|
||||
|
||||
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
|
||||
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
|
||||
|
||||
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, firstDeviceId, new ClientEventAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
synchronized (firstListenerDisplaced) {
|
||||
firstListenerDisplaced.set(true);
|
||||
firstListenerConnectedElsewhere.set(connectedElsewhere);
|
||||
|
||||
firstListenerDisplaced.notifyAll();
|
||||
}
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, secondDeviceId, new ClientEventAdapter() {
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
synchronized (secondListenerDisplaced) {
|
||||
secondListenerDisplaced.set(true);
|
||||
secondListenerDisplaced.notifyAll();
|
||||
}
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
assertFalse(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
final PubSubClientEventManager displacingManager =
|
||||
requestDisconnectionRemotely ? remotePresenceManager : localPresenceManager;
|
||||
|
||||
displacingManager.requestDisconnection(accountIdentifier, List.of(firstDeviceId)).toCompletableFuture().join();
|
||||
|
||||
synchronized (firstListenerDisplaced) {
|
||||
while (!firstListenerDisplaced.get()) {
|
||||
firstListenerDisplaced.wait();
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(firstListenerDisplaced.get());
|
||||
assertFalse(secondListenerDisplaced.get());
|
||||
|
||||
assertFalse(firstListenerConnectedElsewhere.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resubscribe() {
|
||||
@SuppressWarnings("unchecked") final RedisClusterPubSubCommands<byte[], byte[]> pubSubCommands =
|
||||
mock(RedisClusterPubSubCommands.class);
|
||||
|
||||
@SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands<byte[], byte[]> pubSubAsyncCommands =
|
||||
mock(RedisClusterPubSubAsyncCommands.class);
|
||||
|
||||
when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
|
||||
final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder()
|
||||
.binaryPubSubCommands(pubSubCommands)
|
||||
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
|
||||
.build();
|
||||
|
||||
final PubSubClientEventManager presenceManager = new PubSubClientEventManager(clusterClient, Runnable::run);
|
||||
|
||||
presenceManager.start();
|
||||
|
||||
final UUID firstAccountIdentifier = UUID.randomUUID();
|
||||
final byte firstDeviceId = Device.PRIMARY_ID;
|
||||
final int firstSlot = SlotHash.getSlot(PubSubClientEventManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
|
||||
|
||||
final UUID secondAccountIdentifier;
|
||||
final byte secondDeviceId = firstDeviceId + 1;
|
||||
|
||||
// Make sure that the two subscriptions wind up in different slots
|
||||
{
|
||||
UUID candidateIdentifier;
|
||||
|
||||
do {
|
||||
candidateIdentifier = UUID.randomUUID();
|
||||
} while (SlotHash.getSlot(PubSubClientEventManager.getClientEventChannel(candidateIdentifier, secondDeviceId)) == firstSlot);
|
||||
|
||||
secondAccountIdentifier = candidateIdentifier;
|
||||
}
|
||||
|
||||
presenceManager.handleClientConnected(firstAccountIdentifier, firstDeviceId, new ClientEventAdapter()).toCompletableFuture().join();
|
||||
presenceManager.handleClientConnected(secondAccountIdentifier, secondDeviceId, new ClientEventAdapter()).toCompletableFuture().join();
|
||||
|
||||
final int secondSlot = SlotHash.getSlot(PubSubClientEventManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
|
||||
|
||||
final String firstNodeId = UUID.randomUUID().toString();
|
||||
|
||||
final RedisClusterNode firstBeforeNode = mock(RedisClusterNode.class);
|
||||
when(firstBeforeNode.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstBeforeNode.getSlots()).thenReturn(IntStream.range(0, SlotHash.SLOT_COUNT).boxed().toList());
|
||||
|
||||
final RedisClusterNode firstAfterNode = mock(RedisClusterNode.class);
|
||||
when(firstAfterNode.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstAfterNode.getSlots()).thenReturn(IntStream.range(0, SlotHash.SLOT_COUNT)
|
||||
.filter(slot -> slot != secondSlot)
|
||||
.boxed()
|
||||
.toList());
|
||||
|
||||
final RedisClusterNode secondAfterNode = mock(RedisClusterNode.class);
|
||||
when(secondAfterNode.getNodeId()).thenReturn(UUID.randomUUID().toString());
|
||||
when(secondAfterNode.getSlots()).thenReturn(List.of(secondSlot));
|
||||
|
||||
presenceManager.resubscribe(new ClusterTopologyChangedEvent(
|
||||
List.of(firstBeforeNode),
|
||||
List.of(firstAfterNode, secondAfterNode)));
|
||||
|
||||
verify(pubSubCommands).ssubscribe(PubSubClientEventManager.getClientEventChannel(secondAccountIdentifier, secondDeviceId));
|
||||
verify(pubSubCommands, never()).ssubscribe(PubSubClientEventManager.getClientEventChannel(firstAccountIdentifier, firstDeviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void smessageWithoutListener() {
|
||||
@SuppressWarnings("unchecked") final RedisClusterPubSubAsyncCommands<byte[], byte[]> pubSubAsyncCommands =
|
||||
mock(RedisClusterPubSubAsyncCommands.class);
|
||||
|
||||
when(pubSubAsyncCommands.ssubscribe(any())).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
|
||||
final FaultTolerantRedisClusterClient clusterClient = RedisClusterHelper.builder()
|
||||
.binaryPubSubAsyncCommands(pubSubAsyncCommands)
|
||||
.build();
|
||||
|
||||
final PubSubClientEventManager eventManager = new PubSubClientEventManager(clusterClient, Runnable::run);
|
||||
|
||||
eventManager.start();
|
||||
|
||||
final UUID listenerAccountIdentifier = UUID.randomUUID();
|
||||
final byte listenerDeviceId = Device.PRIMARY_ID;
|
||||
|
||||
final UUID noListenerAccountIdentifier = UUID.randomUUID();
|
||||
final byte noListenerDeviceId = listenerDeviceId + 1;
|
||||
|
||||
eventManager.handleClientConnected(listenerAccountIdentifier, listenerDeviceId, new ClientEventAdapter())
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
eventManager.unsubscribeIfMissingListener(
|
||||
new PubSubClientEventManager.AccountAndDeviceIdentifier(listenerAccountIdentifier, listenerDeviceId));
|
||||
|
||||
eventManager.unsubscribeIfMissingListener(
|
||||
new PubSubClientEventManager.AccountAndDeviceIdentifier(noListenerAccountIdentifier, noListenerDeviceId));
|
||||
|
||||
verify(pubSubAsyncCommands, never())
|
||||
.sunsubscribe(PubSubClientEventManager.getClientEventChannel(listenerAccountIdentifier, listenerDeviceId));
|
||||
|
||||
verify(pubSubAsyncCommands)
|
||||
.sunsubscribe(PubSubClientEventManager.getClientEventChannel(noListenerAccountIdentifier, noListenerDeviceId));
|
||||
}
|
||||
}
|
||||
+107
-96
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.redis;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
@@ -19,17 +20,19 @@ import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.Partitions;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
|
||||
import io.lettuce.core.event.Event;
|
||||
import io.lettuce.core.event.EventBus;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -42,15 +45,31 @@ class FaultTolerantPubSubClusterConnectionTest {
|
||||
private RedisClusterPubSubCommands<String, String> pubSubCommands;
|
||||
private FaultTolerantPubSubClusterConnection<String, String> faultTolerantPubSubConnection;
|
||||
|
||||
private TestPublisher<Event> eventPublisher;
|
||||
|
||||
private Consumer<ClusterTopologyChangedEvent> resubscribe;
|
||||
|
||||
private AtomicInteger resubscribeCounter;
|
||||
private CountDownLatch resubscribeFailure;
|
||||
private CountDownLatch resubscribeSuccess;
|
||||
|
||||
private RedisClusterNode nodeInCluster;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
pubSubConnection = mock(StatefulRedisClusterPubSubConnection.class);
|
||||
|
||||
pubSubCommands = mock(RedisClusterPubSubCommands.class);
|
||||
nodeInCluster = mock(RedisClusterNode.class);
|
||||
|
||||
final ClientResources clientResources = mock(ClientResources.class);
|
||||
|
||||
final Partitions partitions = new Partitions();
|
||||
partitions.add(nodeInCluster);
|
||||
|
||||
when(pubSubConnection.sync()).thenReturn(pubSubCommands);
|
||||
when(pubSubConnection.getResources()).thenReturn(clientResources);
|
||||
when(pubSubConnection.getPartitions()).thenReturn(partitions);
|
||||
|
||||
final RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
retryConfiguration.setMaxAttempts(3);
|
||||
@@ -64,108 +83,100 @@ class FaultTolerantPubSubClusterConnectionTest {
|
||||
|
||||
faultTolerantPubSubConnection = new FaultTolerantPubSubClusterConnection<>("test", pubSubConnection,
|
||||
resubscribeRetry, Schedulers.newSingle("test"));
|
||||
|
||||
eventPublisher = TestPublisher.createCold();
|
||||
|
||||
final EventBus eventBus = mock(EventBus.class);
|
||||
when(clientResources.eventBus()).thenReturn(eventBus);
|
||||
|
||||
final Flux<Event> eventFlux = Flux.from(eventPublisher);
|
||||
when(eventBus.get()).thenReturn(eventFlux);
|
||||
|
||||
resubscribeCounter = new AtomicInteger();
|
||||
|
||||
resubscribe = event -> {
|
||||
try {
|
||||
resubscribeCounter.incrementAndGet();
|
||||
pubSubConnection.sync().nodes((ignored) -> true);
|
||||
resubscribeSuccess.countDown();
|
||||
} catch (final RuntimeException e) {
|
||||
resubscribeFailure.countDown();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
resubscribeSuccess = new CountDownLatch(1);
|
||||
resubscribeFailure = new CountDownLatch(1);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ClusterTopologyChangedEventTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void testSubscribeToClusterTopologyChangedEvents() throws Exception {
|
||||
|
||||
private TestPublisher<Event> eventPublisher;
|
||||
when(pubSubConnection.sync())
|
||||
.thenThrow(new RedisException("Cluster unavailable"));
|
||||
|
||||
private Runnable resubscribe;
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(List.of(nodeInCluster), List.of(nodeInCluster)));
|
||||
|
||||
private AtomicInteger resubscribeCounter;
|
||||
private CountDownLatch resubscribeFailure;
|
||||
private CountDownLatch resubscribeSuccess;
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(resubscribe);
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setup() {
|
||||
// ignore inherited stubbing
|
||||
reset(pubSubConnection);
|
||||
assertTrue(resubscribeFailure.await(1, TimeUnit.SECONDS));
|
||||
|
||||
eventPublisher = TestPublisher.createCold();
|
||||
// simulate cluster recovery - no more exceptions, run the retry
|
||||
reset(pubSubConnection);
|
||||
clearInvocations(pubSubCommands);
|
||||
when(pubSubConnection.sync())
|
||||
.thenReturn(pubSubCommands);
|
||||
|
||||
final ClientResources clientResources = mock(ClientResources.class);
|
||||
when(pubSubConnection.getResources())
|
||||
.thenReturn(clientResources);
|
||||
final EventBus eventBus = mock(EventBus.class);
|
||||
when(clientResources.eventBus())
|
||||
.thenReturn(eventBus);
|
||||
assertTrue(resubscribeSuccess.await(1, TimeUnit.SECONDS));
|
||||
|
||||
final Flux<Event> eventFlux = Flux.from(eventPublisher);
|
||||
when(eventBus.get()).thenReturn(eventFlux);
|
||||
|
||||
resubscribeCounter = new AtomicInteger();
|
||||
|
||||
resubscribe = () -> {
|
||||
try {
|
||||
resubscribeCounter.incrementAndGet();
|
||||
pubSubConnection.sync().nodes((ignored) -> true);
|
||||
resubscribeSuccess.countDown();
|
||||
} catch (final RuntimeException e) {
|
||||
resubscribeFailure.countDown();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
resubscribeSuccess = new CountDownLatch(1);
|
||||
resubscribeFailure = new CountDownLatch(1);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void testSubscribeToClusterTopologyChangedEvents() throws Exception {
|
||||
|
||||
when(pubSubConnection.sync())
|
||||
.thenThrow(new RedisException("Cluster unavailable"));
|
||||
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(resubscribe);
|
||||
|
||||
assertTrue(resubscribeFailure.await(1, TimeUnit.SECONDS));
|
||||
|
||||
// simulate cluster recovery - no more exceptions, run the retry
|
||||
reset(pubSubConnection);
|
||||
clearInvocations(pubSubCommands);
|
||||
when(pubSubConnection.sync())
|
||||
.thenReturn(pubSubCommands);
|
||||
|
||||
assertTrue(resubscribeSuccess.await(1, TimeUnit.SECONDS));
|
||||
|
||||
assertTrue(resubscribeCounter.get() >= 2, String.format("resubscribe called %d times", resubscribeCounter.get()));
|
||||
verify(pubSubCommands).nodes(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void testMultipleEventsWithPendingRetries() throws Exception {
|
||||
// more complicated scenario: multiple events while retries are pending
|
||||
|
||||
// cluster is down
|
||||
when(pubSubConnection.sync())
|
||||
.thenThrow(new RedisException("Cluster unavailable"));
|
||||
|
||||
// publish multiple topology changed events
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(Collections.emptyList(), Collections.emptyList()));
|
||||
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(resubscribe);
|
||||
|
||||
assertTrue(resubscribeFailure.await(1, TimeUnit.SECONDS));
|
||||
|
||||
// simulate cluster recovery - no more exceptions, run the retry
|
||||
reset(pubSubConnection);
|
||||
clearInvocations(pubSubCommands);
|
||||
when(pubSubConnection.sync())
|
||||
.thenReturn(pubSubCommands);
|
||||
|
||||
assertTrue(resubscribeSuccess.await(1, TimeUnit.SECONDS));
|
||||
|
||||
verify(pubSubCommands, atLeastOnce()).nodes(any());
|
||||
}
|
||||
assertTrue(resubscribeCounter.get() >= 2, String.format("resubscribe called %d times", resubscribeCounter.get()));
|
||||
verify(pubSubCommands).nodes(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilterClusterTopologyChangeEvents() throws InterruptedException {
|
||||
final CountDownLatch topologyEventLatch = new CountDownLatch(1);
|
||||
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(event -> topologyEventLatch.countDown());
|
||||
|
||||
final RedisClusterNode nodeFromDifferentCluster = mock(RedisClusterNode.class);
|
||||
|
||||
eventPublisher.next(new ClusterTopologyChangedEvent(List.of(nodeFromDifferentCluster), List.of(nodeFromDifferentCluster)));
|
||||
|
||||
assertFalse(topologyEventLatch.await(1, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void testMultipleEventsWithPendingRetries() throws Exception {
|
||||
// more complicated scenario: multiple events while retries are pending
|
||||
|
||||
// cluster is down
|
||||
when(pubSubConnection.sync())
|
||||
.thenThrow(new RedisException("Cluster unavailable"));
|
||||
|
||||
// publish multiple topology changed events
|
||||
final ClusterTopologyChangedEvent clusterTopologyChangedEvent =
|
||||
new ClusterTopologyChangedEvent(List.of(nodeInCluster), List.of(nodeInCluster));
|
||||
|
||||
eventPublisher.next(clusterTopologyChangedEvent);
|
||||
eventPublisher.next(clusterTopologyChangedEvent);
|
||||
eventPublisher.next(clusterTopologyChangedEvent);
|
||||
eventPublisher.next(clusterTopologyChangedEvent);
|
||||
|
||||
faultTolerantPubSubConnection.subscribeToClusterTopologyChangedEvents(resubscribe);
|
||||
|
||||
assertTrue(resubscribeFailure.await(1, TimeUnit.SECONDS));
|
||||
|
||||
// simulate cluster recovery - no more exceptions, run the retry
|
||||
reset(pubSubConnection);
|
||||
clearInvocations(pubSubCommands);
|
||||
when(pubSubConnection.sync())
|
||||
.thenReturn(pubSubCommands);
|
||||
|
||||
assertTrue(resubscribeSuccess.await(1, TimeUnit.SECONDS));
|
||||
|
||||
verify(pubSubCommands, atLeastOnce()).nodes(any());
|
||||
}
|
||||
}
|
||||
+57
-10
@@ -44,6 +44,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
@@ -103,8 +104,8 @@ class LettuceShardCircuitBreakerTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testHandlerWriteBreakerClosed(@Nullable final Throwable t) throws Exception {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testHandlerWriteBreakerClosed(final boolean completeExceptionally) throws Exception {
|
||||
final CircuitBreaker breaker = mock(CircuitBreaker.class);
|
||||
channelCircuitBreakerHandler.breaker = breaker;
|
||||
|
||||
@@ -116,9 +117,11 @@ class LettuceShardCircuitBreakerTest {
|
||||
|
||||
verify(breaker).acquirePermission();
|
||||
|
||||
if (t != null) {
|
||||
command.completeExceptionally(t);
|
||||
verify(breaker).onError(anyLong(), eq(TimeUnit.NANOSECONDS), eq(t));
|
||||
if (completeExceptionally) {
|
||||
final Throwable throwable = new IOException("timeout");
|
||||
|
||||
command.completeExceptionally(throwable);
|
||||
verify(breaker).onError(anyLong(), eq(TimeUnit.NANOSECONDS), eq(throwable));
|
||||
} else {
|
||||
command.complete("PONG");
|
||||
verify(breaker).onSuccess(anyLong(), eq(TimeUnit.NANOSECONDS));
|
||||
@@ -128,12 +131,36 @@ class LettuceShardCircuitBreakerTest {
|
||||
verify(channelHandlerContext).write(command, channelPromise);
|
||||
}
|
||||
|
||||
static List<Throwable> testHandlerWriteBreakerClosed() {
|
||||
final List<Throwable> errors = new ArrayList<>();
|
||||
errors.add(null);
|
||||
errors.add(new IOException("timeout"));
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testHandlerWriteBatchBreakerClosed(final boolean completeExceptionally) throws Exception {
|
||||
final CircuitBreaker breaker = mock(CircuitBreaker.class);
|
||||
channelCircuitBreakerHandler.breaker = breaker;
|
||||
|
||||
return errors;
|
||||
final AsyncCommand<String, String, String> firstCommand = new AsyncCommand<>(
|
||||
new Command<>(CommandType.PING, new StatusOutput<>(StringCodec.ASCII)));
|
||||
final AsyncCommand<String, String, String> secondCommand = new AsyncCommand<>(
|
||||
new Command<>(CommandType.PING, new StatusOutput<>(StringCodec.ASCII)));
|
||||
final ChannelHandlerContext channelHandlerContext = mock(ChannelHandlerContext.class);
|
||||
final ChannelPromise channelPromise = mock(ChannelPromise.class);
|
||||
channelCircuitBreakerHandler.write(channelHandlerContext, List.of(firstCommand, secondCommand), channelPromise);
|
||||
|
||||
verify(breaker).acquirePermission();
|
||||
|
||||
if (completeExceptionally) {
|
||||
final Throwable throwable = new IOException("timeout");
|
||||
|
||||
firstCommand.completeExceptionally(throwable);
|
||||
secondCommand.completeExceptionally(throwable);
|
||||
verify(breaker).onError(anyLong(), eq(TimeUnit.NANOSECONDS), eq(throwable));
|
||||
} else {
|
||||
firstCommand.complete("PONG");
|
||||
secondCommand.complete("PONG");
|
||||
verify(breaker).onSuccess(anyLong(), eq(TimeUnit.NANOSECONDS));
|
||||
}
|
||||
|
||||
// write should always be forwarded when the breaker is closed
|
||||
verify(channelHandlerContext).write(List.of(firstCommand, secondCommand), channelPromise);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,4 +182,24 @@ class LettuceShardCircuitBreakerTest {
|
||||
verifyNoInteractions(channelHandlerContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHandlerWriteBatchBreakerOpen() throws Exception {
|
||||
final CircuitBreaker breaker = mock(CircuitBreaker.class);
|
||||
channelCircuitBreakerHandler.breaker = breaker;
|
||||
|
||||
final CallNotPermittedException callNotPermittedException = mock(CallNotPermittedException.class);
|
||||
doThrow(callNotPermittedException).when(breaker).acquirePermission();
|
||||
|
||||
@SuppressWarnings("unchecked") final AsyncCommand<String, String, String> firstCommand = mock(AsyncCommand.class);
|
||||
@SuppressWarnings("unchecked") final AsyncCommand<String, String, String> secondCommand = mock(AsyncCommand.class);
|
||||
final ChannelHandlerContext channelHandlerContext = mock(ChannelHandlerContext.class);
|
||||
final ChannelPromise channelPromise = mock(ChannelPromise.class);
|
||||
channelCircuitBreakerHandler.write(channelHandlerContext, List.of(firstCommand, secondCommand), channelPromise);
|
||||
|
||||
verify(firstCommand).completeExceptionally(callNotPermittedException);
|
||||
verify(secondCommand).completeExceptionally(callNotPermittedException);
|
||||
verify(channelPromise).tryFailure(callNotPermittedException);
|
||||
|
||||
verifyNoInteractions(channelHandlerContext);
|
||||
}
|
||||
}
|
||||
+6
-9
@@ -43,7 +43,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -73,7 +73,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ExecutorService clientPresenceExecutor;
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private KeysManager keysManager;
|
||||
@@ -111,7 +110,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
clientPresenceExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
@@ -140,6 +138,10 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
when(pubSubClientEventManager.requestDisconnection(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -151,11 +153,10 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
mock(ClientPresenceManager.class),
|
||||
pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
CLOCK,
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
@@ -164,13 +165,9 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
accountLockExecutor.shutdown();
|
||||
clientPresenceExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
clientPresenceExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
|
||||
+5
-12
@@ -36,7 +36,7 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -66,9 +66,8 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private KeysManager keysManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ExecutorService clientPresenceExecutor;
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@@ -104,7 +103,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
clientPresenceExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
@@ -118,7 +116,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
new PhoneNumberIdentifiers(DYNAMO_DB_EXTENSION.getDynamoDbClient(), Tables.PNI.tableName());
|
||||
@@ -146,11 +144,10 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
clientPresenceManager,
|
||||
pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
@@ -160,13 +157,9 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
accountLockExecutor.shutdown();
|
||||
clientPresenceExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
clientPresenceExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -281,7 +274,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
|
||||
assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).map(Account::getNumber).orElseThrow());
|
||||
|
||||
verify(clientPresenceManager).disconnectPresence(existingAccountUuid, Device.PRIMARY_ID);
|
||||
verify(pubSubClientEventManager).requestDisconnection(existingAccountUuid);
|
||||
|
||||
assertEquals(Optional.of(existingAccountUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
|
||||
assertEquals(Optional.empty(), accountsManager.findRecentlyDeletedAccountIdentifier(secondNumber));
|
||||
|
||||
+2
-3
@@ -48,7 +48,7 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
@@ -133,11 +133,10 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
mock(Executor.class),
|
||||
mock(Executor.class),
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager
|
||||
|
||||
+2
-3
@@ -14,7 +14,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -62,11 +62,10 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
mock(ExecutorService.class),
|
||||
mock(ExecutorService.class),
|
||||
Clock.systemUTC(),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
mock(DynamicConfigurationManager.class));
|
||||
|
||||
+10
-17
@@ -79,7 +79,7 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -117,7 +117,7 @@ class AccountsManagerTest {
|
||||
private KeysManager keysManager;
|
||||
private MessagesManager messagesManager;
|
||||
private ProfilesManager profilesManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private ClientPublicKeysManager clientPublicKeysManager;
|
||||
|
||||
private Map<String, UUID> phoneNumberIdentifiersByE164;
|
||||
@@ -152,19 +152,10 @@ class AccountsManagerTest {
|
||||
keysManager = mock(KeysManager.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
profilesManager = mock(ProfilesManager.class);
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
clientPublicKeysManager = mock(ClientPublicKeysManager.class);
|
||||
dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
|
||||
final Executor clientPresenceExecutor = mock(Executor.class);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
final Runnable runnable = invocation.getArgument(0);
|
||||
runnable.run();
|
||||
|
||||
return null;
|
||||
}).when(clientPresenceExecutor).execute(any());
|
||||
|
||||
//noinspection unchecked
|
||||
asyncCommands = mock(RedisAsyncCommands.class);
|
||||
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture("OK"));
|
||||
@@ -247,6 +238,9 @@ class AccountsManagerTest {
|
||||
.stringAsyncCommands(asyncClusterCommands)
|
||||
.build();
|
||||
|
||||
when(pubSubClientEventManager.requestDisconnection(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -258,11 +252,10 @@ class AccountsManagerTest {
|
||||
profilesManager,
|
||||
storageClient,
|
||||
svr2Client,
|
||||
clientPresenceManager,
|
||||
pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
mock(Executor.class),
|
||||
clientPresenceExecutor,
|
||||
CLOCK,
|
||||
LINK_DEVICE_SECRET,
|
||||
dynamicConfigurationManager);
|
||||
@@ -798,7 +791,7 @@ class AccountsManagerTest {
|
||||
verify(keysManager, times(2)).deleteSingleUsePreKeys(account.getUuid(), linkedDevice.getId());
|
||||
verify(keysManager).buildWriteItemsForRemovedDevice(account.getUuid(), account.getPhoneNumberIdentifier(), linkedDevice.getId());
|
||||
verify(clientPublicKeysManager).buildTransactWriteItemForDeletion(account.getUuid(), linkedDevice.getId());
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), linkedDevice.getId());
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(linkedDevice.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -816,7 +809,7 @@ class AccountsManagerTest {
|
||||
assertDoesNotThrow(account::getPrimaryDevice);
|
||||
verify(messagesManager, never()).clear(any(), anyByte());
|
||||
verify(keysManager, never()).deleteSingleUsePreKeys(any(), anyByte());
|
||||
verify(clientPresenceManager, never()).disconnectPresence(any(), anyByte());
|
||||
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -885,7 +878,7 @@ class AccountsManagerTest {
|
||||
verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifiersByE164.get(e164));
|
||||
verify(messagesManager, times(2)).clear(existingUuid);
|
||||
verify(profilesManager, times(2)).deleteAll(existingUuid);
|
||||
verify(clientPresenceManager).disconnectAllPresencesForUuid(existingUuid);
|
||||
verify(pubSubClientEventManager).requestDisconnection(existingUuid);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-3
@@ -35,7 +35,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.mockito.Mockito;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -134,6 +134,9 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
when(messageManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(profileManager.deleteAll(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
when(pubSubClientEventManager.requestDisconnection(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -145,11 +148,10 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
profileManager,
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
pubSubClientEventManager,
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
Executors.newSingleThreadExecutor(),
|
||||
Executors.newSingleThreadExecutor(),
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
|
||||
+2
-9
@@ -33,7 +33,7 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -69,7 +69,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ExecutorService clientPresenceExecutor;
|
||||
|
||||
private KeysManager keysManager;
|
||||
private ClientPublicKeysManager clientPublicKeysManager;
|
||||
@@ -106,7 +105,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
clientPresenceExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
@@ -151,11 +149,10 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
CLOCK,
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
@@ -168,13 +165,9 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
accountsManager.stop();
|
||||
|
||||
accountLockExecutor.shutdown();
|
||||
clientPresenceExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
clientPresenceExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+22
-15
@@ -32,6 +32,8 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEventListener;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
@@ -48,11 +50,12 @@ class MessagePersisterIntegrationTest {
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ExecutorService notificationExecutorService;
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private ExecutorService messageDeletionExecutorService;
|
||||
private ExecutorService clientEventExecutorService;
|
||||
private MessagesCache messagesCache;
|
||||
private MessagesManager messagesManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private MessagePersister messagePersister;
|
||||
private Account account;
|
||||
|
||||
@@ -62,7 +65,6 @@ class MessagePersisterIntegrationTest {
|
||||
void setUp() throws Exception {
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().flushall();
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
@@ -77,11 +79,15 @@ class MessagePersisterIntegrationTest {
|
||||
messageDeletionExecutorService);
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
notificationExecutorService = Executors.newSingleThreadExecutor();
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), notificationExecutorService,
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
|
||||
clientEventExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
pubSubClientEventManager = new PubSubClientEventManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(), clientEventExecutorService);
|
||||
pubSubClientEventManager.start();
|
||||
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
@@ -95,19 +101,19 @@ class MessagePersisterIntegrationTest {
|
||||
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(DevicesHelper.createDevice(Device.PRIMARY_ID)));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
messagesCache.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
notificationExecutorService.shutdown();
|
||||
notificationExecutorService.awaitTermination(15, TimeUnit.SECONDS);
|
||||
|
||||
messageDeletionExecutorService.shutdown();
|
||||
messageDeletionExecutorService.awaitTermination(15, TimeUnit.SECONDS);
|
||||
|
||||
clientEventExecutorService.shutdown();
|
||||
clientEventExecutorService.awaitTermination(15, TimeUnit.SECONDS);
|
||||
|
||||
messageDeliveryScheduler.dispose();
|
||||
|
||||
pubSubClientEventManager.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -136,21 +142,22 @@ class MessagePersisterIntegrationTest {
|
||||
|
||||
final AtomicBoolean messagesPersisted = new AtomicBoolean(false);
|
||||
|
||||
messagesManager.addMessageAvailabilityListener(account.getUuid(), Device.PRIMARY_ID,
|
||||
new MessageAvailabilityListener() {
|
||||
pubSubClientEventManager.handleClientConnected(account.getUuid(), Device.PRIMARY_ID, new ClientEventListener() {
|
||||
@Override
|
||||
public boolean handleNewMessagesAvailable() {
|
||||
return true;
|
||||
public void handleNewMessageAvailable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMessagesPersisted() {
|
||||
public void handleMessagesPersisted() {
|
||||
synchronized (messagesPersisted) {
|
||||
messagesPersisted.set(true);
|
||||
messagesPersisted.notifyAll();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
}
|
||||
});
|
||||
|
||||
messagePersister.start();
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ class MessagePersisterTest {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService,
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
+69
-6
@@ -6,12 +6,22 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
class MessagesCacheInsertScriptTest {
|
||||
@@ -21,8 +31,8 @@ class MessagesCacheInsertScriptTest {
|
||||
|
||||
@Test
|
||||
void testCacheInsertScript() throws Exception {
|
||||
final MessagesCacheInsertScript insertScript = new MessagesCacheInsertScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
final MessagesCacheInsertScript insertScript =
|
||||
new MessagesCacheInsertScript(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
@@ -31,15 +41,68 @@ class MessagesCacheInsertScriptTest {
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
|
||||
assertEquals(1, insertScript.execute(destinationUuid, deviceId, envelope1));
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
|
||||
assertEquals(List.of(envelope1), getStoredMessages(destinationUuid, deviceId));
|
||||
|
||||
final MessageProtos.Envelope envelope2 = MessageProtos.Envelope.newBuilder()
|
||||
.setServerTimestamp(Instant.now().getEpochSecond())
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build();
|
||||
assertEquals(2, insertScript.execute(destinationUuid, deviceId, envelope2));
|
||||
|
||||
assertEquals(1, insertScript.execute(destinationUuid, deviceId, envelope1),
|
||||
"Repeated with same guid should have same message ID");
|
||||
insertScript.execute(destinationUuid, deviceId, envelope2);
|
||||
|
||||
assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId));
|
||||
|
||||
insertScript.execute(destinationUuid, deviceId, envelope1);
|
||||
|
||||
assertEquals(List.of(envelope1, envelope2), getStoredMessages(destinationUuid, deviceId),
|
||||
"Messages with same GUID should be deduplicated");
|
||||
}
|
||||
|
||||
private List<MessageProtos.Envelope> getStoredMessages(final UUID destinationUuid, final byte deviceId) throws IOException {
|
||||
final MessagesCacheGetItemsScript getItemsScript =
|
||||
new MessagesCacheGetItemsScript(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final List<byte[]> queueItems = getItemsScript.execute(destinationUuid, deviceId, 1024, 0)
|
||||
.blockOptional()
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
final List<MessageProtos.Envelope> messages = new ArrayList<>(queueItems.size() / 2);
|
||||
|
||||
for (int i = 0; i < queueItems.size(); i += 2) {
|
||||
try {
|
||||
messages.add(MessageProtos.Envelope.parseFrom(queueItems.get(i)));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnPresence() throws IOException {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final MessagesCacheInsertScript insertScript =
|
||||
new MessagesCacheInsertScript(REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
assertFalse(insertScript.execute(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
.setServerTimestamp(Instant.now().getEpochSecond())
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build()));
|
||||
|
||||
final FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubClusterConnection =
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().createBinaryPubSubConnection();
|
||||
|
||||
pubSubClusterConnection.usePubSubConnection(connection ->
|
||||
connection.sync().ssubscribe(PubSubClientEventManager.getClientEventChannel(destinationUuid, deviceId)));
|
||||
|
||||
assertTrue(insertScript.execute(destinationUuid, deviceId, MessageProtos.Envelope.newBuilder()
|
||||
.setServerTimestamp(Instant.now().getEpochSecond())
|
||||
.setServerGuid(UUID.randomUUID().toString())
|
||||
.build()));
|
||||
}
|
||||
}
|
||||
+111
-197
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
@@ -50,9 +51,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
@@ -64,6 +63,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -98,6 +98,7 @@ class MessagesCacheTest {
|
||||
private MessagesCache messagesCache;
|
||||
|
||||
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private DynamicConfiguration dynamicConfiguration;
|
||||
|
||||
private static final UUID DESTINATION_UUID = UUID.randomUUID();
|
||||
|
||||
@@ -105,30 +106,21 @@ class MessagesCacheTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().flushall();
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(new DynamicMessagesConfiguration(true, true));
|
||||
dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
when(dynamicConfiguration.getMessagesConfiguration()).thenReturn(
|
||||
new DynamicMessagesConfiguration(true, true, true));
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
resubscribeRetryExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService,
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
|
||||
messagesCache.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
messagesCache.stop();
|
||||
|
||||
sharedExecutorService.shutdown();
|
||||
sharedExecutorService.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
@@ -141,8 +133,8 @@ class MessagesCacheTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testInsert(final boolean sealedSender) {
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
assertTrue(messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid, sealedSender)) > 0);
|
||||
assertDoesNotThrow(() -> messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid, sealedSender)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -150,12 +142,13 @@ class MessagesCacheTest {
|
||||
final UUID duplicateGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope duplicateMessage = generateRandomMessage(duplicateGuid, false);
|
||||
|
||||
final long firstId = messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
duplicateMessage);
|
||||
final long secondId = messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
duplicateMessage);
|
||||
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage);
|
||||
messagesCache.insert(duplicateGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID, duplicateMessage);
|
||||
|
||||
assertEquals(firstId, secondId);
|
||||
assertEquals(1, messagesCache.getAllMessages(DESTINATION_UUID, DESTINATION_DEVICE_ID, 0)
|
||||
.count()
|
||||
.blockOptional()
|
||||
.orElse(0L));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -303,8 +296,7 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
final MessagesCache messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
sharedExecutorService, messageDeliveryScheduler, sharedExecutorService, cacheClock,
|
||||
dynamicConfigurationManager);
|
||||
messageDeliveryScheduler, sharedExecutorService, cacheClock, dynamicConfigurationManager);
|
||||
|
||||
final List<MessageProtos.Envelope> actualMessages = Flux.from(
|
||||
messagesCache.get(DESTINATION_UUID, DESTINATION_DEVICE_ID))
|
||||
@@ -394,13 +386,6 @@ class MessagesCacheTest {
|
||||
StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetQueueNameFromKeyspaceChannel() {
|
||||
assertEquals("1b363a31-a429-4fb6-8959-984a025e72ff::7",
|
||||
MessagesCache.getQueueNameFromKeyspaceChannel(
|
||||
"__keyspace@0__:user_queue::{1b363a31-a429-4fb6-8959-984a025e72ff::7}"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
public void testGetQueuesToPersist(final boolean sealedSender) {
|
||||
@@ -415,157 +400,17 @@ class MessagesCacheTest {
|
||||
final List<String> queues = messagesCache.getQueuesToPersist(slot, Instant.now().plusSeconds(60), 100);
|
||||
|
||||
assertEquals(1, queues.size());
|
||||
assertEquals(DESTINATION_UUID, MessagesCache.getAccountUuidFromQueueName(queues.get(0)));
|
||||
assertEquals(DESTINATION_DEVICE_ID, MessagesCache.getDeviceIdFromQueueName(queues.get(0)));
|
||||
assertEquals(DESTINATION_UUID, MessagesCache.getAccountUuidFromQueueName(queues.getFirst()));
|
||||
assertEquals(DESTINATION_DEVICE_ID, MessagesCache.getDeviceIdFromQueueName(queues.getFirst()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNotifyListenerNewMessage() {
|
||||
final AtomicBoolean notified = new AtomicBoolean(false);
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
@CartesianTest
|
||||
void testMultiRecipientMessage(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
|
||||
|
||||
final MessageAvailabilityListener listener = new MessageAvailabilityListener() {
|
||||
@Override
|
||||
public boolean handleNewMessagesAvailable() {
|
||||
synchronized (notified) {
|
||||
notified.set(true);
|
||||
notified.notifyAll();
|
||||
when(dynamicConfiguration.getMessagesConfiguration())
|
||||
.thenReturn(new DynamicMessagesConfiguration(true, true, useSharedMrmData));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMessagesPersisted() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
messagesCache.addMessageAvailabilityListener(DESTINATION_UUID, DESTINATION_DEVICE_ID, listener);
|
||||
messagesCache.insert(messageGuid, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid, true));
|
||||
|
||||
synchronized (notified) {
|
||||
while (!notified.get()) {
|
||||
notified.wait();
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(notified.get());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNotifyListenerPersisted() {
|
||||
final AtomicBoolean notified = new AtomicBoolean(false);
|
||||
|
||||
final MessageAvailabilityListener listener = new MessageAvailabilityListener() {
|
||||
@Override
|
||||
public boolean handleNewMessagesAvailable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMessagesPersisted() {
|
||||
synchronized (notified) {
|
||||
notified.set(true);
|
||||
notified.notifyAll();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
messagesCache.addMessageAvailabilityListener(DESTINATION_UUID, DESTINATION_DEVICE_ID, listener);
|
||||
|
||||
messagesCache.lockQueueForPersistence(DESTINATION_UUID, DESTINATION_DEVICE_ID);
|
||||
messagesCache.unlockQueueForPersistence(DESTINATION_UUID, DESTINATION_DEVICE_ID);
|
||||
|
||||
synchronized (notified) {
|
||||
while (!notified.get()) {
|
||||
notified.wait();
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(notified.get());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Helper class that implements {@link MessageAvailabilityListener#handleNewMessagesAvailable()} by always returning
|
||||
* {@code false}. Its {@code counter} field tracks how many times {@code handleNewMessagesAvailable} has been
|
||||
* called.
|
||||
* <p>
|
||||
* It uses a {@link CompletableFuture} to signal that it has received a “messages available” callback for the first
|
||||
* time.
|
||||
*/
|
||||
private static class NewMessagesAvailabilityClosedListener implements MessageAvailabilityListener {
|
||||
|
||||
private int counter;
|
||||
|
||||
private final Consumer<Integer> messageHandledCallback;
|
||||
private final CompletableFuture<Void> firstMessageHandled = new CompletableFuture<>();
|
||||
|
||||
private NewMessagesAvailabilityClosedListener(final Consumer<Integer> messageHandledCallback) {
|
||||
this.messageHandledCallback = messageHandledCallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleNewMessagesAvailable() {
|
||||
counter++;
|
||||
messageHandledCallback.accept(counter);
|
||||
firstMessageHandled.complete(null);
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMessagesPersisted() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAvailabilityListenerResponses() {
|
||||
final NewMessagesAvailabilityClosedListener listener1 = new NewMessagesAvailabilityClosedListener(
|
||||
count -> assertEquals(1, count));
|
||||
final NewMessagesAvailabilityClosedListener listener2 = new NewMessagesAvailabilityClosedListener(
|
||||
count -> assertEquals(1, count));
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
|
||||
messagesCache.addMessageAvailabilityListener(DESTINATION_UUID, DESTINATION_DEVICE_ID, listener1);
|
||||
final UUID messageGuid1 = UUID.randomUUID();
|
||||
messagesCache.insert(messageGuid1, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid1, true));
|
||||
|
||||
listener1.firstMessageHandled.get();
|
||||
|
||||
// Avoid a race condition by blocking on the message handled future *and* the current notification executor task—
|
||||
// the notification executor task includes unsubscribing `listener1`, and, if we don’t wait, sometimes
|
||||
// `listener2` will get subscribed before `listener1` is cleaned up
|
||||
sharedExecutorService.submit(() -> listener1.firstMessageHandled.get()).get();
|
||||
|
||||
final UUID messageGuid2 = UUID.randomUUID();
|
||||
messagesCache.insert(messageGuid2, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid2, true));
|
||||
|
||||
messagesCache.addMessageAvailabilityListener(DESTINATION_UUID, DESTINATION_DEVICE_ID, listener2);
|
||||
|
||||
final UUID messageGuid3 = UUID.randomUUID();
|
||||
messagesCache.insert(messageGuid3, DESTINATION_UUID, DESTINATION_DEVICE_ID,
|
||||
generateRandomMessage(messageGuid3, true));
|
||||
|
||||
listener2.firstMessageHandled.get();
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testMultiRecipientMessage(final boolean sharedMrmKeyPresent) throws Exception {
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = 1;
|
||||
|
||||
@@ -583,7 +428,7 @@ class MessagesCacheTest {
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 1: messages have content
|
||||
// mrm views phase 2: messages have content
|
||||
.setContent(
|
||||
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
@@ -594,10 +439,70 @@ class MessagesCacheTest {
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
|
||||
if (useSharedMrmData && !sharedMrmKeyPresent) {
|
||||
assertTrue(messages.isEmpty());
|
||||
} else {
|
||||
|
||||
assertEquals(1, messages.size());
|
||||
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
|
||||
assertFalse(messages.getFirst().hasSharedMrmKey());
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
|
||||
.get(destinationServiceId.toLibsignal());
|
||||
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
|
||||
}
|
||||
|
||||
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
|
||||
.join();
|
||||
|
||||
assertTrue(removedMessage.isPresent());
|
||||
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
|
||||
assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty());
|
||||
|
||||
// updating the shared MRM data is purely async, so we just wait for it
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
|
||||
boolean exists;
|
||||
do {
|
||||
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey));
|
||||
} while (exists);
|
||||
}, "Shared MRM data should be deleted asynchronously");
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void testMultiRecipientMessagePhase2MissingContentSafeguard(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean fetchSharedMrmData) {
|
||||
|
||||
when(dynamicConfiguration.getMessagesConfiguration())
|
||||
.thenReturn(new DynamicMessagesConfiguration(true, fetchSharedMrmData, useSharedMrmData));
|
||||
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = 1;
|
||||
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
|
||||
|
||||
final byte[] sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
|
||||
|
||||
final UUID guid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(guid, destinationServiceId, true)
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 2: there is a safeguard against missing content, even if the dynamic configuration
|
||||
// is to not fetch or use shared MRM data
|
||||
.clearContent()
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
|
||||
|
||||
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
|
||||
|
||||
assertEquals(1, messages.size());
|
||||
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
|
||||
assertFalse(messages.getFirst().hasSharedMrmKey());
|
||||
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
|
||||
.get(destinationServiceId.toLibsignal());
|
||||
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
|
||||
@@ -619,19 +524,24 @@ class MessagesCacheTest {
|
||||
}, "Shared MRM data should be deleted asynchronously");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) throws Exception {
|
||||
@CartesianTest
|
||||
void testGetMessagesToPersist(@CartesianTest.Values(booleans = {true, false}) final boolean sharedMrmKeyPresent,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean useSharedMrmData) {
|
||||
|
||||
when(dynamicConfiguration.getMessagesConfiguration())
|
||||
.thenReturn(new DynamicMessagesConfiguration(true, true, useSharedMrmData));
|
||||
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(destinationUuid);
|
||||
final byte deviceId = 1;
|
||||
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(destinationUuid, true);
|
||||
final MessageProtos.Envelope message = generateRandomMessage(messageGuid,
|
||||
new AciServiceIdentifier(destinationUuid), true);
|
||||
|
||||
messagesCache.insert(messageGuid, destinationUuid, deviceId, message);
|
||||
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(
|
||||
new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
|
||||
|
||||
final byte[] sharedMrmDataKey;
|
||||
if (sharedMrmKeyPresent) {
|
||||
@@ -641,31 +551,35 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
final UUID mrmMessageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, true)
|
||||
final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, destinationServiceId, true)
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 1: messages have content
|
||||
// mrm views phase 2: messages have content
|
||||
.setContent(
|
||||
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(new ServiceId.Aci(destinationUuid)))))
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationUuid, deviceId, 100);
|
||||
final List<MessageProtos.Envelope> messages = messagesCache.getMessagesToPersist(destinationUuid, deviceId, 100);
|
||||
|
||||
assertEquals(2, messages.size());
|
||||
if (useSharedMrmData && !sharedMrmKeyPresent) {
|
||||
assertEquals(1, messages.size());
|
||||
} else {
|
||||
assertEquals(2, messages.size());
|
||||
|
||||
assertEquals(mrmMessage.toBuilder().
|
||||
clearSharedMrmKey().
|
||||
setServerGuid(mrmMessageGuid.toString())
|
||||
.build(),
|
||||
messages.getLast());
|
||||
}
|
||||
|
||||
assertEquals(message.toBuilder()
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.build(),
|
||||
messages.getFirst());
|
||||
|
||||
assertEquals(mrmMessage.toBuilder().
|
||||
clearSharedMrmKey().
|
||||
setServerGuid(mrmMessageGuid.toString())
|
||||
.build(),
|
||||
messages.getLast());
|
||||
}
|
||||
|
||||
private List<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId,
|
||||
@@ -697,7 +611,7 @@ class MessagesCacheTest {
|
||||
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
|
||||
messagesCache = new MessagesCache(mockCluster, mock(ExecutorService.class), messageDeliveryScheduler,
|
||||
messagesCache = new MessagesCache(mockCluster, messageDeliveryScheduler,
|
||||
Executors.newSingleThreadExecutor(), Clock.systemUTC(), mock(DynamicConfigurationManager.class));
|
||||
}
|
||||
|
||||
|
||||
+87
-3
@@ -14,8 +14,12 @@ import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.lettuce.core.cluster.api.reactive.RedisAdvancedClusterReactiveCommands;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import io.lettuce.core.cluster.pubsub.StatefulRedisClusterPubSubConnection;
|
||||
import io.lettuce.core.cluster.pubsub.api.async.RedisClusterPubSubAsyncCommands;
|
||||
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
|
||||
public class RedisClusterHelper {
|
||||
@@ -30,7 +34,12 @@ public class RedisClusterHelper {
|
||||
final RedisAdvancedClusterAsyncCommands<String, String> stringAsyncCommands,
|
||||
final RedisAdvancedClusterCommands<byte[], byte[]> binaryCommands,
|
||||
final RedisAdvancedClusterAsyncCommands<byte[], byte[]> binaryAsyncCommands,
|
||||
final RedisAdvancedClusterReactiveCommands<byte[], byte[]> binaryReactiveCommands) {
|
||||
final RedisAdvancedClusterReactiveCommands<byte[], byte[]> binaryReactiveCommands,
|
||||
final RedisClusterPubSubCommands<String, String> stringPubSubCommands,
|
||||
final RedisClusterPubSubAsyncCommands<String, String> stringAsyncPubSubCommands,
|
||||
final RedisClusterPubSubCommands<byte[], byte[]> binaryPubSubCommands,
|
||||
final RedisClusterPubSubAsyncCommands<byte[], byte[]> binaryAsyncPubSubCommands) {
|
||||
|
||||
final FaultTolerantRedisClusterClient cluster = mock(FaultTolerantRedisClusterClient.class);
|
||||
final StatefulRedisClusterConnection<String, String> stringConnection = mock(StatefulRedisClusterConnection.class);
|
||||
final StatefulRedisClusterConnection<byte[], byte[]> binaryConnection = mock(StatefulRedisClusterConnection.class);
|
||||
@@ -59,6 +68,45 @@ public class RedisClusterHelper {
|
||||
return null;
|
||||
}).when(cluster).useBinaryCluster(any(Consumer.class));
|
||||
|
||||
final StatefulRedisClusterPubSubConnection<String, String> stringPubSubConnection =
|
||||
mock(StatefulRedisClusterPubSubConnection.class);
|
||||
|
||||
final StatefulRedisClusterPubSubConnection<byte[], byte[]> binaryPubSubConnection =
|
||||
mock(StatefulRedisClusterPubSubConnection.class);
|
||||
|
||||
final FaultTolerantPubSubClusterConnection<String, String> faultTolerantPubSubClusterConnection =
|
||||
mock(FaultTolerantPubSubClusterConnection.class);
|
||||
|
||||
final FaultTolerantPubSubClusterConnection<byte[], byte[]> faultTolerantBinaryPubSubClusterConnection =
|
||||
mock(FaultTolerantPubSubClusterConnection.class);
|
||||
|
||||
when(stringPubSubConnection.sync()).thenReturn(stringPubSubCommands);
|
||||
when(stringPubSubConnection.async()).thenReturn(stringAsyncPubSubCommands);
|
||||
when(binaryPubSubConnection.sync()).thenReturn(binaryPubSubCommands);
|
||||
when(binaryPubSubConnection.async()).thenReturn(binaryAsyncPubSubCommands);
|
||||
|
||||
when(cluster.createPubSubConnection()).thenReturn(faultTolerantPubSubClusterConnection);
|
||||
when(cluster.createBinaryPubSubConnection()).thenReturn(faultTolerantBinaryPubSubClusterConnection);
|
||||
|
||||
when(faultTolerantPubSubClusterConnection.withPubSubConnection(any(Function.class))).thenAnswer(invocation -> {
|
||||
return invocation.getArgument(0, Function.class).apply(stringPubSubConnection);
|
||||
});
|
||||
|
||||
doAnswer(invocation -> {
|
||||
invocation.getArgument(0, Consumer.class).accept(stringPubSubConnection);
|
||||
return null;
|
||||
}).when(faultTolerantPubSubClusterConnection).usePubSubConnection(any(Consumer.class));
|
||||
|
||||
when(faultTolerantBinaryPubSubClusterConnection.withPubSubConnection(any(Function.class))).thenAnswer(
|
||||
invocation -> {
|
||||
return invocation.getArgument(0, Function.class).apply(binaryPubSubConnection);
|
||||
});
|
||||
|
||||
doAnswer(invocation -> {
|
||||
invocation.getArgument(0, Consumer.class).accept(binaryPubSubConnection);
|
||||
return null;
|
||||
}).when(faultTolerantBinaryPubSubClusterConnection).usePubSubConnection(any(Consumer.class));
|
||||
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@@ -77,6 +125,18 @@ public class RedisClusterHelper {
|
||||
private RedisAdvancedClusterReactiveCommands<byte[], byte[]> binaryReactiveCommands =
|
||||
mock(RedisAdvancedClusterReactiveCommands.class);
|
||||
|
||||
private RedisClusterPubSubCommands<String, String> stringPubSubCommands =
|
||||
mock(RedisClusterPubSubCommands.class);
|
||||
|
||||
private RedisClusterPubSubCommands<byte[], byte[]> binaryPubSubCommands =
|
||||
mock(RedisClusterPubSubCommands.class);
|
||||
|
||||
private RedisClusterPubSubAsyncCommands<String, String> stringPubSubAsyncCommands =
|
||||
mock(RedisClusterPubSubAsyncCommands.class);
|
||||
|
||||
private RedisClusterPubSubAsyncCommands<byte[], byte[]> binaryPubSubAsyncCommands =
|
||||
mock(RedisClusterPubSubAsyncCommands.class);
|
||||
|
||||
private Builder() {
|
||||
|
||||
}
|
||||
@@ -107,9 +167,33 @@ public class RedisClusterHelper {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder stringPubSubCommands(final RedisClusterPubSubCommands<String, String> stringPubSubCommands) {
|
||||
this.stringPubSubCommands = stringPubSubCommands;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder binaryPubSubCommands(final RedisClusterPubSubCommands<byte[], byte[]> binaryPubSubCommands) {
|
||||
this.binaryPubSubCommands = binaryPubSubCommands;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder stringPubSubAsyncCommands(
|
||||
final RedisClusterPubSubAsyncCommands<String, String> stringPubSubAsyncCommands) {
|
||||
this.stringPubSubAsyncCommands = stringPubSubAsyncCommands;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder binaryPubSubAsyncCommands(
|
||||
final RedisClusterPubSubAsyncCommands<byte[], byte[]> binaryPubSubAsyncCommands) {
|
||||
this.binaryPubSubAsyncCommands = binaryPubSubAsyncCommands;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterClient build() {
|
||||
return RedisClusterHelper.buildMockRedisCluster(stringCommands, stringAsyncCommands, binaryCommands, binaryAsyncCommands,
|
||||
binaryReactiveCommands);
|
||||
return RedisClusterHelper.buildMockRedisCluster(stringCommands, stringAsyncCommands, binaryCommands,
|
||||
binaryAsyncCommands,
|
||||
binaryReactiveCommands, stringPubSubCommands, stringPubSubAsyncCommands, binaryPubSubCommands,
|
||||
binaryPubSubAsyncCommands);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+187
-5
@@ -5,17 +5,199 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
class RedisClusterUtilTest {
|
||||
|
||||
@Test
|
||||
void testGetMinimalHashTag() {
|
||||
for (int slot = 0; slot < SlotHash.SLOT_COUNT; slot++) {
|
||||
assertEquals(slot, SlotHash.getSlot(RedisClusterUtil.getMinimalHashTag(slot)));
|
||||
}
|
||||
@Test
|
||||
void testGetMinimalHashTag() {
|
||||
for (int slot = 0; slot < SlotHash.SLOT_COUNT; slot++) {
|
||||
assertEquals(slot, SlotHash.getSlot(RedisClusterUtil.getMinimalHashTag(slot)));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getChangedSlots(final ClusterTopologyChangedEvent event, final boolean[] expectedSlotsChanged) {
|
||||
assertArrayEquals(expectedSlotsChanged, RedisClusterUtil.getChangedSlots(event));
|
||||
}
|
||||
|
||||
private static List<Arguments> getChangedSlots() {
|
||||
final List<Arguments> arguments = new ArrayList<>();
|
||||
|
||||
// Slot moved from one node to another
|
||||
{
|
||||
final String firstNodeId = UUID.randomUUID().toString();
|
||||
final String secondNodeId = UUID.randomUUID().toString();
|
||||
|
||||
final RedisClusterNode firstNodeBefore = mock(RedisClusterNode.class);
|
||||
when(firstNodeBefore.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstNodeBefore.getSlots()).thenReturn(getSlotRange(0, 8192));
|
||||
|
||||
final RedisClusterNode secondNodeBefore = mock(RedisClusterNode.class);
|
||||
when(secondNodeBefore.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeBefore.getSlots()).thenReturn(getSlotRange(8192, 16384));
|
||||
|
||||
final RedisClusterNode firstNodeAfter = mock(RedisClusterNode.class);
|
||||
when(firstNodeAfter.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstNodeAfter.getSlots()).thenReturn(getSlotRange(0, 8191));
|
||||
|
||||
final RedisClusterNode secondNodeAfter = mock(RedisClusterNode.class);
|
||||
when(secondNodeAfter.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeAfter.getSlots()).thenReturn(getSlotRange(8191, 16384));
|
||||
|
||||
final ClusterTopologyChangedEvent clusterTopologyChangedEvent = new ClusterTopologyChangedEvent(
|
||||
List.of(firstNodeBefore, secondNodeBefore),
|
||||
List.of(firstNodeAfter, secondNodeAfter));
|
||||
|
||||
final boolean[] slotsChanged = new boolean[SlotHash.SLOT_COUNT];
|
||||
slotsChanged[8191] = true;
|
||||
|
||||
arguments.add(Arguments.of(clusterTopologyChangedEvent, slotsChanged));
|
||||
}
|
||||
|
||||
// New node added to cluster
|
||||
{
|
||||
final String firstNodeId = UUID.randomUUID().toString();
|
||||
final String secondNodeId = UUID.randomUUID().toString();
|
||||
|
||||
final RedisClusterNode firstNodeBefore = mock(RedisClusterNode.class);
|
||||
when(firstNodeBefore.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstNodeBefore.getSlots()).thenReturn(getSlotRange(0, 8192));
|
||||
|
||||
final RedisClusterNode secondNodeBefore = mock(RedisClusterNode.class);
|
||||
when(secondNodeBefore.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeBefore.getSlots()).thenReturn(getSlotRange(8192, 16384));
|
||||
|
||||
final RedisClusterNode firstNodeAfter = mock(RedisClusterNode.class);
|
||||
when(firstNodeAfter.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstNodeAfter.getSlots()).thenReturn(getSlotRange(0, 8192));
|
||||
|
||||
final RedisClusterNode secondNodeAfter = mock(RedisClusterNode.class);
|
||||
when(secondNodeAfter.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeAfter.getSlots()).thenReturn(getSlotRange(8192, 12288));
|
||||
|
||||
final RedisClusterNode thirdNodeAfter = mock(RedisClusterNode.class);
|
||||
when(thirdNodeAfter.getNodeId()).thenReturn(UUID.randomUUID().toString());
|
||||
when(thirdNodeAfter.getSlots()).thenReturn(getSlotRange(12288, 16384));
|
||||
|
||||
final ClusterTopologyChangedEvent clusterTopologyChangedEvent = new ClusterTopologyChangedEvent(
|
||||
List.of(firstNodeBefore, secondNodeBefore),
|
||||
List.of(firstNodeAfter, secondNodeAfter, thirdNodeAfter));
|
||||
|
||||
final boolean[] slotsChanged = new boolean[SlotHash.SLOT_COUNT];
|
||||
|
||||
for (int slot = 12288; slot < 16384; slot++) {
|
||||
slotsChanged[slot] = true;
|
||||
}
|
||||
|
||||
arguments.add(Arguments.of(clusterTopologyChangedEvent, slotsChanged));
|
||||
}
|
||||
|
||||
// Node removed from cluster
|
||||
{
|
||||
final String firstNodeId = UUID.randomUUID().toString();
|
||||
final String secondNodeId = UUID.randomUUID().toString();
|
||||
|
||||
final RedisClusterNode firstNodeBefore = mock(RedisClusterNode.class);
|
||||
when(firstNodeBefore.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstNodeBefore.getSlots()).thenReturn(getSlotRange(0, 8192));
|
||||
|
||||
final RedisClusterNode secondNodeBefore = mock(RedisClusterNode.class);
|
||||
when(secondNodeBefore.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeBefore.getSlots()).thenReturn(getSlotRange(8192, 12288));
|
||||
|
||||
final RedisClusterNode thirdNodeBefore = mock(RedisClusterNode.class);
|
||||
when(thirdNodeBefore.getNodeId()).thenReturn(UUID.randomUUID().toString());
|
||||
when(thirdNodeBefore.getSlots()).thenReturn(getSlotRange(12288, 16384));
|
||||
|
||||
final RedisClusterNode firstNodeAfter = mock(RedisClusterNode.class);
|
||||
when(firstNodeAfter.getNodeId()).thenReturn(firstNodeId);
|
||||
when(firstNodeAfter.getSlots()).thenReturn(getSlotRange(0, 8192));
|
||||
|
||||
final RedisClusterNode secondNodeAfter = mock(RedisClusterNode.class);
|
||||
when(secondNodeAfter.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeAfter.getSlots()).thenReturn(getSlotRange(8192, 16384));
|
||||
|
||||
final ClusterTopologyChangedEvent clusterTopologyChangedEvent = new ClusterTopologyChangedEvent(
|
||||
List.of(firstNodeBefore, secondNodeBefore, thirdNodeBefore),
|
||||
List.of(firstNodeAfter, secondNodeAfter));
|
||||
|
||||
final boolean[] slotsChanged = new boolean[SlotHash.SLOT_COUNT];
|
||||
|
||||
for (int slot = 12288; slot < 16384; slot++) {
|
||||
slotsChanged[slot] = true;
|
||||
}
|
||||
|
||||
arguments.add(Arguments.of(clusterTopologyChangedEvent, slotsChanged));
|
||||
}
|
||||
|
||||
// Node added, node removed, and slot moved
|
||||
// Node removed from cluster
|
||||
{
|
||||
final String secondNodeId = UUID.randomUUID().toString();
|
||||
final String thirdNodeId = UUID.randomUUID().toString();
|
||||
|
||||
final RedisClusterNode firstNodeBefore = mock(RedisClusterNode.class);
|
||||
when(firstNodeBefore.getNodeId()).thenReturn(UUID.randomUUID().toString());
|
||||
when(firstNodeBefore.getSlots()).thenReturn(getSlotRange(0, 1));
|
||||
|
||||
final RedisClusterNode secondNodeBefore = mock(RedisClusterNode.class);
|
||||
when(secondNodeBefore.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeBefore.getSlots()).thenReturn(getSlotRange(1, 8192));
|
||||
|
||||
final RedisClusterNode thirdNodeBefore = mock(RedisClusterNode.class);
|
||||
when(thirdNodeBefore.getNodeId()).thenReturn(thirdNodeId);
|
||||
when(thirdNodeBefore.getSlots()).thenReturn(getSlotRange(8192, 16384));
|
||||
|
||||
final RedisClusterNode secondNodeAfter = mock(RedisClusterNode.class);
|
||||
when(secondNodeAfter.getNodeId()).thenReturn(secondNodeId);
|
||||
when(secondNodeAfter.getSlots()).thenReturn(getSlotRange(0, 8191));
|
||||
|
||||
final RedisClusterNode thirdNodeAfter = mock(RedisClusterNode.class);
|
||||
when(thirdNodeAfter.getNodeId()).thenReturn(thirdNodeId);
|
||||
when(thirdNodeAfter.getSlots()).thenReturn(getSlotRange(8191, 16383));
|
||||
|
||||
final RedisClusterNode fourthNodeAfter = mock(RedisClusterNode.class);
|
||||
when(fourthNodeAfter.getNodeId()).thenReturn(UUID.randomUUID().toString());
|
||||
when(fourthNodeAfter.getSlots()).thenReturn(getSlotRange(16383, 16384));
|
||||
|
||||
final ClusterTopologyChangedEvent clusterTopologyChangedEvent = new ClusterTopologyChangedEvent(
|
||||
List.of(firstNodeBefore, secondNodeBefore, thirdNodeBefore),
|
||||
List.of(secondNodeAfter, thirdNodeAfter, fourthNodeAfter));
|
||||
|
||||
final boolean[] slotsChanged = new boolean[SlotHash.SLOT_COUNT];
|
||||
slotsChanged[0] = true;
|
||||
slotsChanged[8191] = true;
|
||||
slotsChanged[16383] = true;
|
||||
|
||||
arguments.add(Arguments.of(clusterTopologyChangedEvent, slotsChanged));
|
||||
}
|
||||
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private static List<Integer> getSlotRange(final int startInclusive, final int endExclusive) {
|
||||
final List<Integer> slots = new ArrayList<>(endExclusive - startInclusive);
|
||||
|
||||
for (int i = startInclusive; i < endExclusive; i++) {
|
||||
slots.add(i);
|
||||
}
|
||||
|
||||
return slots;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -98,7 +98,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService,
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), Tables.MESSAGES.tableName(), Duration.ofDays(7),
|
||||
|
||||
+7
-7
@@ -57,7 +57,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
@@ -124,8 +124,8 @@ class WebSocketConnectionTest {
|
||||
new WebSocketAccountAuthenticator(accountAuthenticator, mock(PrincipalSupplier.class));
|
||||
AuthenticatedConnectListener connectListener = new AuthenticatedConnectListener(receiptSender, messagesManager,
|
||||
new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class),
|
||||
mock(ClientPresenceManager.class), retrySchedulingExecutor, messageDeliveryScheduler, clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class));
|
||||
mock(PubSubClientEventManager.class), retrySchedulingExecutor,
|
||||
messageDeliveryScheduler, clientReleaseManager, mock(MessageDeliveryLoopMonitor.class));
|
||||
WebSocketSessionContext sessionContext = mock(WebSocketSessionContext.class);
|
||||
|
||||
when(accountAuthenticator.authenticate(eq(new BasicCredentials(VALID_USER, VALID_PASSWORD))))
|
||||
@@ -268,7 +268,7 @@ class WebSocketConnectionTest {
|
||||
// or wait for anything.
|
||||
connection.start();
|
||||
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
synchronized (sendCounter) {
|
||||
while (sendCounter.get() < 1) {
|
||||
@@ -276,7 +276,7 @@ class WebSocketConnectionTest {
|
||||
}
|
||||
}
|
||||
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
synchronized (sendCounter) {
|
||||
while (sendCounter.get() < 2) {
|
||||
@@ -693,7 +693,7 @@ class WebSocketConnectionTest {
|
||||
|
||||
when(client.sendRequest(eq("PUT"), eq("/api/v1/message"), any(List.class), any(Optional.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
return CompletableFuture.completedFuture(successResponse);
|
||||
});
|
||||
@@ -741,7 +741,7 @@ class WebSocketConnectionTest {
|
||||
|
||||
verify(messagesManager).getMessagesForDeviceReactive(account.getUuid(), device, false);
|
||||
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
verify(messagesManager).getMessagesForDeviceReactive(account.getUuid(), device, true);
|
||||
}
|
||||
|
||||
-1
@@ -73,7 +73,6 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
pushNotificationExperimentSamples,
|
||||
null,
|
||||
null,
|
||||
|
||||
-1
@@ -66,7 +66,6 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
-1
@@ -62,7 +62,6 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
pushNotificationExperimentSamples,
|
||||
null,
|
||||
null,
|
||||
|
||||
@@ -66,6 +66,7 @@ braintree:
|
||||
supportedCurrenciesByPaymentMethod:
|
||||
PAYPAL:
|
||||
- usd
|
||||
- xts
|
||||
pubSubPublisher:
|
||||
type: stub
|
||||
|
||||
@@ -155,9 +156,6 @@ dynamoDbTables:
|
||||
cacheCluster: # Redis server configuration for cache cluster
|
||||
type: local
|
||||
|
||||
clientPresenceCluster: # Redis server configuration for client presence cluster
|
||||
type: local
|
||||
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
type: local
|
||||
|
||||
@@ -372,10 +370,11 @@ subscription: # configuration for Stripe subscriptions
|
||||
backupLevels:
|
||||
201:
|
||||
playProductId: EXAMPLE
|
||||
mediaTtl: P30D
|
||||
prices: {}
|
||||
levels:
|
||||
500:
|
||||
badge: EXAMPLE
|
||||
badge: TEST
|
||||
prices:
|
||||
# list of ISO 4217 currency codes and amounts for the given badge level
|
||||
xts:
|
||||
@@ -389,11 +388,11 @@ oneTimeDonations:
|
||||
boost:
|
||||
level: 1
|
||||
expiration: P90D
|
||||
badge: EXAMPLE
|
||||
badge: TEST
|
||||
gift:
|
||||
level: 10
|
||||
expiration: P90D
|
||||
badge: EXAMPLE
|
||||
badge: TEST
|
||||
currencies:
|
||||
# ISO 4217 currency codes and amounts in those currencies
|
||||
xts:
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 15ad3d3c82...c5376ea7df.
+11
-14
@@ -62,9 +62,6 @@ public class WebSocketClient {
|
||||
pendingRequestMapper.remove(requestId);
|
||||
future.completeExceptionally(x);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeSuccess() {}
|
||||
});
|
||||
} catch (WebSocketException e) {
|
||||
logger.debug("Write", e);
|
||||
@@ -87,8 +84,17 @@ public class WebSocketClient {
|
||||
return session.isOpen();
|
||||
}
|
||||
|
||||
public void close(int code, String message) {
|
||||
session.close(code, message);
|
||||
public void close(final int code, final String message) {
|
||||
session.close(code, message, new WriteCallback() {
|
||||
@Override
|
||||
public void writeFailed(final Throwable throwable) {
|
||||
try {
|
||||
session.disconnect();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to disconnect session", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean shouldDeliverStories() {
|
||||
@@ -96,16 +102,7 @@ public class WebSocketClient {
|
||||
return Stories.parseReceiveStoriesHeader(value);
|
||||
}
|
||||
|
||||
public void hardDisconnectQuietly() {
|
||||
try {
|
||||
session.disconnect();
|
||||
} catch (Exception e) {
|
||||
// quietly we said
|
||||
}
|
||||
}
|
||||
|
||||
private long generateRequestId() {
|
||||
return Math.abs(SECURE_RANDOM.nextLong());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user