mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 05:56:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3036a149bb | ||
|
|
0dcb4b645c | ||
|
|
d71082b491 | ||
|
|
fc4c8d6054 | ||
|
|
1a27c7eabc | ||
|
|
b2e9602aba | ||
|
|
408b959441 | ||
|
|
35fc98a188 | ||
|
|
92f6a79e1f | ||
|
|
5a9c8e304c | ||
|
|
8f94ed68a3 | ||
|
|
a4cd30451c | ||
|
|
ce1a4b94cb | ||
|
|
92a0deffcf | ||
|
|
97b6f6028b | ||
|
|
99e300a640 | ||
|
|
611e8c39ee | ||
|
|
af55287dee | ||
|
|
01f1c263a6 | ||
|
|
24ea6a9f1d | ||
|
|
46c800b8b7 | ||
|
|
f10be893ce | ||
|
|
c606c1664f | ||
|
|
90a938fe2b | ||
|
|
225932b4c9 | ||
|
|
6b850b9894 | ||
|
|
d8ef796a46 | ||
|
|
943a5d1036 | ||
|
|
e600e9c583 | ||
|
|
b25da8ceaa | ||
|
|
f7388f6492 | ||
|
|
10cdb7387d | ||
|
|
dd436dd1dd | ||
|
|
13b84635b5 | ||
|
|
144d1ea280 | ||
|
|
27534d408f | ||
|
|
b80a2921aa | ||
|
|
0a23ce870a | ||
|
|
ba1e100b42 | ||
|
|
2bc237468d | ||
|
|
c355ef8d53 | ||
|
|
3052d88164 | ||
|
|
1feb23ba99 | ||
|
|
767f650e6f | ||
|
|
59a0fd0799 | ||
|
|
00b5cfcf17 | ||
|
|
f7217944e7 | ||
|
|
9e342f253d | ||
|
|
20c48b6bb2 | ||
|
|
572004d37a | ||
|
|
4f9e7bb572 | ||
|
|
df9b692a32 | ||
|
|
0a322d5a9f | ||
|
|
59eb6d10c1 | ||
|
|
affb219d72 | ||
|
|
a57ce1dd17 | ||
|
|
4e7ace3b48 | ||
|
|
b100b3c36b | ||
|
|
b64b27e5ea | ||
|
|
81c1ba6eef | ||
|
|
46b981bb2f | ||
|
|
93ae4d1ee6 | ||
|
|
9c53d818f4 | ||
|
|
efb2a1d913 | ||
|
|
e5a2c1ab10 | ||
|
|
550c0c7625 | ||
|
|
0abc269a3e | ||
|
|
6b3cbe7882 | ||
|
|
67ed035b36 | ||
|
|
ca25105f13 | ||
|
|
ad30786f4a | ||
|
|
ff0bdcd0c2 | ||
|
|
2e01da5ec1 | ||
|
|
8fb37a0024 | ||
|
|
9412a7424c |
No files matched your search
@@ -11,6 +11,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.squareup.okhttp.mockwebserver.MockResponse;
|
||||
import com.squareup.okhttp.mockwebserver.RecordedRequest;
|
||||
import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -147,6 +148,7 @@ public class SenderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void testNetworkError() throws TimeoutException, InterruptedException, IOException {
|
||||
MockResponse response = new MockResponse().setResponseCode(200)
|
||||
.setBody(fixture("fixtures/response-success.json"));
|
||||
|
||||
+2
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.tomakehurst.wiremock.junit.WireMockRule;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -61,6 +62,7 @@ public class SimultaneousSenderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void testSimultaneousFailure() throws TimeoutException, InterruptedException {
|
||||
stubFor(post(urlPathEqualTo("/gcm/send"))
|
||||
.willReturn(aResponse()
|
||||
|
||||
@@ -8,6 +8,22 @@
|
||||
<maven>3.0.0</maven>
|
||||
</prerequisites>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<name>Central Repository</name>
|
||||
<url>https://repo.maven.apache.org/maven2</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>dynamodb-local-oregon</id>
|
||||
<name>DynamoDB Local Release Repository</name>
|
||||
<url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<modules>
|
||||
<module>redis-dispatch</module>
|
||||
<module>websocket-resources</module>
|
||||
@@ -19,9 +35,10 @@
|
||||
<dropwizard.version>2.0.13</dropwizard.version>
|
||||
<resilience4j.version>1.5.0</resilience4j.version>
|
||||
<mockito.version>2.25.1</mockito.version>
|
||||
<aws.sdk.version>1.11.939</aws.sdk.version>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<TextSecureServer.version>4.93</TextSecureServer.version>
|
||||
<TextSecureServer.version>5.23</TextSecureServer.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
@@ -145,10 +162,38 @@
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope>test</includeScope>
|
||||
<includeTypes>so,dll,dylib</includeTypes>
|
||||
<outputDirectory>${project.build.directory}/lib</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M1</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<property>
|
||||
<name>sqlite4java.library.path</name>
|
||||
<value>${project.build.directory}/lib</value>
|
||||
</property>
|
||||
</systemProperties>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
|
||||
@@ -134,12 +134,5 @@ remoteConfig:
|
||||
- # Nth authorized token
|
||||
globalConfig: # keys and values that are given to clients on GET /v1/config
|
||||
|
||||
featureFlag:
|
||||
authorizedTokens:
|
||||
- # 1st authorized token
|
||||
- # 2nd authorized token
|
||||
- # ...
|
||||
- # Nth authorized token
|
||||
|
||||
paymentService:
|
||||
userAuthenticationTokenSharedSecret: # hex-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
+26
-4
@@ -83,12 +83,22 @@
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-s3</artifactId>
|
||||
<version>1.11.366</version>
|
||||
<version>${aws.sdk.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-sqs</artifactId>
|
||||
<version>1.11.366</version>
|
||||
<version>${aws.sdk.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-appconfig</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -150,7 +160,7 @@
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
<version>8.11.0</version>
|
||||
<version>8.12.17</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
@@ -192,6 +202,19 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>1.13.6</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-runtime</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>pl.pragmatists</groupId>
|
||||
<artifactId>JUnitParams</artifactId>
|
||||
@@ -257,7 +280,6 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
+35
-6
@@ -9,15 +9,17 @@ import io.dropwizard.Configuration;
|
||||
import io.dropwizard.client.JerseyClientConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AccountDatabaseCrawlerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ApnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AppConfigConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DatabaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.FeatureFlagConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcmConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AccountsDatabaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MaxDeviceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageDynamoDbConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MicrometerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PushConfiguration;
|
||||
@@ -106,11 +108,26 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private RedisConfiguration pushScheduler;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private RedisClusterConfiguration pushSchedulerCluster;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private MessageCacheConfiguration messageCache;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private RedisClusterConfiguration clientPresenceCluster;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private MessageDynamoDbConfiguration messageDynamoDb;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -134,7 +151,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private DatabaseConfiguration accountsDatabase;
|
||||
private AccountsDatabaseConfiguration accountsDatabase;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -209,7 +226,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private FeatureFlagConfiguration featureFlag;
|
||||
private AppConfigConfiguration appConfig;
|
||||
|
||||
private Map<String, String> transparentDataIndex = new HashMap<>();
|
||||
|
||||
@@ -273,10 +290,22 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return messageCache;
|
||||
}
|
||||
|
||||
public RedisClusterConfiguration getClientPresenceClusterConfiguration() {
|
||||
return clientPresenceCluster;
|
||||
}
|
||||
|
||||
public RedisConfiguration getPushScheduler() {
|
||||
return pushScheduler;
|
||||
}
|
||||
|
||||
public RedisClusterConfiguration getPushSchedulerCluster() {
|
||||
return pushSchedulerCluster;
|
||||
}
|
||||
|
||||
public MessageDynamoDbConfiguration getMessageDynamoDbConfiguration() {
|
||||
return messageDynamoDb;
|
||||
}
|
||||
|
||||
public DatabaseConfiguration getMessageStoreConfiguration() {
|
||||
return messageStore;
|
||||
}
|
||||
@@ -285,7 +314,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return abuseDatabase;
|
||||
}
|
||||
|
||||
public DatabaseConfiguration getAccountsDatabaseConfiguration() {
|
||||
public AccountsDatabaseConfiguration getAccountsDatabaseConfiguration() {
|
||||
return accountsDatabase;
|
||||
}
|
||||
|
||||
@@ -359,7 +388,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return remoteConfig;
|
||||
}
|
||||
|
||||
public FeatureFlagConfiguration getFeatureFlagConfiguration() {
|
||||
return featureFlag;
|
||||
public AppConfigConfiguration getAppConfig() {
|
||||
return appConfig;
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
@@ -55,7 +59,6 @@ import org.whispersystems.textsecuregcm.controllers.AttachmentControllerV3;
|
||||
import org.whispersystems.textsecuregcm.controllers.CertificateController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DeviceController;
|
||||
import org.whispersystems.textsecuregcm.controllers.DirectoryController;
|
||||
import org.whispersystems.textsecuregcm.controllers.FeatureFlagsController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeysController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
@@ -67,6 +70,7 @@ import org.whispersystems.textsecuregcm.controllers.SecureBackupController;
|
||||
import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.StickerController;
|
||||
import org.whispersystems.textsecuregcm.controllers.VoiceVerificationController;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.liquibase.NameableMigrationsBundle;
|
||||
@@ -117,6 +121,7 @@ import org.whispersystems.textsecuregcm.storage.ActiveUserCounter;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryReconciler;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryReconciliationClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlags;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
@@ -124,6 +129,7 @@ import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
import org.whispersystems.textsecuregcm.storage.Messages;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingAccounts;
|
||||
import org.whispersystems.textsecuregcm.storage.PendingAccountsManager;
|
||||
@@ -145,11 +151,14 @@ import org.whispersystems.textsecuregcm.websocket.DeadLetterHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteFeatureFlagTask;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.DisableRequestLoggingTask;
|
||||
import org.whispersystems.textsecuregcm.workers.EnableRequestLoggingTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
|
||||
import org.whispersystems.textsecuregcm.workers.GetRedisCommandStatsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.GetRedisSlowlogCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ListFeatureFlagsTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetCrawlerAccelerationTask;
|
||||
import org.whispersystems.textsecuregcm.workers.SetFeatureFlagTask;
|
||||
import org.whispersystems.textsecuregcm.workers.VacuumCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
@@ -260,14 +269,23 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantDatabase messageDatabase = new FaultTolerantDatabase("message_database", messageJdbi, config.getMessageStoreConfiguration().getCircuitBreakerConfiguration());
|
||||
FaultTolerantDatabase abuseDatabase = new FaultTolerantDatabase("abuse_database", abuseJdbi, config.getAbuseDatabaseConfiguration().getCircuitBreakerConfiguration());
|
||||
|
||||
AmazonDynamoDBClientBuilder messageDynamoDbClientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(config.getMessageDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) config.getMessageDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) config.getMessageDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDB messageDynamoDb = new DynamoDB(messageDynamoDbClientBuilder.build());
|
||||
|
||||
Accounts accounts = new Accounts(accountDatabase);
|
||||
PendingAccounts pendingAccounts = new PendingAccounts(accountDatabase);
|
||||
PendingDevices pendingDevices = new PendingDevices (accountDatabase);
|
||||
Usernames usernames = new Usernames(accountDatabase);
|
||||
ReservedUsernames reservedUsernames = new ReservedUsernames(accountDatabase);
|
||||
Profiles profiles = new Profiles(accountDatabase);
|
||||
Keys keys = new Keys(accountDatabase);
|
||||
Keys keys = new Keys(accountDatabase, config.getAccountsDatabaseConfiguration().getKeyOperationRetryConfiguration());
|
||||
Messages messages = new Messages(messageDatabase);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(messageDynamoDb, config.getMessageDynamoDbConfiguration().getTableName(), config.getMessageDynamoDbConfiguration().getTimeToLive());
|
||||
AbusiveHostRules abusiveHostRules = new AbusiveHostRules(abuseDatabase);
|
||||
RemoteConfigs remoteConfigs = new RemoteConfigs(accountDatabase);
|
||||
FeatureFlags featureFlags = new FeatureFlags(accountDatabase);
|
||||
@@ -280,12 +298,22 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ReplicatedJedisPool directoryClient = directoryClientFactory.getRedisClientPool();
|
||||
ReplicatedJedisPool pushSchedulerClient = pushSchedulerClientFactory.getRedisClientPool();
|
||||
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
ConnectionEventLogger.logConnectionEvents(redisClusterClientResources);
|
||||
ClientResources generalCacheClientResources = ClientResources.builder().build();
|
||||
ClientResources messageCacheClientResources = ClientResources.builder().build();
|
||||
ClientResources presenceClientResources = ClientResources.builder().build();
|
||||
ClientResources metricsCacheClientResources = ClientResources.builder().build();
|
||||
ClientResources pushSchedulerCacheClientResources = ClientResources.builder().ioThreadPoolSize(4).build();
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", config.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster messagesCacheCluster = new FaultTolerantRedisCluster("messages_cluster", config.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster metricsCluster = new FaultTolerantRedisCluster("metrics_cluster", config.getMetricsClusterConfiguration(), redisClusterClientResources);
|
||||
ConnectionEventLogger.logConnectionEvents(generalCacheClientResources);
|
||||
ConnectionEventLogger.logConnectionEvents(messageCacheClientResources);
|
||||
ConnectionEventLogger.logConnectionEvents(presenceClientResources);
|
||||
ConnectionEventLogger.logConnectionEvents(metricsCacheClientResources);
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", config.getCacheClusterConfiguration(), generalCacheClientResources);
|
||||
FaultTolerantRedisCluster messagesCluster = new FaultTolerantRedisCluster("message_insert_cluster", config.getMessageCacheConfiguration().getRedisClusterConfiguration(), messageCacheClientResources);
|
||||
FaultTolerantRedisCluster clientPresenceCluster = new FaultTolerantRedisCluster("client_presence_cluster", config.getClientPresenceClusterConfiguration(), presenceClientResources);
|
||||
FaultTolerantRedisCluster metricsCluster = new FaultTolerantRedisCluster("metrics_cluster", config.getMetricsClusterConfiguration(), metricsCacheClientResources);
|
||||
FaultTolerantRedisCluster pushSchedulerCluster = new FaultTolerantRedisCluster("push_scheduler", config.getPushSchedulerCluster(), pushSchedulerCacheClientResources);
|
||||
|
||||
BlockingQueue<Runnable> keyspaceNotificationDispatchQueue = new ArrayBlockingQueue<>(10_000);
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "keyspaceNotificationDispatchQueueSize"), Collections.emptyList(), keyspaceNotificationDispatchQueue);
|
||||
@@ -295,16 +323,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(getClass(), "apnSender-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService gcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "gcmSender-%d")).maxThreads(1).minThreads(1).build();
|
||||
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(messagesCacheCluster, recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
DynamicConfigurationManager dynamicConfigurationManager = new DynamicConfigurationManager(config.getAppConfig().getApplication(), config.getAppConfig().getEnvironment(), config.getAppConfig().getConfigurationName());
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
DirectoryManager directory = new DirectoryManager(directoryClient);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue(config.getDirectoryConfiguration().getSqsConfiguration());
|
||||
PendingAccountsManager pendingAccountsManager = new PendingAccountsManager(pendingAccounts, cacheCluster);
|
||||
PendingDevicesManager pendingDevicesManager = new PendingDevicesManager(pendingDevices, cacheCluster);
|
||||
UsernamesManager usernamesManager = new UsernamesManager(usernames, reservedUsernames, cacheCluster);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCacheCluster, keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messagesCluster, keyspaceNotificationDispatchExecutor);
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster);
|
||||
MessagesManager messagesManager = new MessagesManager(messages, messagesCache, pushLatencyManager);
|
||||
MessagesManager messagesManager = new MessagesManager(messages, messagesDynamoDb, messagesCache, pushLatencyManager, experimentEnrollmentManager);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheCluster, directoryQueue, keys, messagesManager, usernamesManager, profilesManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
FeatureFlagsManager featureFlagsManager = new FeatureFlagsManager(featureFlags, recurringJobExecutor);
|
||||
@@ -327,7 +358,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ExternalServiceCredentialGenerator backupCredentialsGenerator = new ExternalServiceCredentialGenerator(config.getSecureBackupServiceConfiguration().getUserAuthenticationTokenSharedSecret(), new byte[0], false);
|
||||
ExternalServiceCredentialGenerator paymentsCredentialsGenerator = new ExternalServiceCredentialGenerator(config.getPaymentsServiceConfiguration().getUserAuthenticationTokenSharedSecret(), new byte[0], false);
|
||||
|
||||
ApnFallbackManager apnFallbackManager = new ApnFallbackManager(pushSchedulerClient, apnSender, accountsManager);
|
||||
ApnFallbackManager apnFallbackManager = new ApnFallbackManager(pushSchedulerClient, pushSchedulerCluster, apnSender, accountsManager);
|
||||
TwilioSmsSender twilioSmsSender = new TwilioSmsSender(config.getTwilioConfiguration());
|
||||
SmsSender smsSender = new SmsSender(twilioSmsSender);
|
||||
MessageSender messageSender = new MessageSender(apnFallbackManager, clientPresenceManager, messagesManager, gcmSender, apnSender, pushLatencyManager);
|
||||
@@ -335,7 +366,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration());
|
||||
RecaptchaClient recaptchaClient = new RecaptchaClient(config.getRecaptchaConfiguration().getSecret());
|
||||
|
||||
MessagePersister messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, Duration.ofMinutes(config.getMessageCacheConfiguration().getPersistDelayMinutes()));
|
||||
MessagePersister messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, featureFlagsManager, Duration.ofMinutes(config.getMessageCacheConfiguration().getPersistDelayMinutes()));
|
||||
|
||||
final List<AccountDatabaseCrawlerListener> accountDatabaseCrawlerListeners = new ArrayList<>();
|
||||
accountDatabaseCrawlerListeners.add(new PushFeedbackProcessor(accountsManager, directoryQueue));
|
||||
@@ -361,6 +392,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(messagePersister);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
environment.lifecycle().manage(featureFlagsManager);
|
||||
environment.lifecycle().manage(dynamicConfigurationManager);
|
||||
|
||||
AWSCredentials credentials = new BasicAWSCredentials(config.getCdnConfiguration().getAccessKey(), config.getCdnConfiguration().getAccessSecret());
|
||||
AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
|
||||
@@ -377,11 +409,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
AttachmentControllerV2 attachmentControllerV2 = new AttachmentControllerV2(rateLimiters, config.getAwsAttachmentsConfiguration().getAccessKey(), config.getAwsAttachmentsConfiguration().getAccessSecret(), config.getAwsAttachmentsConfiguration().getRegion(), config.getAwsAttachmentsConfiguration().getBucket());
|
||||
AttachmentControllerV3 attachmentControllerV3 = new AttachmentControllerV3(rateLimiters, config.getGcpAttachmentsConfiguration().getDomain(), config.getGcpAttachmentsConfiguration().getEmail(), config.getGcpAttachmentsConfiguration().getMaxSizeInBytes(), config.getGcpAttachmentsConfiguration().getPathPrefix(), config.getGcpAttachmentsConfiguration().getRsaSigningKey());
|
||||
KeysController keysController = new KeysController(rateLimiters, keys, accountsManager, directoryQueue);
|
||||
MessageController messageController = new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, messagesManager, apnFallbackManager);
|
||||
MessageController messageController = new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, messagesManager, apnFallbackManager, featureFlagsManager);
|
||||
ProfileController profileController = new ProfileController(rateLimiters, accountsManager, profilesManager, usernamesManager, cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner, config.getCdnConfiguration().getBucket(), zkProfileOperations, isZkEnabled);
|
||||
StickerController stickerController = new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(), config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(), config.getCdnConfiguration().getBucket());
|
||||
RemoteConfigController remoteConfigController = new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().getAuthorizedTokens(), config.getRemoteConfigConfiguration().getGlobalConfig());
|
||||
FeatureFlagsController featureFlagsController = new FeatureFlagsController(featureFlagsManager, config.getFeatureFlagConfiguration().getAuthorizedTokens());
|
||||
|
||||
AuthFilter<BasicCredentials, Account> accountAuthFilter = new BasicCredentialAuthFilter.Builder<Account>().setAuthenticator(accountAuthenticator).buildAuthFilter ();
|
||||
AuthFilter<BasicCredentials, DisabledPermittedAccount> disabledPermittedAccountAuthFilter = new BasicCredentialAuthFilter.Builder<DisabledPermittedAccount>().setAuthenticator(disabledPermittedAccountAuthenticator).buildAuthFilter();
|
||||
@@ -411,7 +442,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(profileController);
|
||||
environment.jersey().register(stickerController);
|
||||
environment.jersey().register(remoteConfigController);
|
||||
environment.jersey().register(featureFlagsController);
|
||||
|
||||
///
|
||||
WebSocketEnvironment<Account> webSocketEnvironment = new WebSocketEnvironment<>(environment, config.getWebSocketConfiguration(), 90000);
|
||||
@@ -446,8 +476,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
provisioning.addMapping("/v1/websocket/provisioning/");
|
||||
provisioning.setAsyncSupported(true);
|
||||
|
||||
environment.admin().addTask(new EnableRequestLoggingTask());
|
||||
environment.admin().addTask(new DisableRequestLoggingTask());
|
||||
environment.admin().addTask(new SetRequestLoggingEnabledTask());
|
||||
environment.admin().addTask(new SetCrawlerAccelerationTask(accountDatabaseCrawlerCache));
|
||||
environment.admin().addTask(new ListFeatureFlagsTask(featureFlagsManager));
|
||||
environment.admin().addTask(new SetFeatureFlagTask(featureFlagsManager));
|
||||
environment.admin().addTask(new DeleteFeatureFlagTask(featureFlagsManager));
|
||||
|
||||
///
|
||||
|
||||
|
||||
@@ -37,4 +37,12 @@ public class AmbiguousIdentifier {
|
||||
public boolean hasNumber() {
|
||||
return number != null;
|
||||
}
|
||||
|
||||
public int sendingGateHash() {
|
||||
if (uuid != null) {
|
||||
return (int)(uuid.getLeastSignificantBits() & 0xff);
|
||||
} else {
|
||||
return number.hashCode() & 0xff;
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class AccountsDatabaseConfiguration extends DatabaseConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private RetryConfiguration keyOperationRetry = new RetryConfiguration();
|
||||
|
||||
public RetryConfiguration getKeyOperationRetryConfiguration() {
|
||||
return keyOperationRetry;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class AppConfigConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String application;
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String environment;
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
private String configuration;
|
||||
|
||||
public String getApplication() {
|
||||
return application;
|
||||
}
|
||||
|
||||
public String getEnvironment() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
public String getConfigurationName() {
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class FeatureFlagConfiguration {
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private List<String> authorizedTokens = new LinkedList<>();
|
||||
|
||||
public List<String> getAuthorizedTokens() {
|
||||
return authorizedTokens;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import java.time.Duration;
|
||||
|
||||
public class MessageDynamoDbConfiguration {
|
||||
private String region;
|
||||
private String tableName;
|
||||
private Duration timeToLive = Duration.ofDays(7);
|
||||
private Duration clientExecutionTimeout = Duration.ofSeconds(30);
|
||||
private Duration clientRequestTimeout = Duration.ofSeconds(10);
|
||||
|
||||
@Valid
|
||||
@NotEmpty
|
||||
public String getRegion() {
|
||||
return region;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotEmpty
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Valid
|
||||
public Duration getTimeToLive() {
|
||||
return timeToLive;
|
||||
}
|
||||
|
||||
public Duration getClientExecutionTimeout() {
|
||||
return clientExecutionTimeout;
|
||||
}
|
||||
|
||||
public Duration getClientRequestTimeout() {
|
||||
return clientRequestTimeout;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private Map<String, DynamicExperimentEnrollmentConfiguration> experiments = Collections.emptyMap();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Max;
|
||||
import javax.validation.constraints.Min;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class DynamicExperimentEnrollmentConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private Set<UUID> enrolledUuids = Collections.emptySet();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
private int enrollmentPercentage = 0;
|
||||
|
||||
public Set<UUID> getEnrolledUuids() {
|
||||
return enrolledUuids;
|
||||
}
|
||||
|
||||
public int getEnrollmentPercentage() {
|
||||
return enrollmentPercentage;
|
||||
}
|
||||
}
|
||||
+63
-55
@@ -85,6 +85,7 @@ public class AccountController {
|
||||
private final Meter filteredHostMeter = metricRegistry.meter(name(AccountController.class, "filtered_host" ));
|
||||
private final Meter rateLimitedHostMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_host" ));
|
||||
private final Meter rateLimitedPrefixMeter = metricRegistry.meter(name(AccountController.class, "rate_limited_prefix"));
|
||||
private final Meter captchaRequiredMeter = metricRegistry.meter(name(AccountController.class, "captcha_required" ));
|
||||
private final Meter captchaSuccessMeter = metricRegistry.meter(name(AccountController.class, "captcha_success" ));
|
||||
private final Meter captchaFailureMeter = metricRegistry.meter(name(AccountController.class, "captcha_failure" ));
|
||||
|
||||
@@ -186,6 +187,10 @@ public class AccountController {
|
||||
throw new WebApplicationException(Response.status(400).build());
|
||||
}
|
||||
|
||||
if (number.startsWith("+98")) {
|
||||
transport = "voice";
|
||||
}
|
||||
|
||||
String requester = Arrays.stream(forwardedFor.split(","))
|
||||
.map(String::trim)
|
||||
.reduce((a, b) -> b)
|
||||
@@ -195,6 +200,8 @@ public class AccountController {
|
||||
CaptchaRequirement requirement = requiresCaptcha(number, transport, forwardedFor, requester, captcha, storedChallenge, pushChallenge);
|
||||
|
||||
if (requirement.isCaptchaRequired()) {
|
||||
captchaRequiredMeter.mark();
|
||||
|
||||
if (requirement.isAutoBlock() && shouldAutoBlock(requester)) {
|
||||
logger.info("Auto-block: " + requester);
|
||||
abusiveHostRules.setBlockedHost(requester, "Auto-Block");
|
||||
@@ -536,62 +543,63 @@ public class AccountController {
|
||||
Optional<String> pushChallenge)
|
||||
{
|
||||
|
||||
if (captchaToken.isPresent()) {
|
||||
boolean validToken = recaptchaClient.verify(captchaToken.get(), requester);
|
||||
|
||||
if (validToken) {
|
||||
captchaSuccessMeter.mark();
|
||||
return new CaptchaRequirement(false, false);
|
||||
} else {
|
||||
captchaFailureMeter.mark();
|
||||
return new CaptchaRequirement(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
if (pushChallenge.isPresent()) {
|
||||
Optional<String> storedPushChallenge = storedVerificationCode.map(StoredVerificationCode::getPushCode);
|
||||
|
||||
if (!pushChallenge.get().equals(storedPushChallenge.orElse(null))) {
|
||||
return new CaptchaRequirement(true, false);
|
||||
}
|
||||
} else {
|
||||
return new CaptchaRequirement(true, false);
|
||||
}
|
||||
|
||||
List<AbusiveHostRule> abuseRules = abusiveHostRules.getAbusiveHostRulesFor(requester);
|
||||
|
||||
for (AbusiveHostRule abuseRule : abuseRules) {
|
||||
if (abuseRule.isBlocked()) {
|
||||
logger.info("Blocked host: " + transport + ", " + number + ", " + requester + " (" + forwardedFor + ")");
|
||||
blockedHostMeter.mark();
|
||||
return new CaptchaRequirement(true, false);
|
||||
}
|
||||
|
||||
if (!abuseRule.getRegions().isEmpty()) {
|
||||
if (abuseRule.getRegions().stream().noneMatch(number::startsWith)) {
|
||||
logger.info("Restricted host: " + transport + ", " + number + ", " + requester + " (" + forwardedFor + ")");
|
||||
filteredHostMeter.mark();
|
||||
return new CaptchaRequirement(true, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
rateLimiters.getSmsVoiceIpLimiter().validate(requester);
|
||||
} catch (RateLimitExceededException e) {
|
||||
logger.info("Rate limited exceeded: " + transport + ", " + number + ", " + requester + " (" + forwardedFor + ")");
|
||||
rateLimitedHostMeter.mark();
|
||||
return new CaptchaRequirement(true, true);
|
||||
}
|
||||
|
||||
try {
|
||||
rateLimiters.getSmsVoicePrefixLimiter().validate(Util.getNumberPrefix(number));
|
||||
} catch (RateLimitExceededException e) {
|
||||
logger.info("Prefix rate limit exceeded: " + transport + ", " + number + ", (" + forwardedFor + ")");
|
||||
rateLimitedPrefixMeter.mark();
|
||||
return new CaptchaRequirement(true, true);
|
||||
}
|
||||
|
||||
return new CaptchaRequirement(false, false);
|
||||
// if (captchaToken.isPresent()) {
|
||||
// boolean validToken = recaptchaClient.verify(captchaToken.get(), requester);
|
||||
//
|
||||
// if (validToken) {
|
||||
// captchaSuccessMeter.mark();
|
||||
// return new CaptchaRequirement(false, false);
|
||||
// } else {
|
||||
// captchaFailureMeter.mark();
|
||||
// return new CaptchaRequirement(true, false);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if (pushChallenge.isPresent()) {
|
||||
// Optional<String> storedPushChallenge = storedVerificationCode.map(StoredVerificationCode::getPushCode);
|
||||
//
|
||||
// if (!pushChallenge.get().equals(storedPushChallenge.orElse(null))) {
|
||||
// return new CaptchaRequirement(true, false);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// List<AbusiveHostRule> abuseRules = abusiveHostRules.getAbusiveHostRulesFor(requester);
|
||||
//
|
||||
// for (AbusiveHostRule abuseRule : abuseRules) {
|
||||
// if (abuseRule.isBlocked()) {
|
||||
// logger.info("Blocked host: " + transport + ", " + number + ", " + requester + " (" + forwardedFor + ")");
|
||||
// blockedHostMeter.mark();
|
||||
// return new CaptchaRequirement(true, false);
|
||||
// }
|
||||
//
|
||||
// if (!abuseRule.getRegions().isEmpty()) {
|
||||
// if (abuseRule.getRegions().stream().noneMatch(number::startsWith)) {
|
||||
// logger.info("Restricted host: " + transport + ", " + number + ", " + requester + " (" + forwardedFor + ")");
|
||||
// filteredHostMeter.mark();
|
||||
// return new CaptchaRequirement(true, false);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// rateLimiters.getSmsVoiceIpLimiter().validate(requester);
|
||||
// } catch (RateLimitExceededException e) {
|
||||
// logger.info("Rate limited exceeded: " + transport + ", " + number + ", " + requester + " (" + forwardedFor + ")");
|
||||
// rateLimitedHostMeter.mark();
|
||||
// return new CaptchaRequirement(true, true);
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// rateLimiters.getSmsVoicePrefixLimiter().validate(Util.getNumberPrefix(number));
|
||||
// } catch (RateLimitExceededException e) {
|
||||
// logger.info("Prefix rate limit exceeded: " + transport + ", " + number + ", (" + forwardedFor + ")");
|
||||
// rateLimitedPrefixMeter.mark();
|
||||
// return new CaptchaRequirement(true, true);
|
||||
// }
|
||||
//
|
||||
// return new CaptchaRequirement(false, false);
|
||||
}
|
||||
|
||||
@Timed
|
||||
|
||||
+3
-39
@@ -138,18 +138,7 @@ public class DirectoryController {
|
||||
public Response getTokenPresence(@Auth Account account, @PathParam("token") String token)
|
||||
throws RateLimitExceededException
|
||||
{
|
||||
rateLimiters.getContactsLimiter().validate(account.getNumber());
|
||||
|
||||
try {
|
||||
Optional<ClientContact> contact = directory.get(decodeToken(token));
|
||||
|
||||
if (contact.isPresent()) return Response.ok().entity(contact.get()).build();
|
||||
else return Response.status(404).build();
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.info("Bad token", e);
|
||||
return Response.status(404).build();
|
||||
}
|
||||
return Response.status(429).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -157,37 +146,12 @@ public class DirectoryController {
|
||||
@Path("/tokens")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public ClientContacts getContactIntersection(@Auth Account account,
|
||||
public Response getContactIntersection(@Auth Account account,
|
||||
@HeaderParam("X-Forwarded-For") String forwardedFor,
|
||||
@Valid ClientContactTokens contacts)
|
||||
throws RateLimitExceededException
|
||||
{
|
||||
String requester = Arrays.stream(forwardedFor.split(","))
|
||||
.map(String::trim)
|
||||
.reduce((a, b) -> b)
|
||||
.orElseThrow();
|
||||
|
||||
if (Stream.of(FRONTED_REGIONS).noneMatch(region -> account.getNumber().startsWith(region))) {
|
||||
rateLimiters.getContactsIpLimiter().validate(requester);
|
||||
}
|
||||
|
||||
rateLimiters.getContactsLimiter().validate(account.getNumber(), contacts.getContacts().size());
|
||||
contactsHistogram.update(contacts.getContacts().size());
|
||||
contactsMeter.mark(contacts.getContacts().size());
|
||||
|
||||
try {
|
||||
List<byte[]> tokens = new LinkedList<>();
|
||||
|
||||
for (String encodedContact : contacts.getContacts()) {
|
||||
tokens.add(decodeToken(encodedContact));
|
||||
}
|
||||
|
||||
List<ClientContact> intersection = directory.get(tokens);
|
||||
return new ClientContacts(intersection);
|
||||
} catch (IOException e) {
|
||||
logger.info("Bad token", e);
|
||||
throw new WebApplicationException(Response.status(400).build());
|
||||
}
|
||||
return Response.status(429).build();
|
||||
}
|
||||
|
||||
private byte[] decodeToken(String encoded) throws IOException {
|
||||
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.FormParam;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Path("/v1/featureflag")
|
||||
public class FeatureFlagsController {
|
||||
|
||||
private final FeatureFlagsManager featureFlagsManager;
|
||||
private final List<byte[]> authorizedTokens;
|
||||
|
||||
public FeatureFlagsController(final FeatureFlagsManager featureFlagsManager, final List<String> authorizedTokens) {
|
||||
this.featureFlagsManager = featureFlagsManager;
|
||||
this.authorizedTokens = authorizedTokens.stream().map(token -> token.getBytes(StandardCharsets.UTF_8)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Map<String, Boolean> get(@HeaderParam("Token") final String token) {
|
||||
if (!isAuthorized(token)) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
return featureFlagsManager.getAllFlags();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/{featureFlag}")
|
||||
public void set(@HeaderParam("Token") final String token, @PathParam("featureFlag") final String featureFlag, @FormParam("active") final boolean active) {
|
||||
if (!isAuthorized(token)) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
featureFlagsManager.setFeatureFlag(featureFlag, active);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/{featureFlag}")
|
||||
public void delete(@HeaderParam("Token") final String token, @PathParam("featureFlag") final String featureFlag) {
|
||||
if (!isAuthorized(token)) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
featureFlagsManager.deleteFeatureFlag(featureFlag);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isAuthorized(final String token) {
|
||||
if (token == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
boolean authorized = false;
|
||||
|
||||
for (final byte[] authorizedToken : authorizedTokens) {
|
||||
//noinspection IfStatementMissingBreakInLoop
|
||||
if (MessageDigest.isEqual(authorizedToken, tokenBytes)) {
|
||||
authorized = true;
|
||||
}
|
||||
}
|
||||
|
||||
return authorized;
|
||||
}
|
||||
}
|
||||
+107
-60
@@ -12,6 +12,7 @@ import com.codahale.metrics.Timer;
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -36,6 +37,7 @@ import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.Base64;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
@@ -74,7 +76,7 @@ public class MessageController {
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Meter unidentifiedMeter = metricRegistry.meter(name(getClass(), "delivery", "unidentified"));
|
||||
private final Meter identifiedMeter = metricRegistry.meter(name(getClass(), "delivery", "identified" ));
|
||||
private final Meter rejectOversizeMessageMeter = metricRegistry.meter(name(getClass(), "rejectOversizeMessage"));
|
||||
private final Meter rejectOver256kibMessageMeter = metricRegistry.meter(name(getClass(), "rejectOver256kibMessage"));
|
||||
private final Timer sendMessageInternalTimer = metricRegistry.timer(name(getClass(), "sendMessageInternal"));
|
||||
private final Histogram outgoingMessageListSizeHistogram = metricRegistry.histogram(name(getClass(), "outgoingMessageListSize"));
|
||||
|
||||
@@ -85,17 +87,20 @@ public class MessageController {
|
||||
private final MessagesManager messagesManager;
|
||||
private final ApnFallbackManager apnFallbackManager;
|
||||
|
||||
private final FeatureFlagsManager featureFlagsManager;
|
||||
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = name(MessageController.class, "messageContentSize");
|
||||
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
|
||||
|
||||
private static final int MAX_MESSAGE_SIZE = 1024 * 1024;
|
||||
private static final long MAX_MESSAGE_SIZE = DataSize.kibibytes(256).toBytes();
|
||||
|
||||
public MessageController(RateLimiters rateLimiters,
|
||||
MessageSender messageSender,
|
||||
ReceiptSender receiptSender,
|
||||
AccountsManager accountsManager,
|
||||
MessagesManager messagesManager,
|
||||
ApnFallbackManager apnFallbackManager)
|
||||
ApnFallbackManager apnFallbackManager,
|
||||
FeatureFlagsManager featureFlagsManager)
|
||||
{
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.messageSender = messageSender;
|
||||
@@ -103,6 +108,7 @@ public class MessageController {
|
||||
this.accountsManager = accountsManager;
|
||||
this.messagesManager = messagesManager;
|
||||
this.apnFallbackManager = apnFallbackManager;
|
||||
this.featureFlagsManager = featureFlagsManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -110,85 +116,126 @@ public class MessageController {
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public SendMessageResponse sendMessage(@Auth Optional<Account> source,
|
||||
public Response sendMessage(@Auth Optional<Account> source,
|
||||
@HeaderParam(OptionalAccess.UNIDENTIFIED) Optional<Anonymous> accessKey,
|
||||
@HeaderParam("User-Agent") String userAgent,
|
||||
@PathParam("destination") AmbiguousIdentifier destinationName,
|
||||
@Valid IncomingMessageList messages)
|
||||
throws RateLimitExceededException
|
||||
{
|
||||
if (!source.isPresent() && !accessKey.isPresent()) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (source.isPresent() && !source.get().isFor(destinationName)) {
|
||||
rateLimiters.getMessagesLimiter().validate(source.get().getNumber() + "__" + destinationName);
|
||||
}
|
||||
|
||||
if (source.isPresent() && !source.get().isFor(destinationName)) {
|
||||
identifiedMeter.mark();
|
||||
} else if (!source.isPresent()) {
|
||||
unidentifiedMeter.mark();
|
||||
}
|
||||
|
||||
for (final IncomingMessage message : messages.getMessages()) {
|
||||
int contentLength = 0;
|
||||
|
||||
if (!Util.isEmpty(message.getContent())) {
|
||||
contentLength += message.getContent().length();
|
||||
if (shouldSend(destinationName)) {
|
||||
if (!source.isPresent() && !accessKey.isPresent()) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (!Util.isEmpty(message.getBody())) {
|
||||
contentLength += message.getBody().length();
|
||||
if (source.isPresent() && !source.get().isFor(destinationName)) {
|
||||
rateLimiters.getMessagesLimiter().validate(source.get().getNumber() + "__" + destinationName);
|
||||
}
|
||||
|
||||
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, UserAgentTagUtil.getUserAgentTags(userAgent)).record(contentLength);
|
||||
|
||||
if (contentLength > MAX_MESSAGE_SIZE) {
|
||||
// TODO Reject the request
|
||||
rejectOversizeMessageMeter.mark();
|
||||
if (source.isPresent() && !source.get().isFor(destinationName)) {
|
||||
identifiedMeter.mark();
|
||||
} else if (!source.isPresent()) {
|
||||
unidentifiedMeter.mark();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
boolean isSyncMessage = source.isPresent() && source.get().isFor(destinationName);
|
||||
for (final IncomingMessage message : messages.getMessages()) {
|
||||
int contentLength = 0;
|
||||
|
||||
Optional<Account> destination;
|
||||
if (!Util.isEmpty(message.getContent())) {
|
||||
contentLength += message.getContent().length();
|
||||
}
|
||||
|
||||
if (!isSyncMessage) destination = accountsManager.get(destinationName);
|
||||
else destination = source;
|
||||
if (!Util.isEmpty(message.getBody())) {
|
||||
contentLength += message.getBody().length();
|
||||
}
|
||||
|
||||
OptionalAccess.verify(source, accessKey, destination);
|
||||
assert(destination.isPresent());
|
||||
Metrics.summary(CONTENT_SIZE_DISTRIBUTION_NAME, UserAgentTagUtil.getUserAgentTags(userAgent)).record(contentLength);
|
||||
|
||||
validateCompleteDeviceList(destination.get(), messages.getMessages(), isSyncMessage);
|
||||
validateRegistrationIds(destination.get(), messages.getMessages());
|
||||
|
||||
for (IncomingMessage incomingMessage : messages.getMessages()) {
|
||||
Optional<Device> destinationDevice = destination.get().getDevice(incomingMessage.getDestinationDeviceId());
|
||||
|
||||
if (destinationDevice.isPresent()) {
|
||||
sendMessage(source, destination.get(), destinationDevice.get(), messages.getTimestamp(), messages.isOnline(), incomingMessage);
|
||||
if (contentLength > MAX_MESSAGE_SIZE) {
|
||||
rejectOver256kibMessageMeter.mark();
|
||||
return Response.status(Response.Status.REQUEST_ENTITY_TOO_LARGE).build();
|
||||
}
|
||||
}
|
||||
|
||||
return new SendMessageResponse(!isSyncMessage && source.isPresent() && source.get().getEnabledDeviceCount() > 1);
|
||||
} catch (NoSuchUserException e) {
|
||||
throw new WebApplicationException(Response.status(404).build());
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
try {
|
||||
boolean isSyncMessage = source.isPresent() && source.get().isFor(destinationName);
|
||||
|
||||
Optional<Account> destination;
|
||||
|
||||
if (!isSyncMessage) destination = accountsManager.get(destinationName);
|
||||
else destination = source;
|
||||
|
||||
OptionalAccess.verify(source, accessKey, destination);
|
||||
assert(destination.isPresent());
|
||||
|
||||
validateCompleteDeviceList(destination.get(), messages.getMessages(), isSyncMessage);
|
||||
validateRegistrationIds(destination.get(), messages.getMessages());
|
||||
|
||||
for (IncomingMessage incomingMessage : messages.getMessages()) {
|
||||
Optional<Device> destinationDevice = destination.get().getDevice(incomingMessage.getDestinationDeviceId());
|
||||
|
||||
if (destinationDevice.isPresent()) {
|
||||
sendMessage(source, destination.get(), destinationDevice.get(), messages.getTimestamp(), messages.isOnline(), incomingMessage);
|
||||
}
|
||||
}
|
||||
|
||||
return Response.ok(new SendMessageResponse(!isSyncMessage && source.isPresent() && source.get().getEnabledDeviceCount() > 1)).build();
|
||||
} catch (NoSuchUserException e) {
|
||||
throw new WebApplicationException(Response.status(404).build());
|
||||
} catch (MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
.build());
|
||||
}
|
||||
} else {
|
||||
if (featureFlagsManager.isFeatureFlagActive("SEND_ALL_200_STATUS")) {
|
||||
// Forgive me for what I must do
|
||||
return Response.ok(new SendMessageResponse(false)).build();
|
||||
} else {
|
||||
return Response.status(503).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldSend(final AmbiguousIdentifier destination) {
|
||||
final double hash = destination.sendingGateHash();
|
||||
|
||||
return (hash / 256.0) < getSuccessPercentage();
|
||||
}
|
||||
|
||||
private double getSuccessPercentage() {
|
||||
if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_1_PERCENT")) {
|
||||
return 0.01;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_2_PERCENT")) {
|
||||
return 0.02;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_4_PERCENT")) {
|
||||
return 0.04;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_8_PERCENT")) {
|
||||
return 0.08;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_16_PERCENT")) {
|
||||
return 0.16;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_32_PERCENT")) {
|
||||
return 0.32;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_48_PERCENT")) {
|
||||
return 0.48;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_64_PERCENT")) {
|
||||
return 0.64;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_80_PERCENT")) {
|
||||
return 0.80;
|
||||
} else if (featureFlagsManager.isFeatureFlagActive("SEND_MESSAGE_100_PERCENT")) {
|
||||
return 1.0d;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+13
-5
@@ -110,7 +110,7 @@ public class ProfileController {
|
||||
String avatar = request.isAvatar() ? generateAvatarObjectName() : null;
|
||||
Optional<ProfileAvatarUploadAttributes> response = Optional.empty();
|
||||
|
||||
profilesManager.set(account.getUuid(), new VersionedProfile(request.getVersion(), request.getName(), avatar, request.getCommitment().serialize()));
|
||||
profilesManager.set(account.getUuid(), new VersionedProfile(request.getVersion(), request.getName(), avatar, request.getAboutEmoji(), request.getAbout(), request.getCommitment().serialize()));
|
||||
|
||||
if (request.isAvatar()) {
|
||||
Optional<String> currentAvatar = Optional.empty();
|
||||
@@ -189,15 +189,19 @@ public class ProfileController {
|
||||
|
||||
assert(accountProfile.isPresent());
|
||||
|
||||
Optional<String> username = usernamesManager.get(accountProfile.get().getUuid());
|
||||
Optional<VersionedProfile> profile = profilesManager.get(uuid, version);
|
||||
Optional<String> username = usernamesManager.get(accountProfile.get().getUuid());
|
||||
Optional<VersionedProfile> profile = profilesManager.get(uuid, version);
|
||||
|
||||
String name = profile.map(VersionedProfile::getName).orElse(accountProfile.get().getProfileName());
|
||||
String avatar = profile.map(VersionedProfile::getAvatar).orElse(accountProfile.get().getAvatar());
|
||||
String name = profile.map(VersionedProfile::getName).orElse(accountProfile.get().getProfileName());
|
||||
String about = profile.map(VersionedProfile::getAbout).orElse(null);
|
||||
String aboutEmoji = profile.map(VersionedProfile::getAboutEmoji).orElse(null);
|
||||
String avatar = profile.map(VersionedProfile::getAvatar).orElse(accountProfile.get().getAvatar());
|
||||
|
||||
Optional<ProfileKeyCredentialResponse> credential = getProfileCredential(credentialRequest, profile, uuid);
|
||||
|
||||
return Optional.of(new Profile(name,
|
||||
about,
|
||||
aboutEmoji,
|
||||
avatar,
|
||||
accountProfile.get().getIdentityKey(),
|
||||
UnidentifiedAccessChecksum.generateFor(accountProfile.get().getUnidentifiedAccessKey()),
|
||||
@@ -236,6 +240,8 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
return new Profile(accountProfile.get().getProfileName(),
|
||||
null,
|
||||
null,
|
||||
accountProfile.get().getAvatar(),
|
||||
accountProfile.get().getIdentityKey(),
|
||||
UnidentifiedAccessChecksum.generateFor(accountProfile.get().getUnidentifiedAccessKey()),
|
||||
@@ -309,6 +315,8 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
return new Profile(accountProfile.get().getProfileName(),
|
||||
null,
|
||||
null,
|
||||
accountProfile.get().getAvatar(),
|
||||
accountProfile.get().getIdentityKey(),
|
||||
UnidentifiedAccessChecksum.generateFor(accountProfile.get().getUnidentifiedAccessKey()),
|
||||
|
||||
+21
-2
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.validator.constraints.NotEmpty;
|
||||
import org.signal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
@@ -21,12 +22,20 @@ public class CreateProfileRequest {
|
||||
private String version;
|
||||
|
||||
@JsonProperty
|
||||
@ExactlySize({108})
|
||||
@ExactlySize({108, 380})
|
||||
private String name;
|
||||
|
||||
@JsonProperty
|
||||
private boolean avatar;
|
||||
|
||||
@JsonProperty
|
||||
@ExactlySize({0, 80})
|
||||
private String aboutEmoji;
|
||||
|
||||
@JsonProperty
|
||||
@ExactlySize({0, 208, 376, 720})
|
||||
private String about;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@JsonDeserialize(using = ProfileKeyCommitmentAdapter.Deserializing.class)
|
||||
@@ -35,10 +44,12 @@ public class CreateProfileRequest {
|
||||
|
||||
public CreateProfileRequest() {}
|
||||
|
||||
public CreateProfileRequest(ProfileKeyCommitment commitment, String version, String name, boolean wantsAvatar) {
|
||||
public CreateProfileRequest(ProfileKeyCommitment commitment, String version, String name, String aboutEmoji, String about, boolean wantsAvatar) {
|
||||
this.commitment = commitment;
|
||||
this.version = version;
|
||||
this.name = name;
|
||||
this.aboutEmoji = aboutEmoji;
|
||||
this.about = about;
|
||||
this.avatar = wantsAvatar;
|
||||
}
|
||||
|
||||
@@ -57,4 +68,12 @@ public class CreateProfileRequest {
|
||||
public boolean isAvatar() {
|
||||
return avatar;
|
||||
}
|
||||
|
||||
public String getAboutEmoji() {
|
||||
return StringUtils.stripToNull(aboutEmoji);
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return StringUtils.stripToNull(about);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,12 @@ public class Profile {
|
||||
@JsonProperty
|
||||
private String name;
|
||||
|
||||
@JsonProperty
|
||||
private String about;
|
||||
|
||||
@JsonProperty
|
||||
private String aboutEmoji;
|
||||
|
||||
@JsonProperty
|
||||
private String avatar;
|
||||
|
||||
@@ -52,13 +58,15 @@ public class Profile {
|
||||
|
||||
public Profile() {}
|
||||
|
||||
public Profile(String name, String avatar, String identityKey,
|
||||
public Profile(String name, String about, String aboutEmoji, String avatar, String identityKey,
|
||||
String unidentifiedAccess, boolean unrestrictedUnidentifiedAccess,
|
||||
UserCapabilities capabilities, String username, UUID uuid,
|
||||
ProfileKeyCredentialResponse credential,
|
||||
List<PaymentAddress> payments)
|
||||
{
|
||||
this.name = name;
|
||||
this.about = about;
|
||||
this.aboutEmoji = aboutEmoji;
|
||||
this.avatar = avatar;
|
||||
this.identityKey = identityKey;
|
||||
this.unidentifiedAccess = unidentifiedAccess;
|
||||
@@ -80,6 +88,14 @@ public class Profile {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return about;
|
||||
}
|
||||
|
||||
public String getAboutEmoji() {
|
||||
return aboutEmoji;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public String getAvatar() {
|
||||
return avatar;
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class ExperimentEnrollmentManager {
|
||||
|
||||
private final DynamicConfigurationManager dynamicConfigurationManager;
|
||||
|
||||
public ExperimentEnrollmentManager(final DynamicConfigurationManager dynamicConfigurationManager) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public boolean isEnrolled(final UUID accountUuid, final String experimentName) {
|
||||
final Optional<DynamicExperimentEnrollmentConfiguration> maybeConfiguration = dynamicConfigurationManager.getConfiguration().getExperimentEnrollmentConfiguration(experimentName);
|
||||
|
||||
final Set<UUID> enrolledUuids = maybeConfiguration.map(DynamicExperimentEnrollmentConfiguration::getEnrolledUuids)
|
||||
.orElse(Collections.emptySet());
|
||||
|
||||
final boolean enrolled;
|
||||
|
||||
if (enrolledUuids.contains(accountUuid)) {
|
||||
enrolled = true;
|
||||
} else {
|
||||
final int threshold = maybeConfiguration.map(DynamicExperimentEnrollmentConfiguration::getEnrollmentPercentage).orElse(0);
|
||||
final int enrollmentHash = ((accountUuid.hashCode() ^ experimentName.hashCode()) & Integer.MAX_VALUE) % 100;
|
||||
|
||||
enrolled = enrollmentHash < threshold;
|
||||
}
|
||||
|
||||
return enrolled;
|
||||
}
|
||||
}
|
||||
+242
-148
@@ -9,8 +9,14 @@ import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.RatioGauge;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.LuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisException;
|
||||
import org.whispersystems.textsecuregcm.redis.ReplicatedJedisPool;
|
||||
@@ -19,89 +25,197 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import redis.clients.jedis.exceptions.JedisException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.exceptions.JedisException;
|
||||
|
||||
public class ApnFallbackManager implements Managed, Runnable {
|
||||
public class ApnFallbackManager implements Managed {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ApnFallbackManager.class);
|
||||
|
||||
private static final String PENDING_NOTIFICATIONS_KEY = "PENDING_APN";
|
||||
private static final String SINGLETON_PENDING_NOTIFICATIONS_KEY = "PENDING_APN";
|
||||
static final String NEXT_SLOT_TO_PERSIST_KEY = "pending_notification_next_slot";
|
||||
|
||||
private static final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private static final Meter delivered = metricRegistry.meter(name(ApnFallbackManager.class, "voip_delivered"));
|
||||
private static final Meter sent = metricRegistry.meter(name(ApnFallbackManager.class, "voip_sent" ));
|
||||
private static final Meter retry = metricRegistry.meter(name(ApnFallbackManager.class, "voip_retry"));
|
||||
private static final Meter evicted = metricRegistry.meter(name(ApnFallbackManager.class, "voip_evicted"));
|
||||
private static final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private static final Meter delivered = metricRegistry.meter(name(ApnFallbackManager.class, "voip_delivered"));
|
||||
private static final Meter sent = metricRegistry.meter(name(ApnFallbackManager.class, "voip_sent" ));
|
||||
private static final Meter retry = metricRegistry.meter(name(ApnFallbackManager.class, "voip_retry"));
|
||||
private static final Meter evicted = metricRegistry.meter(name(ApnFallbackManager.class, "voip_evicted"));
|
||||
private static final Meter singletonDestinations = metricRegistry.meter(name(ApnFallbackManager.class, "singleton_destinations"));
|
||||
private static final Meter clusterDestinations = metricRegistry.meter(name(ApnFallbackManager.class, "cluster_destinations"));
|
||||
|
||||
static {
|
||||
metricRegistry.register(name(ApnFallbackManager.class, "voip_ratio"), new VoipRatioGauge(delivered, sent));
|
||||
}
|
||||
|
||||
private final APNSender apnSender;
|
||||
private final AccountsManager accountsManager;
|
||||
private final APNSender apnSender;
|
||||
private final AccountsManager accountsManager;
|
||||
private final FaultTolerantRedisCluster cluster;
|
||||
|
||||
private final ReplicatedJedisPool jedisPool;
|
||||
private final InsertOperation insertOperation;
|
||||
private final GetOperation getOperation;
|
||||
private final RemoveOperation removeOperation;
|
||||
private final LuaScript getSingletonScript;
|
||||
private final LuaScript removeSingletonScript;
|
||||
|
||||
private final ClusterLuaScript getClusterScript;
|
||||
private final ClusterLuaScript insertClusterScript;
|
||||
private final ClusterLuaScript removeClusterScript;
|
||||
|
||||
private AtomicBoolean running = new AtomicBoolean(false);
|
||||
private boolean finished;
|
||||
private final Thread singletonWorkerThread;
|
||||
private final Thread[] clusterWorkerThreads = new Thread[CLUSTER_WORKER_THREAD_COUNT];
|
||||
|
||||
private static final int CLUSTER_WORKER_THREAD_COUNT = 4;
|
||||
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
private class SingletonCacheWorker implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (running.get()) {
|
||||
try {
|
||||
for (final String numberAndDevice : getPendingDestinationsFromSingletonCache(100)) {
|
||||
singletonDestinations.mark();
|
||||
|
||||
Optional<Pair<String, Long>> separated = getSeparated(numberAndDevice);
|
||||
|
||||
if (!separated.isPresent()) {
|
||||
removeFromSingleton(numberAndDevice);
|
||||
continue;
|
||||
}
|
||||
|
||||
Optional<Account> account = accountsManager.get(separated.get().first());
|
||||
|
||||
if (!account.isPresent()) {
|
||||
removeFromSingleton(numberAndDevice);
|
||||
continue;
|
||||
}
|
||||
|
||||
Optional<Device> device = account.get().getDevice(separated.get().second());
|
||||
|
||||
if (!device.isPresent()) {
|
||||
removeFromSingleton(numberAndDevice);
|
||||
continue;
|
||||
}
|
||||
|
||||
sendNotification(account.get(), device.get());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.warn("Exception while operating", e);
|
||||
}
|
||||
|
||||
Util.sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ClusterCacheWorker implements Runnable {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (running.get()) {
|
||||
try {
|
||||
final long entriesProcessed = processNextSlot();
|
||||
|
||||
if (entriesProcessed == 0) {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("Exception while operating", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
long processNextSlot() {
|
||||
final int slot = getNextSlot();
|
||||
|
||||
List<String> pendingDestinations;
|
||||
long entriesProcessed = 0;
|
||||
|
||||
do {
|
||||
pendingDestinations = getPendingDestinationsFromClusterCache(slot, 100);
|
||||
entriesProcessed += pendingDestinations.size();
|
||||
|
||||
for (final String uuidAndDevice : pendingDestinations) {
|
||||
clusterDestinations.mark();
|
||||
|
||||
final Optional<Pair<String, Long>> separated = getSeparated(uuidAndDevice);
|
||||
|
||||
final Optional<Account> maybeAccount = separated.map(Pair::first)
|
||||
.map(UUID::fromString)
|
||||
.flatMap(accountsManager::get);
|
||||
|
||||
final Optional<Device> maybeDevice = separated.map(Pair::second)
|
||||
.flatMap(deviceId -> maybeAccount.flatMap(account -> account.getDevice(deviceId)));
|
||||
|
||||
if (maybeAccount.isPresent() && maybeDevice.isPresent()) {
|
||||
sendNotification(maybeAccount.get(), maybeDevice.get());
|
||||
} else {
|
||||
removeFromCluster(uuidAndDevice);
|
||||
}
|
||||
}
|
||||
} while (!pendingDestinations.isEmpty());
|
||||
|
||||
return entriesProcessed;
|
||||
}
|
||||
}
|
||||
|
||||
public ApnFallbackManager(ReplicatedJedisPool jedisPool,
|
||||
FaultTolerantRedisCluster cluster,
|
||||
APNSender apnSender,
|
||||
AccountsManager accountsManager)
|
||||
throws IOException
|
||||
{
|
||||
this.apnSender = apnSender;
|
||||
this.accountsManager = accountsManager;
|
||||
this.jedisPool = jedisPool;
|
||||
this.insertOperation = new InsertOperation(jedisPool);
|
||||
this.getOperation = new GetOperation(jedisPool);
|
||||
this.removeOperation = new RemoveOperation(jedisPool);
|
||||
}
|
||||
this.cluster = cluster;
|
||||
|
||||
public void schedule(Account account, Device device) throws RedisException {
|
||||
try {
|
||||
sent.mark();
|
||||
insertOperation.insert(account, device, System.currentTimeMillis() + (15 * 1000), (15 * 1000));
|
||||
} catch (JedisException e) {
|
||||
throw new RedisException(e);
|
||||
this.getSingletonScript = LuaScript.fromResource(jedisPool, "lua/apn/get.lua");
|
||||
this.removeSingletonScript = LuaScript.fromResource(jedisPool, "lua/apn/remove.lua");
|
||||
|
||||
this.getClusterScript = ClusterLuaScript.fromResource(cluster, "lua/apn/get.lua", ScriptOutputType.MULTI);
|
||||
this.insertClusterScript = ClusterLuaScript.fromResource(cluster, "lua/apn/insert.lua", ScriptOutputType.VALUE);
|
||||
this.removeClusterScript = ClusterLuaScript.fromResource(cluster, "lua/apn/remove.lua", ScriptOutputType.INTEGER);
|
||||
|
||||
this.singletonWorkerThread = new Thread(new SingletonCacheWorker(), "ApnFallbackManagerSingletonWorker");
|
||||
|
||||
for (int i = 0; i < this.clusterWorkerThreads.length; i++) {
|
||||
this.clusterWorkerThreads[i] = new Thread(new ClusterCacheWorker(), "ApnFallbackManagerClusterWorker-" + i);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isScheduled(Account account, Device device) throws RedisException {
|
||||
try {
|
||||
String endpoint = "apn_device::" + account.getNumber() + "::" + device.getId();
|
||||
public void schedule(Account account, Device device) throws RedisException {
|
||||
schedule(account, device, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
try (Jedis jedis = jedisPool.getReadResource()) {
|
||||
return jedis.zscore(PENDING_NOTIFICATIONS_KEY, endpoint) != null;
|
||||
}
|
||||
} catch (JedisException e) {
|
||||
@VisibleForTesting
|
||||
void schedule(Account account, Device device, long timestamp) throws RedisException {
|
||||
try {
|
||||
sent.mark();
|
||||
insert(account, device, timestamp + (15 * 1000), (15 * 1000));
|
||||
} catch (io.lettuce.core.RedisException e) {
|
||||
throw new RedisException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void cancel(Account account, Device device) throws RedisException {
|
||||
try {
|
||||
if (removeOperation.remove(account, device)) {
|
||||
if (remove(account, device)) {
|
||||
delivered.mark();
|
||||
}
|
||||
} catch (JedisException e) {
|
||||
} catch (JedisException | io.lettuce.core.RedisException e) {
|
||||
throw new RedisException(e);
|
||||
}
|
||||
}
|
||||
@@ -109,77 +223,45 @@ public class ApnFallbackManager implements Managed, Runnable {
|
||||
@Override
|
||||
public synchronized void start() {
|
||||
running.set(true);
|
||||
new Thread(this).start();
|
||||
singletonWorkerThread.start();
|
||||
|
||||
for (final Thread clusterWorkerThread : clusterWorkerThreads) {
|
||||
clusterWorkerThread.start();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
public synchronized void stop() throws InterruptedException {
|
||||
running.set(false);
|
||||
while (!finished) Util.wait(this);
|
||||
}
|
||||
singletonWorkerThread.join();
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (running.get()) {
|
||||
try {
|
||||
List<byte[]> pendingNotifications = getOperation.getPending(100);
|
||||
|
||||
for (byte[] pendingNotification : pendingNotifications) {
|
||||
String numberAndDevice = new String(pendingNotification);
|
||||
Optional<Pair<String, Long>> separated = getSeparated(numberAndDevice);
|
||||
|
||||
if (!separated.isPresent()) {
|
||||
removeOperation.remove(numberAndDevice);
|
||||
continue;
|
||||
}
|
||||
|
||||
Optional<Account> account = accountsManager.get(separated.get().first());
|
||||
|
||||
if (!account.isPresent()) {
|
||||
removeOperation.remove(numberAndDevice);
|
||||
continue;
|
||||
}
|
||||
|
||||
Optional<Device> device = account.get().getDevice(separated.get().second());
|
||||
|
||||
if (!device.isPresent()) {
|
||||
removeOperation.remove(numberAndDevice);
|
||||
continue;
|
||||
}
|
||||
|
||||
String apnId = device.get().getVoipApnId();
|
||||
|
||||
if (apnId == null) {
|
||||
removeOperation.remove(account.get(), device.get());
|
||||
continue;
|
||||
}
|
||||
|
||||
long deviceLastSeen = device.get().getLastSeen();
|
||||
|
||||
if (deviceLastSeen < System.currentTimeMillis() - TimeUnit.DAYS.toMillis(90)) {
|
||||
evicted.mark();
|
||||
removeOperation.remove(account.get(), device.get());
|
||||
continue;
|
||||
}
|
||||
|
||||
apnSender.sendMessage(new ApnMessage(apnId, separated.get().first(), separated.get().second(), true, Optional.empty()));
|
||||
retry.mark();
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.warn("Exception while operating", e);
|
||||
}
|
||||
|
||||
Util.sleep(1000);
|
||||
}
|
||||
|
||||
synchronized (ApnFallbackManager.this) {
|
||||
finished = true;
|
||||
notifyAll();
|
||||
for (final Thread clusterWorkerThread : clusterWorkerThreads) {
|
||||
clusterWorkerThread.join();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<Pair<String, Long>> getSeparated(String encoded) {
|
||||
private void sendNotification(final Account account, final Device device) {
|
||||
String apnId = device.getVoipApnId();
|
||||
|
||||
if (apnId == null) {
|
||||
remove(account, device);
|
||||
return;
|
||||
}
|
||||
|
||||
long deviceLastSeen = device.getLastSeen();
|
||||
|
||||
if (deviceLastSeen < System.currentTimeMillis() - TimeUnit.DAYS.toMillis(90)) {
|
||||
evicted.mark();
|
||||
remove(account, device);
|
||||
return;
|
||||
}
|
||||
|
||||
apnSender.sendMessage(new ApnMessage(apnId, account.getNumber(), device.getId(), true, Optional.empty()));
|
||||
retry.mark();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<Pair<String, Long>> getSeparated(String encoded) {
|
||||
try {
|
||||
if (encoded == null) return Optional.empty();
|
||||
|
||||
@@ -197,66 +279,78 @@ public class ApnFallbackManager implements Managed, Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
private static class RemoveOperation {
|
||||
|
||||
private final LuaScript luaScript;
|
||||
|
||||
RemoveOperation(ReplicatedJedisPool jedisPool) throws IOException {
|
||||
this.luaScript = LuaScript.fromResource(jedisPool, "lua/apn/remove.lua");
|
||||
}
|
||||
|
||||
boolean remove(Account account, Device device) {
|
||||
String endpoint = "apn_device::" + account.getNumber() + "::" + device.getId();
|
||||
return remove(endpoint);
|
||||
}
|
||||
|
||||
boolean remove(String endpoint) {
|
||||
if (!PENDING_NOTIFICATIONS_KEY.equals(endpoint)) {
|
||||
List<byte[]> keys = Arrays.asList(PENDING_NOTIFICATIONS_KEY.getBytes(), endpoint.getBytes());
|
||||
List<byte[]> args = Collections.emptyList();
|
||||
|
||||
return ((long)luaScript.execute(keys, args)) > 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
private boolean remove(Account account, Device device) {
|
||||
final boolean removedFromSingleton = removeFromSingleton(getSingletonEndpointKey(account, device));
|
||||
final boolean removedFromCluster = removeFromCluster(getClusterEndpointKey(account, device));
|
||||
|
||||
return removedFromSingleton || removedFromCluster;
|
||||
}
|
||||
|
||||
private static class GetOperation {
|
||||
private boolean removeFromSingleton(String endpoint) {
|
||||
if (!SINGLETON_PENDING_NOTIFICATIONS_KEY.equals(endpoint)) {
|
||||
List<byte[]> keys = Arrays.asList(SINGLETON_PENDING_NOTIFICATIONS_KEY.getBytes(), endpoint.getBytes());
|
||||
List<byte[]> args = Collections.emptyList();
|
||||
|
||||
private final LuaScript luaScript;
|
||||
|
||||
GetOperation(ReplicatedJedisPool jedisPool) throws IOException {
|
||||
this.luaScript = LuaScript.fromResource(jedisPool, "lua/apn/get.lua");
|
||||
return ((long)removeSingletonScript.execute(keys, args)) > 0;
|
||||
}
|
||||
|
||||
@SuppressWarnings("SameParameterValue")
|
||||
List<byte[]> getPending(int limit) {
|
||||
List<byte[]> keys = Arrays.asList(PENDING_NOTIFICATIONS_KEY.getBytes());
|
||||
List<byte[]> args = Arrays.asList(String.valueOf(System.currentTimeMillis()).getBytes(), String.valueOf(limit).getBytes());
|
||||
|
||||
return (List<byte[]>) luaScript.execute(keys, args);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static class InsertOperation {
|
||||
private boolean removeFromCluster(final String endpoint) {
|
||||
final long removed = (long)removeClusterScript.execute(List.of(getClusterPendingNotificationQueueKey(endpoint), endpoint),
|
||||
Collections.emptyList());
|
||||
|
||||
private final LuaScript luaScript;
|
||||
return removed > 0;
|
||||
}
|
||||
|
||||
InsertOperation(ReplicatedJedisPool jedisPool) throws IOException {
|
||||
this.luaScript = LuaScript.fromResource(jedisPool, "lua/apn/insert.lua");
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<String> getPendingDestinationsFromSingletonCache(final int limit) {
|
||||
List<byte[]> keys = List.of(SINGLETON_PENDING_NOTIFICATIONS_KEY.getBytes());
|
||||
List<byte[]> args = List.of(String.valueOf(System.currentTimeMillis()).getBytes(), String.valueOf(limit).getBytes());
|
||||
|
||||
public void insert(Account account, Device device, long timestamp, long interval) {
|
||||
String endpoint = "apn_device::" + account.getNumber() + "::" + device.getId();
|
||||
return ((List<byte[]>) getSingletonScript.execute(keys, args))
|
||||
.stream()
|
||||
.map(bytes -> new String(bytes, StandardCharsets.UTF_8))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<byte[]> keys = Arrays.asList(PENDING_NOTIFICATIONS_KEY.getBytes(), endpoint.getBytes());
|
||||
List<byte[]> args = Arrays.asList(String.valueOf(timestamp).getBytes(), String.valueOf(interval).getBytes(),
|
||||
account.getNumber().getBytes(), String.valueOf(device.getId()).getBytes());
|
||||
@SuppressWarnings("unchecked")
|
||||
@VisibleForTesting
|
||||
List<String> getPendingDestinationsFromClusterCache(final int slot, final int limit) {
|
||||
return (List<String>)getClusterScript.execute(List.of(getClusterPendingNotificationQueueKey(slot)),
|
||||
List.of(String.valueOf(System.currentTimeMillis()), String.valueOf(limit)));
|
||||
}
|
||||
|
||||
luaScript.execute(keys, args);
|
||||
}
|
||||
private void insert(final Account account, final Device device, final long timestamp, final long interval) {
|
||||
final String endpoint = getClusterEndpointKey(account, device);
|
||||
|
||||
insertClusterScript.execute(List.of(getClusterPendingNotificationQueueKey(endpoint), endpoint),
|
||||
List.of(String.valueOf(timestamp),
|
||||
String.valueOf(interval),
|
||||
account.getUuid().toString(),
|
||||
String.valueOf(device.getId())));
|
||||
}
|
||||
|
||||
private String getSingletonEndpointKey(final Account account, final Device device) {
|
||||
return "apn_device::" + account.getNumber() + "::" + device.getId();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getClusterEndpointKey(final Account account, final Device device) {
|
||||
return "apn_device::{" + account.getUuid() + "::" + device.getId() + "}";
|
||||
}
|
||||
|
||||
private String getClusterPendingNotificationQueueKey(final String endpoint) {
|
||||
return getClusterPendingNotificationQueueKey(SlotHash.getSlot(endpoint));
|
||||
}
|
||||
|
||||
private String getClusterPendingNotificationQueueKey(final int slot) {
|
||||
return SINGLETON_PENDING_NOTIFICATIONS_KEY + "::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}";
|
||||
}
|
||||
|
||||
private int getNextSlot() {
|
||||
return (int)(cluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY)) % SlotHash.SLOT_COUNT);
|
||||
}
|
||||
|
||||
private static class VoipRatioGauge extends RatioGauge {
|
||||
|
||||
@@ -38,6 +38,7 @@ public class ReceiptSender {
|
||||
|
||||
Account destinationAccount = getDestinationAccount(destination);
|
||||
Envelope.Builder message = Envelope.newBuilder()
|
||||
.setServerTimestamp(System.currentTimeMillis())
|
||||
.setSource(source.getNumber())
|
||||
.setSourceUuid(source.getUuid().toString())
|
||||
.setSourceDevice((int) source.getAuthenticatedDevice().get().getId())
|
||||
|
||||
-1
@@ -82,7 +82,6 @@ public class FaultTolerantRedisCluster {
|
||||
this.clusterClient.setOptions(ClusterClientOptions.builder()
|
||||
.validateClusterNodeMembership(false)
|
||||
.topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
|
||||
.enablePeriodicRefresh()
|
||||
.enableAllAdaptiveRefreshTriggers()
|
||||
.build())
|
||||
.build());
|
||||
|
||||
@@ -139,7 +139,9 @@ public class Account implements Principal {
|
||||
}
|
||||
|
||||
public boolean isGv1MigrationSupported() {
|
||||
return devices.stream().allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isGv1Migration());
|
||||
return devices.stream()
|
||||
.filter(Device::isEnabled)
|
||||
.allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isGv1Migration());
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
|
||||
+3
-2
@@ -119,9 +119,10 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
List<Account> chunkAccounts = readChunk(fromUuid, chunkSize);
|
||||
|
||||
if (chunkAccounts.isEmpty()) {
|
||||
logger.info("Finished crawl");
|
||||
listeners.forEach(listener -> listener.onCrawlEnd(fromUuid));
|
||||
cache.setLastUuid(Optional.empty());
|
||||
cache.clearAccelerate();
|
||||
cache.setAccelerated(false);
|
||||
} else {
|
||||
try {
|
||||
for (AccountDatabaseCrawlerListener listener : listeners) {
|
||||
@@ -130,7 +131,7 @@ public class AccountDatabaseCrawler implements Managed, Runnable {
|
||||
cache.setLastUuid(Optional.of(chunkAccounts.get(chunkAccounts.size() - 1).getUuid()));
|
||||
} catch (AccountDatabaseCrawlerRestartException e) {
|
||||
cache.setLastUuid(Optional.empty());
|
||||
cache.clearAccelerate();
|
||||
cache.setAccelerated(false);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+6
-2
@@ -31,8 +31,12 @@ public class AccountDatabaseCrawlerCache {
|
||||
this.unlockClusterScript = ClusterLuaScript.fromResource(cacheCluster, "lua/account_database_crawler/unlock.lua", ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
public void clearAccelerate() {
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(ACCELERATE_KEY));
|
||||
public void setAccelerated(final boolean accelerated) {
|
||||
if (accelerated) {
|
||||
cacheCluster.useCluster(connection -> connection.sync().set(ACCELERATE_KEY, "1"));
|
||||
} else {
|
||||
cacheCluster.useCluster(connection -> connection.sync().del(ACCELERATE_KEY));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAccelerated() {
|
||||
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.appconfig.AmazonAppConfig;
|
||||
import com.amazonaws.services.appconfig.AmazonAppConfigClient;
|
||||
import com.amazonaws.services.appconfig.model.GetConfigurationRequest;
|
||||
import com.amazonaws.services.appconfig.model.GetConfigurationResult;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public class DynamicConfigurationManager implements Managed {
|
||||
|
||||
private final String application;
|
||||
private final String environment;
|
||||
private final String configurationName;
|
||||
private final String clientId;
|
||||
private final AmazonAppConfig appConfigClient;
|
||||
|
||||
private final AtomicReference<DynamicConfiguration> configuration = new AtomicReference<>();
|
||||
private final AtomicBoolean running = new AtomicBoolean(true);
|
||||
private final Logger logger = LoggerFactory.getLogger(DynamicConfigurationManager.class);
|
||||
|
||||
private GetConfigurationResult lastConfigResult;
|
||||
|
||||
private boolean initialized = false;
|
||||
|
||||
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(new YAMLFactory()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
public DynamicConfigurationManager(String application, String environment, String configurationName) {
|
||||
this(AmazonAppConfigClient.builder()
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(10000).withRequestTimeout(10000))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance())
|
||||
.build(),
|
||||
application, environment, configurationName, UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicConfigurationManager(AmazonAppConfig appConfigClient, String application, String environment, String configurationName, String clientId) {
|
||||
this.appConfigClient = appConfigClient;
|
||||
this.application = application;
|
||||
this.environment = environment;
|
||||
this.configurationName = configurationName;
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public DynamicConfiguration getConfiguration() {
|
||||
synchronized (this) {
|
||||
while (!initialized) Util.wait(this);
|
||||
}
|
||||
|
||||
return configuration.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
configuration.set(retrieveInitialDynamicConfiguration());
|
||||
|
||||
synchronized (this) {
|
||||
this.initialized = true;
|
||||
this.notifyAll();
|
||||
}
|
||||
|
||||
new Thread(() -> {
|
||||
while (running.get()) {
|
||||
try {
|
||||
retrieveDynamicConfiguration().ifPresent(configuration::set);
|
||||
} catch (Throwable t) {
|
||||
logger.warn("Error retrieving dynamic configuration", t);
|
||||
}
|
||||
|
||||
Util.sleep(5000);
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running.set(false);
|
||||
}
|
||||
|
||||
private Optional<DynamicConfiguration> retrieveDynamicConfiguration() throws JsonProcessingException {
|
||||
final String previousVersion = lastConfigResult != null ? lastConfigResult.getConfigurationVersion() : null;
|
||||
|
||||
lastConfigResult = appConfigClient.getConfiguration(new GetConfigurationRequest().withApplication(application)
|
||||
.withEnvironment(environment)
|
||||
.withConfiguration(configurationName)
|
||||
.withClientId(clientId)
|
||||
.withClientConfigurationVersion(previousVersion));
|
||||
|
||||
final Optional<DynamicConfiguration> maybeDynamicConfiguration;
|
||||
|
||||
if (!StringUtils.equals(lastConfigResult.getConfigurationVersion(), previousVersion)) {
|
||||
logger.info("Received new config version: {}", lastConfigResult.getConfigurationVersion());
|
||||
maybeDynamicConfiguration = Optional.of(OBJECT_MAPPER.readValue(StandardCharsets.UTF_8.decode(lastConfigResult.getContent().asReadOnlyBuffer()).toString(), DynamicConfiguration.class));
|
||||
} else {
|
||||
// No change since last version
|
||||
maybeDynamicConfiguration = Optional.empty();
|
||||
}
|
||||
|
||||
return maybeDynamicConfiguration;
|
||||
}
|
||||
|
||||
private DynamicConfiguration retrieveInitialDynamicConfiguration() {
|
||||
for (;;) {
|
||||
try {
|
||||
final Optional<DynamicConfiguration> maybeDynamicConfiguration = retrieveDynamicConfiguration();
|
||||
|
||||
if (maybeDynamicConfiguration.isPresent()) {
|
||||
return maybeDynamicConfiguration.get();
|
||||
} else {
|
||||
throw new IllegalStateException("No initial configuration available");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
logger.warn("Error retrieving initial dynamic configuration", t);
|
||||
Util.sleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,23 +4,33 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.codahale.metrics.Counter;
|
||||
import com.codahale.metrics.Meter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.Timer;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import org.jdbi.v3.core.JdbiException;
|
||||
import org.jdbi.v3.core.statement.PreparedBatch;
|
||||
import org.jdbi.v3.core.statement.UnableToExecuteStatementException;
|
||||
import org.jdbi.v3.core.transaction.SerializableTransactionRunner;
|
||||
import org.jdbi.v3.core.transaction.TransactionIsolationLevel;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKey;
|
||||
import org.whispersystems.textsecuregcm.storage.mappers.KeyRecordRowMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class Keys {
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Meter fallbackMeter = metricRegistry.meter(name(Keys.class, "fallback"));
|
||||
private final Timer storeTimer = metricRegistry.timer(name(Keys.class, "store" ));
|
||||
private final Timer getDevicetTimer = metricRegistry.timer(name(Keys.class, "getDevice"));
|
||||
private final Timer getTimer = metricRegistry.timer(name(Keys.class, "get" ));
|
||||
@@ -28,58 +38,81 @@ public class Keys {
|
||||
private final Timer vacuumTimer = metricRegistry.timer(name(Keys.class, "vacuum" ));
|
||||
|
||||
private final FaultTolerantDatabase database;
|
||||
private final Retry retry;
|
||||
|
||||
public Keys(FaultTolerantDatabase database) {
|
||||
public Keys(FaultTolerantDatabase database, RetryConfiguration retryConfiguration) {
|
||||
this.database = database;
|
||||
this.database.getDatabase().registerRowMapper(new KeyRecordRowMapper());
|
||||
this.database.getDatabase().setTransactionHandler(new SerializableTransactionRunner());
|
||||
this.database.getDatabase().getConfig(SerializableTransactionRunner.Configuration.class).setMaxRetries(10);
|
||||
|
||||
this.retry = Retry.of("keys", retryConfiguration.toRetryConfigBuilder().build());
|
||||
}
|
||||
|
||||
public void store(String number, long deviceId, List<PreKey> keys) {
|
||||
database.use(jdbi -> jdbi.useTransaction(TransactionIsolationLevel.SERIALIZABLE, handle -> {
|
||||
try (Timer.Context ignored = storeTimer.time()) {
|
||||
PreparedBatch preparedBatch = handle.prepareBatch("INSERT INTO keys (number, device_id, key_id, public_key) VALUES (:number, :device_id, :key_id, :public_key)");
|
||||
retry.executeRunnable(() -> {
|
||||
database.use(jdbi -> jdbi.useTransaction(TransactionIsolationLevel.SERIALIZABLE, handle -> {
|
||||
try (Timer.Context ignored = storeTimer.time()) {
|
||||
PreparedBatch preparedBatch = handle.prepareBatch("INSERT INTO keys (number, device_id, key_id, public_key) VALUES (:number, :device_id, :key_id, :public_key)");
|
||||
|
||||
for (PreKey key : keys) {
|
||||
preparedBatch.bind("number", number)
|
||||
.bind("device_id", deviceId)
|
||||
.bind("key_id", key.getKeyId())
|
||||
.bind("public_key", key.getPublicKey())
|
||||
.add();
|
||||
for (PreKey key : keys) {
|
||||
preparedBatch.bind("number", number)
|
||||
.bind("device_id", deviceId)
|
||||
.bind("key_id", key.getKeyId())
|
||||
.bind("public_key", key.getPublicKey())
|
||||
.add();
|
||||
}
|
||||
|
||||
handle.createUpdate("DELETE FROM keys WHERE number = :number AND device_id = :device_id")
|
||||
.bind("number", number)
|
||||
.bind("device_id", deviceId)
|
||||
.execute();
|
||||
|
||||
preparedBatch.execute();
|
||||
}
|
||||
|
||||
handle.createUpdate("DELETE FROM keys WHERE number = :number AND device_id = :device_id")
|
||||
.bind("number", number)
|
||||
.bind("device_id", deviceId)
|
||||
.execute();
|
||||
|
||||
preparedBatch.execute();
|
||||
}
|
||||
}));
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
public List<KeyRecord> get(String number, long deviceId) {
|
||||
return database.with(jdbi -> jdbi.inTransaction(TransactionIsolationLevel.SERIALIZABLE, handle -> {
|
||||
try (Timer.Context ignored = getDevicetTimer.time()) {
|
||||
return handle.createQuery("DELETE FROM keys WHERE id IN (SELECT id FROM keys WHERE number = :number AND device_id = :device_id ORDER BY key_id ASC LIMIT 1) RETURNING *")
|
||||
.bind("number", number)
|
||||
.bind("device_id", deviceId)
|
||||
.mapTo(KeyRecord.class)
|
||||
.list();
|
||||
}
|
||||
}));
|
||||
/* try {
|
||||
return database.with(jdbi -> jdbi.inTransaction(TransactionIsolationLevel.SERIALIZABLE, handle -> {
|
||||
try (Timer.Context ignored = getDevicetTimer.time()) {
|
||||
return handle.createQuery("DELETE FROM keys WHERE id IN (SELECT id FROM keys WHERE number = :number AND device_id = :device_id ORDER BY key_id ASC LIMIT 1) RETURNING *")
|
||||
.bind("number", number)
|
||||
.bind("device_id", deviceId)
|
||||
.mapTo(KeyRecord.class)
|
||||
.list();
|
||||
}
|
||||
}));
|
||||
} catch (JdbiException e) {
|
||||
// TODO 2021-01-13 Replace this with a retry once desktop clients better handle HTTP/500 responses
|
||||
fallbackMeter.mark();
|
||||
return Collections.emptyList();
|
||||
} */
|
||||
|
||||
// 2021-01-15 Emergency service recovery measure
|
||||
return new LinkedList<>();
|
||||
}
|
||||
|
||||
public List<KeyRecord> get(String number) {
|
||||
return database.with(jdbi -> jdbi.inTransaction(TransactionIsolationLevel.SERIALIZABLE, handle -> {
|
||||
try (Timer.Context ignored = getTimer.time()) {
|
||||
return handle.createQuery("DELETE FROM keys WHERE id IN (SELECT DISTINCT ON (number, device_id) id FROM keys WHERE number = :number ORDER BY number, device_id, key_id ASC) RETURNING *")
|
||||
.bind("number", number)
|
||||
.mapTo(KeyRecord.class)
|
||||
.list();
|
||||
}
|
||||
}));
|
||||
/* try {
|
||||
return database.with(jdbi -> jdbi.inTransaction(TransactionIsolationLevel.SERIALIZABLE, handle -> {
|
||||
try (Timer.Context ignored = getTimer.time()) {
|
||||
return handle.createQuery("DELETE FROM keys WHERE id IN (SELECT DISTINCT ON (number, device_id) id FROM keys WHERE number = :number ORDER BY number, device_id, key_id ASC) RETURNING *")
|
||||
.bind("number", number)
|
||||
.mapTo(KeyRecord.class)
|
||||
.list();
|
||||
}
|
||||
}));
|
||||
} catch (JdbiException e) {
|
||||
// TODO 2021-01-13 Replace this with a retry once desktop clients better handle HTTP/500 responses
|
||||
fallbackMeter.mark();
|
||||
return Collections.emptyList();
|
||||
} */
|
||||
|
||||
// 2021-01-15 Emergency service recovery measure
|
||||
return new LinkedList<>();
|
||||
}
|
||||
|
||||
public int getCount(String number, long deviceId) {
|
||||
|
||||
+41
-28
@@ -28,14 +28,15 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class MessagePersister implements Managed {
|
||||
|
||||
private final MessagesCache messagesCache;
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final MessagesCache messagesCache;
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final FeatureFlagsManager featureFlagsManager;
|
||||
|
||||
private final Duration persistDelay;
|
||||
|
||||
private final Thread workerThread;
|
||||
private volatile boolean running;
|
||||
private final Thread[] workerThreads = new Thread[WORKER_THREAD_COUNT];
|
||||
private volatile boolean running;
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Timer getQueuesTimer = metricRegistry.timer(name(MessagePersister.class, "getQueues"));
|
||||
@@ -48,30 +49,37 @@ public class MessagePersister implements Managed {
|
||||
static final int QUEUE_BATCH_LIMIT = 100;
|
||||
static final int MESSAGE_BATCH_LIMIT = 100;
|
||||
|
||||
private static final int WORKER_THREAD_COUNT = 4;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache, final MessagesManager messagesManager, final AccountsManager accountsManager, final Duration persistDelay) {
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.persistDelay = persistDelay;
|
||||
public MessagePersister(final MessagesCache messagesCache, final MessagesManager messagesManager, final AccountsManager accountsManager, final FeatureFlagsManager featureFlagsManager, final Duration persistDelay) {
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.featureFlagsManager = featureFlagsManager;
|
||||
this.persistDelay = persistDelay;
|
||||
|
||||
this.workerThread = new Thread(() -> {
|
||||
while (running) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextQueues(Instant.now());
|
||||
queueCountHistogram.update(queuesPersisted);
|
||||
for (int i = 0; i < workerThreads.length; i++) {
|
||||
workerThreads[i] = new Thread(() -> {
|
||||
while (running) {
|
||||
if (featureFlagsManager.isFeatureFlagActive("DISABLE_MESSAGE_PERSISTER")) {
|
||||
Util.sleep(1000);
|
||||
} else {
|
||||
try {
|
||||
final int queuesPersisted = persistNextQueues(Instant.now());
|
||||
queueCountHistogram.update(queuesPersisted);
|
||||
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
}
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
}
|
||||
}
|
||||
}, "MessagePersisterWorker");
|
||||
|
||||
metricRegistry.gauge(name(getClass(), "workerThreadRunning"), () -> () -> workerThread.isAlive() ? 1 : 0);
|
||||
}, "MessagePersisterWorker-" + i);
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -82,17 +90,22 @@ public class MessagePersister implements Managed {
|
||||
@Override
|
||||
public void start() {
|
||||
running = true;
|
||||
workerThread.start();
|
||||
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
workerThread.start();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
|
||||
try {
|
||||
workerThread.join();
|
||||
} catch (final InterruptedException e) {
|
||||
logger.warn("Interrupted while waiting for worker thread to complete current operation");
|
||||
for (final Thread workerThread : workerThreads) {
|
||||
try {
|
||||
workerThread.join();
|
||||
} catch (final InterruptedException e) {
|
||||
logger.warn("Interrupted while waiting for worker thread to complete current operation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,6 @@ public class Messages {
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private final Timer storeTimer = metricRegistry.timer(name(Messages.class, "store" ));
|
||||
private final Timer loadTimer = metricRegistry.timer(name(Messages.class, "load" ));
|
||||
private final Timer hasMessagesTimer = metricRegistry.timer(name(Messages.class, "hasMessages" ));
|
||||
private final Timer removeBySourceTimer = metricRegistry.timer(name(Messages.class, "removeBySource"));
|
||||
private final Timer removeByGuidTimer = metricRegistry.timer(name(Messages.class, "removeByGuid" ));
|
||||
private final Timer removeByIdTimer = metricRegistry.timer(name(Messages.class, "removeById" ));
|
||||
|
||||
@@ -48,7 +48,8 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class MessagesCache extends RedisClusterPubSubAdapter<String, String> implements Managed {
|
||||
|
||||
private final FaultTolerantRedisCluster redisCluster;
|
||||
private final FaultTolerantRedisCluster insertCluster;
|
||||
private final FaultTolerantRedisCluster readDeleteCluster;
|
||||
private final FaultTolerantPubSubConnection<String, String> pubSubConnection;
|
||||
|
||||
private final ExecutorService notificationExecutorService;
|
||||
@@ -93,20 +94,21 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class);
|
||||
|
||||
public MessagesCache(final FaultTolerantRedisCluster redisCluster, final ExecutorService notificationExecutorService) throws IOException {
|
||||
public MessagesCache(final FaultTolerantRedisCluster insertCluster, final FaultTolerantRedisCluster readDeleteCluster, final ExecutorService notificationExecutorService) throws IOException {
|
||||
|
||||
this.redisCluster = redisCluster;
|
||||
this.pubSubConnection = redisCluster.createPubSubConnection();
|
||||
this.insertCluster = insertCluster;
|
||||
this.readDeleteCluster = readDeleteCluster;
|
||||
this.pubSubConnection = readDeleteCluster.createPubSubConnection();
|
||||
|
||||
this.notificationExecutorService = notificationExecutorService;
|
||||
|
||||
this.insertScript = ClusterLuaScript.fromResource(redisCluster, "lua/insert_item.lua", ScriptOutputType.INTEGER);
|
||||
this.removeByIdScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_item_by_id.lua", ScriptOutputType.VALUE);
|
||||
this.removeBySenderScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_item_by_sender.lua", ScriptOutputType.VALUE);
|
||||
this.removeByGuidScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_item_by_guid.lua", ScriptOutputType.MULTI);
|
||||
this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.MULTI);
|
||||
this.removeQueueScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_queue.lua", ScriptOutputType.STATUS);
|
||||
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_queues_to_persist.lua", ScriptOutputType.MULTI);
|
||||
this.insertScript = ClusterLuaScript.fromResource(insertCluster, "lua/insert_item.lua", ScriptOutputType.INTEGER);
|
||||
this.removeByIdScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/remove_item_by_id.lua", ScriptOutputType.VALUE);
|
||||
this.removeBySenderScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/remove_item_by_sender.lua", ScriptOutputType.VALUE);
|
||||
this.removeByGuidScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/remove_item_by_guid.lua", ScriptOutputType.MULTI);
|
||||
this.getItemsScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/get_items.lua", ScriptOutputType.MULTI);
|
||||
this.removeQueueScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/remove_queue.lua", ScriptOutputType.STATUS);
|
||||
this.getQueuesToPersistScript = ClusterLuaScript.fromResource(readDeleteCluster, "lua/get_queues_to_persist.lua", ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -125,6 +127,8 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
private void resubscribeAll() {
|
||||
logger.info("Got topology change event, resubscribing all keyspace notifications");
|
||||
|
||||
final Set<String> queueNames;
|
||||
|
||||
synchronized (messageListenersByQueueName) {
|
||||
@@ -154,7 +158,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
insertEphemeralTimer.record(() -> {
|
||||
final byte[] ephemeralQueueKey = getEphemeralMessageQueueKey(destinationUuid, destinationDevice);
|
||||
|
||||
redisCluster.useBinaryCluster(connection -> {
|
||||
insertCluster.useBinaryCluster(connection -> {
|
||||
connection.sync().rpush(ephemeralQueueKey, message.toByteArray());
|
||||
connection.sync().expire(ephemeralQueueKey, MAX_EPHEMERAL_MESSAGE_DELAY.toSeconds());
|
||||
});
|
||||
@@ -223,7 +227,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
public boolean hasMessages(final UUID destinationUuid, final long destinationDevice) {
|
||||
return redisCluster.withBinaryCluster(connection -> connection.sync().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) > 0);
|
||||
return readDeleteCluster.withBinaryCluster(connection -> connection.sync().zcard(getMessageQueueKey(destinationUuid, destinationDevice)) > 0);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -260,7 +264,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
@VisibleForTesting
|
||||
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final long destinationDevice, final int limit) {
|
||||
return getMessagesTimer.record(() -> {
|
||||
final List<ScoredValue<byte[]>> scoredMessages = redisCluster.withBinaryCluster(connection -> connection.sync().zrangeWithScores(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
final List<ScoredValue<byte[]>> scoredMessages = readDeleteCluster.withBinaryCluster(connection -> connection.sync().zrangeWithScores(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
final List<MessageProtos.Envelope> envelopes = new ArrayList<>(scoredMessages.size());
|
||||
|
||||
for (final ScoredValue<byte[]> scoredMessage : scoredMessages) {
|
||||
@@ -283,7 +287,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
Optional<MessageProtos.Envelope> takeEphemeralMessage(final UUID destinationUuid, final long destinationDevice, final long currentTimeMillis) {
|
||||
final long earliestAllowableTimestamp = currentTimeMillis - MAX_EPHEMERAL_MESSAGE_DELAY.toMillis();
|
||||
|
||||
return takeEphemeralMessageTimer.record(() -> redisCluster.withBinaryCluster(connection -> {
|
||||
return takeEphemeralMessageTimer.record(() -> readDeleteCluster.withBinaryCluster(connection -> {
|
||||
byte[] messageBytes;
|
||||
|
||||
while ((messageBytes = connection.sync().lpop(getEphemeralMessageQueueKey(destinationUuid, destinationDevice))) != null) {
|
||||
@@ -320,7 +324,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
int getNextSlotToPersist() {
|
||||
return (int)(redisCluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY)) % SlotHash.SLOT_COUNT);
|
||||
return (int)(readDeleteCluster.withCluster(connection -> connection.sync().incr(NEXT_SLOT_TO_PERSIST_KEY)) % SlotHash.SLOT_COUNT);
|
||||
}
|
||||
|
||||
List<String> getQueuesToPersist(final int slot, final Instant maxTime, final int limit) {
|
||||
@@ -331,15 +335,15 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
}
|
||||
|
||||
void addQueueToPersist(final UUID accountUuid, final long deviceId) {
|
||||
redisCluster.useBinaryCluster(connection -> connection.sync().zadd(getQueueIndexKey(accountUuid, deviceId), ZAddArgs.Builder.nx(), System.currentTimeMillis(), getMessageQueueKey(accountUuid, deviceId)));
|
||||
readDeleteCluster.useBinaryCluster(connection -> connection.sync().zadd(getQueueIndexKey(accountUuid, deviceId), ZAddArgs.Builder.nx(), System.currentTimeMillis(), getMessageQueueKey(accountUuid, deviceId)));
|
||||
}
|
||||
|
||||
void lockQueueForPersistence(final UUID accountUuid, final long deviceId) {
|
||||
redisCluster.useBinaryCluster(connection -> connection.sync().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE));
|
||||
readDeleteCluster.useBinaryCluster(connection -> connection.sync().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE));
|
||||
}
|
||||
|
||||
void unlockQueueForPersistence(final UUID accountUuid, final long deviceId) {
|
||||
redisCluster.useBinaryCluster(connection -> connection.sync().del(getPersistInProgressKey(accountUuid, deviceId)));
|
||||
readDeleteCluster.useBinaryCluster(connection -> connection.sync().del(getPersistInProgressKey(accountUuid, deviceId)));
|
||||
}
|
||||
|
||||
public void addMessageAvailabilityListener(final UUID destinationUuid, final long deviceId, final MessageAvailabilityListener listener) {
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Index;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
|
||||
import com.amazonaws.services.dynamodbv2.document.api.QueryApi;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
|
||||
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
import static io.micrometer.core.instrument.Metrics.counter;
|
||||
import static io.micrometer.core.instrument.Metrics.timer;
|
||||
|
||||
public class MessagesDynamoDb {
|
||||
private static final int MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE = 25; // This was arbitrarily chosen and may be entirely too high.
|
||||
private static final int DYNAMO_DB_MAX_BATCH_SIZE = 25; // This limit comes from Amazon Dynamo DB itself. It will reject batch writes larger than this.
|
||||
public static final int RESULT_SET_CHUNK_SIZE = 100;
|
||||
|
||||
private static final String KEY_PARTITION = "H";
|
||||
private static final String KEY_SORT = "S";
|
||||
private static final String LOCAL_INDEX_MESSAGE_UUID_NAME = "Message_UUID_Index";
|
||||
private static final String LOCAL_INDEX_MESSAGE_UUID_KEY_SORT = "U";
|
||||
|
||||
private static final String KEY_TYPE = "T";
|
||||
private static final String KEY_RELAY = "R";
|
||||
private static final String KEY_TIMESTAMP = "TS";
|
||||
private static final String KEY_SOURCE = "SN";
|
||||
private static final String KEY_SOURCE_UUID = "SU";
|
||||
private static final String KEY_SOURCE_DEVICE = "SD";
|
||||
private static final String KEY_MESSAGE = "M";
|
||||
private static final String KEY_CONTENT = "C";
|
||||
private static final String KEY_TTL = "E";
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private final Timer batchWriteItemsFirstPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "true");
|
||||
private final Timer batchWriteItemsRetryPass = timer(name(getClass(), "batchWriteItems"), "firstAttempt", "false");
|
||||
private final Counter batchWriteItemsUnprocessed = counter(name(getClass(), "batchWriteItemsUnprocessed"));
|
||||
private final Timer storeTimer = timer(name(getClass(), "store"));
|
||||
private final Timer loadTimer = timer(name(getClass(), "load"));
|
||||
private final Timer deleteBySourceAndTimestamp = timer(name(getClass(), "delete", "sourceAndTimestamp"));
|
||||
private final Timer deleteByGuid = timer(name(getClass(), "delete", "guid"));
|
||||
private final Timer deleteByAccount = timer(name(getClass(), "delete", "account"));
|
||||
private final Timer deleteByDevice = timer(name(getClass(), "delete", "device"));
|
||||
|
||||
private final DynamoDB dynamoDb;
|
||||
private final String tableName;
|
||||
private final Duration timeToLive;
|
||||
|
||||
public MessagesDynamoDb(DynamoDB dynamoDb, String tableName, Duration timeToLive) {
|
||||
this.dynamoDb = dynamoDb;
|
||||
this.tableName = tableName;
|
||||
this.timeToLive = timeToLive;
|
||||
}
|
||||
|
||||
public void store(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
storeTimer.record(() -> doInBatches(messages, (messageBatch) -> storeBatch(messageBatch, destinationAccountUuid, destinationDeviceId), DYNAMO_DB_MAX_BATCH_SIZE));
|
||||
}
|
||||
|
||||
private void storeBatch(final List<MessageProtos.Envelope> messages, final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
if (messages.size() > DYNAMO_DB_MAX_BATCH_SIZE) {
|
||||
throw new IllegalArgumentException("Maximum batch size of " + DYNAMO_DB_MAX_BATCH_SIZE + " execeeded with " + messages.size() + " messages");
|
||||
}
|
||||
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
TableWriteItems items = new TableWriteItems(tableName);
|
||||
for (MessageProtos.Envelope message : messages) {
|
||||
final UUID messageUuid = UUID.fromString(message.getServerGuid());
|
||||
final Item item = new Item().withBinary(KEY_PARTITION, partitionKey)
|
||||
.withBinary(KEY_SORT, convertSortKey(destinationDeviceId, message.getServerTimestamp(), messageUuid))
|
||||
.withBinary(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT, convertLocalIndexMessageUuidSortKey(messageUuid))
|
||||
.withInt(KEY_TYPE, message.getType().getNumber())
|
||||
.withLong(KEY_TIMESTAMP, message.getTimestamp())
|
||||
.withLong(KEY_TTL, getTtlForMessage(message));
|
||||
if (message.hasRelay() && message.getRelay().length() > 0) {
|
||||
item.withString(KEY_RELAY, message.getRelay());
|
||||
}
|
||||
if (message.hasSource()) {
|
||||
item.withString(KEY_SOURCE, message.getSource());
|
||||
}
|
||||
if (message.hasSourceUuid()) {
|
||||
item.withBinary(KEY_SOURCE_UUID, convertUuidToBytes(UUID.fromString(message.getSourceUuid())));
|
||||
}
|
||||
if (message.hasSourceDevice()) {
|
||||
item.withInt(KEY_SOURCE_DEVICE, message.getSourceDevice());
|
||||
}
|
||||
if (message.hasLegacyMessage()) {
|
||||
item.withBinary(KEY_MESSAGE, message.getLegacyMessage().toByteArray());
|
||||
}
|
||||
if (message.hasContent()) {
|
||||
item.withBinary(KEY_CONTENT, message.getContent().toByteArray());
|
||||
}
|
||||
items.addItemToPut(item);
|
||||
}
|
||||
|
||||
executeTableWriteItemsUntilComplete(items);
|
||||
}
|
||||
|
||||
public List<OutgoingMessageEntity> load(final UUID destinationAccountUuid, final long destinationDeviceId, final int requestedNumberOfMessagesToFetch) {
|
||||
return loadTimer.record(() -> {
|
||||
final int numberOfMessagesToFetch = Math.min(requestedNumberOfMessagesToFetch, RESULT_SET_CHUNK_SIZE);
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withConsistentRead(true)
|
||||
.withKeyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.withMaxResultSize(numberOfMessagesToFetch);
|
||||
final Table table = dynamoDb.getTable(tableName);
|
||||
List<OutgoingMessageEntity> messageEntities = new ArrayList<>(numberOfMessagesToFetch);
|
||||
for (Item message : table.query(querySpec)) {
|
||||
messageEntities.add(convertItemToOutgoingMessageEntity(message));
|
||||
}
|
||||
return messageEntities;
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<OutgoingMessageEntity> deleteMessageByDestinationAndSourceAndTimestamp(final UUID destinationAccountUuid, final long destinationDeviceId, final String source, final long timestamp) {
|
||||
return deleteBySourceAndTimestamp.record(() -> {
|
||||
if (StringUtils.isEmpty(source)) {
|
||||
throw new IllegalArgumentException("must specify a source");
|
||||
}
|
||||
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true)
|
||||
.withKeyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.withFilterExpression("#source = :source AND #timestamp = :timestamp")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT,
|
||||
"#source", KEY_SOURCE,
|
||||
"#timestamp", KEY_TIMESTAMP))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId),
|
||||
":source", source,
|
||||
":timestamp", timestamp));
|
||||
|
||||
final Table table = dynamoDb.getTable(tableName);
|
||||
return deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(table, partitionKey, querySpec, table);
|
||||
});
|
||||
}
|
||||
|
||||
public Optional<OutgoingMessageEntity> deleteMessageByDestinationAndGuid(final UUID destinationAccountUuid, final long destinationDeviceId, final UUID messageUuid) {
|
||||
return deleteByGuid.record(() -> {
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true)
|
||||
.withKeyConditionExpression("#part = :part AND #uuid = :uuid")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#uuid", LOCAL_INDEX_MESSAGE_UUID_KEY_SORT))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":uuid", convertLocalIndexMessageUuidSortKey(messageUuid)));
|
||||
final Table table = dynamoDb.getTable(tableName);
|
||||
final Index index = table.getIndex(LOCAL_INDEX_MESSAGE_UUID_NAME);
|
||||
return deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(table, partitionKey, querySpec, index);
|
||||
});
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private Optional<OutgoingMessageEntity> deleteItemsMatchingQueryAndReturnFirstOneActuallyDeleted(Table table, byte[] partitionKey, QuerySpec querySpec, QueryApi queryApi) {
|
||||
Optional<OutgoingMessageEntity> result = Optional.empty();
|
||||
for (Item item : queryApi.query(querySpec)) {
|
||||
final byte[] rangeKeyValue = item.getBinary(KEY_SORT);
|
||||
DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey(KEY_PARTITION, partitionKey, KEY_SORT, rangeKeyValue);
|
||||
if (result.isEmpty()) {
|
||||
deleteItemSpec.withReturnValues(ReturnValue.ALL_OLD);
|
||||
}
|
||||
final DeleteItemOutcome deleteItemOutcome = table.deleteItem(deleteItemSpec);
|
||||
if (deleteItemOutcome.getItem().hasAttribute(KEY_PARTITION)) {
|
||||
result = Optional.of(convertItemToOutgoingMessageEntity(deleteItemOutcome.getItem()));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
deleteByAccount.record(() -> {
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withHashKey(KEY_PARTITION, partitionKey)
|
||||
.withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true);
|
||||
deleteRowsMatchingQuery(partitionKey, querySpec);
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
deleteByDevice.record(() -> {
|
||||
final byte[] partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.withNameMap(Map.of("#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.withValueMap(Map.of(":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.withProjectionExpression(KEY_SORT)
|
||||
.withConsistentRead(true);
|
||||
deleteRowsMatchingQuery(partitionKey, querySpec);
|
||||
});
|
||||
}
|
||||
|
||||
private OutgoingMessageEntity convertItemToOutgoingMessageEntity(Item message) {
|
||||
final SortKey sortKey = convertSortKey(message.getBinary(KEY_SORT));
|
||||
final UUID messageUuid = convertLocalIndexMessageUuidSortKey(message.getBinary(LOCAL_INDEX_MESSAGE_UUID_KEY_SORT));
|
||||
final int type = message.getInt(KEY_TYPE);
|
||||
final String relay = message.getString(KEY_RELAY);
|
||||
final long timestamp = message.getLong(KEY_TIMESTAMP);
|
||||
final String source = message.getString(KEY_SOURCE);
|
||||
final UUID sourceUuid = message.hasAttribute(KEY_SOURCE_UUID) ? convertUuidFromBytes(message.getBinary(KEY_SOURCE_UUID), "message source uuid") : null;
|
||||
final int sourceDevice = message.hasAttribute(KEY_SOURCE_DEVICE) ? message.getInt(KEY_SOURCE_DEVICE) : 0;
|
||||
final byte[] messageBytes = message.getBinary(KEY_MESSAGE);
|
||||
final byte[] content = message.getBinary(KEY_CONTENT);
|
||||
return new OutgoingMessageEntity(-1L, false, messageUuid, type, relay, timestamp, source, sourceUuid, sourceDevice, messageBytes, content, sortKey.getServerTimestamp());
|
||||
}
|
||||
|
||||
private void deleteRowsMatchingQuery(byte[] partitionKey, QuerySpec querySpec) {
|
||||
final Table table = dynamoDb.getTable(tableName);
|
||||
doInBatches(table.query(querySpec), (itemBatch) -> deleteItems(partitionKey, itemBatch), DYNAMO_DB_MAX_BATCH_SIZE);
|
||||
}
|
||||
|
||||
private void deleteItems(byte[] partitionKey, List<Item> items) {
|
||||
final TableWriteItems tableWriteItems = new TableWriteItems(tableName);
|
||||
items.stream().map((x) -> new PrimaryKey(KEY_PARTITION, partitionKey, KEY_SORT, x.getBinary(KEY_SORT))).forEach(tableWriteItems::addPrimaryKeyToDelete);
|
||||
executeTableWriteItemsUntilComplete(tableWriteItems);
|
||||
}
|
||||
|
||||
private void executeTableWriteItemsUntilComplete(TableWriteItems items) {
|
||||
AtomicReference<BatchWriteItemOutcome> outcome = new AtomicReference<>();
|
||||
batchWriteItemsFirstPass.record(() -> {
|
||||
outcome.set(dynamoDb.batchWriteItem(items));
|
||||
});
|
||||
int attemptCount = 0;
|
||||
while (!outcome.get().getUnprocessedItems().isEmpty() && attemptCount < MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE) {
|
||||
batchWriteItemsRetryPass.record(() -> {
|
||||
outcome.set(dynamoDb.batchWriteItemUnprocessed(outcome.get().getUnprocessedItems()));
|
||||
});
|
||||
++attemptCount;
|
||||
}
|
||||
if (!outcome.get().getUnprocessedItems().isEmpty()) {
|
||||
logger.error("Attempt count ({}) reached max ({}}) before applying all batch writes to dynamo. {} unprocessed items remain.", attemptCount, MAX_ATTEMPTS_TO_SAVE_BATCH_WRITE, outcome.get().getUnprocessedItems().size());
|
||||
batchWriteItemsUnprocessed.increment(outcome.get().getUnprocessedItems().size());
|
||||
}
|
||||
}
|
||||
|
||||
private long getTtlForMessage(MessageProtos.Envelope message) {
|
||||
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
|
||||
}
|
||||
|
||||
private static <T> void doInBatches(final Iterable<T> items, final Consumer<List<T>> action, final int batchSize) {
|
||||
List<T> batch = new ArrayList<>(batchSize);
|
||||
|
||||
for (T item : items) {
|
||||
batch.add(item);
|
||||
|
||||
if (batch.size() == batchSize) {
|
||||
action.accept(batch);
|
||||
batch.clear();
|
||||
}
|
||||
}
|
||||
if (!batch.isEmpty()) {
|
||||
action.accept(batch);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] convertPartitionKey(final UUID destinationAccountUuid) {
|
||||
return convertUuidToBytes(destinationAccountUuid);
|
||||
}
|
||||
|
||||
private static UUID convertPartitionKey(final byte[] bytes) {
|
||||
return convertUuidFromBytes(bytes, "partition key");
|
||||
}
|
||||
|
||||
private static byte[] convertSortKey(final long destinationDeviceId, final long serverTimestamp, final UUID messageUuid) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[32]);
|
||||
byteBuffer.putLong(destinationDeviceId);
|
||||
byteBuffer.putLong(serverTimestamp);
|
||||
byteBuffer.putLong(messageUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(messageUuid.getLeastSignificantBits());
|
||||
return byteBuffer.array();
|
||||
}
|
||||
|
||||
private static byte[] convertDestinationDeviceIdToSortKeyPrefix(final long destinationDeviceId) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[8]);
|
||||
byteBuffer.putLong(destinationDeviceId);
|
||||
return byteBuffer.array();
|
||||
}
|
||||
|
||||
private static SortKey convertSortKey(final byte[] bytes) {
|
||||
if (bytes.length != 32) {
|
||||
throw new IllegalArgumentException("unexpected sort key byte length");
|
||||
}
|
||||
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
|
||||
final long destinationDeviceId = byteBuffer.getLong();
|
||||
final long serverTimestamp = byteBuffer.getLong();
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
final long leastSigBits = byteBuffer.getLong();
|
||||
return new SortKey(destinationDeviceId, serverTimestamp, new UUID(mostSigBits, leastSigBits));
|
||||
}
|
||||
|
||||
private static byte[] convertLocalIndexMessageUuidSortKey(final UUID messageUuid) {
|
||||
return convertUuidToBytes(messageUuid);
|
||||
}
|
||||
|
||||
private static UUID convertLocalIndexMessageUuidSortKey(final byte[] bytes) {
|
||||
return convertUuidFromBytes(bytes, "local index message uuid sort key");
|
||||
}
|
||||
|
||||
private static byte[] convertUuidToBytes(final UUID uuid) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(uuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(uuid.getLeastSignificantBits());
|
||||
return byteBuffer.array();
|
||||
}
|
||||
|
||||
private static UUID convertUuidFromBytes(final byte[] bytes, final String name) {
|
||||
if (bytes.length != 16) {
|
||||
throw new IllegalArgumentException("unexpected " + name + " byte length; was " + bytes.length + " but expected 16");
|
||||
}
|
||||
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
|
||||
final long mostSigBits = byteBuffer.getLong();
|
||||
final long leastSigBits = byteBuffer.getLong();
|
||||
return new UUID(mostSigBits, leastSigBits);
|
||||
}
|
||||
|
||||
private static final class SortKey {
|
||||
private final long destinationDeviceId;
|
||||
private final long serverTimestamp;
|
||||
private final UUID messageUuid;
|
||||
|
||||
public SortKey(long destinationDeviceId, long serverTimestamp, UUID messageUuid) {
|
||||
this.destinationDeviceId = destinationDeviceId;
|
||||
this.serverTimestamp = serverTimestamp;
|
||||
this.messageUuid = messageUuid;
|
||||
}
|
||||
|
||||
public long getDestinationDeviceId() {
|
||||
return destinationDeviceId;
|
||||
}
|
||||
|
||||
public long getServerTimestamp() {
|
||||
return serverTimestamp;
|
||||
}
|
||||
|
||||
public UUID getMessageUuid() {
|
||||
return messageUuid;
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
-34
@@ -12,6 +12,7 @@ import com.codahale.metrics.SharedMetricRegistries;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.util.Constants;
|
||||
@@ -26,22 +27,28 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
public class MessagesManager {
|
||||
|
||||
private static final String READ_DYNAMODB_EXPERIMENT = "messages_dynamodb_read";
|
||||
private static final String WRITE_DYNAMODB_EXPERIMENT = "messages_dynamodb_write";
|
||||
private static final String DISABLE_RDS_EXPERIMENT = "messages_disable_rds";
|
||||
|
||||
private static final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
private static final Meter cacheHitByIdMeter = metricRegistry.meter(name(MessagesManager.class, "cacheHitById" ));
|
||||
private static final Meter cacheMissByIdMeter = metricRegistry.meter(name(MessagesManager.class, "cacheMissById" ));
|
||||
private static final Meter cacheHitByNameMeter = metricRegistry.meter(name(MessagesManager.class, "cacheHitByName" ));
|
||||
private static final Meter cacheMissByNameMeter = metricRegistry.meter(name(MessagesManager.class, "cacheMissByName"));
|
||||
private static final Meter cacheHitByGuidMeter = metricRegistry.meter(name(MessagesManager.class, "cacheHitByGuid" ));
|
||||
private static final Meter cacheMissByGuidMeter = metricRegistry.meter(name(MessagesManager.class, "cacheMissByGuid"));
|
||||
|
||||
private final Messages messages;
|
||||
private final MessagesCache messagesCache;
|
||||
private final Messages messages;
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final PushLatencyManager pushLatencyManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
public MessagesManager(Messages messages, MessagesCache messagesCache, PushLatencyManager pushLatencyManager) {
|
||||
this.messages = messages;
|
||||
this.messagesCache = messagesCache;
|
||||
public MessagesManager(Messages messages, MessagesDynamoDb messagesDynamoDb, MessagesCache messagesCache, PushLatencyManager pushLatencyManager, ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
this.messages = messages;
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.pushLatencyManager = pushLatencyManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
public void insert(UUID destinationUuid, long destinationDevice, Envelope message) {
|
||||
@@ -63,39 +70,58 @@ public class MessagesManager {
|
||||
public OutgoingMessageEntityList getMessagesForDevice(String destination, UUID destinationUuid, long destinationDevice, final String userAgent, final boolean cachedMessagesOnly) {
|
||||
RedisOperation.unchecked(() -> pushLatencyManager.recordQueueRead(destinationUuid, destinationDevice, userAgent));
|
||||
|
||||
List<OutgoingMessageEntity> messages = cachedMessagesOnly ? new ArrayList<>() : this.messages.load(destination, destinationDevice);
|
||||
List<OutgoingMessageEntity> messageList = new ArrayList<>();
|
||||
|
||||
if (messages.size() < Messages.RESULT_SET_CHUNK_SIZE) {
|
||||
messages.addAll(messagesCache.get(destinationUuid, destinationDevice, Messages.RESULT_SET_CHUNK_SIZE - messages.size()));
|
||||
if (!cachedMessagesOnly && !experimentEnrollmentManager.isEnrolled(destinationUuid, DISABLE_RDS_EXPERIMENT)) {
|
||||
messageList.addAll(messages.load(destination, destinationDevice));
|
||||
}
|
||||
|
||||
return new OutgoingMessageEntityList(messages, messages.size() >= Messages.RESULT_SET_CHUNK_SIZE);
|
||||
if (messageList.size() < Messages.RESULT_SET_CHUNK_SIZE && !cachedMessagesOnly && experimentEnrollmentManager.isEnrolled(destinationUuid, READ_DYNAMODB_EXPERIMENT)) {
|
||||
messageList.addAll(messagesDynamoDb.load(destinationUuid, destinationDevice, Messages.RESULT_SET_CHUNK_SIZE - messageList.size()));
|
||||
}
|
||||
|
||||
if (messageList.size() < Messages.RESULT_SET_CHUNK_SIZE) {
|
||||
messageList.addAll(messagesCache.get(destinationUuid, destinationDevice, Messages.RESULT_SET_CHUNK_SIZE - messageList.size()));
|
||||
}
|
||||
|
||||
return new OutgoingMessageEntityList(messageList, messageList.size() >= Messages.RESULT_SET_CHUNK_SIZE);
|
||||
}
|
||||
|
||||
public void clear(String destination, UUID destinationUuid) {
|
||||
// TODO Remove this null check in a fully-UUID-ified world
|
||||
if (destinationUuid != null) {
|
||||
this.messagesCache.clear(destinationUuid);
|
||||
messagesCache.clear(destinationUuid);
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, WRITE_DYNAMODB_EXPERIMENT)) {
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
|
||||
}
|
||||
if (!experimentEnrollmentManager.isEnrolled(destinationUuid, DISABLE_RDS_EXPERIMENT)) {
|
||||
messages.clear(destination);
|
||||
}
|
||||
} else {
|
||||
messages.clear(destination);
|
||||
}
|
||||
|
||||
this.messages.clear(destination);
|
||||
}
|
||||
|
||||
public void clear(String destination, UUID destinationUuid, long deviceId) {
|
||||
// TODO Remove this null check in a fully-UUID-ified world
|
||||
if (destinationUuid != null) {
|
||||
this.messagesCache.clear(destinationUuid, deviceId);
|
||||
messagesCache.clear(destinationUuid, deviceId);
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, WRITE_DYNAMODB_EXPERIMENT)) {
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId);
|
||||
}
|
||||
if (!experimentEnrollmentManager.isEnrolled(destinationUuid, DISABLE_RDS_EXPERIMENT)) {
|
||||
messages.clear(destination, deviceId);
|
||||
}
|
||||
|
||||
this.messages.clear(destination, deviceId);
|
||||
}
|
||||
|
||||
public Optional<OutgoingMessageEntity> delete(String destination, UUID destinationUuid, long destinationDevice, String source, long timestamp)
|
||||
{
|
||||
public Optional<OutgoingMessageEntity> delete(String destination, UUID destinationUuid, long destinationDevice, String source, long timestamp) {
|
||||
Optional<OutgoingMessageEntity> removed = messagesCache.remove(destinationUuid, destinationDevice, source, timestamp);
|
||||
|
||||
if (!removed.isPresent()) {
|
||||
removed = this.messages.remove(destination, destinationDevice, source, timestamp);
|
||||
if (removed.isEmpty()) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, WRITE_DYNAMODB_EXPERIMENT)) {
|
||||
removed = messagesDynamoDb.deleteMessageByDestinationAndSourceAndTimestamp(destinationUuid, destinationDevice, source, timestamp);
|
||||
}
|
||||
if (removed.isEmpty() && !experimentEnrollmentManager.isEnrolled(destinationUuid, DISABLE_RDS_EXPERIMENT)) {
|
||||
removed = messages.remove(destination, destinationDevice, source, timestamp);
|
||||
}
|
||||
cacheMissByNameMeter.mark();
|
||||
} else {
|
||||
cacheHitByNameMeter.mark();
|
||||
@@ -107,8 +133,13 @@ public class MessagesManager {
|
||||
public Optional<OutgoingMessageEntity> delete(String destination, UUID destinationUuid, long deviceId, UUID guid) {
|
||||
Optional<OutgoingMessageEntity> removed = messagesCache.remove(destinationUuid, deviceId, guid);
|
||||
|
||||
if (!removed.isPresent()) {
|
||||
removed = this.messages.remove(destination, guid);
|
||||
if (removed.isEmpty()) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, WRITE_DYNAMODB_EXPERIMENT)) {
|
||||
removed = messagesDynamoDb.deleteMessageByDestinationAndGuid(destinationUuid, deviceId, guid);
|
||||
}
|
||||
if (removed.isEmpty() && !experimentEnrollmentManager.isEnrolled(destinationUuid, DISABLE_RDS_EXPERIMENT)) {
|
||||
removed = messages.remove(destination, guid);
|
||||
}
|
||||
cacheMissByGuidMeter.mark();
|
||||
} else {
|
||||
cacheHitByGuidMeter.mark();
|
||||
@@ -117,18 +148,17 @@ public class MessagesManager {
|
||||
return removed;
|
||||
}
|
||||
|
||||
public void delete(String destination, UUID destinationUuid, long deviceId, long id, boolean cached) {
|
||||
if (cached) {
|
||||
messagesCache.remove(destinationUuid, deviceId, id);
|
||||
cacheHitByIdMeter.mark();
|
||||
} else {
|
||||
this.messages.remove(destination, id);
|
||||
cacheMissByIdMeter.mark();
|
||||
}
|
||||
@Deprecated
|
||||
public void delete(String destination, long id) {
|
||||
messages.remove(destination, id);
|
||||
}
|
||||
|
||||
public void persistMessages(final String destination, final UUID destinationUuid, final long destinationDeviceId, final List<Envelope> messages) {
|
||||
this.messages.store(messages, destination, destinationDeviceId);
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, WRITE_DYNAMODB_EXPERIMENT)) {
|
||||
messagesDynamoDb.store(messages, destinationUuid, destinationDeviceId);
|
||||
} else {
|
||||
this.messages.store(messages, destination, destinationDeviceId);
|
||||
}
|
||||
messagesCache.remove(destinationUuid, destinationDeviceId, messages.stream().map(message -> UUID.fromString(message.getServerGuid())).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ public class Profiles {
|
||||
public static final String VERSION = "version";
|
||||
public static final String NAME = "name";
|
||||
public static final String AVATAR = "avatar";
|
||||
public static final String ABOUT_EMOJI = "about_emoji";
|
||||
public static final String ABOUT = "about";
|
||||
public static final String COMMITMENT = "commitment";
|
||||
|
||||
private final MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate(Constants.METRICS_NAME);
|
||||
@@ -41,11 +43,13 @@ public class Profiles {
|
||||
public void set(UUID uuid, VersionedProfile profile) {
|
||||
database.use(jdbi -> jdbi.useHandle(handle -> {
|
||||
try (Timer.Context ignored = setTimer.time()) {
|
||||
handle.createUpdate("INSERT INTO profiles (" + UID + ", " + VERSION + ", " + NAME + ", " + AVATAR + ", " + COMMITMENT + ") VALUES (:uuid, :version, :name, :avatar, :commitment) ON CONFLICT (" + UID + ", " + VERSION + ") DO UPDATE SET " + NAME + " = EXCLUDED." + NAME + ", " + AVATAR + " = EXCLUDED." + AVATAR)
|
||||
handle.createUpdate("INSERT INTO profiles (" + UID + ", " + VERSION + ", " + NAME + ", " + AVATAR + ", " + ABOUT_EMOJI + ", " + ABOUT + ", " + COMMITMENT + ") VALUES (:uuid, :version, :name, :avatar, :about_emoji, :about, :commitment) ON CONFLICT (" + UID + ", " + VERSION + ") DO UPDATE SET " + NAME + " = EXCLUDED." + NAME + ", " + AVATAR + " = EXCLUDED." + AVATAR + ", " + ABOUT + " = EXCLUDED." + ABOUT + ", " + ABOUT_EMOJI + " = EXCLUDED." + ABOUT_EMOJI)
|
||||
.bind("uuid", uuid)
|
||||
.bind("version", profile.getVersion())
|
||||
.bind("name", profile.getName())
|
||||
.bind("avatar", profile.getAvatar())
|
||||
.bind("about_emoji", profile.getAboutEmoji())
|
||||
.bind("about", profile.getAbout())
|
||||
.bind("commitment", profile.getCommitment())
|
||||
.execute();
|
||||
}
|
||||
|
||||
+17
-2
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
public class VersionedProfile {
|
||||
@@ -22,6 +21,12 @@ public class VersionedProfile {
|
||||
@JsonProperty
|
||||
private String avatar;
|
||||
|
||||
@JsonProperty
|
||||
private String aboutEmoji;
|
||||
|
||||
@JsonProperty
|
||||
private String about;
|
||||
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@@ -29,10 +34,12 @@ public class VersionedProfile {
|
||||
|
||||
public VersionedProfile() {}
|
||||
|
||||
public VersionedProfile(String version, String name, String avatar, byte[] commitment) {
|
||||
public VersionedProfile(String version, String name, String avatar, String aboutEmoji, String about, byte[] commitment) {
|
||||
this.version = version;
|
||||
this.name = name;
|
||||
this.avatar = avatar;
|
||||
this.aboutEmoji = aboutEmoji;
|
||||
this.about = about;
|
||||
this.commitment = commitment;
|
||||
}
|
||||
|
||||
@@ -48,6 +55,14 @@ public class VersionedProfile {
|
||||
return avatar;
|
||||
}
|
||||
|
||||
public String getAboutEmoji() {
|
||||
return aboutEmoji;
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return about;
|
||||
}
|
||||
|
||||
public byte[] getCommitment() {
|
||||
return commitment;
|
||||
}
|
||||
|
||||
+2
@@ -20,6 +20,8 @@ public class VersionedProfileMapper implements RowMapper<VersionedProfile> {
|
||||
return new VersionedProfile(resultSet.getString(Profiles.VERSION),
|
||||
resultSet.getString(Profiles.NAME),
|
||||
resultSet.getString(Profiles.AVATAR),
|
||||
resultSet.getString(Profiles.ABOUT_EMOJI),
|
||||
resultSet.getString(Profiles.ABOUT),
|
||||
resultSet.getBytes(Profiles.COMMITMENT));
|
||||
}
|
||||
}
|
||||
+16
-9
@@ -43,6 +43,7 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -145,7 +146,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
if (throwable == null) {
|
||||
if (isSuccessResponse(response)) {
|
||||
if (storedMessageInfo.isPresent()) {
|
||||
messagesManager.delete(account.getNumber(), account.getUuid(), device.getId(), storedMessageInfo.get().id, storedMessageInfo.get().cached);
|
||||
messagesManager.delete(account.getNumber(), account.getUuid(), device.getId(), storedMessageInfo.get().getGuid());
|
||||
}
|
||||
|
||||
if (message.getType() != Envelope.Type.RECEIPT) {
|
||||
@@ -252,13 +253,17 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
|
||||
final Envelope envelope = builder.build();
|
||||
|
||||
if (envelope.getSerializedSize() > MAX_DESKTOP_MESSAGE_SIZE && isDesktopClient) {
|
||||
messagesManager.delete(account.getNumber(), account.getUuid(), device.getId(), message.getId(), message.isCached());
|
||||
if (message.getGuid() == null || (envelope.getSerializedSize() > MAX_DESKTOP_MESSAGE_SIZE && isDesktopClient)) {
|
||||
if (message.getGuid() == null) {
|
||||
messagesManager.delete(account.getNumber(), message.getId()); // TODO(ehren): Remove once the message DB is gone.
|
||||
} else {
|
||||
messagesManager.delete(account.getNumber(), account.getUuid(), device.getId(), message.getGuid());
|
||||
}
|
||||
discardedMessagesMeter.mark();
|
||||
|
||||
sendFutures[i] = CompletableFuture.completedFuture(null);
|
||||
} else {
|
||||
sendFutures[i] = sendMessage(builder.build(), Optional.of(new StoredMessageInfo(message.getId(), message.isCached())));
|
||||
sendFutures[i] = sendMessage(builder.build(), Optional.of(new StoredMessageInfo(message.getGuid())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,12 +312,14 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
}
|
||||
|
||||
private static class StoredMessageInfo {
|
||||
private final long id;
|
||||
private final boolean cached;
|
||||
private final UUID guid;
|
||||
|
||||
private StoredMessageInfo(long id, boolean cached) {
|
||||
this.id = id;
|
||||
this.cached = cached;
|
||||
public StoredMessageInfo(UUID guid) {
|
||||
this.guid = guid;
|
||||
}
|
||||
|
||||
public UUID getGuid() {
|
||||
return guid;
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.servlets.tasks.Task;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public abstract class AbstractFeatureFlagTask extends Task {
|
||||
|
||||
private final FeatureFlagsManager featureFlagsManager;
|
||||
|
||||
protected AbstractFeatureFlagTask(final String name, final FeatureFlagsManager featureFlagsManager) {
|
||||
super(name);
|
||||
|
||||
this.featureFlagsManager = featureFlagsManager;
|
||||
}
|
||||
|
||||
protected FeatureFlagsManager getFeatureFlagsManager() {
|
||||
return featureFlagsManager;
|
||||
}
|
||||
|
||||
protected void printFeatureFlags(final PrintWriter out) {
|
||||
out.println("Feature flags:");
|
||||
featureFlagsManager.getAllFlags().forEach((flag, active) -> out.println(flag + ": " + active));
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class DeleteFeatureFlagTask extends AbstractFeatureFlagTask {
|
||||
|
||||
public DeleteFeatureFlagTask(final FeatureFlagsManager featureFlagsManager) {
|
||||
super("delete-feature-flag", featureFlagsManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> parameters, final PrintWriter out) {
|
||||
if (parameters.containsKey("flag")) {
|
||||
for (final String flag : parameters.getOrDefault("flag", Collections.emptyList())) {
|
||||
out.println("Deleting feature flag: " + flag);
|
||||
getFeatureFlagsManager().deleteFeatureFlag(flag);
|
||||
}
|
||||
|
||||
out.println();
|
||||
printFeatureFlags(out);
|
||||
} else {
|
||||
out.println("Usage: delete-feature-flag?flag=FLAG_NAME[&flag=FLAG_NAME2&flag=...]");
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-4
@@ -5,6 +5,10 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import io.dropwizard.Application;
|
||||
import io.dropwizard.cli.EnvironmentCommand;
|
||||
@@ -17,6 +21,7 @@ import org.jdbi.v3.core.Jdbi;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClientFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
@@ -26,10 +31,12 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Accounts;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.storage.Messages;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
@@ -84,27 +91,39 @@ public class DeleteUserCommand extends EnvironmentCommand<WhisperServerConfigura
|
||||
FaultTolerantDatabase messageDatabase = new FaultTolerantDatabase("message_database", messageJdbi, configuration.getMessageStoreConfiguration().getCircuitBreakerConfiguration());
|
||||
ClientResources redisClusterClientResources = ClientResources.builder().build();
|
||||
|
||||
AmazonDynamoDBClientBuilder clientBuilder = AmazonDynamoDBClientBuilder
|
||||
.standard()
|
||||
.withRegion(configuration.getMessageDynamoDbConfiguration().getRegion())
|
||||
.withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(((int) configuration.getMessageDynamoDbConfiguration().getClientExecutionTimeout().toMillis()))
|
||||
.withRequestTimeout((int) configuration.getMessageDynamoDbConfiguration().getClientRequestTimeout().toMillis()))
|
||||
.withCredentials(InstanceProfileCredentialsProvider.getInstance());
|
||||
DynamoDB messageDynamoDb = new DynamoDB(clientBuilder.build());
|
||||
|
||||
FaultTolerantRedisCluster cacheCluster = new FaultTolerantRedisCluster("main_cache_cluster", configuration.getCacheClusterConfiguration(), redisClusterClientResources);
|
||||
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle().executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(4).build();
|
||||
|
||||
DynamicConfigurationManager dynamicConfigurationManager = new DynamicConfigurationManager(configuration.getAppConfig().getApplication(), configuration.getAppConfig().getEnvironment(), configuration.getAppConfig().getConfigurationName());
|
||||
ExperimentEnrollmentManager experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
|
||||
Accounts accounts = new Accounts(accountDatabase);
|
||||
Usernames usernames = new Usernames(accountDatabase);
|
||||
Profiles profiles = new Profiles(accountDatabase);
|
||||
ReservedUsernames reservedUsernames = new ReservedUsernames(accountDatabase);
|
||||
Keys keys = new Keys(accountDatabase);
|
||||
Keys keys = new Keys(accountDatabase, configuration.getAccountsDatabaseConfiguration().getKeyOperationRetryConfiguration());
|
||||
Messages messages = new Messages(messageDatabase);
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(messageDynamoDb, configuration.getMessageDynamoDbConfiguration().getTableName(), configuration.getMessageDynamoDbConfiguration().getTimeToLive());
|
||||
ReplicatedJedisPool redisClient = new RedisClientFactory("directory_cache_delete_command", configuration.getDirectoryConfiguration().getRedisConfiguration().getUrl(), configuration.getDirectoryConfiguration().getRedisConfiguration().getReplicaUrls(), configuration.getDirectoryConfiguration().getRedisConfiguration().getCircuitBreakerConfiguration()).getRedisClientPool();
|
||||
FaultTolerantRedisCluster messagesCacheCluster = new FaultTolerantRedisCluster("messages_cluster", configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster messageInsertCacheCluster = new FaultTolerantRedisCluster("message_insert_cluster", configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster messageReadDeleteCluster = new FaultTolerantRedisCluster("message_read_delete_cluster", configuration.getMessageCacheConfiguration().getRedisClusterConfiguration(), redisClusterClientResources);
|
||||
FaultTolerantRedisCluster metricsCluster = new FaultTolerantRedisCluster("metrics_cluster", configuration.getMetricsClusterConfiguration(), redisClusterClientResources);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCacheCluster, keyspaceNotificationDispatchExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messageInsertCacheCluster, messageReadDeleteCluster, keyspaceNotificationDispatchExecutor);
|
||||
PushLatencyManager pushLatencyManager = new PushLatencyManager(metricsCluster);
|
||||
DirectoryQueue directoryQueue = new DirectoryQueue (configuration.getDirectoryConfiguration().getSqsConfiguration());
|
||||
DirectoryManager directory = new DirectoryManager(redisClient );
|
||||
UsernamesManager usernamesManager = new UsernamesManager(usernames, reservedUsernames, cacheCluster);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesManager messagesManager = new MessagesManager(messages, messagesCache, pushLatencyManager);
|
||||
MessagesManager messagesManager = new MessagesManager(messages, messagesDynamoDb, messagesCache, pushLatencyManager, new ExperimentEnrollmentManager(dynamicConfigurationManager));
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheCluster, directoryQueue, keys, messagesManager, usernamesManager, profilesManager);
|
||||
|
||||
for (String user: users) {
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.servlets.tasks.Task;
|
||||
import org.whispersystems.textsecuregcm.util.logging.RequestLogManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class DisableRequestLoggingTask extends Task {
|
||||
|
||||
public DisableRequestLoggingTask() {
|
||||
super("disable-request-logging");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> map, final PrintWriter printWriter) {
|
||||
RequestLogManager.setRequestLoggingEnabled(false);
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.servlets.tasks.Task;
|
||||
import org.whispersystems.textsecuregcm.util.logging.RequestLogManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class EnableRequestLoggingTask extends Task {
|
||||
|
||||
public EnableRequestLoggingTask() {
|
||||
super("enable-request-logging");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> map, final PrintWriter printWriter) {
|
||||
RequestLogManager.setRequestLoggingEnabled(true);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ListFeatureFlagsTask extends AbstractFeatureFlagTask {
|
||||
|
||||
public ListFeatureFlagsTask(final FeatureFlagsManager featureFlagsManager) {
|
||||
super("list-feature-flags", featureFlagsManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> parameters, final PrintWriter out) {
|
||||
printFeatureFlags(out);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.servlets.tasks.Task;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawlerCache;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SetCrawlerAccelerationTask extends Task {
|
||||
|
||||
private final AccountDatabaseCrawlerCache crawlerCache;
|
||||
|
||||
public SetCrawlerAccelerationTask(final AccountDatabaseCrawlerCache crawlerCache) {
|
||||
super("set-crawler-accelerated");
|
||||
|
||||
this.crawlerCache = crawlerCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> parameters, final PrintWriter out) {
|
||||
if (parameters.containsKey("accelerated") && parameters.get("accelerated").size() == 1) {
|
||||
final boolean accelerated = "true".equalsIgnoreCase(parameters.get("accelerated").get(0));
|
||||
|
||||
crawlerCache.setAccelerated(accelerated);
|
||||
out.println("Set accelerated: " + accelerated);
|
||||
} else {
|
||||
out.println("Usage: set-crawler-accelerated?accelerated=[true|false]");
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class SetFeatureFlagTask extends AbstractFeatureFlagTask {
|
||||
|
||||
public SetFeatureFlagTask(final FeatureFlagsManager featureFlagsManager) {
|
||||
super("set-feature-flag", featureFlagsManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> parameters, final PrintWriter out) {
|
||||
final Optional<String> maybeFlag = Optional.ofNullable(parameters.get("flag"))
|
||||
.flatMap(values -> values.stream().findFirst());
|
||||
|
||||
final Optional<Boolean> maybeActive = Optional.ofNullable(parameters.get("active"))
|
||||
.flatMap(values -> values.stream().findFirst())
|
||||
.map(Boolean::valueOf);
|
||||
|
||||
if (maybeFlag.isPresent() && maybeActive.isPresent()) {
|
||||
getFeatureFlagsManager().setFeatureFlag(maybeFlag.get(), maybeActive.get());
|
||||
|
||||
out.format("Set %s to %s\n", maybeFlag.get(), maybeActive.get());
|
||||
out.println();
|
||||
printFeatureFlags(out);
|
||||
} else {
|
||||
out.println("Usage: set-feature-flag?flag=FLAG_NAME&active=[true|false]");
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import io.dropwizard.servlets.tasks.Task;
|
||||
import org.whispersystems.textsecuregcm.util.logging.RequestLogManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class SetRequestLoggingEnabledTask extends Task {
|
||||
|
||||
public SetRequestLoggingEnabledTask() {
|
||||
super("set-request-logging-enabled");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Map<String, List<String>> parameters, final PrintWriter out) {
|
||||
if (parameters.containsKey("enabled") && parameters.get("enabled").size() == 1) {
|
||||
final boolean enabled = Boolean.parseBoolean(parameters.get("enabled").get(0));
|
||||
|
||||
RequestLogManager.setRequestLoggingEnabled(enabled);
|
||||
|
||||
if (enabled) {
|
||||
out.println("Request logging now enabled");
|
||||
} else {
|
||||
out.println("Request logging now disabled");
|
||||
}
|
||||
} else {
|
||||
out.println("Usage: set-request-logging-enabled?enabled=[true|false]");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ public class VacuumCommand extends ConfiguredCommand<WhisperServerConfiguration>
|
||||
FaultTolerantDatabase messageDatabase = new FaultTolerantDatabase("message_database_vacuum", messageJdbi, messageDbConfig.getCircuitBreakerConfiguration());
|
||||
|
||||
Accounts accounts = new Accounts(accountDatabase);
|
||||
Keys keys = new Keys(accountDatabase);
|
||||
Keys keys = new Keys(accountDatabase, config.getAccountsDatabaseConfiguration().getKeyOperationRetryConfiguration());
|
||||
PendingAccounts pendingAccounts = new PendingAccounts(accountDatabase);
|
||||
Messages messages = new Messages(messageDatabase);
|
||||
FeatureFlags featureFlags = new FeatureFlags(accountDatabase);
|
||||
|
||||
@@ -339,4 +339,16 @@
|
||||
</createTable>
|
||||
</changeSet>
|
||||
|
||||
<changeSet id="20" author="jon">
|
||||
<addColumn tableName="profiles">
|
||||
<column name="about" type="text">
|
||||
<constraints nullable="true"/>
|
||||
</column>
|
||||
|
||||
<column name="about_emoji" type="text">
|
||||
<constraints nullable="true"/>
|
||||
</column>
|
||||
</addColumn>
|
||||
</changeSet>
|
||||
|
||||
</databaseChangeLog>
|
||||
@@ -1,5 +1,7 @@
|
||||
-- keys: pending (KEYS[1])
|
||||
-- argv: max_time (ARGV[1]), limit (ARGV[2])
|
||||
local pendingNotificationQueue = KEYS[1]
|
||||
|
||||
local maxTime = ARGV[1]
|
||||
local limit = ARGV[2]
|
||||
|
||||
local hgetall = function (key)
|
||||
local bulk = redis.call('HGETALL', key)
|
||||
@@ -44,7 +46,7 @@ local getNextInterval = function(interval)
|
||||
end
|
||||
|
||||
|
||||
local results = redis.call("ZRANGEBYSCORE", KEYS[1], 0, ARGV[1], "LIMIT", 0, ARGV[2])
|
||||
local results = redis.call("ZRANGEBYSCORE", pendingNotificationQueue, 0, maxTime, "LIMIT", 0, limit)
|
||||
local collated = {}
|
||||
|
||||
if results and next(results) then
|
||||
@@ -59,12 +61,10 @@ if results and next(results) then
|
||||
local nextInterval = getNextInterval(tonumber(lastInterval))
|
||||
|
||||
redis.call("HSET", name, "interval", nextInterval)
|
||||
redis.call("ZADD", KEYS[1], tonumber(ARGV[1]) + nextInterval, name)
|
||||
redis.call("ZADD", pendingNotificationQueue, tonumber(maxTime) + nextInterval, name)
|
||||
|
||||
collated[i] = pending["account"] .. ":" .. pending["device"]
|
||||
end
|
||||
end
|
||||
|
||||
return collated
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
-- keys: pending (KEYS[1]), user (KEYS[2])
|
||||
-- args: timestamp (ARGV[1]), interval (ARGV[2]), account (ARGV[3]), device (ARGV[4])
|
||||
local pendingNotificationQueue = KEYS[1]
|
||||
local endpoint = KEYS[2]
|
||||
|
||||
redis.call("HSET", KEYS[2], "created", ARGV[1])
|
||||
redis.call("HSET", KEYS[2], "interval", ARGV[2])
|
||||
redis.call("HSET", KEYS[2], "account", ARGV[3])
|
||||
redis.call("HSET", KEYS[2], "device", ARGV[4])
|
||||
local timestamp = ARGV[1]
|
||||
local interval = ARGV[2]
|
||||
local account = ARGV[3]
|
||||
local deviceId = ARGV[4]
|
||||
|
||||
redis.call("ZADD", KEYS[1], ARGV[1], KEYS[2])
|
||||
redis.call("HSET", endpoint, "created", timestamp)
|
||||
redis.call("HSET", endpoint, "interval", interval)
|
||||
redis.call("HSET", endpoint, "account", account)
|
||||
redis.call("HSET", endpoint, "device", deviceId)
|
||||
|
||||
redis.call("ZADD", pendingNotificationQueue, timestamp, endpoint)
|
||||
@@ -1,4 +1,5 @@
|
||||
-- keys: queue KEYS[1], endpoint (KEYS[2])
|
||||
local pendingNotificationQueue = KEYS[1]
|
||||
local endpoint = KEYS[2]
|
||||
|
||||
redis.call("DEL", KEYS[2])
|
||||
return redis.call("ZREM", KEYS[1], KEYS[2])
|
||||
redis.call("DEL", endpoint)
|
||||
return redis.call("ZREM", pendingNotificationQueue, endpoint)
|
||||
@@ -132,4 +132,8 @@
|
||||
</addColumn>
|
||||
</changeSet>
|
||||
|
||||
<changeSet runInTransaction="false" id="14" author="ehren">
|
||||
<sql>DROP INDEX CONCURRENTLY IF EXISTS public.destination_index;</sql>
|
||||
</changeSet>
|
||||
|
||||
</databaseChangeLog>
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class DynamicConfigurationTest {
|
||||
|
||||
@Test
|
||||
public void testParseExperimentConfig() throws JsonProcessingException {
|
||||
{
|
||||
final String emptyConfigYaml = "test: true";
|
||||
final DynamicConfiguration emptyConfig = DynamicConfigurationManager.OBJECT_MAPPER.readValue(emptyConfigYaml, DynamicConfiguration.class);
|
||||
|
||||
assertFalse(emptyConfig.getExperimentEnrollmentConfiguration("test").isPresent());
|
||||
}
|
||||
|
||||
{
|
||||
final String experimentConfigYaml =
|
||||
"experiments:\n" +
|
||||
" percentageOnly:\n" +
|
||||
" enrollmentPercentage: 12\n" +
|
||||
" uuidsAndPercentage:\n" +
|
||||
" enrolledUuids:\n" +
|
||||
" - 717b1c09-ed0b-4120-bb0e-f4697534b8e1\n" +
|
||||
" - 279f264c-56d7-4bbf-b9da-de718ff90903\n" +
|
||||
" enrollmentPercentage: 77\n" +
|
||||
" uuidsOnly:\n" +
|
||||
" enrolledUuids:\n" +
|
||||
" - 71618739-114c-4b1f-bb0d-6478a44eb600";
|
||||
|
||||
final DynamicConfiguration config = DynamicConfigurationManager.OBJECT_MAPPER.readValue(experimentConfigYaml, DynamicConfiguration.class);
|
||||
|
||||
assertFalse(config.getExperimentEnrollmentConfiguration("unconfigured").isPresent());
|
||||
|
||||
assertTrue(config.getExperimentEnrollmentConfiguration("percentageOnly").isPresent());
|
||||
assertEquals(12, config.getExperimentEnrollmentConfiguration("percentageOnly").get().getEnrollmentPercentage());
|
||||
assertEquals(Collections.emptySet(), config.getExperimentEnrollmentConfiguration("percentageOnly").get().getEnrolledUuids());
|
||||
|
||||
assertTrue(config.getExperimentEnrollmentConfiguration("uuidsAndPercentage").isPresent());
|
||||
assertEquals(77, config.getExperimentEnrollmentConfiguration("uuidsAndPercentage").get().getEnrollmentPercentage());
|
||||
assertEquals(Set.of(UUID.fromString("717b1c09-ed0b-4120-bb0e-f4697534b8e1"), UUID.fromString("279f264c-56d7-4bbf-b9da-de718ff90903")),
|
||||
config.getExperimentEnrollmentConfiguration("uuidsAndPercentage").get().getEnrolledUuids());
|
||||
|
||||
assertTrue(config.getExperimentEnrollmentConfiguration("uuidsOnly").isPresent());
|
||||
assertEquals(0, config.getExperimentEnrollmentConfiguration("uuidsOnly").get().getEnrollmentPercentage());
|
||||
assertEquals(Set.of(UUID.fromString("71618739-114c-4b1f-bb0d-6478a44eb600")),
|
||||
config.getExperimentEnrollmentConfiguration("uuidsOnly").get().getEnrolledUuids());
|
||||
}
|
||||
}
|
||||
}
|
||||
-163
@@ -1,163 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit.ResourceTestRule;
|
||||
import junitparams.JUnitParamsRunner;
|
||||
import junitparams.Parameters;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAccount;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.Form;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(JUnitParamsRunner.class)
|
||||
public class FeatureFlagsControllerTest {
|
||||
|
||||
private static final FeatureFlagsManager FEATURE_FLAG_MANAGER = mock(FeatureFlagsManager.class);
|
||||
private static final FeatureFlagsController FEATURE_FLAG_CONTROLLER = new FeatureFlagsController(FEATURE_FLAG_MANAGER, List.of("first", "second"));
|
||||
|
||||
@Rule
|
||||
public final ResourceTestRule resources = ResourceTestRule.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(ImmutableSet.of(Account.class, DisabledPermittedAccount.class)))
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new DeviceLimitExceededExceptionMapper())
|
||||
.addResource(FEATURE_FLAG_CONTROLLER)
|
||||
.build();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
reset(FEATURE_FLAG_MANAGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSet() {
|
||||
{
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/featureflag/testFlag")
|
||||
.request()
|
||||
.header("Token", "first")
|
||||
.put(Entity.form(new Form().param("active", "true")));
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(FEATURE_FLAG_MANAGER).setFeatureFlag("testFlag", true);
|
||||
}
|
||||
|
||||
{
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/featureflag/secondFlag")
|
||||
.request()
|
||||
.header("Token", "first")
|
||||
.put(Entity.form(new Form().param("active", "false")));
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(FEATURE_FLAG_MANAGER).setFeatureFlag("secondFlag", false);
|
||||
}
|
||||
|
||||
{
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/featureflag/testFlag")
|
||||
.request()
|
||||
.header("Token", "bogus-token")
|
||||
.put(Entity.form(new Form().param("active", "true")));
|
||||
|
||||
assertEquals(401, response.getStatus());
|
||||
verifyNoMoreInteractions(FEATURE_FLAG_MANAGER);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Test
|
||||
public void testGet() {
|
||||
final Map<String, Boolean> managedFlags = Map.of("activeFlag", true, "inactiveFlag", false);
|
||||
when(FEATURE_FLAG_MANAGER.getAllFlags()).thenReturn(managedFlags);
|
||||
|
||||
{
|
||||
final Map returnedFlags = resources.getJerseyTest()
|
||||
.target("/v1/featureflag")
|
||||
.request()
|
||||
.header("Token", "first")
|
||||
.get(Map.class);
|
||||
|
||||
verify(FEATURE_FLAG_MANAGER).getAllFlags();
|
||||
assertEquals(managedFlags, returnedFlags);
|
||||
}
|
||||
|
||||
{
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/featureflag")
|
||||
.request()
|
||||
.header("Token", "bogus-token")
|
||||
.get();
|
||||
|
||||
assertEquals(401, response.getStatus());
|
||||
verifyNoMoreInteractions(FEATURE_FLAG_MANAGER);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelete() {
|
||||
{
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/featureflag/testFlag")
|
||||
.request()
|
||||
.header("Token", "first")
|
||||
.delete();
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(FEATURE_FLAG_MANAGER).deleteFeatureFlag("testFlag");
|
||||
}
|
||||
|
||||
{
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/featureflag/testFlag")
|
||||
.request()
|
||||
.header("Token", "bogus-token")
|
||||
.delete();
|
||||
|
||||
assertEquals(401, response.getStatus());
|
||||
verifyNoMoreInteractions(FEATURE_FLAG_MANAGER);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "argumentsForTestIsAuthorized")
|
||||
public void testIsAuthorized(final String token, final boolean expectAuthorized) {
|
||||
assertEquals(expectAuthorized, FEATURE_FLAG_CONTROLLER.isAuthorized(token));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private Object argumentsForTestIsAuthorized() {
|
||||
return new Object[] {
|
||||
new Object[] { "first", true },
|
||||
new Object[] { "second", true },
|
||||
new Object[] { "third", false },
|
||||
new Object[] { "firstfirstfirst", false },
|
||||
new Object[] { null, false }
|
||||
};
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.experiment;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicExperimentEnrollmentConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ExperimentEnrollmentManagerTest {
|
||||
|
||||
private DynamicExperimentEnrollmentConfiguration experimentEnrollmentConfiguration;
|
||||
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private Account account;
|
||||
|
||||
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
|
||||
private static final String EXPERIMENT_NAME = "test";
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
final DynamicConfigurationManager dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
|
||||
experimentEnrollmentConfiguration = mock(DynamicExperimentEnrollmentConfiguration.class);
|
||||
experimentEnrollmentManager = new ExperimentEnrollmentManager(dynamicConfigurationManager);
|
||||
account = mock(Account.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getExperimentEnrollmentConfiguration(EXPERIMENT_NAME)).thenReturn(Optional.of(experimentEnrollmentConfiguration));
|
||||
when(account.getUuid()).thenReturn(ACCOUNT_UUID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEnrolled() {
|
||||
assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), EXPERIMENT_NAME));
|
||||
assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), EXPERIMENT_NAME + "-unrelated-experiment"));
|
||||
|
||||
when(experimentEnrollmentConfiguration.getEnrolledUuids()).thenReturn(Set.of(ACCOUNT_UUID));
|
||||
assertTrue(experimentEnrollmentManager.isEnrolled(account.getUuid(), EXPERIMENT_NAME));
|
||||
|
||||
when(experimentEnrollmentConfiguration.getEnrolledUuids()).thenReturn(Collections.emptySet());
|
||||
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(0);
|
||||
|
||||
assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), EXPERIMENT_NAME));
|
||||
|
||||
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
|
||||
assertTrue(experimentEnrollmentManager.isEnrolled(account.getUuid(), EXPERIMENT_NAME));
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClientFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.AbstractRedisClusterTest;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisException;
|
||||
import org.whispersystems.textsecuregcm.redis.ReplicatedJedisPool;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.embedded.RedisServer;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeFalse;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ApnFallbackManagerTest extends AbstractRedisClusterTest {
|
||||
|
||||
private Account account;
|
||||
private Device device;
|
||||
|
||||
private APNSender apnSender;
|
||||
|
||||
private ApnFallbackManager apnFallbackManager;
|
||||
|
||||
private static RedisServer redisServer;
|
||||
|
||||
private static final UUID ACCOUNT_UUID = UUID.randomUUID();
|
||||
private static final String ACCOUNT_NUMBER = "+18005551234";
|
||||
private static final long DEVICE_ID = 1L;
|
||||
private static final String VOIP_APN_ID = RandomStringUtils.randomAlphanumeric(32);
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpRedisSingleton() throws Exception {
|
||||
assumeFalse(System.getProperty("os.name").equalsIgnoreCase("windows"));
|
||||
|
||||
redisServer = RedisServer.builder()
|
||||
.setting("appendonly no")
|
||||
.setting("dir " + System.getProperty("java.io.tmpdir"))
|
||||
.port(AbstractRedisClusterTest.getNextRedisClusterPort())
|
||||
.build();
|
||||
|
||||
redisServer.start();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
final String redisUrl = String.format("redis://127.0.0.1:%d", redisServer.ports().get(0));
|
||||
|
||||
final ReplicatedJedisPool replicatedJedisPool = new RedisClientFactory("test-pool",
|
||||
redisUrl,
|
||||
List.of(redisUrl),
|
||||
new CircuitBreakerConfiguration()).getRedisClientPool();
|
||||
|
||||
try (final Jedis jedis = replicatedJedisPool.getWriteResource()) {
|
||||
jedis.flushAll();
|
||||
}
|
||||
|
||||
device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
when(device.getVoipApnId()).thenReturn(VOIP_APN_ID);
|
||||
when(device.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
|
||||
account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(ACCOUNT_UUID);
|
||||
when(account.getNumber()).thenReturn(ACCOUNT_NUMBER);
|
||||
when(account.getDevice(DEVICE_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.get(ACCOUNT_NUMBER)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.get(ACCOUNT_UUID)).thenReturn(Optional.of(account));
|
||||
|
||||
apnSender = mock(APNSender.class);
|
||||
|
||||
apnFallbackManager = new ApnFallbackManager(replicatedJedisPool, getRedisCluster(), apnSender, accountsManager);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownRedisSingleton() {
|
||||
redisServer.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClusterInsert() throws RedisException {
|
||||
final String endpoint = apnFallbackManager.getClusterEndpointKey(account, device);
|
||||
|
||||
assertTrue(apnFallbackManager.getPendingDestinationsFromClusterCache(SlotHash.getSlot(endpoint), 1).isEmpty());
|
||||
|
||||
apnFallbackManager.schedule(account, device, System.currentTimeMillis() - 30_000);
|
||||
|
||||
final List<String> pendingDestinations = apnFallbackManager.getPendingDestinationsFromClusterCache(SlotHash.getSlot(endpoint), 2);
|
||||
assertEquals(1, pendingDestinations.size());
|
||||
|
||||
final Optional<Pair<String, Long>> maybeUuidAndDeviceId = ApnFallbackManager.getSeparated(pendingDestinations.get(0));
|
||||
|
||||
assertTrue(maybeUuidAndDeviceId.isPresent());
|
||||
assertEquals(ACCOUNT_UUID.toString(), maybeUuidAndDeviceId.get().first());
|
||||
assertEquals(DEVICE_ID, (long)maybeUuidAndDeviceId.get().second());
|
||||
|
||||
assertTrue(apnFallbackManager.getPendingDestinationsFromClusterCache(SlotHash.getSlot(endpoint), 1).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessNextSlot() throws RedisException {
|
||||
final ApnFallbackManager.ClusterCacheWorker worker = apnFallbackManager.new ClusterCacheWorker();
|
||||
|
||||
apnFallbackManager.schedule(account, device, System.currentTimeMillis() - 30_000);
|
||||
|
||||
final int slot = SlotHash.getSlot(apnFallbackManager.getClusterEndpointKey(account, device));
|
||||
final int previousSlot = (slot + SlotHash.SLOT_COUNT - 1) % SlotHash.SLOT_COUNT;
|
||||
|
||||
getRedisCluster().withCluster(connection -> connection.sync().set(ApnFallbackManager.NEXT_SLOT_TO_PERSIST_KEY, String.valueOf(previousSlot)));
|
||||
|
||||
assertEquals(1, worker.processNextSlot());
|
||||
|
||||
final ArgumentCaptor<ApnMessage> messageCaptor = ArgumentCaptor.forClass(ApnMessage.class);
|
||||
verify(apnSender).sendMessage(messageCaptor.capture());
|
||||
|
||||
final ApnMessage message = messageCaptor.getValue();
|
||||
|
||||
assertEquals(VOIP_APN_ID, message.getApnId());
|
||||
assertEquals(ACCOUNT_NUMBER, message.getNumber());
|
||||
assertEquals(DEVICE_ID, message.getDeviceId());
|
||||
|
||||
assertEquals(0, worker.processNextSlot());
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.appconfig.AmazonAppConfig;
|
||||
import com.amazonaws.services.appconfig.model.GetConfigurationRequest;
|
||||
import com.amazonaws.services.appconfig.model.GetConfigurationResult;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class DynamicConfigurationManagerTest {
|
||||
|
||||
private DynamicConfigurationManager dynamicConfigurationManager;
|
||||
private AmazonAppConfig appConfig;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.appConfig = mock(AmazonAppConfig.class);
|
||||
this.dynamicConfigurationManager = new DynamicConfigurationManager(appConfig, "foo", "bar", "baz", "poof");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetConfig() {
|
||||
ArgumentCaptor<GetConfigurationRequest> captor = ArgumentCaptor.forClass(GetConfigurationRequest.class);
|
||||
when(appConfig.getConfiguration(captor.capture())).thenReturn(new GetConfigurationResult().withContent(ByteBuffer.wrap("test: true".getBytes()))
|
||||
.withConfigurationVersion("1"));
|
||||
|
||||
dynamicConfigurationManager.start();
|
||||
|
||||
assertThat(captor.getValue().getApplication()).isEqualTo("foo");
|
||||
assertThat(captor.getValue().getEnvironment()).isEqualTo("bar");
|
||||
assertThat(captor.getValue().getConfiguration()).isEqualTo("baz");
|
||||
assertThat(captor.getValue().getClientId()).isEqualTo("poof");
|
||||
|
||||
assertThat(dynamicConfigurationManager.getConfiguration()).isNotNull();
|
||||
}
|
||||
}
|
||||
+46
-19
@@ -5,6 +5,12 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
|
||||
import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.Table;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.opentable.db.postgres.embedded.LiquibasePreparer;
|
||||
import com.opentable.db.postgres.junit.EmbeddedPostgresRules;
|
||||
@@ -18,11 +24,12 @@ import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.redis.AbstractRedisClusterTest;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbRule;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -35,6 +42,8 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -43,11 +52,15 @@ public class MessagePersisterIntegrationTest extends AbstractRedisClusterTest {
|
||||
@Rule
|
||||
public PreparedDbRule db = EmbeddedPostgresRules.preparedDatabase(LiquibasePreparer.forClasspathLocation("messagedb.xml"));
|
||||
|
||||
@Rule
|
||||
public MessagesDynamoDbRule messagesDynamoDbRule = new MessagesDynamoDbRule();
|
||||
|
||||
private ExecutorService notificationExecutorService;
|
||||
private MessagesCache messagesCache;
|
||||
private MessagesManager messagesManager;
|
||||
private MessagePersister messagePersister;
|
||||
private Account account;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final Duration PERSIST_DELAY = Duration.ofMinutes(10);
|
||||
|
||||
@@ -62,12 +75,16 @@ public class MessagePersisterIntegrationTest extends AbstractRedisClusterTest {
|
||||
});
|
||||
|
||||
final Messages messages = new Messages(new FaultTolerantDatabase("messages-test", Jdbi.create(db.getTestDatabase()), new CircuitBreakerConfiguration()));
|
||||
final MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(messagesDynamoDbRule.getDynamoDB(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), anyString())).thenReturn(Boolean.TRUE);
|
||||
|
||||
notificationExecutorService = Executors.newSingleThreadExecutor();
|
||||
messagesCache = new MessagesCache(getRedisCluster(), notificationExecutorService);
|
||||
messagesManager = new MessagesManager(messages, messagesCache, mock(PushLatencyManager.class));
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, PERSIST_DELAY);
|
||||
messagesCache = new MessagesCache(getRedisCluster(), getRedisCluster(), notificationExecutorService);
|
||||
messagesManager = new MessagesManager(messages, messagesDynamoDb, messagesCache, mock(PushLatencyManager.class), experimentEnrollmentManager);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, mock(FeatureFlagsManager.class), PERSIST_DELAY);
|
||||
|
||||
account = mock(Account.class);
|
||||
|
||||
@@ -139,25 +156,35 @@ public class MessagePersisterIntegrationTest extends AbstractRedisClusterTest {
|
||||
|
||||
final List<MessageProtos.Envelope> persistedMessages = new ArrayList<>(messageCount);
|
||||
|
||||
try (final PreparedStatement statement = db.getTestDatabase().getConnection().prepareStatement("SELECT * FROM messages WHERE destination = ? ORDER BY timestamp ASC")) {
|
||||
statement.setString(1, account.getNumber());
|
||||
|
||||
try (final ResultSet resultSet = statement.executeQuery()) {
|
||||
while (resultSet.next()) {
|
||||
persistedMessages.add(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(resultSet.getString("guid"))
|
||||
.setType(MessageProtos.Envelope.Type.valueOf(resultSet.getInt("type")))
|
||||
.setTimestamp(resultSet.getLong("timestamp"))
|
||||
.setServerTimestamp(resultSet.getLong("server_timestamp"))
|
||||
.setContent(ByteString.copyFrom(resultSet.getBytes("content")))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
DynamoDB dynamoDB = messagesDynamoDbRule.getDynamoDB();
|
||||
Table table = dynamoDB.getTable(MessagesDynamoDbRule.TABLE_NAME);
|
||||
final ItemCollection<ScanOutcome> scan = table.scan(new ScanSpec());
|
||||
for (Item item : scan) {
|
||||
persistedMessages.add(MessageProtos.Envelope.newBuilder()
|
||||
.setServerGuid(convertBinaryToUuid(item.getBinary("U")).toString())
|
||||
.setType(MessageProtos.Envelope.Type.valueOf(item.getInt("T")))
|
||||
.setTimestamp(item.getLong("TS"))
|
||||
.setServerTimestamp(extractServerTimestamp(item.getBinary("S")))
|
||||
.setContent(ByteString.copyFrom(item.getBinary("C")))
|
||||
.build());
|
||||
}
|
||||
|
||||
assertEquals(expectedMessages, persistedMessages);
|
||||
}
|
||||
|
||||
private static UUID convertBinaryToUuid(byte[] bytes) {
|
||||
ByteBuffer bb = ByteBuffer.wrap(bytes);
|
||||
long msb = bb.getLong();
|
||||
long lsb = bb.getLong();
|
||||
return new UUID(msb, lsb);
|
||||
}
|
||||
|
||||
private static long extractServerTimestamp(byte[] bytes) {
|
||||
ByteBuffer bb = ByteBuffer.wrap(bytes);
|
||||
bb.getLong();
|
||||
return bb.getLong();
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, final long timestamp) {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setTimestamp(timestamp)
|
||||
|
||||
+2
-2
@@ -67,8 +67,8 @@ public class MessagePersisterTest extends AbstractRedisClusterTest {
|
||||
when(account.getNumber()).thenReturn(DESTINATION_ACCOUNT_NUMBER);
|
||||
|
||||
notificationExecutorService = Executors.newSingleThreadExecutor();
|
||||
messagesCache = new MessagesCache(getRedisCluster(), notificationExecutorService);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, PERSIST_DELAY);
|
||||
messagesCache = new MessagesCache(getRedisCluster(), getRedisCluster(), notificationExecutorService);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, mock(FeatureFlagsManager.class), PERSIST_DELAY);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
final String destination = invocation.getArgument(0, String.class);
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ public class MessagesCacheTest extends AbstractRedisClusterTest {
|
||||
getRedisCluster().useCluster(connection -> connection.sync().masters().commands().configSet("notify-keyspace-events", "Klgz"));
|
||||
|
||||
notificationExecutorService = Executors.newSingleThreadExecutor();
|
||||
messagesCache = new MessagesCache(getRedisCluster(), notificationExecutorService);
|
||||
messagesCache = new MessagesCache(getRedisCluster(), getRedisCluster(), notificationExecutorService);
|
||||
|
||||
messagesCache.start();
|
||||
}
|
||||
|
||||
+186
-152
@@ -186,11 +186,12 @@ public class AccountControllerTest {
|
||||
when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
|
||||
when(senderRegLockAccount.getUuid()).thenReturn(SENDER_REG_LOCK_UUID);
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), "1234-push")));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OLD)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(31), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("333333", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_REG_LOCK)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PIN)).thenReturn(Optional.of(new StoredVerificationCode("444444", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_OVER_PREFIX)).thenReturn(Optional.of(new StoredVerificationCode("777777", System.currentTimeMillis(), "1234-push")));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_PREAUTH)).thenReturn(Optional.of(new StoredVerificationCode("555555", System.currentTimeMillis(), "validchallenge")));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_HAS_STORAGE)).thenReturn(Optional.of(new StoredVerificationCode("666666", System.currentTimeMillis(), null)));
|
||||
when(pendingAccountsManager.getCodeForNumber(SENDER_TRANSFER)).thenReturn(Optional.of(new StoredVerificationCode("1234", System.currentTimeMillis(), null)));
|
||||
@@ -243,6 +244,25 @@ public class AccountControllerTest {
|
||||
verifyNoMoreInteractions(apnSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFcmPreauthIvoryCoast() throws Exception {
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/fcm/preauth/mytoken/+2250707312345")
|
||||
.request()
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
ArgumentCaptor<GcmMessage> captor = ArgumentCaptor.forClass(GcmMessage.class);
|
||||
|
||||
verify(gcmSender, times(1)).sendMessage(captor.capture());
|
||||
assertThat(captor.getValue().getGcmId()).isEqualTo("mytoken");
|
||||
assertThat(captor.getValue().getData().isPresent()).isTrue();
|
||||
assertThat(captor.getValue().getData().get().length()).isEqualTo(32);
|
||||
|
||||
verifyNoMoreInteractions(apnSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetApnPreauth() throws Exception {
|
||||
Response response = resources.getJerseyTest()
|
||||
@@ -268,6 +288,7 @@ public class AccountControllerTest {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", NICE_HOST)
|
||||
.get();
|
||||
@@ -275,7 +296,7 @@ public class AccountControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(smsSender).deliverSmsVerification(eq(SENDER), eq(Optional.empty()), anyString());
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(NICE_HOST));
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(NICE_HOST));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -291,24 +312,24 @@ public class AccountControllerTest {
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(smsSender).deliverSmsVerification(eq(SENDER_PREAUTH), eq(Optional.empty()), anyString());
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(NICE_HOST));
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(NICE_HOST));
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void testSendCodeWithInvalidPreauth() throws Exception {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER_PREAUTH))
|
||||
// .queryParam("challenge", "invalidchallenge")
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", NICE_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
// }
|
||||
@Test
|
||||
public void testSendCodeWithInvalidPreauth() throws Exception {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER_PREAUTH))
|
||||
.queryParam("challenge", "invalidchallenge")
|
||||
.request()
|
||||
.header("X-Forwarded-For", NICE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendCodeWithNoPreauth() throws Exception {
|
||||
@@ -319,10 +340,9 @@ public class AccountControllerTest {
|
||||
.header("X-Forwarded-For", NICE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(smsSender).deliverSmsVerification(eq(SENDER_PREAUTH), eq(Optional.empty()), anyString());
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(NICE_HOST));
|
||||
verify(smsSender, never()).deliverSmsVerification(eq(SENDER_PREAUTH), eq(Optional.empty()), anyString());
|
||||
}
|
||||
|
||||
|
||||
@@ -332,6 +352,7 @@ public class AccountControllerTest {
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("client", "ios")
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", NICE_HOST)
|
||||
.get();
|
||||
@@ -347,6 +368,7 @@ public class AccountControllerTest {
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("client", "android-ng")
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", NICE_HOST)
|
||||
.get();
|
||||
@@ -356,157 +378,169 @@ public class AccountControllerTest {
|
||||
verify(smsSender).deliverSmsVerification(eq(SENDER), eq(Optional.of("android-ng")), anyString());
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void testSendAbusiveHost() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", ABUSIVE_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(ABUSIVE_HOST));
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
@Test
|
||||
public void testSendAbusiveHost() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", ABUSIVE_HOST)
|
||||
.get();
|
||||
|
||||
// @Test
|
||||
// public void testSendAbusiveHostWithValidCaptcha() throws IOException {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .queryParam("captcha", VALID_CAPTCHA_TOKEN)
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", ABUSIVE_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(200);
|
||||
//
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
// verify(recaptchaClient).verify(eq(VALID_CAPTCHA_TOKEN), eq(ABUSIVE_HOST));
|
||||
// verify(smsSender).deliverSmsVerification(eq(SENDER), eq(Optional.empty()), anyString());
|
||||
// }
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
// @Test
|
||||
// public void testSendAbusiveHostWithInvalidCaptcha() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .queryParam("captcha", INVALID_CAPTCHA_TOKEN)
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", ABUSIVE_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
// verify(recaptchaClient).verify(eq(INVALID_CAPTCHA_TOKEN), eq(ABUSIVE_HOST));
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(ABUSIVE_HOST));
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void testSendRateLimitedHostAutoBlock() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", RATE_LIMITED_IP_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RATE_LIMITED_IP_HOST));
|
||||
// verify(abusiveHostRules).setBlockedHost(eq(RATE_LIMITED_IP_HOST), eq("Auto-Block"));
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
//
|
||||
// verifyNoMoreInteractions(recaptchaClient);
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
@Test
|
||||
public void testSendAbusiveHostWithValidCaptcha() throws IOException {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("captcha", VALID_CAPTCHA_TOKEN)
|
||||
.request()
|
||||
.header("X-Forwarded-For", ABUSIVE_HOST)
|
||||
.get();
|
||||
|
||||
// @Test
|
||||
// public void testSendRateLimitedPrefixAutoBlock() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER_OVER_PREFIX))
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", RATE_LIMITED_PREFIX_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RATE_LIMITED_PREFIX_HOST));
|
||||
// verify(abusiveHostRules).setBlockedHost(eq(RATE_LIMITED_PREFIX_HOST), eq("Auto-Block"));
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
//
|
||||
// verifyNoMoreInteractions(recaptchaClient);
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
// @Test
|
||||
// public void testSendRateLimitedHostNoAutoBlock() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", RATE_LIMITED_HOST2)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RATE_LIMITED_HOST2));
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
//
|
||||
// verifyNoMoreInteractions(recaptchaClient);
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
verify(recaptchaClient).verify(eq(VALID_CAPTCHA_TOKEN), eq(ABUSIVE_HOST));
|
||||
verify(smsSender).deliverSmsVerification(eq(SENDER), eq(Optional.empty()), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendAbusiveHostWithInvalidCaptcha() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("captcha", INVALID_CAPTCHA_TOKEN)
|
||||
.request()
|
||||
.header("X-Forwarded-For", ABUSIVE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
verify(recaptchaClient).verify(eq(INVALID_CAPTCHA_TOKEN), eq(ABUSIVE_HOST));
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendRateLimitedHostAutoBlock() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", RATE_LIMITED_IP_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RATE_LIMITED_IP_HOST));
|
||||
verify(abusiveHostRules).setBlockedHost(eq(RATE_LIMITED_IP_HOST), eq("Auto-Block"));
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
|
||||
verifyNoMoreInteractions(recaptchaClient);
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendRateLimitedPrefixAutoBlock() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER_OVER_PREFIX))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", RATE_LIMITED_PREFIX_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RATE_LIMITED_PREFIX_HOST));
|
||||
verify(abusiveHostRules).setBlockedHost(eq(RATE_LIMITED_PREFIX_HOST), eq("Auto-Block"));
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
|
||||
verifyNoMoreInteractions(recaptchaClient);
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendRateLimitedHostNoAutoBlock() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", RATE_LIMITED_HOST2)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RATE_LIMITED_HOST2));
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
|
||||
verifyNoMoreInteractions(recaptchaClient);
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
|
||||
// @Test
|
||||
// public void testSendMultipleHost() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", NICE_HOST + ", " + ABUSIVE_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verify(abusiveHostRules, times(1)).getAbusiveHostRulesFor(eq(ABUSIVE_HOST));
|
||||
//
|
||||
// verifyNoMoreInteractions(abusiveHostRules);
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
@Test
|
||||
public void testSendMultipleHost() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", NICE_HOST + ", " + ABUSIVE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(abusiveHostRules, times(1)).getAbusiveHostRulesFor(eq(ABUSIVE_HOST));
|
||||
|
||||
verifyNoMoreInteractions(abusiveHostRules);
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
|
||||
// @Test
|
||||
// public void testSendRestrictedHostOut() {
|
||||
// Response response =
|
||||
// resources.getJerseyTest()
|
||||
// .target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
// .request()
|
||||
// .header("X-Forwarded-For", RESTRICTED_HOST)
|
||||
// .get();
|
||||
//
|
||||
// assertThat(response.getStatus()).isEqualTo(402);
|
||||
//
|
||||
// verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RESTRICTED_HOST));
|
||||
// verifyNoMoreInteractions(smsSender);
|
||||
// }
|
||||
@Test
|
||||
public void testSendRestrictedHostOut() {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", SENDER))
|
||||
.queryParam("challenge", "1234-push")
|
||||
.request()
|
||||
.header("X-Forwarded-For", RESTRICTED_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(402);
|
||||
|
||||
verify(abusiveHostRules).getAbusiveHostRulesFor(eq(RESTRICTED_HOST));
|
||||
verifyNoMoreInteractions(smsSender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendRestrictedIn() throws Exception {
|
||||
final String number = "+12345678901";
|
||||
final String challenge = "challenge";
|
||||
|
||||
when(pendingAccountsManager.getCodeForNumber(number)).thenReturn(Optional.of(new StoredVerificationCode("123456", System.currentTimeMillis(), challenge)));
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/sms/code/%s", "+12345678901"))
|
||||
.target(String.format("/v1/accounts/sms/code/%s", number))
|
||||
.queryParam("challenge", challenge)
|
||||
.request()
|
||||
.header("X-Forwarded-For", RESTRICTED_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(smsSender).deliverSmsVerification(eq("+12345678901"), eq(Optional.empty()), anyString());
|
||||
verify(smsSender).deliverSmsVerification(eq(number), eq(Optional.empty()), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-4
@@ -190,9 +190,6 @@ public class DirectoryControllerTest {
|
||||
.put(Entity.entity(new ClientContactTokens(tokens), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.readEntity(ClientContactTokens.class).getContacts()).isEqualTo(expectedResponse);
|
||||
|
||||
verify(ipLimiter).validate("1.1.1.1");
|
||||
assertThat(response.getStatus()).isEqualTo(429);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -11,6 +11,7 @@ import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit.ResourceTestRule;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -34,6 +35,7 @@ import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.Base64;
|
||||
@@ -69,6 +71,7 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.asJson;
|
||||
import static org.whispersystems.textsecuregcm.tests.util.JsonHelpers.jsonFixture;
|
||||
|
||||
@Ignore
|
||||
public class MessageControllerTest {
|
||||
|
||||
private static final String SINGLE_DEVICE_RECIPIENT = "+14151111111";
|
||||
@@ -84,6 +87,7 @@ public class MessageControllerTest {
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final RateLimiter rateLimiter = mock(RateLimiter.class);
|
||||
private final ApnFallbackManager apnFallbackManager = mock(ApnFallbackManager.class);
|
||||
private final FeatureFlagsManager featureFlagsManager = mock(FeatureFlagsManager.class);
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -93,7 +97,7 @@ public class MessageControllerTest {
|
||||
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(ImmutableSet.of(Account.class, DisabledPermittedAccount.class)))
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new MessageController(rateLimiters, messageSender, receiptSender, accountsManager,
|
||||
messagesManager, apnFallbackManager))
|
||||
messagesManager, apnFallbackManager, featureFlagsManager))
|
||||
.build();
|
||||
|
||||
|
||||
|
||||
+80
-8
@@ -9,6 +9,7 @@ import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit.ResourceTestRule;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.Before;
|
||||
import org.junit.ClassRule;
|
||||
@@ -51,6 +52,7 @@ import static org.mockito.Mockito.argThat;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
@@ -91,6 +93,8 @@ public class ProfileControllerTest {
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
reset(s3client);
|
||||
|
||||
when(rateLimiters.getProfileLimiter()).thenReturn(rateLimiter);
|
||||
when(rateLimiters.getUsernameLookupLimiter()).thenReturn(usernameRateLimiter);
|
||||
|
||||
@@ -125,7 +129,7 @@ public class ProfileControllerTest {
|
||||
when(accountsManager.get(argThat((ArgumentMatcher<AmbiguousIdentifier>) identifier -> identifier != null && identifier.hasNumber() && identifier.getNumber().equals(AuthHelper.VALID_NUMBER)))).thenReturn(Optional.of(capabilitiesAccount));
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq("someversion"))).thenReturn(Optional.empty());
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile("validversion", "validname", "profiles/validavatar", "validcommitmnet".getBytes())));
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile("validversion", "validname", "profiles/validavatar", "emoji", "about", "validcommitmnet".getBytes())));
|
||||
|
||||
clearInvocations(rateLimiter);
|
||||
clearInvocations(accountsManager);
|
||||
@@ -302,7 +306,7 @@ public class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", true), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", null, null, true), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
@@ -315,7 +319,8 @@ public class ProfileControllerTest {
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isEqualTo(uploadAttributes.getKey());
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("someversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
}
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull(); }
|
||||
|
||||
@Test
|
||||
public void testSetProfileWantAvatarUploadWithBadProfileSize() throws InvalidInputException {
|
||||
@@ -325,7 +330,7 @@ public class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion", "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", true), MediaType.APPLICATION_JSON_TYPE));
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion", "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", null, null, true), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
}
|
||||
@@ -340,7 +345,7 @@ public class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", false), MediaType.APPLICATION_JSON_TYPE));
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", null, null, false), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
@@ -359,17 +364,18 @@ public class ProfileControllerTest {
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("anotherversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
}
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull(); }
|
||||
|
||||
@Test
|
||||
public void testSetProvfileWithAvatarUploadAndPreviousAvatar() throws InvalidInputException {
|
||||
public void testSetProfileWithAvatarUploadAndPreviousAvatar() throws InvalidInputException {
|
||||
ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(AuthHelper.VALID_UUID_TWO);
|
||||
|
||||
ProfileAvatarUploadAttributes uploadAttributes= resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", true), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", null, null, true), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
@@ -381,6 +387,70 @@ public class ProfileControllerTest {
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull(); }
|
||||
|
||||
@Test
|
||||
public void testSetProfileExtendedName() throws InvalidInputException {
|
||||
ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(AuthHelper.VALID_UUID_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", name, null, null, true), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq("profilesBucket"), eq("profiles/validavatar"));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetProfileEmojiAndBioText() throws InvalidInputException {
|
||||
ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(AuthHelper.VALID_UUID);
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String emoji = RandomStringUtils.randomAlphanumeric(80);
|
||||
final String text = RandomStringUtils.randomAlphanumeric(720);
|
||||
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_NUMBER_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, false), MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
|
||||
ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
verify(profilesManager, times(1)).get(eq(AuthHelper.VALID_UUID_TWO), eq("anotherversion"));
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
|
||||
verify(AuthHelper.VALID_ACCOUNT_TWO).setProfileName(name);
|
||||
verify(AuthHelper.VALID_ACCOUNT_TWO).setAvatar(null);
|
||||
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("anotherversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isEqualTo(emoji);
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isEqualTo(text);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -393,6 +463,8 @@ public class ProfileControllerTest {
|
||||
|
||||
assertThat(profile.getIdentityKey()).isEqualTo("bar");
|
||||
assertThat(profile.getName()).isEqualTo("validname");
|
||||
assertThat(profile.getAbout()).isEqualTo("about");
|
||||
assertThat(profile.getAboutEmoji()).isEqualTo("emoji");
|
||||
assertThat(profile.getAvatar()).isEqualTo("profiles/validavatar");
|
||||
assertThat(profile.getCapabilities().isGv2()).isFalse();
|
||||
assertThat(profile.getCapabilities().isGv1Migration()).isFalse();
|
||||
|
||||
+2
-2
@@ -148,7 +148,7 @@ public class AccountDatabaseCrawlerTest {
|
||||
verify(account2, times(0)).getNumber();
|
||||
verify(listener, times(1)).timeAndProcessCrawlChunk(eq(Optional.of(ACCOUNT1)), eq(Arrays.asList(account2)));
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.empty()));
|
||||
verify(cache, times(1)).clearAccelerate();
|
||||
verify(cache, times(1)).setAccelerated(false);
|
||||
verify(cache, times(1)).isAccelerated();
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
@@ -175,7 +175,7 @@ public class AccountDatabaseCrawlerTest {
|
||||
verify(account2, times(0)).getNumber();
|
||||
verify(listener, times(1)).onCrawlEnd(eq(Optional.of(ACCOUNT2)));
|
||||
verify(cache, times(1)).setLastUuid(eq(Optional.empty()));
|
||||
verify(cache, times(1)).clearAccelerate();
|
||||
verify(cache, times(1)).setAccelerated(false);
|
||||
verify(cache, times(1)).isAccelerated();
|
||||
verify(cache, times(1)).releaseActiveWork(any(String.class));
|
||||
|
||||
|
||||
+6
-1
@@ -73,8 +73,13 @@ public class AccountTest {
|
||||
when(gv2IncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(gv1MigrationCapableDevice.getCapabilities()).thenReturn(new Device.DeviceCapabilities(true, true, true, true, true, true));
|
||||
when(gv1MigrationCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(gv1MigrationIncapableDevice.getCapabilities()).thenReturn(new Device.DeviceCapabilities(true, true, true, true, true, false));
|
||||
when(gv1MigrationIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(gv1MigrationIncapableExpiredDevice.getCapabilities()).thenReturn(new Device.DeviceCapabilities(true, true, true, true, true, false));
|
||||
when(gv1MigrationIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -195,6 +200,6 @@ public class AccountTest {
|
||||
public void isGv1MigrationSupported() {
|
||||
assertTrue(new Account("+18005551234", UUID.randomUUID(), Set.of(gv1MigrationCapableDevice), "1234".getBytes(StandardCharsets.UTF_8)).isGv1MigrationSupported());
|
||||
assertFalse(new Account("+18005551234", UUID.randomUUID(), Set.of(gv1MigrationCapableDevice, gv1MigrationIncapableDevice), "1234".getBytes(StandardCharsets.UTF_8)).isGv1MigrationSupported());
|
||||
assertFalse(new Account("+18005551234", UUID.randomUUID(), Set.of(gv1MigrationCapableDevice, gv1MigrationIncapableExpiredDevice), "1234".getBytes(StandardCharsets.UTF_8)).isGv1MigrationSupported());
|
||||
assertTrue(new Account("+18005551234", UUID.randomUUID(), Set.of(gv1MigrationCapableDevice, gv1MigrationIncapableExpiredDevice), "1234".getBytes(StandardCharsets.UTF_8)).isGv1MigrationSupported());
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import com.opentable.db.postgres.embedded.LiquibasePreparer;
|
||||
import com.opentable.db.postgres.junit.EmbeddedPostgresRules;
|
||||
import com.opentable.db.postgres.junit.PreparedDbRule;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import org.jdbi.v3.core.HandleCallback;
|
||||
import org.jdbi.v3.core.HandleConsumer;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.jdbi.v3.core.statement.UnableToExecuteStatementException;
|
||||
@@ -16,9 +17,12 @@ import org.jdbi.v3.core.transaction.SerializableTransactionRunner;
|
||||
import org.jdbi.v3.core.transaction.TransactionException;
|
||||
import org.jdbi.v3.core.transaction.TransactionIsolationLevel;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AccountsDatabaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.PreKey;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyRecord;
|
||||
@@ -27,6 +31,7 @@ import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -36,6 +41,7 @@ import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@Ignore
|
||||
public class KeysTest {
|
||||
|
||||
@Rule
|
||||
@@ -49,7 +55,7 @@ public class KeysTest {
|
||||
Jdbi.create(db.getTestDatabase()),
|
||||
new CircuitBreakerConfiguration());
|
||||
|
||||
this.keys = new Keys(faultTolerantDatabase);
|
||||
this.keys = new Keys(faultTolerantDatabase, new RetryConfiguration());
|
||||
}
|
||||
|
||||
|
||||
@@ -343,7 +349,10 @@ public class KeysTest {
|
||||
configuration.setRingBufferSizeInClosedState(2);
|
||||
configuration.setFailureRateThreshold(50);
|
||||
|
||||
Keys keys = new Keys(new FaultTolerantDatabase("testBreaker", jdbi, configuration));
|
||||
RetryConfiguration retryConfiguration = new RetryConfiguration();
|
||||
retryConfiguration.setMaxAttempts(1);
|
||||
|
||||
Keys keys = new Keys(new FaultTolerantDatabase("testBreaker", jdbi, configuration), retryConfiguration);
|
||||
|
||||
List<PreKey> deviceOnePreKeys = new LinkedList<>();
|
||||
|
||||
@@ -383,6 +392,31 @@ public class KeysTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetry() {
|
||||
Jdbi jdbi = mock(Jdbi.class);
|
||||
doThrow(new TransactionException("Database error!")).doNothing().when(jdbi).useTransaction(any(TransactionIsolationLevel.class), any(HandleConsumer.class));
|
||||
when(jdbi.getConfig(any())).thenReturn(mock(SerializableTransactionRunner.Configuration.class));
|
||||
|
||||
Keys keys = new Keys(new FaultTolerantDatabase("testBreaker", jdbi, new CircuitBreakerConfiguration()), new RetryConfiguration());
|
||||
|
||||
// We're happy as long as nothing throws an exception
|
||||
keys.store("+18005551234", 1, Collections.emptyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetKeysWithException() {
|
||||
Jdbi jdbi = mock(Jdbi.class);
|
||||
when(jdbi.getConfig(any())).thenReturn(mock(SerializableTransactionRunner.Configuration.class));
|
||||
|
||||
when(jdbi.inTransaction(any(TransactionIsolationLevel.class), any(HandleCallback.class)))
|
||||
.thenThrow(new TransactionException("Database error!"));
|
||||
|
||||
Keys keys = new Keys(new FaultTolerantDatabase("testBreaker", jdbi, new CircuitBreakerConfiguration()), new RetryConfiguration());
|
||||
|
||||
assertThat(keys.get("+18005551234")).isEqualTo(Collections.emptyList());
|
||||
assertThat(keys.get("+18005551234", 1)).isEqualTo(Collections.emptyList());
|
||||
}
|
||||
|
||||
private void verifyStoredState(PreparedStatement statement, String number, int deviceId) throws SQLException {
|
||||
statement.setString(1, number);
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.storage;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import org.junit.Before;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbRule;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MessagesDynamoDbTest {
|
||||
private static final Random random = new Random();
|
||||
private static final MessageProtos.Envelope MESSAGE1;
|
||||
private static final MessageProtos.Envelope MESSAGE2;
|
||||
private static final MessageProtos.Envelope MESSAGE3;
|
||||
|
||||
static {
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
MessageProtos.Envelope.Builder builder = MessageProtos.Envelope.newBuilder();
|
||||
builder.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER);
|
||||
builder.setTimestamp(123456789L);
|
||||
builder.setContent(ByteString.copyFrom(new byte[]{(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF}));
|
||||
builder.setServerGuid(UUID.randomUUID().toString());
|
||||
builder.setServerTimestamp(serverTimestamp);
|
||||
|
||||
MESSAGE1 = builder.build();
|
||||
|
||||
builder.setType(MessageProtos.Envelope.Type.CIPHERTEXT);
|
||||
builder.setSource("12348675309");
|
||||
builder.setSourceUuid(UUID.randomUUID().toString());
|
||||
builder.setSourceDevice(1);
|
||||
builder.setContent(ByteString.copyFromUtf8("MOO"));
|
||||
builder.setServerGuid(UUID.randomUUID().toString());
|
||||
builder.setServerTimestamp(serverTimestamp + 1);
|
||||
|
||||
MESSAGE2 = builder.build();
|
||||
|
||||
builder.setType(MessageProtos.Envelope.Type.UNIDENTIFIED_SENDER);
|
||||
builder.clearSource();
|
||||
builder.clearSourceUuid();
|
||||
builder.clearSourceDevice();
|
||||
builder.setContent(ByteString.copyFromUtf8("COW"));
|
||||
builder.setServerGuid(UUID.randomUUID().toString());
|
||||
builder.setServerTimestamp(serverTimestamp); // Test same millisecond arrival for two different messages
|
||||
|
||||
MESSAGE3 = builder.build();
|
||||
}
|
||||
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
|
||||
@ClassRule
|
||||
public static MessagesDynamoDbRule dynamoDbRule = new MessagesDynamoDbRule();
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
messagesDynamoDb = new MessagesDynamoDb(dynamoDbRule.getDynamoDB(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServerStart() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSimpleFetchAfterInsert() {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final int destinationDeviceId = random.nextInt(255) + 1;
|
||||
messagesDynamoDb.store(List.of(MESSAGE1, MESSAGE2, MESSAGE3), destinationUuid, destinationDeviceId);
|
||||
|
||||
final List<OutgoingMessageEntity> messagesStored = messagesDynamoDb.load(destinationUuid, destinationDeviceId, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE);
|
||||
assertThat(messagesStored).isNotNull().hasSize(3);
|
||||
final MessageProtos.Envelope firstMessage = MESSAGE1.getServerGuid().compareTo(MESSAGE3.getServerGuid()) < 0 ? MESSAGE1 : MESSAGE3;
|
||||
final MessageProtos.Envelope secondMessage = firstMessage == MESSAGE1 ? MESSAGE3 : MESSAGE1;
|
||||
assertThat(messagesStored).element(0).satisfies(verify(firstMessage));
|
||||
assertThat(messagesStored).element(1).satisfies(verify(secondMessage));
|
||||
assertThat(messagesStored).element(2).satisfies(verify(MESSAGE2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteForDestination() {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final UUID secondDestinationUuid = UUID.randomUUID();
|
||||
messagesDynamoDb.store(List.of(MESSAGE1), destinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE2), secondDestinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE3), destinationUuid, 2);
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE3));
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE2));
|
||||
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteForDestinationDevice() {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final UUID secondDestinationUuid = UUID.randomUUID();
|
||||
messagesDynamoDb.store(List.of(MESSAGE1), destinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE2), secondDestinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE3), destinationUuid, 2);
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE3));
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE2));
|
||||
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, 2);
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteMessageByDestinationAndSourceAndTimestamp() {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final UUID secondDestinationUuid = UUID.randomUUID();
|
||||
messagesDynamoDb.store(List.of(MESSAGE1), destinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE2), secondDestinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE3), destinationUuid, 2);
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE3));
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE2));
|
||||
|
||||
messagesDynamoDb.deleteMessageByDestinationAndSourceAndTimestamp(secondDestinationUuid, 1, MESSAGE2.getSource(), MESSAGE2.getTimestamp());
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE3));
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteMessageByDestinationAndGuid() {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final UUID secondDestinationUuid = UUID.randomUUID();
|
||||
messagesDynamoDb.store(List.of(MESSAGE1), destinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE2), secondDestinationUuid, 1);
|
||||
messagesDynamoDb.store(List.of(MESSAGE3), destinationUuid, 2);
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE3));
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE2));
|
||||
|
||||
messagesDynamoDb.deleteMessageByDestinationAndGuid(secondDestinationUuid, 1, UUID.fromString(MESSAGE2.getServerGuid()));
|
||||
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE1));
|
||||
assertThat(messagesDynamoDb.load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1).element(0).satisfies(verify(MESSAGE3));
|
||||
assertThat(messagesDynamoDb.load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
}
|
||||
|
||||
private static void verify(OutgoingMessageEntity retrieved, MessageProtos.Envelope inserted) {
|
||||
assertThat(retrieved.getTimestamp()).isEqualTo(inserted.getTimestamp());
|
||||
assertThat(retrieved.getSource()).isEqualTo(inserted.hasSource() ? inserted.getSource() : null);
|
||||
assertThat(retrieved.getSourceUuid()).isEqualTo(inserted.hasSourceUuid() ? UUID.fromString(inserted.getSourceUuid()) : null);
|
||||
assertThat(retrieved.getSourceDevice()).isEqualTo(inserted.getSourceDevice());
|
||||
assertThat(retrieved.getRelay()).isEqualTo(inserted.hasRelay() ? inserted.getRelay() : null);
|
||||
assertThat(retrieved.getType()).isEqualTo(inserted.getType().getNumber());
|
||||
assertThat(retrieved.getContent()).isEqualTo(inserted.hasContent() ? inserted.getContent().toByteArray() : null);
|
||||
assertThat(retrieved.getMessage()).isEqualTo(inserted.hasLegacyMessage() ? inserted.getLegacyMessage().toByteArray() : null);
|
||||
assertThat(retrieved.getServerTimestamp()).isEqualTo(inserted.getServerTimestamp());
|
||||
assertThat(retrieved.getGuid()).isEqualTo(UUID.fromString(inserted.getServerGuid()));
|
||||
}
|
||||
|
||||
private static VerifyMessage verify(MessageProtos.Envelope expected) {
|
||||
return new VerifyMessage(expected);
|
||||
}
|
||||
|
||||
private static final class VerifyMessage implements Consumer<OutgoingMessageEntity> {
|
||||
private final MessageProtos.Envelope expected;
|
||||
|
||||
public VerifyMessage(MessageProtos.Envelope expected) {
|
||||
this.expected = expected;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(OutgoingMessageEntity outgoingMessageEntity) {
|
||||
verify(outgoingMessageEntity, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -62,7 +62,7 @@ public class ProfilesManagerTest {
|
||||
Profiles profiles = mock(Profiles.class);
|
||||
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", "somecommitment".getBytes());
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null, "somecommitment".getBytes());
|
||||
|
||||
when(commands.hget(eq("profiles::" + uuid.toString()), eq("someversion"))).thenReturn(null);
|
||||
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
|
||||
@@ -88,7 +88,7 @@ public class ProfilesManagerTest {
|
||||
Profiles profiles = mock(Profiles.class);
|
||||
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", "somecommitment".getBytes());
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null, "somecommitment".getBytes());
|
||||
|
||||
when(commands.hget(eq("profiles::" + uuid.toString()), eq("someversion"))).thenThrow(new RedisException("Connection lost"));
|
||||
when(profiles.get(eq(uuid), eq("someversion"))).thenReturn(Optional.of(profile));
|
||||
|
||||
+37
-9
@@ -41,7 +41,7 @@ public class ProfilesTest {
|
||||
@Test
|
||||
public void testSetGet() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", "acommitment".getBytes());
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", "emoji", "the very model of a modern major general", "acommitment".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
@@ -50,12 +50,30 @@ public class ProfilesTest {
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profile.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profile.getAboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetGetNullOptionalFields() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", null, null, null, "acommitment".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profile.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profile.getAboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetReplace() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", "acommitment".getBytes());
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", null, null, "acommitment".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
@@ -64,23 +82,29 @@ public class ProfilesTest {
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isNull();
|
||||
assertThat(retrieved.get().getAboutEmoji()).isNull();
|
||||
|
||||
VersionedProfile updated = new VersionedProfile("123", "bar", "baz", "boof".getBytes());
|
||||
VersionedProfile updated = new VersionedProfile("123", "bar", "baz", "emoji", "bio", "boof".getBytes());
|
||||
profiles.set(uuid, updated);
|
||||
|
||||
retrieved = profiles.get(uuid, "123");
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(updated.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(updated.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(updated.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(updated.getAboutEmoji());
|
||||
|
||||
// Commitment should be unchanged after an overwrite
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(updated.getAvatar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleVersions() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profileOne = new VersionedProfile("123", "foo", "avatarLocation", "acommitmnet".getBytes());
|
||||
VersionedProfile profileTwo = new VersionedProfile("345", "bar", "baz", "boof".getBytes());
|
||||
VersionedProfile profileOne = new VersionedProfile("123", "foo", "avatarLocation", null, null, "acommitmnet".getBytes());
|
||||
VersionedProfile profileTwo = new VersionedProfile("345", "bar", "baz", "emoji", "i keep typing emoju for some reason", "boof".getBytes());
|
||||
|
||||
profiles.set(uuid, profileOne);
|
||||
profiles.set(uuid, profileTwo);
|
||||
@@ -91,6 +115,8 @@ public class ProfilesTest {
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profileOne.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profileOne.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profileOne.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profileOne.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profileOne.getAboutEmoji());
|
||||
|
||||
retrieved = profiles.get(uuid, "345");
|
||||
|
||||
@@ -98,12 +124,14 @@ public class ProfilesTest {
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profileTwo.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profileTwo.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profileTwo.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profileTwo.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profileTwo.getAboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMissing() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", "aDigest".getBytes());
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", null, null, "aDigest".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "888");
|
||||
@@ -114,8 +142,8 @@ public class ProfilesTest {
|
||||
@Test
|
||||
public void testDelete() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profileOne = new VersionedProfile("123", "foo", "avatarLocation", "aDigest".getBytes());
|
||||
VersionedProfile profileTwo = new VersionedProfile("345", "bar", "baz", "boof".getBytes());
|
||||
VersionedProfile profileOne = new VersionedProfile("123", "foo", "avatarLocation", null, null, "aDigest".getBytes());
|
||||
VersionedProfile profileTwo = new VersionedProfile("345", "bar", "baz", null, null, "boof".getBytes());
|
||||
|
||||
profiles.set(uuid, profileOne);
|
||||
profiles.set(uuid, profileTwo);
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import com.almworks.sqlite4java.SQLite;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.client.builder.AwsClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
|
||||
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
|
||||
import org.junit.rules.ExternalResource;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
|
||||
public class LocalDynamoDbRule extends ExternalResource {
|
||||
private DynamoDBProxyServer server;
|
||||
private int port;
|
||||
|
||||
@Override
|
||||
protected void before() throws Throwable {
|
||||
super.before();
|
||||
SQLite.setLibraryPath("target/lib"); // if you see a library failed to load error, you need to run mvn test-compile at least once first
|
||||
ServerSocket serverSocket = new ServerSocket(0);
|
||||
serverSocket.setReuseAddress(false);
|
||||
port = serverSocket.getLocalPort();
|
||||
serverSocket.close();
|
||||
server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", String.valueOf(port)});
|
||||
server.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void after() {
|
||||
try {
|
||||
server.stop();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
super.after();
|
||||
}
|
||||
|
||||
public DynamoDB getDynamoDB() {
|
||||
AmazonDynamoDBClientBuilder clientBuilder =
|
||||
AmazonDynamoDBClientBuilder.standard()
|
||||
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, "local-test-region"))
|
||||
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("accessKey", "secretKey")));
|
||||
return new DynamoDB(clientBuilder.build());
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
|
||||
import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex;
|
||||
import com.amazonaws.services.dynamodbv2.model.Projection;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProjectionType;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
|
||||
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
|
||||
|
||||
public class MessagesDynamoDbRule extends LocalDynamoDbRule {
|
||||
|
||||
public static final String TABLE_NAME = "Signal_Messages_UnitTest";
|
||||
|
||||
@Override
|
||||
protected void before() throws Throwable {
|
||||
super.before();
|
||||
DynamoDB dynamoDB = getDynamoDB();
|
||||
CreateTableRequest createTableRequest = new CreateTableRequest()
|
||||
.withTableName(TABLE_NAME)
|
||||
.withKeySchema(new KeySchemaElement("H", "HASH"),
|
||||
new KeySchemaElement("S", "RANGE"))
|
||||
.withAttributeDefinitions(new AttributeDefinition("H", ScalarAttributeType.B),
|
||||
new AttributeDefinition("S", ScalarAttributeType.B),
|
||||
new AttributeDefinition("U", ScalarAttributeType.B))
|
||||
.withProvisionedThroughput(new ProvisionedThroughput(20L, 20L))
|
||||
.withLocalSecondaryIndexes(new LocalSecondaryIndex().withIndexName("Message_UUID_Index")
|
||||
.withKeySchema(new KeySchemaElement("H", "HASH"),
|
||||
new KeySchemaElement("U", "RANGE"))
|
||||
.withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY)));
|
||||
dynamoDB.createTable(createTableRequest);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void after() {
|
||||
super.after();
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -20,6 +20,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.CircuitBreakerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.PushLatencyManager;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.redis.AbstractRedisClusterTest;
|
||||
@@ -28,11 +29,14 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.Messages;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MessagesDynamoDbRule;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -47,6 +51,7 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atMost;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -60,13 +65,18 @@ public class WebSocketConnectionIntegrationTest extends AbstractRedisClusterTest
|
||||
@Rule
|
||||
public PreparedDbRule db = EmbeddedPostgresRules.preparedDatabase(LiquibasePreparer.forClasspathLocation("messagedb.xml"));
|
||||
|
||||
@Rule
|
||||
public MessagesDynamoDbRule messagesDynamoDbRule = new MessagesDynamoDbRule();
|
||||
|
||||
private ExecutorService executorService;
|
||||
private Messages messages;
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagesCache messagesCache;
|
||||
private Account account;
|
||||
private Device device;
|
||||
private WebSocketClient webSocketClient;
|
||||
private WebSocketConnection webSocketConnection;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
@@ -81,18 +91,21 @@ public class WebSocketConnectionIntegrationTest extends AbstractRedisClusterTest
|
||||
|
||||
executorService = Executors.newSingleThreadExecutor();
|
||||
messages = new Messages(new FaultTolerantDatabase("messages-test", Jdbi.create(db.getTestDatabase()), new CircuitBreakerConfiguration()));
|
||||
messagesCache = new MessagesCache(getRedisCluster(), executorService);
|
||||
messagesCache = new MessagesCache(getRedisCluster(), getRedisCluster(), executorService);
|
||||
messagesDynamoDb = new MessagesDynamoDb(messagesDynamoDbRule.getDynamoDB(), MessagesDynamoDbRule.TABLE_NAME, Duration.ofDays(7));
|
||||
account = mock(Account.class);
|
||||
device = mock(Device.class);
|
||||
webSocketClient = mock(WebSocketClient.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(device.getId()).thenReturn(1L);
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), anyString())).thenReturn(Boolean.FALSE);
|
||||
|
||||
webSocketConnection = new WebSocketConnection(
|
||||
mock(ReceiptSender.class),
|
||||
new MessagesManager(messages, messagesCache, mock(PushLatencyManager.class)),
|
||||
new MessagesManager(messages, messagesDynamoDb, messagesCache, mock(PushLatencyManager.class), experimentEnrollmentManager),
|
||||
account,
|
||||
device,
|
||||
webSocketClient);
|
||||
|
||||
+3
-3
@@ -195,7 +195,7 @@ public class WebSocketConnectionTest {
|
||||
futures.get(0).completeExceptionally(new IOException());
|
||||
futures.get(2).completeExceptionally(new IOException());
|
||||
|
||||
verify(storedMessages, times(1)).delete(eq(account.getNumber()), eq(accountUuid), eq(2L), eq(2L), eq(false));
|
||||
verify(storedMessages, times(1)).delete(eq(account.getNumber()), eq(accountUuid), eq(2L), eq(outgoingMessages.get(1).getGuid()));
|
||||
verify(receiptSender, times(1)).sendReceipt(eq(account), eq("sender1"), eq(2222L));
|
||||
|
||||
connection.stop();
|
||||
@@ -712,7 +712,7 @@ public class WebSocketConnectionTest {
|
||||
|
||||
// We should delete all three messages even though we only sent two; one got discarded because it was too big for
|
||||
// desktop clients.
|
||||
verify(storedMessages, times(3)).delete(eq(account.getNumber()), eq(accountUuid), eq(2L), anyLong(), anyBoolean());
|
||||
verify(storedMessages, times(3)).delete(eq(account.getNumber()), eq(accountUuid), eq(2L), any(UUID.class));
|
||||
|
||||
connection.stop();
|
||||
verify(client).close(anyInt(), anyString());
|
||||
@@ -785,7 +785,7 @@ public class WebSocketConnectionTest {
|
||||
futures.get(1).complete(response);
|
||||
futures.get(2).complete(response);
|
||||
|
||||
verify(storedMessages, times(3)).delete(eq(account.getNumber()), eq(accountUuid), eq(2L), anyLong(), anyBoolean());
|
||||
verify(storedMessages, times(3)).delete(eq(account.getNumber()), eq(accountUuid), eq(2L), any(UUID.class));
|
||||
|
||||
connection.stop();
|
||||
verify(client).close(anyInt(), anyString());
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class DeleteFeatureFlagTaskTest {
|
||||
|
||||
private FeatureFlagsManager featureFlagsManager;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
featureFlagsManager = mock(FeatureFlagsManager.class);
|
||||
|
||||
when(featureFlagsManager.getAllFlags()).thenReturn(Collections.emptyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecute() {
|
||||
final DeleteFeatureFlagTask task = new DeleteFeatureFlagTask(featureFlagsManager);
|
||||
|
||||
task.execute(Map.of("flag", List.of("test-flag-1", "test-flag-2")), mock(PrintWriter.class));
|
||||
verify(featureFlagsManager).deleteFeatureFlag("test-flag-1");
|
||||
verify(featureFlagsManager).deleteFeatureFlag("test-flag-2");
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.whispersystems.textsecuregcm.storage.FeatureFlagsManager;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class SetFeatureFlagTaskTest {
|
||||
|
||||
private FeatureFlagsManager featureFlagsManager;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
featureFlagsManager = mock(FeatureFlagsManager.class);
|
||||
|
||||
when(featureFlagsManager.getAllFlags()).thenReturn(Collections.emptyMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecute() {
|
||||
final SetFeatureFlagTask task = new SetFeatureFlagTask(featureFlagsManager);
|
||||
|
||||
task.execute(Map.of("flag", List.of("test-flag"), "active", List.of("true")), mock(PrintWriter.class));
|
||||
|
||||
verify(featureFlagsManager).setFeatureFlag("test-flag", true);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user