mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:46:47 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef716aacc2 | ||
|
|
c91242ed60 | ||
|
|
e536a40740 | ||
|
|
5aaf4cad20 | ||
|
|
1c167ec150 | ||
|
|
9898e18ae2 | ||
|
|
b182c3d86d | ||
|
|
96a4d4c8ac |
No files matched your search
@@ -160,9 +160,6 @@ dynamoDbTables:
|
||||
cacheCluster: # Redis server configuration for cache cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
clientPresenceCluster: # Redis server configuration for client presence cluster
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
uri: redis://redis.example.com:6379/
|
||||
|
||||
|
||||
@@ -165,11 +165,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private MessageCacheConfiguration messageCache;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private FaultTolerantRedisClusterFactory clientPresenceCluster;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -411,10 +406,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return messageCache;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getClientPresenceClusterConfiguration() {
|
||||
return clientPresenceCluster;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getPushSchedulerCluster() {
|
||||
return pushSchedulerCluster;
|
||||
}
|
||||
|
||||
@@ -191,7 +191,6 @@ import org.whispersystems.textsecuregcm.metrics.TrafficSource;
|
||||
import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
|
||||
import org.whispersystems.textsecuregcm.providers.RedisClusterHealthCheck;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.MessageSender;
|
||||
import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
@@ -452,8 +451,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient clientPresenceCluster = config.getClientPresenceClusterConfiguration()
|
||||
.build("client_presence", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -543,11 +540,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
.build();
|
||||
ExecutorService clientPresenceExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "clientPresence-%d"))
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
.build();
|
||||
// unbounded executor (same as cachedThreadPool)
|
||||
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "remoteStorage-%d"))
|
||||
@@ -617,8 +609,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
secureValueRecoveryServiceExecutor, secureValueRecoveryServiceRetryExecutor, config.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, config.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster, recurringJobExecutor,
|
||||
keyspaceNotificationDispatchExecutor);
|
||||
PubSubClientEventManager pubSubClientEventManager = new PubSubClientEventManager(messagesCluster, clientEventExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profiles, cacheCluster);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, keyspaceNotificationDispatchExecutor,
|
||||
@@ -637,9 +627,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client,
|
||||
clientPresenceManager, pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
secureStorageClient, secureValueRecovery2Client, pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor,
|
||||
clock, config.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
|
||||
@@ -668,7 +657,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new MessageDeliveryLoopMonitor(rateLimitersCluster);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, clientPresenceManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
accountsManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
|
||||
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
|
||||
@@ -745,7 +734,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
environment.lifecycle().manage(pubSubClientEventManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
@@ -998,8 +986,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
|
||||
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class));
|
||||
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
|
||||
pubSubClientEventManager));
|
||||
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager));
|
||||
environment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
///
|
||||
@@ -1009,11 +996,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator, new AccountPrincipalSupplier(accountsManager)));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, clientPresenceManager, pubSubClientEventManager, websocketScheduledExecutor,
|
||||
pushNotificationScheduler, pubSubClientEventManager, websocketScheduledExecutor,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor));
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
|
||||
pubSubClientEventManager));
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
@@ -1155,8 +1141,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
WebSocketEnvironment<AuthenticatedDevice> provisioningEnvironment = new WebSocketEnvironment<>(environment,
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
|
||||
pubSubClientEventManager));
|
||||
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(pubSubClientEventManager));
|
||||
|
||||
-5
@@ -25,7 +25,6 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.Svr3Credentials;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -55,7 +54,6 @@ public class RegistrationLockVerificationManager {
|
||||
private static final String PHONE_VERIFICATION_TYPE_TAG_NAME = "phoneVerificationType";
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
|
||||
private final ExternalServiceCredentialsGenerator svr3CredentialGenerator;
|
||||
@@ -65,7 +63,6 @@ public class RegistrationLockVerificationManager {
|
||||
|
||||
public RegistrationLockVerificationManager(
|
||||
final AccountsManager accounts,
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
|
||||
final ExternalServiceCredentialsGenerator svr3CredentialGenerator,
|
||||
@@ -73,7 +70,6 @@ public class RegistrationLockVerificationManager {
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.accounts = accounts;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.svr2CredentialGenerator = svr2CredentialGenerator;
|
||||
this.svr3CredentialGenerator = svr3CredentialGenerator;
|
||||
@@ -165,7 +161,6 @@ public class RegistrationLockVerificationManager {
|
||||
}
|
||||
|
||||
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
clientPresenceManager.disconnectAllPresences(updatedAccount.getUuid(), deviceIds);
|
||||
pubSubClientEventManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
|
||||
|
||||
try {
|
||||
|
||||
+1
-4
@@ -9,7 +9,6 @@ import org.glassfish.jersey.server.monitoring.ApplicationEvent;
|
||||
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
|
||||
@@ -21,11 +20,9 @@ public class WebsocketRefreshApplicationEventListener implements ApplicationEven
|
||||
private final WebsocketRefreshRequestEventListener websocketRefreshRequestEventListener;
|
||||
|
||||
public WebsocketRefreshApplicationEventListener(final AccountsManager accountsManager,
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final PubSubClientEventManager pubSubClientEventManager) {
|
||||
|
||||
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(clientPresenceManager,
|
||||
pubSubClientEventManager,
|
||||
this.websocketRefreshRequestEventListener = new WebsocketRefreshRequestEventListener(pubSubClientEventManager,
|
||||
new LinkedDeviceRefreshRequirementProvider(accountsManager),
|
||||
new PhoneNumberChangeRefreshRequirementProvider(accountsManager));
|
||||
}
|
||||
|
||||
-5
@@ -19,12 +19,10 @@ import org.glassfish.jersey.server.monitoring.RequestEvent.Type;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEventListener;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
|
||||
public class WebsocketRefreshRequestEventListener implements RequestEventListener {
|
||||
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final WebsocketRefreshRequirementProvider[] providers;
|
||||
|
||||
@@ -37,11 +35,9 @@ public class WebsocketRefreshRequestEventListener implements RequestEventListene
|
||||
private static final Logger logger = LoggerFactory.getLogger(WebsocketRefreshRequestEventListener.class);
|
||||
|
||||
public WebsocketRefreshRequestEventListener(
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final WebsocketRefreshRequirementProvider... providers) {
|
||||
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.providers = providers;
|
||||
}
|
||||
@@ -64,7 +60,6 @@ public class WebsocketRefreshRequestEventListener implements RequestEventListene
|
||||
.forEach(pair -> {
|
||||
try {
|
||||
displacedDevices.incrementAndGet();
|
||||
clientPresenceManager.disconnectPresence(pair.first(), pair.second());
|
||||
pubSubClientEventManager.requestDisconnection(pair.first(), List.of(pair.second()));
|
||||
} catch (final Exception e) {
|
||||
logger.error("Could not displace device presence", e);
|
||||
|
||||
-1
@@ -22,7 +22,6 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
|
||||
+27
-43
@@ -15,10 +15,7 @@ import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -37,8 +34,10 @@ import javax.ws.rs.ServerErrorException;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.signal.keytransparency.client.AciMonitorRequest;
|
||||
import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.MonitorKey;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -60,12 +59,6 @@ public class KeyTransparencyController {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(KeyTransparencyController.class);
|
||||
@VisibleForTesting
|
||||
static final Duration KEY_TRANSPARENCY_RPC_TIMEOUT = Duration.ofSeconds(15);
|
||||
@VisibleForTesting
|
||||
static final byte USERNAME_PREFIX = (byte) 'u';
|
||||
@VisibleForTesting
|
||||
static final byte E164_PREFIX = (byte) 'n';
|
||||
@VisibleForTesting
|
||||
static final byte ACI_PREFIX = (byte) 'a';
|
||||
private final KeyTransparencyServiceClient keyTransparencyServiceClient;
|
||||
|
||||
public KeyTransparencyController(
|
||||
@@ -139,9 +132,10 @@ public class KeyTransparencyController {
|
||||
identifiers. Enforced unauthenticated endpoint.
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "All search keys exist in the log", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "200", description = "All identifiers exist in the log", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
|
||||
@ApiResponse(responseCode = "404", description = "At least one search key lookup did not find the key")
|
||||
@ApiResponse(responseCode = "403", description = "One or more of the provided commitment indexes did not match")
|
||||
@ApiResponse(responseCode = "404", description = "At least one identifier was not found")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@POST
|
||||
@@ -156,26 +150,34 @@ public class KeyTransparencyController {
|
||||
requireNotAuthenticated(authenticatedAccount);
|
||||
|
||||
try {
|
||||
final List<MonitorKey> monitorKeys = new ArrayList<>(List.of(
|
||||
createMonitorKey(getFullSearchKeyByteString(ACI_PREFIX, request.aci().value().toCompactByteArray()),
|
||||
request.aci().positions(),
|
||||
ByteString.copyFrom(request.aci().commitmentIndex()))
|
||||
));
|
||||
final AciMonitorRequest aciMonitorRequest = AciMonitorRequest.newBuilder()
|
||||
.setAci(ByteString.copyFrom(request.aci().value().toCompactByteArray()))
|
||||
.addAllEntries(request.aci().positions())
|
||||
.setCommitmentIndex(ByteString.copyFrom(request.aci().commitmentIndex()))
|
||||
.build();
|
||||
|
||||
request.usernameHash().ifPresent(usernameHash ->
|
||||
monitorKeys.add(createMonitorKey(getFullSearchKeyByteString(USERNAME_PREFIX, usernameHash.value()),
|
||||
usernameHash.positions(), ByteString.copyFrom(usernameHash.commitmentIndex()))));
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest = request.usernameHash().map(usernameHash ->
|
||||
UsernameHashMonitorRequest.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash.value()))
|
||||
.addAllEntries(usernameHash.positions())
|
||||
.setCommitmentIndex(ByteString.copyFrom(usernameHash.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
request.e164().ifPresent(e164 ->
|
||||
monitorKeys.add(
|
||||
createMonitorKey(getFullSearchKeyByteString(E164_PREFIX, e164.value().getBytes(StandardCharsets.UTF_8)),
|
||||
e164.positions(), ByteString.copyFrom(e164.commitmentIndex()))));
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest = request.e164().map(e164 ->
|
||||
E164MonitorRequest.newBuilder()
|
||||
.setE164(e164.value())
|
||||
.addAllEntries(e164.positions())
|
||||
.setCommitmentIndex(ByteString.copyFrom(e164.commitmentIndex()))
|
||||
.build());
|
||||
|
||||
return new KeyTransparencyMonitorResponse(keyTransparencyServiceClient.monitor(
|
||||
monitorKeys,
|
||||
aciMonitorRequest,
|
||||
usernameHashMonitorRequest,
|
||||
e164MonitorRequest,
|
||||
request.lastNonDistinguishedTreeHeadSize(),
|
||||
request.lastDistinguishedTreeHeadSize(),
|
||||
KEY_TRANSPARENCY_RPC_TIMEOUT).join());
|
||||
|
||||
} catch (final CancellationException exception) {
|
||||
LOGGER.error("Unexpected cancellation from key transparency service", exception);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, exception);
|
||||
@@ -242,28 +244,10 @@ public class KeyTransparencyController {
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, unwrapped);
|
||||
}
|
||||
|
||||
private static MonitorKey createMonitorKey(final ByteString fullSearchKey, final List<Long> positions,
|
||||
final ByteString commitmentIndex) {
|
||||
return MonitorKey.newBuilder()
|
||||
.setSearchKey(fullSearchKey)
|
||||
.addAllEntries(positions)
|
||||
.setCommitmentIndex(commitmentIndex)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void requireNotAuthenticated(final Optional<AuthenticatedDevice> authenticatedAccount) {
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new BadRequestException("Endpoint requires unauthenticated access");
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static ByteString getFullSearchKeyByteString(final byte prefix, final byte[] searchKeyBytes) {
|
||||
final ByteBuffer fullSearchKeyBuffer = ByteBuffer.allocate(searchKeyBytes.length + 1);
|
||||
fullSearchKeyBuffer.put(prefix);
|
||||
fullSearchKeyBuffer.put(searchKeyBytes);
|
||||
fullSearchKeyBuffer.flip();
|
||||
|
||||
return ByteString.copyFrom(fullSearchKeyBuffer.array());
|
||||
}
|
||||
}
|
||||
+14
-10
@@ -19,18 +19,19 @@ import java.security.cert.X509Certificate;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.signal.keytransparency.client.AciMonitorRequest;
|
||||
import org.signal.keytransparency.client.ConsistencyParameters;
|
||||
import org.signal.keytransparency.client.DistinguishedRequest;
|
||||
import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.KeyTransparencyQueryServiceGrpc;
|
||||
import org.signal.keytransparency.client.MonitorKey;
|
||||
import org.signal.keytransparency.client.MonitorRequest;
|
||||
import org.signal.keytransparency.client.SearchRequest;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
@@ -138,19 +139,22 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
.thenApply(AbstractMessageLite::toByteArray);
|
||||
}
|
||||
|
||||
public CompletableFuture<byte[]> monitor(final List<MonitorKey> monitorKeys,
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public CompletableFuture<byte[]> monitor(final AciMonitorRequest aciMonitorRequest,
|
||||
final Optional<UsernameHashMonitorRequest> usernameHashMonitorRequest,
|
||||
final Optional<E164MonitorRequest> e164MonitorRequest,
|
||||
final long lastTreeHeadSize,
|
||||
final long distinguishedTreeHeadSize,
|
||||
final Duration timeout) {
|
||||
final MonitorRequest.Builder monitorRequestBuilder = MonitorRequest.newBuilder()
|
||||
.addAllContactKeys(monitorKeys);
|
||||
.setAci(aciMonitorRequest)
|
||||
.setConsistency(ConsistencyParameters.newBuilder()
|
||||
.setLast(lastTreeHeadSize)
|
||||
.setDistinguished(distinguishedTreeHeadSize)
|
||||
.build());
|
||||
|
||||
final ConsistencyParameters consistency = ConsistencyParameters.newBuilder()
|
||||
.setLast(lastTreeHeadSize)
|
||||
.setDistinguished(distinguishedTreeHeadSize)
|
||||
.build();
|
||||
|
||||
monitorRequestBuilder.setConsistency(consistency);
|
||||
usernameHashMonitorRequest.ifPresent(monitorRequestBuilder::setUsernameHash);
|
||||
e164MonitorRequest.ifPresent(monitorRequestBuilder::setE164);
|
||||
|
||||
return CompletableFutureUtil.toCompletableFuture(stub.withDeadline(toDeadline(timeout))
|
||||
.monitor(monitorRequestBuilder.build()), callbackExecutor)
|
||||
|
||||
@@ -16,6 +16,11 @@ public interface ClientEventListener {
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersistedPubSub();
|
||||
|
||||
/**
|
||||
* Indicates that the client's presence has been displaced and the listener should close the client's underlying
|
||||
* network connection.
|
||||
|
||||
-390
@@ -1,390 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.LettuceFutures;
|
||||
import io.lettuce.core.RedisFuture;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
/**
|
||||
* The client presence manager keeps track of which clients are actively connected and "present" to receive messages.
|
||||
* Only one client per account/device may be present at a time; if a second client for the same account/device declares
|
||||
* its presence, the previous client is displaced.
|
||||
* <p/>
|
||||
* The client presence manager depends on Redis keyspace notifications and requires that the Redis instance support at
|
||||
* least the following notification types: {@code K$z}.
|
||||
*/
|
||||
public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, String> implements Managed {
|
||||
|
||||
private final String managerId = UUID.randomUUID().toString();
|
||||
private final String connectedClientSetKey = getConnectedClientSetKey(managerId);
|
||||
|
||||
private final FaultTolerantRedisClusterClient presenceCluster;
|
||||
private final FaultTolerantPubSubClusterConnection<String, String> pubSubConnection;
|
||||
|
||||
private final ClusterLuaScript clearPresenceScript;
|
||||
private final ClusterLuaScript renewPresenceScript;
|
||||
|
||||
private final ExecutorService keyspaceNotificationExecutorService;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private ScheduledFuture<?> pruneMissingPeersFuture;
|
||||
|
||||
private final Map<String, DisplacedPresenceListener> displacementListenersByPresenceKey = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletionStage<?>> pendingPresenceSetsByPresenceKey = new ConcurrentHashMap<>();
|
||||
|
||||
private final Timer checkPresenceTimer;
|
||||
private final Timer setPresenceTimer;
|
||||
private final Timer clearPresenceTimer;
|
||||
private final Timer prunePeersTimer;
|
||||
private final Counter pruneClientMeter;
|
||||
private final Counter remoteDisplacementMeter;
|
||||
private final Counter pubSubMessageMeter;
|
||||
private final Counter displacementListenerAlreadyRemovedCounter;
|
||||
|
||||
private static final int PRUNE_PEERS_INTERVAL_SECONDS = (int) Duration.ofSeconds(30).toSeconds();
|
||||
private static final int PRESENCE_EXPIRATION_SECONDS = (int) Duration.ofMinutes(11).toSeconds();
|
||||
|
||||
static final String MANAGER_SET_KEY = "presence::managers";
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClientPresenceManager.class);
|
||||
|
||||
public ClientPresenceManager(final FaultTolerantRedisClusterClient presenceCluster,
|
||||
final ScheduledExecutorService scheduledExecutorService,
|
||||
final ExecutorService keyspaceNotificationExecutorService) throws IOException {
|
||||
this.presenceCluster = presenceCluster;
|
||||
this.pubSubConnection = this.presenceCluster.createPubSubConnection();
|
||||
this.clearPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/clear_presence.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
this.renewPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/renew_presence.lua",
|
||||
ScriptOutputType.VALUE);
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.keyspaceNotificationExecutorService = keyspaceNotificationExecutorService;
|
||||
|
||||
Metrics.gauge(name(getClass(), "localClientCount"), this, ignored -> displacementListenersByPresenceKey.size());
|
||||
|
||||
this.checkPresenceTimer = Metrics.timer(name(getClass(), "checkPresence"));
|
||||
this.setPresenceTimer = Metrics.timer(name(getClass(), "setPresence"));
|
||||
this.clearPresenceTimer = Metrics.timer(name(getClass(), "clearPresence"));
|
||||
this.prunePeersTimer = Metrics.timer(name(getClass(), "prunePeers"));
|
||||
this.pruneClientMeter = Metrics.counter(name(getClass(), "pruneClient"));
|
||||
this.remoteDisplacementMeter = Metrics.counter(name(getClass(), "remoteDisplacement"));
|
||||
this.pubSubMessageMeter = Metrics.counter(name(getClass(), "pubSubMessage"));
|
||||
this.displacementListenerAlreadyRemovedCounter = Metrics.counter(
|
||||
name(getClass(), "displacementListenerAlreadyRemoved"));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FaultTolerantPubSubClusterConnection<String, String> getPubSubConnection() {
|
||||
return pubSubConnection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
connection.addListener(this);
|
||||
|
||||
final String presenceChannel = getManagerPresenceChannel(managerId);
|
||||
final int slot = SlotHash.getSlot(presenceChannel);
|
||||
|
||||
connection.sync().nodes(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM) && node.hasSlot(slot))
|
||||
.commands()
|
||||
.subscribe(presenceChannel);
|
||||
});
|
||||
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribeAll);
|
||||
|
||||
presenceCluster.useCluster(connection -> connection.sync().sadd(MANAGER_SET_KEY, managerId));
|
||||
|
||||
pruneMissingPeersFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
pruneMissingPeers();
|
||||
} catch (final Throwable t) {
|
||||
log.warn("Failed to prune missing peers", t);
|
||||
}
|
||||
}, new Random().nextInt(PRUNE_PEERS_INTERVAL_SECONDS), PRUNE_PEERS_INTERVAL_SECONDS, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
pubSubConnection.usePubSubConnection(connection -> connection.removeListener(this));
|
||||
|
||||
if (pruneMissingPeersFuture != null) {
|
||||
pruneMissingPeersFuture.cancel(false);
|
||||
}
|
||||
|
||||
for (final String presenceKey : displacementListenersByPresenceKey.keySet()) {
|
||||
clearPresence(presenceKey);
|
||||
}
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
connection.sync().srem(MANAGER_SET_KEY, managerId);
|
||||
connection.sync().del(getConnectedClientSetKey(managerId));
|
||||
});
|
||||
|
||||
pubSubConnection.usePubSubConnection(
|
||||
connection -> connection.sync().upstream().commands().unsubscribe(getManagerPresenceChannel(managerId)));
|
||||
}
|
||||
|
||||
public void setPresent(final UUID accountUuid, final byte deviceId,
|
||||
final DisplacedPresenceListener displacementListener) {
|
||||
|
||||
setPresenceTimer.record(() -> {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
displacePresence(presenceKey, true);
|
||||
|
||||
displacementListenersByPresenceKey.put(presenceKey, displacementListener);
|
||||
|
||||
final CompletableFuture<Void> presenceFuture = new CompletableFuture<>();
|
||||
final CompletionStage<?> previousFuture = pendingPresenceSetsByPresenceKey.put(presenceKey, presenceFuture);
|
||||
if (previousFuture != null) {
|
||||
log.debug("Another presence is already pending for {}:{}", accountUuid, deviceId);
|
||||
}
|
||||
|
||||
subscribeForRemotePresenceChanges(presenceKey);
|
||||
|
||||
presenceCluster.withCluster(connection -> {
|
||||
final RedisAdvancedClusterAsyncCommands<String, String> commands = connection.async();
|
||||
|
||||
commands.sadd(connectedClientSetKey, presenceKey);
|
||||
return commands.setex(presenceKey, PRESENCE_EXPIRATION_SECONDS, managerId);
|
||||
}).whenComplete((result, throwable) -> {
|
||||
if (throwable != null) {
|
||||
presenceFuture.completeExceptionally(throwable);
|
||||
} else {
|
||||
presenceFuture.complete(null);
|
||||
}
|
||||
});
|
||||
|
||||
presenceFuture.whenComplete(
|
||||
(ignored, throwable) -> pendingPresenceSetsByPresenceKey.remove(presenceKey, presenceFuture));
|
||||
});
|
||||
}
|
||||
|
||||
public void renewPresence(final UUID accountUuid, final byte deviceId) {
|
||||
renewPresenceScript.execute(List.of(getPresenceKey(accountUuid, deviceId)),
|
||||
List.of(managerId, String.valueOf(PRESENCE_EXPIRATION_SECONDS)));
|
||||
}
|
||||
|
||||
public void disconnectAllPresences(final UUID accountUuid, final List<Byte> deviceIds) {
|
||||
|
||||
List<String> presenceKeys = new ArrayList<>();
|
||||
deviceIds.forEach(deviceId -> {
|
||||
String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
if (isLocallyPresent(accountUuid, deviceId)) {
|
||||
displacePresence(presenceKey, false);
|
||||
}
|
||||
presenceKeys.add(presenceKey);
|
||||
});
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
List<RedisFuture<Long>> futures = presenceKeys.stream().map(key -> connection.async().del(key)).toList();
|
||||
LettuceFutures.awaitAll(connection.getTimeout(), futures.toArray(new RedisFuture[0]));
|
||||
});
|
||||
}
|
||||
|
||||
public void disconnectAllPresencesForUuid(final UUID accountUuid) {
|
||||
disconnectAllPresences(accountUuid, Device.ALL_POSSIBLE_DEVICE_IDS);
|
||||
}
|
||||
|
||||
public void disconnectPresence(final UUID accountUuid, final byte deviceId) {
|
||||
disconnectAllPresences(accountUuid, List.of(deviceId));
|
||||
}
|
||||
|
||||
private void displacePresence(final String presenceKey, final boolean connectedElsewhere) {
|
||||
final DisplacedPresenceListener displacementListener = displacementListenersByPresenceKey.get(presenceKey);
|
||||
|
||||
if (displacementListener != null) {
|
||||
displacementListener.handleDisplacement(connectedElsewhere);
|
||||
}
|
||||
|
||||
clearPresence(presenceKey);
|
||||
}
|
||||
|
||||
public boolean isPresent(final UUID accountUuid, final byte deviceId) {
|
||||
return checkPresenceTimer.record(() ->
|
||||
presenceCluster.withCluster(connection ->
|
||||
connection.sync().exists(getPresenceKey(accountUuid, deviceId))) == 1);
|
||||
}
|
||||
|
||||
public boolean isLocallyPresent(final UUID accountUuid, final byte deviceId) {
|
||||
return displacementListenersByPresenceKey.containsKey(getPresenceKey(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
public boolean clearPresence(final UUID accountUuid, final byte deviceId, final DisplacedPresenceListener listener) {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
if (displacementListenersByPresenceKey.remove(presenceKey, listener)) {
|
||||
return clearPresence(presenceKey);
|
||||
} else {
|
||||
displacementListenerAlreadyRemovedCounter.increment();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean clearPresence(final String presenceKey) {
|
||||
return clearPresenceTimer.record(() -> {
|
||||
displacementListenersByPresenceKey.remove(presenceKey);
|
||||
unsubscribeFromRemotePresenceChanges(presenceKey);
|
||||
|
||||
final boolean removed = clearPresenceScript.execute(List.of(presenceKey), List.of(managerId)) != null;
|
||||
presenceCluster.useCluster(connection -> connection.sync().srem(connectedClientSetKey, presenceKey));
|
||||
|
||||
return removed;
|
||||
});
|
||||
}
|
||||
|
||||
private void subscribeForRemotePresenceChanges(final String presenceKey) {
|
||||
final int slot = SlotHash.getSlot(presenceKey);
|
||||
|
||||
pubSubConnection.usePubSubConnection(
|
||||
connection -> connection.sync().nodes(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM) && node.hasSlot(slot))
|
||||
.commands()
|
||||
.subscribe(getKeyspaceNotificationChannel(presenceKey)));
|
||||
}
|
||||
|
||||
private void resubscribeAll(final ClusterTopologyChangedEvent event) {
|
||||
for (final String presenceKey : displacementListenersByPresenceKey.keySet()) {
|
||||
subscribeForRemotePresenceChanges(presenceKey);
|
||||
}
|
||||
}
|
||||
|
||||
private void unsubscribeFromRemotePresenceChanges(final String presenceKey) {
|
||||
pubSubConnection.usePubSubConnection(
|
||||
connection -> connection.sync().upstream().commands().unsubscribe(getKeyspaceNotificationChannel(presenceKey)));
|
||||
}
|
||||
|
||||
void pruneMissingPeers() {
|
||||
prunePeersTimer.record(() -> {
|
||||
final Set<String> peerIds = presenceCluster.withCluster(
|
||||
connection -> connection.sync().smembers(MANAGER_SET_KEY));
|
||||
peerIds.remove(managerId);
|
||||
|
||||
for (final String peerId : peerIds) {
|
||||
final boolean peerMissing = presenceCluster.withCluster(
|
||||
connection -> connection.sync().publish(getManagerPresenceChannel(peerId), "ping") == 0);
|
||||
|
||||
if (peerMissing) {
|
||||
log.debug("Presence manager {} did not respond to ping", peerId);
|
||||
|
||||
final String connectedClientsKey = getConnectedClientSetKey(peerId);
|
||||
|
||||
String presenceKey;
|
||||
|
||||
while ((presenceKey = presenceCluster.withCluster(connection -> connection.sync().spop(connectedClientsKey)))
|
||||
!= null) {
|
||||
clearPresenceScript.execute(List.of(presenceKey), List.of(peerId));
|
||||
pruneClientMeter.increment();
|
||||
}
|
||||
|
||||
presenceCluster.useCluster(connection -> {
|
||||
connection.sync().del(connectedClientsKey);
|
||||
connection.sync().srem(MANAGER_SET_KEY, peerId);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void message(final RedisClusterNode node, final String channel, final String message) {
|
||||
pubSubMessageMeter.increment();
|
||||
|
||||
if (channel.startsWith("__keyspace@0__:presence::{")) {
|
||||
if ("set".equals(message) || "del".equals(message)) {
|
||||
// "set" might mean the client has connected to another host, although it might just be our own `set`,
|
||||
// because we subscribe for changes before setting the key.
|
||||
// for "del", another process has indicated the client should be disconnected
|
||||
final boolean maybeConnectedElsewhere = "set".equals(message);
|
||||
|
||||
// At this point, we're on a Lettuce IO thread and need to dispatch to a separate thread before making
|
||||
// synchronous Lettuce calls to avoid deadlocking.
|
||||
keyspaceNotificationExecutorService.execute(() -> {
|
||||
final String clientPresenceKey = channel.substring("__keyspace@0__:".length());
|
||||
|
||||
final CompletionStage<?> pendingConnection = pendingPresenceSetsByPresenceKey.getOrDefault(clientPresenceKey,
|
||||
CompletableFuture.completedFuture(null));
|
||||
|
||||
pendingConnection.thenCompose(ignored -> {
|
||||
if (maybeConnectedElsewhere) {
|
||||
return presenceCluster.withCluster(connection -> connection.async().get(clientPresenceKey))
|
||||
.thenApply(currentManagerId -> !managerId.equals(currentManagerId));
|
||||
}
|
||||
|
||||
return CompletableFuture.completedFuture(true);
|
||||
})
|
||||
.exceptionally(ignored -> true)
|
||||
.thenAcceptAsync(shouldDisplace -> {
|
||||
if (shouldDisplace) {
|
||||
try {
|
||||
displacePresence(clientPresenceKey, maybeConnectedElsewhere);
|
||||
remoteDisplacementMeter.increment();
|
||||
} catch (final Exception e) {
|
||||
log.warn("Error displacing presence", e);
|
||||
}
|
||||
}
|
||||
}, keyspaceNotificationExecutorService);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getManagerId() {
|
||||
return managerId;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getPresenceKey(final UUID accountUuid, final byte deviceId) {
|
||||
return "presence::{" + accountUuid.toString() + "::" + deviceId + "}";
|
||||
}
|
||||
|
||||
private static String getKeyspaceNotificationChannel(final String presenceKey) {
|
||||
return "__keyspace@0__:" + presenceKey;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getConnectedClientSetKey(final String managerId) {
|
||||
return "presence::clients::" + managerId;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getManagerPresenceChannel(final String managerId) {
|
||||
return "presence::manager::" + managerId;
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
/**
|
||||
* A displaced presence listener is notified when a specific client's presence has been displaced because the same
|
||||
* client opened a newer connection to the Signal service.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface DisplacedPresenceListener {
|
||||
|
||||
void handleDisplacement(boolean connectedElsewhere);
|
||||
}
|
||||
+27
-1
@@ -58,6 +58,11 @@ public class PubSubClientEventManager extends RedisClusterPubSubAdapter<byte[],
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
private final byte[] MESSAGES_PERSISTED_EVENT_BYTES = ClientEvent.newBuilder()
|
||||
.setMessagesPersisted(MessagesPersistedEvent.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
@Nullable
|
||||
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
|
||||
|
||||
@@ -240,10 +245,29 @@ public class PubSubClientEventManager extends RedisClusterPubSubAdapter<byte[],
|
||||
}
|
||||
|
||||
return pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().spublish(getClientPresenceKey(accountIdentifier, deviceId), NEW_MESSAGE_EVENT_BYTES))
|
||||
connection.async().spublish(getClientPresenceKey(accountIdentifier, deviceId), NEW_MESSAGE_EVENT_BYTES))
|
||||
.thenApply(listeners -> listeners > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes an event notifying a specific device that messages have been persisted from short-term to long-term
|
||||
* storage.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for which messages have been persisted
|
||||
* @param deviceId the ID of the device within the target account
|
||||
*
|
||||
* @return a future that completes when the event has been published
|
||||
*/
|
||||
public CompletionStage<Void> handleMessagesPersisted(final UUID accountIdentifier, final byte deviceId) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("Presence manager not started");
|
||||
}
|
||||
|
||||
return pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().spublish(getClientPresenceKey(accountIdentifier, deviceId), MESSAGES_PERSISTED_EVENT_BYTES))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether a client with the given account/device is connected to this presence manager instance.
|
||||
*
|
||||
@@ -347,6 +371,8 @@ public class PubSubClientEventManager extends RedisClusterPubSubAdapter<byte[],
|
||||
|
||||
case DISCONNECT_REQUESTED -> listenerEventExecutor.execute(() -> listener.handleConnectionDisplaced(false));
|
||||
|
||||
case MESSAGES_PERSISTED -> listenerEventExecutor.execute(listener::handleMessagesPersistedPubSub);
|
||||
|
||||
default -> logger.warn("Unexpected client event type: {}", clientEvent.getClass());
|
||||
}
|
||||
} else {
|
||||
|
||||
+6
-22
@@ -68,19 +68,17 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
@@ -126,12 +124,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
private final ProfilesManager profilesManager;
|
||||
private final SecureStorageClient secureStorageClient;
|
||||
private final SecureValueRecovery2Client secureValueRecovery2Client;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final ClientPublicKeysManager clientPublicKeysManager;
|
||||
private final Executor accountLockExecutor;
|
||||
private final Executor clientPresenceExecutor;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
@@ -206,12 +202,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final ProfilesManager profilesManager,
|
||||
final SecureStorageClient secureStorageClient,
|
||||
final SecureValueRecovery2Client secureValueRecovery2Client,
|
||||
final ClientPresenceManager clientPresenceManager,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final Executor accountLockExecutor,
|
||||
final Executor clientPresenceExecutor,
|
||||
final Clock clock,
|
||||
final byte[] linkDeviceSecret,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
@@ -225,12 +219,10 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
this.profilesManager = profilesManager;
|
||||
this.secureStorageClient = secureStorageClient;
|
||||
this.secureValueRecovery2Client = secureValueRecovery2Client;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.registrationRecoveryPasswordsManager = requireNonNull(registrationRecoveryPasswordsManager);
|
||||
this.clientPublicKeysManager = clientPublicKeysManager;
|
||||
this.accountLockExecutor = accountLockExecutor;
|
||||
this.clientPresenceExecutor = clientPresenceExecutor;
|
||||
this.clock = requireNonNull(clock);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
|
||||
@@ -333,10 +325,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
keysManager.deleteSingleUsePreKeys(pni),
|
||||
messagesManager.clear(aci),
|
||||
profilesManager.deleteAll(aci))
|
||||
.thenRunAsync(() -> {
|
||||
clientPresenceManager.disconnectAllPresencesForUuid(aci);
|
||||
pubSubClientEventManager.requestDisconnection(aci);
|
||||
}, clientPresenceExecutor)
|
||||
.thenCompose(ignored -> pubSubClientEventManager.requestDisconnection(aci))
|
||||
.thenCompose(ignored -> accounts.reclaimAccount(e.getExistingAccount(), account, additionalWriteItems))
|
||||
.thenCompose(ignored -> {
|
||||
// We should have cleared all messages before overwriting the old account, but more may have arrived
|
||||
@@ -598,12 +587,11 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
return CompletableFuture.failedFuture(throwable);
|
||||
})
|
||||
.whenCompleteAsync((ignored, throwable) -> {
|
||||
.whenComplete((ignored, throwable) -> {
|
||||
if (throwable == null) {
|
||||
RedisOperation.unchecked(() -> clientPresenceManager.disconnectPresence(accountIdentifier, deviceId));
|
||||
pubSubClientEventManager.requestDisconnection(accountIdentifier, List.of(deviceId));
|
||||
}
|
||||
}, clientPresenceExecutor);
|
||||
});
|
||||
}
|
||||
|
||||
public Account changeNumber(final Account account,
|
||||
@@ -1248,11 +1236,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber()))
|
||||
.thenCompose(ignored -> accounts.delete(account.getUuid(), additionalWriteItems))
|
||||
.thenCompose(ignored -> redisDeleteAsync(account))
|
||||
.thenRunAsync(() -> {
|
||||
RedisOperation.unchecked(() -> clientPresenceManager.disconnectAllPresencesForUuid(account.getUuid()));
|
||||
|
||||
pubSubClientEventManager.requestDisconnection(account.getUuid());
|
||||
}, clientPresenceExecutor);
|
||||
.thenRun(() -> pubSubClientEventManager.requestDisconnection(account.getUuid()));
|
||||
}
|
||||
|
||||
private String getAccountMapKey(String key) {
|
||||
|
||||
+7
-1
@@ -22,6 +22,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
|
||||
|
||||
@@ -30,6 +31,7 @@ public class MessagePersister implements Managed {
|
||||
private final MessagesCache messagesCache;
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
|
||||
private final Duration persistDelay;
|
||||
|
||||
@@ -63,13 +65,16 @@ public class MessagePersister implements Managed {
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache, final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager, final Duration persistDelay,
|
||||
final PubSubClientEventManager pubSubClientEventManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Duration persistDelay,
|
||||
final int dedicatedProcessWorkerThreadCount
|
||||
) {
|
||||
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.persistDelay = persistDelay;
|
||||
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
|
||||
|
||||
@@ -206,6 +211,7 @@ public class MessagePersister implements Managed {
|
||||
maybeUnlink(account, deviceId); // may throw, in which case we'll retry later by the usual mechanism
|
||||
} finally {
|
||||
messagesCache.unlockQueueForPersistence(accountUuid, deviceId);
|
||||
pubSubClientEventManager.handleMessagesPersisted(accountUuid, deviceId);
|
||||
sample.stop(persistQueueTimer);
|
||||
}
|
||||
|
||||
|
||||
-26
@@ -9,16 +9,12 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
@@ -38,8 +34,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
private static final String AUTHENTICATED_TAG_NAME = "authenticated";
|
||||
|
||||
private static final long RENEW_PRESENCE_INTERVAL_MINUTES = 5;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthenticatedConnectListener.class);
|
||||
|
||||
private final ReceiptSender receiptSender;
|
||||
@@ -47,7 +41,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final MessageMetrics messageMetrics;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final PubSubClientEventManager pubSubClientEventManager;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
@@ -62,7 +55,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
MessageMetrics messageMetrics,
|
||||
PushNotificationManager pushNotificationManager,
|
||||
PushNotificationScheduler pushNotificationScheduler,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
PubSubClientEventManager pubSubClientEventManager,
|
||||
ScheduledExecutorService scheduledExecutorService,
|
||||
Scheduler messageDeliveryScheduler,
|
||||
@@ -73,7 +65,6 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
this.messageMetrics = messageMetrics;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.pubSubClientEventManager = pubSubClientEventManager;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
@@ -110,21 +101,11 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor);
|
||||
|
||||
final AtomicReference<ScheduledFuture<?>> renewPresenceFutureReference = new AtomicReference<>();
|
||||
|
||||
context.addWebsocketClosedListener((closingContext, statusCode, reason) -> {
|
||||
final ScheduledFuture<?> renewPresenceFuture = renewPresenceFutureReference.get();
|
||||
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(false);
|
||||
}
|
||||
|
||||
// We begin the shutdown process by removing this client's "presence," which means it will again begin to
|
||||
// receive push notifications for inbound messages. We should do this first because, at this point, the
|
||||
// connection has already closed and attempts to actually deliver a message via the connection will not succeed.
|
||||
// It's preferable to start sending push notifications as soon as possible.
|
||||
RedisOperation.unchecked(() -> clientPresenceManager.clearPresence(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection));
|
||||
|
||||
pubSubClientEventManager.handleClientDisconnected(auth.getAccount().getUuid(),
|
||||
auth.getAuthenticatedDevice().getId());
|
||||
|
||||
@@ -153,14 +134,7 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
|
||||
// Finally, we register this client's presence, which suppresses push notifications. We do this last because
|
||||
// receiving extra push notifications is generally preferable to missing out on a push notification.
|
||||
clientPresenceManager.setPresent(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
|
||||
pubSubClientEventManager.handleClientConnected(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId(), connection);
|
||||
|
||||
renewPresenceFutureReference.set(scheduledExecutorService.scheduleAtFixedRate(() -> RedisOperation.unchecked(() ->
|
||||
clientPresenceManager.renewPresence(auth.getAccount().getUuid(), auth.getAuthenticatedDevice().getId())),
|
||||
RENEW_PRESENCE_INTERVAL_MINUTES,
|
||||
RENEW_PRESENCE_INTERVAL_MINUTES,
|
||||
TimeUnit.MINUTES));
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
|
||||
+17
-22
@@ -46,7 +46,6 @@ import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEventListener;
|
||||
import org.whispersystems.textsecuregcm.push.DisplacedPresenceListener;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
@@ -64,15 +63,13 @@ import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, DisplacedPresenceListener, ClientEventListener {
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, ClientEventListener {
|
||||
|
||||
private static final DistributionSummary messageTime = Metrics.summary(
|
||||
name(MessageController.class, "messageDeliveryDuration"));
|
||||
private static final DistributionSummary primaryDeviceMessageTime = Metrics.summary(
|
||||
name(MessageController.class, "primaryDeviceMessageDeliveryDuration"));
|
||||
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
|
||||
private static final Counter messagesPersistedCounter = Metrics.counter(
|
||||
name(WebSocketConnection.class, "messagesPersisted"));
|
||||
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
|
||||
private static final Counter sendFailuresCounter = Metrics.counter(name(WebSocketConnection.class, "sendFailures"));
|
||||
|
||||
@@ -91,6 +88,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
private static final String SEND_MESSAGE_ERROR_COUNTER = MetricsUtil.name(WebSocketConnection.class,
|
||||
"sendMessageError");
|
||||
private static final String MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class, "messagesAvailable");
|
||||
private static final String MESSAGES_PERSISTED_COUNTER_NAME = name(WebSocketConnection.class, "messagesPersisted");
|
||||
|
||||
private static final String PRESENCE_MANAGER_TAG = "presenceManager";
|
||||
private static final String STATUS_CODE_TAG = "status";
|
||||
@@ -474,10 +472,6 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
PRESENCE_MANAGER_TAG, "legacy")
|
||||
.increment();
|
||||
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -486,6 +480,10 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
Metrics.counter(MESSAGE_AVAILABLE_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -495,33 +493,30 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
Metrics.counter(CLIENT_CLOSED_MESSAGE_AVAILABLE_COUNTER_NAME).increment();
|
||||
return false;
|
||||
}
|
||||
messagesPersistedCounter.increment();
|
||||
|
||||
storedMessageState.set(StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
Metrics.counter(MESSAGES_PERSISTED_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "legacy")
|
||||
.increment();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisplacement(final boolean connectedElsewhere) {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)),
|
||||
Tag.of(PRESENCE_MANAGER_TAG, "legacy")
|
||||
);
|
||||
public void handleMessagesPersistedPubSub() {
|
||||
Metrics.counter(MESSAGES_PERSISTED_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
|
||||
storedMessageState.set(StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)),
|
||||
Tag.of(PRESENCE_MANAGER_TAG, "pubsub")
|
||||
);
|
||||
Tag.of("connectedElsewhere", String.valueOf(connectedElsewhere)));
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
|
||||
|
||||
|
||||
+4
-14
@@ -35,7 +35,6 @@ import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSam
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.FcmSender;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -77,7 +76,7 @@ record CommandDependencies(
|
||||
ReportMessageManager reportMessageManager,
|
||||
MessagesCache messagesCache,
|
||||
MessagesManager messagesManager,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
PubSubClientEventManager pubSubClientEventManager,
|
||||
KeysManager keysManager,
|
||||
APNSender apnSender,
|
||||
FcmSender fcmSender,
|
||||
@@ -118,8 +117,6 @@ record CommandDependencies(
|
||||
FaultTolerantRedisClient pubsubClient =
|
||||
configuration.getRedisPubSubConfiguration().build("pubsub", redisClientResourcesBuilder.build());
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(name, "recurringJob-%d")).threads(2).build();
|
||||
Scheduler messageDeliveryScheduler = Schedulers.fromExecutorService(
|
||||
environment.lifecycle().executorService("messageDelivery").minThreads(4).maxThreads(4).build());
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle()
|
||||
@@ -132,8 +129,6 @@ record CommandDependencies(
|
||||
.executorService(name(name, "storageService-%d")).maxThreads(8).minThreads(8).build();
|
||||
ExecutorService accountLockExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "accountLock-%d")).minThreads(8).maxThreads(8).build();
|
||||
ExecutorService clientPresenceExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "clientPresence-%d")).minThreads(8).maxThreads(8).build();
|
||||
ExecutorService remoteStorageHttpExecutor = environment.lifecycle()
|
||||
.executorService(name(name, "remoteStorage-%d"))
|
||||
.minThreads(0).maxThreads(Integer.MAX_VALUE).workQueue(new SynchronousQueue<>())
|
||||
@@ -205,8 +200,6 @@ record CommandDependencies(
|
||||
messageDeletionExecutor);
|
||||
FaultTolerantRedisClusterClient messagesCluster = configuration.getMessageCacheConfiguration()
|
||||
.getRedisClusterConfiguration().build("messages", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisClusterClient clientPresenceCluster = configuration.getClientPresenceClusterConfiguration()
|
||||
.build("client_presence", redisClientResourcesBuilder);
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = configuration.getRateLimitersCluster().build("rate_limiters",
|
||||
redisClientResourcesBuilder);
|
||||
SecureValueRecovery2Client secureValueRecovery2Client = new SecureValueRecovery2Client(
|
||||
@@ -215,8 +208,6 @@ record CommandDependencies(
|
||||
configuration.getSvr2Configuration());
|
||||
SecureStorageClient secureStorageClient = new SecureStorageClient(storageCredentialsGenerator,
|
||||
storageServiceExecutor, storageServiceRetryExecutor, configuration.getSecureStorageServiceConfiguration());
|
||||
ClientPresenceManager clientPresenceManager = new ClientPresenceManager(clientPresenceCluster,
|
||||
recurringJobExecutor, keyspaceNotificationDispatchExecutor);
|
||||
PubSubClientEventManager pubSubClientEventManager = new PubSubClientEventManager(messagesCluster, clientEventExecutor);
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, keyspaceNotificationDispatchExecutor,
|
||||
messageDeliveryScheduler, messageDeletionExecutor, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
@@ -234,8 +225,8 @@ record CommandDependencies(
|
||||
new ClientPublicKeysManager(clientPublicKeys, accountLockManager, accountLockExecutor);
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, clientPresenceManager, pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
secureStorageClient, secureValueRecovery2Client, pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor,
|
||||
clock, configuration.getLinkDeviceSecretConfiguration().secret().value(), dynamicConfigurationManager);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
@@ -272,7 +263,6 @@ record CommandDependencies(
|
||||
|
||||
environment.lifecycle().manage(apnSender);
|
||||
environment.lifecycle().manage(messagesCache);
|
||||
environment.lifecycle().manage(clientPresenceManager);
|
||||
environment.lifecycle().manage(pubSubClientEventManager);
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
|
||||
@@ -282,7 +272,7 @@ record CommandDependencies(
|
||||
reportMessageManager,
|
||||
messagesCache,
|
||||
messagesManager,
|
||||
clientPresenceManager,
|
||||
pubSubClientEventManager,
|
||||
keys,
|
||||
apnSender,
|
||||
fcmSender,
|
||||
|
||||
+5
-2
@@ -60,8 +60,11 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
});
|
||||
}
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(), deps.messagesManager(),
|
||||
deps.accountsManager(), deps.dynamicConfigurationManager(),
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(),
|
||||
deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.pubSubClientEventManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ message ClientEvent {
|
||||
NewMessageAvailableEvent new_message_available = 1;
|
||||
ClientConnectedEvent client_connected = 2;
|
||||
DisconnectRequested disconnect_requested = 3;
|
||||
MessagesPersistedEvent messages_persisted = 4;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,3 +37,10 @@ message ClientConnectedEvent {
|
||||
*/
|
||||
message DisconnectRequested {
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term
|
||||
* storage to long-term storage.
|
||||
*/
|
||||
message MessagesPersistedEvent {
|
||||
}
|
||||
@@ -34,7 +34,7 @@ service KeyTransparencyQueryService {
|
||||
*/
|
||||
rpc Search(SearchRequest) returns (SearchResponse) {}
|
||||
/**
|
||||
* An endpoint that allows users to monitor a set of identifiers by returning proof that the log continues to be
|
||||
* An endpoint that allows users to monitor a group of identifiers by returning proof that the log continues to be
|
||||
* constructed correctly in later entries for those identifiers.
|
||||
*/
|
||||
rpc Monitor(MonitorRequest) returns (MonitorResponse) {}
|
||||
@@ -141,7 +141,7 @@ message DistinguishedRequest {
|
||||
|
||||
/**
|
||||
* DistinguishedResponse contains the tree head and search proof for the most
|
||||
* recent `distinguished` key in the log.
|
||||
* recent `distinguished` key in the log.
|
||||
*/
|
||||
message DistinguishedResponse {
|
||||
/**
|
||||
@@ -286,46 +286,34 @@ message PrefixSearchResult {
|
||||
uint32 counter = 2;
|
||||
}
|
||||
|
||||
message MonitorKey {
|
||||
/**
|
||||
* The key to search for in the log tree.
|
||||
*/
|
||||
bytes search_key = 1;
|
||||
/**
|
||||
* A list of log tree positions maintained by a client for the identifier being monitored.
|
||||
* Each position is in the direct path to a key version and corresponds to a tree head
|
||||
* that has been verified to contain that version or greater.
|
||||
* The key transparency server uses this list to compute which log entries to return
|
||||
* in the corresponding MonitorProof.
|
||||
*/
|
||||
message MonitorRequest {
|
||||
AciMonitorRequest aci = 1;
|
||||
optional UsernameHashMonitorRequest username_hash = 2;
|
||||
optional E164MonitorRequest e164 = 3;
|
||||
ConsistencyParameters consistency = 4;
|
||||
}
|
||||
|
||||
message AciMonitorRequest {
|
||||
bytes aci = 1;
|
||||
repeated uint64 entries = 2;
|
||||
/**
|
||||
* The commitment index for the identifier. This is derived from vrf_proof in
|
||||
* the SearchResponse.
|
||||
*/
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message UsernameHashMonitorRequest {
|
||||
bytes username_hash = 1;
|
||||
repeated uint64 entries = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message MonitorRequest {
|
||||
/**
|
||||
* TODO: Remove this protobuf field in the KT server
|
||||
*/
|
||||
repeated MonitorKey owned_keys = 1;
|
||||
/**
|
||||
* The list of identifiers that the client would like to monitor.
|
||||
* All identifiers *must* belong to the same user.
|
||||
*/
|
||||
repeated MonitorKey contact_keys = 2;
|
||||
/**
|
||||
* The tree head size(s) to prove consistency against.
|
||||
*/
|
||||
ConsistencyParameters consistency = 3;
|
||||
message E164MonitorRequest {
|
||||
string e164 = 1;
|
||||
repeated uint64 entries = 2;
|
||||
bytes commitment_index = 3;
|
||||
}
|
||||
|
||||
message MonitorProof {
|
||||
/**
|
||||
* Generated based on the monitored entries provided in MonitorKey.entries. Each ProofStep
|
||||
* Generated based on the monitored entry provided in MonitorRequest.entries. Each ProofStep
|
||||
* corresponds to a log tree entry that exists in the search path to each monitored entry
|
||||
* and that came *after* that monitored entry. It proves that the log tree has been constructed
|
||||
* correctly at that later entry. This list also includes any remaining entries
|
||||
@@ -342,17 +330,22 @@ message MonitorResponse {
|
||||
*/
|
||||
FullTreeHead tree_head = 1;
|
||||
/**
|
||||
* TODO: Remove this protobuf field in the KT server
|
||||
* A proof that the MonitorRequest's ACI continues to be constructed correctly in later entries of the log tree.
|
||||
*/
|
||||
repeated MonitorProof owned_proofs = 2;
|
||||
MonitorProof aci = 2;
|
||||
/**
|
||||
* A list of proofs, one for each identifier in MonitorRequest.contact_keys, each proving that the given identifier
|
||||
* continues to be constructed correctly in later entries of the log tree.
|
||||
* A proof that the username hash continues to be constructed correctly in later entries of the log tree.
|
||||
* Will be absent if the request did not include a UsernameHashMonitorRequest.
|
||||
*/
|
||||
repeated MonitorProof contact_proofs = 3;
|
||||
optional MonitorProof username_hash = 3;
|
||||
/**
|
||||
* A proof that the e164 continues to be constructed correctly in later entries of the log tree.
|
||||
* Will be absent if the request did not include a E164MonitorRequest.
|
||||
*/
|
||||
optional MonitorProof e164 = 4;
|
||||
/**
|
||||
* A batch inclusion proof that the log entries involved in the binary search for each of the entries
|
||||
* being monitored in MonitorKey.entries are included in the current log tree.
|
||||
* being monitored in the request are included in the current log tree.
|
||||
*/
|
||||
repeated bytes inclusion = 4;
|
||||
repeated bytes inclusion = 5;
|
||||
}
|
||||
+2
-13
@@ -59,7 +59,6 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -96,7 +95,6 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
.build();
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
|
||||
private LinkedDeviceRefreshRequirementProvider provider;
|
||||
@@ -104,13 +102,12 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
|
||||
provider = new LinkedDeviceRefreshRequirementProvider(accountsManager);
|
||||
|
||||
final WebsocketRefreshRequestEventListener listener =
|
||||
new WebsocketRefreshRequestEventListener(clientPresenceManager, pubSubClientEventManager, provider);
|
||||
new WebsocketRefreshRequestEventListener(pubSubClientEventManager, provider);
|
||||
|
||||
when(applicationEventListener.onRequest(any())).thenReturn(listener);
|
||||
|
||||
@@ -121,9 +118,6 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
.forEach(deviceId -> account.addDevice(DevicesHelper.createDevice((byte) deviceId)));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
|
||||
|
||||
account.getDevices()
|
||||
.forEach(device -> when(clientPresenceManager.isPresent(uuid, device.getId())).thenReturn(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -145,10 +139,6 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
|
||||
assertEquals(initialDeviceCount + addedDeviceNames.size(), account.getDevices().size());
|
||||
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 1);
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 2);
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), (byte) 3);
|
||||
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 1));
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 2));
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of((byte) 3));
|
||||
@@ -180,11 +170,10 @@ class LinkedDeviceRefreshRequirementProviderTest {
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
initialDeviceIds.forEach(deviceId -> {
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), deviceId);
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(deviceId));
|
||||
});
|
||||
|
||||
verifyNoMoreInteractions(clientPresenceManager);
|
||||
verifyNoMoreInteractions(pubSubClientEventManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-16
@@ -47,7 +47,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -75,7 +74,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
private static final AccountAuthenticator AUTHENTICATOR = mock(AccountAuthenticator.class);
|
||||
private static final AccountsManager ACCOUNTS_MANAGER = mock(AccountsManager.class);
|
||||
private static final ClientPresenceManager CLIENT_PRESENCE = mock(ClientPresenceManager.class);
|
||||
private static final PubSubClientEventManager PUBSUB_CLIENT_PRESENCE = mock(PubSubClientEventManager.class);
|
||||
|
||||
private WebSocketClient client;
|
||||
@@ -86,7 +84,7 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
reset(AUTHENTICATOR, CLIENT_PRESENCE, ACCOUNTS_MANAGER);
|
||||
reset(AUTHENTICATOR, ACCOUNTS_MANAGER, PUBSUB_CLIENT_PRESENCE);
|
||||
client = new WebSocketClient();
|
||||
client.start();
|
||||
|
||||
@@ -125,9 +123,9 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
|
||||
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE, PUBSUB_CLIENT_PRESENCE));
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, PUBSUB_CLIENT_PRESENCE));
|
||||
environment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, CLIENT_PRESENCE, PUBSUB_CLIENT_PRESENCE));
|
||||
.register(new WebsocketRefreshApplicationEventListener(ACCOUNTS_MANAGER, PUBSUB_CLIENT_PRESENCE));
|
||||
webSocketEnvironment.setConnectListener(webSocketSessionContext -> {
|
||||
});
|
||||
|
||||
@@ -201,7 +199,7 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Event listeners can fire after responses are sent
|
||||
verify(ACCOUNTS_MANAGER, timeout(5000).times(1)).getByAccountIdentifier(eq(account1.getUuid()));
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
|
||||
verifyNoMoreInteractions(ACCOUNTS_MANAGER);
|
||||
}
|
||||
|
||||
@@ -215,10 +213,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Make sure we disconnect the account if the account has changed numbers. Event listeners can fire after responses
|
||||
// are sent, so use a timeout.
|
||||
verify(CLIENT_PRESENCE, timeout(5000))
|
||||
.disconnectPresence(eq(account1.getUuid()), eq(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
|
||||
verify(PUBSUB_CLIENT_PRESENCE, timeout(5000))
|
||||
.requestDisconnection(account1.getUuid(), List.of(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
|
||||
@@ -235,10 +229,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Make sure we disconnect the account if the account has changed numbers. Event listeners can fire after responses
|
||||
// are sent, so use a timeout.
|
||||
verify(CLIENT_PRESENCE, timeout(5000))
|
||||
.disconnectPresence(eq(account1.getUuid()), eq(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
|
||||
verify(PUBSUB_CLIENT_PRESENCE, timeout(5000))
|
||||
.requestDisconnection(account1.getUuid(), List.of(authenticatedDevice.getId()));
|
||||
verifyNoMoreInteractions(PUBSUB_CLIENT_PRESENCE);
|
||||
@@ -255,7 +245,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Shouldn't even read the account if the method has not been annotated
|
||||
verifyNoMoreInteractions(ACCOUNTS_MANAGER);
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -269,7 +258,6 @@ class PhoneNumberChangeRefreshRequirementProviderTest {
|
||||
|
||||
// Shouldn't even read the account if the method has not been annotated
|
||||
verifyNoMoreInteractions(ACCOUNTS_MANAGER);
|
||||
verifyNoMoreInteractions(CLIENT_PRESENCE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-6
@@ -33,7 +33,6 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -47,7 +46,6 @@ import org.whispersystems.textsecuregcm.util.Pair;
|
||||
class RegistrationLockVerificationManagerTest {
|
||||
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
private final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialsGenerator = mock(
|
||||
ExternalServiceCredentialsGenerator.class);
|
||||
@@ -58,7 +56,7 @@ class RegistrationLockVerificationManagerTest {
|
||||
private static PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, clientPresenceManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
accountsManager, pubSubClientEventManager, svr2CredentialsGenerator, svr3CredentialsGenerator,
|
||||
registrationRecoveryPasswordsManager, pushNotificationManager, rateLimiters);
|
||||
|
||||
private final RateLimiter pinLimiter = mock(RateLimiter.class);
|
||||
@@ -109,7 +107,6 @@ class RegistrationLockVerificationManagerTest {
|
||||
} else {
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
}
|
||||
verify(clientPresenceManager).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
try {
|
||||
verify(pushNotificationManager).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
|
||||
@@ -133,7 +130,6 @@ class RegistrationLockVerificationManagerTest {
|
||||
verify(pushNotificationManager, never()).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
|
||||
} catch (NotPushRegisteredException npre) {}
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
verify(clientPresenceManager, never()).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
|
||||
});
|
||||
}
|
||||
@@ -172,7 +168,6 @@ class RegistrationLockVerificationManagerTest {
|
||||
|
||||
verify(account, never()).lockAuthTokenHash();
|
||||
verify(registrationRecoveryPasswordsManager, never()).removeForNumber(account.getNumber());
|
||||
verify(clientPresenceManager, never()).disconnectAllPresences(account.getUuid(), List.of(Device.PRIMARY_ID));
|
||||
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
|
||||
}
|
||||
|
||||
|
||||
+2
-6
@@ -79,7 +79,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -111,7 +110,6 @@ class DeviceControllerTest {
|
||||
private static final Account account = mock(Account.class);
|
||||
private static final Account maxedAccount = mock(Account.class);
|
||||
private static final Device primaryDevice = mock(Device.class);
|
||||
private static final ClientPresenceManager clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
private static final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
private static final Map<String, Integer> deviceConfiguration = new HashMap<>();
|
||||
private static final TestClock testClock = TestClock.now();
|
||||
@@ -133,8 +131,7 @@ class DeviceControllerTest {
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager,
|
||||
pubSubClientEventManager))
|
||||
.addProvider(new WebsocketRefreshApplicationEventListener(accountsManager, pubSubClientEventManager))
|
||||
.addProvider(new DeviceLimitExceededExceptionMapper())
|
||||
.addResource(deviceController)
|
||||
.build();
|
||||
@@ -174,8 +171,7 @@ class DeviceControllerTest {
|
||||
asyncCommands,
|
||||
account,
|
||||
maxedAccount,
|
||||
primaryDevice,
|
||||
clientPresenceManager
|
||||
primaryDevice
|
||||
);
|
||||
|
||||
testClock.unpin();
|
||||
|
||||
+4
-18
@@ -18,8 +18,6 @@ import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.controllers.KeyTransparencyController.ACI_PREFIX;
|
||||
import static org.whispersystems.textsecuregcm.controllers.KeyTransparencyController.getFullSearchKeyByteString;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
@@ -124,18 +122,6 @@ public class KeyTransparencyControllerTest {
|
||||
monitorRatelimiter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFullSearchKey() {
|
||||
final byte[] charBytes = new byte[]{ACI_PREFIX};
|
||||
final byte[] aci = ACI.toCompactByteArray();
|
||||
|
||||
final byte[] expectedFullSearchKey = new byte[aci.length + 1];
|
||||
System.arraycopy(charBytes, 0, expectedFullSearchKey, 0, charBytes.length);
|
||||
System.arraycopy(aci, 0, expectedFullSearchKey, charBytes.length, aci.length);
|
||||
|
||||
assertArrayEquals(expectedFullSearchKey, getFullSearchKeyByteString(ACI_PREFIX, aci).toByteArray());
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@@ -309,7 +295,7 @@ public class KeyTransparencyControllerTest {
|
||||
|
||||
@Test
|
||||
void monitorSuccess() {
|
||||
when(keyTransparencyServiceClient.monitor(any(), anyLong(), anyLong(), any()))
|
||||
when(keyTransparencyServiceClient.monitor(any(), any(), any(), anyLong(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(TestRandomUtil.nextBytes(16)));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -328,7 +314,7 @@ public class KeyTransparencyControllerTest {
|
||||
assertNotNull(keyTransparencyMonitorResponse.serializedResponse());
|
||||
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(
|
||||
any(), eq(3L), eq(4L), eq(KeyTransparencyController.KEY_TRANSPARENCY_RPC_TIMEOUT));
|
||||
any(), any(), any(), eq(3L), eq(4L), eq(KeyTransparencyController.KEY_TRANSPARENCY_RPC_TIMEOUT));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,7 +337,7 @@ public class KeyTransparencyControllerTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void monitorGrpcErrors(final Status grpcStatus, final int httpStatus) {
|
||||
when(keyTransparencyServiceClient.monitor(any(), anyLong(), anyLong(), any()))
|
||||
when(keyTransparencyServiceClient.monitor(any(), any(), any(), anyLong(), anyLong(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new CompletionException(new StatusRuntimeException(grpcStatus))));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -363,7 +349,7 @@ public class KeyTransparencyControllerTest {
|
||||
new KeyTransparencyMonitorRequest.AciMonitor(ACI, List.of(3L), COMMITMENT_INDEX),
|
||||
Optional.empty(), Optional.empty(), 3L, 4L))))) {
|
||||
assertEquals(httpStatus, response.getStatus());
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(any(), anyLong(), anyLong(), any());
|
||||
verify(keyTransparencyServiceClient, times(1)).monitor(any(), any(), any(), anyLong(), anyLong(), any());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-413
@@ -1,413 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
class ClientPresenceManagerTest {
|
||||
|
||||
@RegisterExtension
|
||||
static final RedisClusterExtension REDIS_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
|
||||
private static final DisplacedPresenceListener NO_OP = connectedElsewhere -> {
|
||||
};
|
||||
|
||||
private boolean expectExceptionOnClientPresenceManagerStop = false;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().flushall();
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
presenceRenewalExecutorService = Executors.newSingleThreadScheduledExecutor();
|
||||
clientPresenceManager = new ClientPresenceManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
presenceRenewalExecutorService,
|
||||
presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void tearDown() throws Exception {
|
||||
presenceRenewalExecutorService.shutdown();
|
||||
presenceRenewalExecutorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||
|
||||
try {
|
||||
clientPresenceManager.stop();
|
||||
} catch (final Exception e) {
|
||||
if (!expectExceptionOnClientPresenceManagerStop) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsPresent() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
assertTrue(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsLocallyPresent() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
assertFalse(clientPresenceManager.isLocallyPresent(accountUuid, deviceId));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> connection.sync().flushall());
|
||||
|
||||
assertTrue(clientPresenceManager.isLocallyPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLocalDisplacement() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final AtomicInteger displacementCounter = new AtomicInteger(0);
|
||||
final DisplacedPresenceListener displacementListener = connectedElsewhere -> displacementCounter.incrementAndGet();
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, displacementListener);
|
||||
|
||||
assertEquals(0, displacementCounter.get());
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, displacementListener);
|
||||
|
||||
assertEquals(1, displacementCounter.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemoteDisplacement() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
|
||||
clientPresenceManager.start();
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, connectedElsewhere -> displaced.complete(null));
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(ClientPresenceManager.getPresenceKey(accountUuid, deviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRemoteDisplacementAfterTopologyChange() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
|
||||
clientPresenceManager.start();
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, connectedElsewhere -> displaced.complete(null));
|
||||
|
||||
clientPresenceManager.getPubSubConnection()
|
||||
.usePubSubConnection(connection -> connection.getResources().eventBus()
|
||||
.publish(new ClusterTopologyChangedEvent(List.of(), List.of())));
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(ClientPresenceManager.getPresenceKey(accountUuid, deviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
assertFalse(clientPresenceManager.clearPresence(accountUuid, deviceId,
|
||||
ignored -> fail("this listener should never be called")));
|
||||
assertTrue(clientPresenceManager.clearPresence(accountUuid, deviceId, NO_OP));
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(
|
||||
connection -> connection.sync().set(ClientPresenceManager.getPresenceKey(accountUuid, deviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
assertFalse(clientPresenceManager.clearPresence(accountUuid, deviceId, NO_OP));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPruneMissingPeers() {
|
||||
final String presentPeerId = UUID.randomUUID().toString();
|
||||
final String missingPeerId = UUID.randomUUID().toString();
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().sadd(ClientPresenceManager.MANAGER_SET_KEY, presentPeerId);
|
||||
connection.sync().sadd(ClientPresenceManager.MANAGER_SET_KEY, missingPeerId);
|
||||
});
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
addClientPresence(presentPeerId);
|
||||
addClientPresence(missingPeerId);
|
||||
}
|
||||
|
||||
clientPresenceManager.getPubSubConnection().usePubSubConnection(
|
||||
connection -> connection.sync().upstream().commands()
|
||||
.subscribe(ClientPresenceManager.getManagerPresenceChannel(presentPeerId)));
|
||||
clientPresenceManager.pruneMissingPeers();
|
||||
|
||||
assertEquals(1, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
connection -> connection.sync().exists(ClientPresenceManager.getConnectedClientSetKey(presentPeerId))));
|
||||
assertTrue(REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
(Function<StatefulRedisClusterConnection<String, String>, Boolean>) connection -> connection.sync()
|
||||
.sismember(ClientPresenceManager.MANAGER_SET_KEY, presentPeerId)));
|
||||
|
||||
assertEquals(0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
connection -> connection.sync().exists(ClientPresenceManager.getConnectedClientSetKey(missingPeerId))));
|
||||
assertFalse(REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(
|
||||
(Function<StatefulRedisClusterConnection<String, String>, Boolean>) connection -> connection.sync()
|
||||
.sismember(ClientPresenceManager.MANAGER_SET_KEY, missingPeerId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInitialPresenceExpiration() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(ClientPresenceManager.getPresenceKey(accountUuid, deviceId)).intValue());
|
||||
|
||||
assertTrue(ttl > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRenewPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final String presenceKey = ClientPresenceManager.getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().set(presenceKey, clientPresenceManager.getManagerId()));
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(presenceKey).intValue());
|
||||
|
||||
assertEquals(-1, ttl);
|
||||
}
|
||||
|
||||
clientPresenceManager.renewPresence(accountUuid, deviceId);
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(presenceKey).intValue());
|
||||
|
||||
assertTrue(ttl > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExpiredPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
|
||||
assertTrue(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
// Hackily set this key to expire immediately
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().expire(ClientPresenceManager.getPresenceKey(accountUuid, deviceId), 0));
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
private void addClientPresence(final String managerId) {
|
||||
final String clientPresenceKey = ClientPresenceManager.getPresenceKey(UUID.randomUUID(), (byte) 7);
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().set(clientPresenceKey, managerId);
|
||||
connection.sync().sadd(ClientPresenceManager.getConnectedClientSetKey(managerId), clientPresenceKey);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearAllOnStop() {
|
||||
final int localAccounts = 10;
|
||||
final UUID[] localUuids = new UUID[localAccounts];
|
||||
final byte[] localDeviceIds = new byte[localAccounts];
|
||||
|
||||
for (int i = 0; i < localAccounts; i++) {
|
||||
localUuids[i] = UUID.randomUUID();
|
||||
localDeviceIds[i] = (byte) i;
|
||||
|
||||
clientPresenceManager.setPresent(localUuids[i], localDeviceIds[i], NO_OP);
|
||||
}
|
||||
|
||||
final UUID displacedAccountUuid = UUID.randomUUID();
|
||||
final byte displacedAccountDeviceId = 7;
|
||||
|
||||
clientPresenceManager.setPresent(displacedAccountUuid, displacedAccountDeviceId, NO_OP);
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> connection.sync()
|
||||
.set(ClientPresenceManager.getPresenceKey(displacedAccountUuid, displacedAccountDeviceId),
|
||||
UUID.randomUUID().toString()));
|
||||
|
||||
clientPresenceManager.stop();
|
||||
|
||||
for (int i = 0; i < localAccounts; i++) {
|
||||
localUuids[i] = UUID.randomUUID();
|
||||
localDeviceIds[i] = (byte) i;
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(localUuids[i], localDeviceIds[i]));
|
||||
}
|
||||
|
||||
assertTrue(clientPresenceManager.isPresent(displacedAccountUuid, displacedAccountDeviceId));
|
||||
|
||||
expectExceptionOnClientPresenceManagerStop = true;
|
||||
}
|
||||
|
||||
@Nested
|
||||
class MultiServerTest {
|
||||
|
||||
private ClientPresenceManager server1;
|
||||
private ClientPresenceManager server2;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> {
|
||||
connection.sync().flushall();
|
||||
connection.sync().upstream().commands().configSet("notify-keyspace-events", "K$glz");
|
||||
});
|
||||
|
||||
final ScheduledExecutorService scheduledExecutorService1 = mock(ScheduledExecutorService.class);
|
||||
final ExecutorService keyspaceNotificationExecutorService1 = Executors.newSingleThreadExecutor();
|
||||
server1 = new ClientPresenceManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
scheduledExecutorService1, keyspaceNotificationExecutorService1);
|
||||
|
||||
final ScheduledExecutorService scheduledExecutorService2 = mock(ScheduledExecutorService.class);
|
||||
final ExecutorService keyspaceNotificationExecutorService2 = Executors.newSingleThreadExecutor();
|
||||
server2 = new ClientPresenceManager(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
scheduledExecutorService2, keyspaceNotificationExecutorService2);
|
||||
|
||||
server1.start();
|
||||
server2.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
server2.stop();
|
||||
server1.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetPresentRemotely() {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
server1.setPresent(uuid1, deviceId, listener1);
|
||||
|
||||
server2.setPresent(uuid1, deviceId, connectedElsewhere -> {});
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDisconnectPresenceLocally() {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
server1.setPresent(uuid1, deviceId, listener1);
|
||||
|
||||
server1.disconnectPresence(uuid1, deviceId);
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDisconnectPresenceRemotely() {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
server1.setPresent(uuid1, deviceId, listener1);
|
||||
|
||||
server2.disconnectPresence(uuid1, deviceId);
|
||||
|
||||
displaced.join();
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 100)
|
||||
void testConcurrentConnection() throws Exception {
|
||||
final UUID uuid1 = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final CompletableFuture<?> displaced = new CompletableFuture<>();
|
||||
final DisplacedPresenceListener listener1 = connectedElsewhere -> displaced.complete(null);
|
||||
|
||||
final Thread server1Thread = new Thread(() -> server1.setPresent(uuid1, deviceId, listener1));
|
||||
final Thread server2Thread = new Thread(() -> server2.setPresent(uuid1, deviceId, listener1));
|
||||
|
||||
server1Thread.start();
|
||||
server2Thread.start();
|
||||
|
||||
displaced.join();
|
||||
server2Thread.join();
|
||||
server1Thread.join();
|
||||
|
||||
while (server1.isLocallyPresent(uuid1, deviceId) == server2.isLocallyPresent(uuid1, deviceId)) {
|
||||
Thread.sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+34
-12
@@ -20,8 +20,10 @@ import io.lettuce.core.cluster.pubsub.api.async.RedisClusterPubSubAsyncCommands;
|
||||
import io.lettuce.core.cluster.pubsub.api.sync.RedisClusterPubSubCommands;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
@@ -56,6 +58,10 @@ class PubSubClientEventManagerTest {
|
||||
public void handleNewMessageAvailable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessagesPersistedPubSub() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConnectionDisplaced(final boolean connectedElsewhere) {
|
||||
}
|
||||
@@ -93,8 +99,8 @@ class PubSubClientEventManagerTest {
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final AtomicBoolean firstListenerDisplaced = new AtomicBoolean(false);
|
||||
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
|
||||
|
||||
final AtomicBoolean secondListenerDisplaced = new AtomicBoolean(false);
|
||||
final AtomicBoolean firstListenerConnectedElsewhere = new AtomicBoolean(false);
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, deviceId, new ClientEventAdapter() {
|
||||
@@ -140,15 +146,12 @@ class PubSubClientEventManagerTest {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final AtomicBoolean messageReceived = new AtomicBoolean(false);
|
||||
final CountDownLatch messageReceivedLatch = new CountDownLatch(1);
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, deviceId, new ClientEventAdapter() {
|
||||
@Override
|
||||
public void handleNewMessageAvailable() {
|
||||
synchronized (messageReceived) {
|
||||
messageReceived.set(true);
|
||||
messageReceived.notifyAll();
|
||||
}
|
||||
messageReceivedLatch.countDown();
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
@@ -157,13 +160,32 @@ class PubSubClientEventManagerTest {
|
||||
|
||||
assertTrue(messagePresenceManager.handleNewMessageAvailable(accountIdentifier, deviceId).toCompletableFuture().join());
|
||||
|
||||
synchronized (messageReceived) {
|
||||
while (!messageReceived.get()) {
|
||||
messageReceived.wait();
|
||||
}
|
||||
}
|
||||
assertTrue(messageReceivedLatch.await(2, TimeUnit.SECONDS),
|
||||
"Message not received within time limit");
|
||||
}
|
||||
|
||||
assertTrue(messageReceived.get());
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void handleMessagesPersisted(final boolean messagesPersistedRemotely) throws InterruptedException {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
final CountDownLatch messagesPersistedLatch = new CountDownLatch(1);
|
||||
|
||||
localPresenceManager.handleClientConnected(accountIdentifier, deviceId, new ClientEventAdapter() {
|
||||
@Override
|
||||
public void handleMessagesPersistedPubSub() {
|
||||
messagesPersistedLatch.countDown();
|
||||
}
|
||||
}).toCompletableFuture().join();
|
||||
|
||||
final PubSubClientEventManager persistingPresenceManager =
|
||||
messagesPersistedRemotely ? remotePresenceManager : localPresenceManager;
|
||||
|
||||
persistingPresenceManager.handleMessagesPersisted(accountIdentifier, deviceId).toCompletableFuture().join();
|
||||
|
||||
assertTrue(messagesPersistedLatch.await(2, TimeUnit.SECONDS),
|
||||
"Message persistence event not received within time limit");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-10
@@ -43,7 +43,6 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
@@ -74,7 +73,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ExecutorService clientPresenceExecutor;
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private KeysManager keysManager;
|
||||
@@ -112,7 +110,6 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
clientPresenceExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
@@ -141,6 +138,10 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
when(registrationRecoveryPasswordsManager.removeForNumber(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
when(pubSubClientEventManager.requestDisconnection(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -152,12 +153,10 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
CLOCK,
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
@@ -166,13 +165,9 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
accountLockExecutor.shutdown();
|
||||
clientPresenceExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
clientPresenceExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
|
||||
-12
@@ -36,7 +36,6 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
@@ -67,10 +66,8 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
static final RedisClusterExtension CACHE_CLUSTER_EXTENSION = RedisClusterExtension.builder().build();
|
||||
|
||||
private KeysManager keysManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ExecutorService clientPresenceExecutor;
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
|
||||
@@ -106,7 +103,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
clientPresenceExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
@@ -120,7 +116,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers =
|
||||
@@ -149,12 +144,10 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
clientPresenceManager,
|
||||
pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
@@ -164,13 +157,9 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
accountLockExecutor.shutdown();
|
||||
clientPresenceExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
clientPresenceExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -285,7 +274,6 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
|
||||
assertEquals(secondNumber, accountsManager.getByAccountIdentifier(originalUuid).map(Account::getNumber).orElseThrow());
|
||||
|
||||
verify(clientPresenceManager).disconnectAllPresencesForUuid(existingAccountUuid);
|
||||
verify(pubSubClientEventManager).requestDisconnection(existingAccountUuid);
|
||||
|
||||
assertEquals(Optional.of(existingAccountUuid), accountsManager.findRecentlyDeletedAccountIdentifier(originalNumber));
|
||||
|
||||
-3
@@ -48,7 +48,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -134,12 +133,10 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
mock(Executor.class),
|
||||
mock(Executor.class),
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager
|
||||
|
||||
-3
@@ -14,7 +14,6 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
@@ -63,12 +62,10 @@ public class AccountsManagerDeviceTransferIntegrationTest {
|
||||
mock(ProfilesManager.class),
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
mock(ExecutorService.class),
|
||||
mock(ExecutorService.class),
|
||||
Clock.systemUTC(),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
mock(DynamicConfigurationManager.class));
|
||||
|
||||
+3
-17
@@ -79,7 +79,6 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -118,7 +117,6 @@ class AccountsManagerTest {
|
||||
private KeysManager keysManager;
|
||||
private MessagesManager messagesManager;
|
||||
private ProfilesManager profilesManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private ClientPublicKeysManager clientPublicKeysManager;
|
||||
|
||||
@@ -154,20 +152,10 @@ class AccountsManagerTest {
|
||||
keysManager = mock(KeysManager.class);
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
profilesManager = mock(ProfilesManager.class);
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
clientPublicKeysManager = mock(ClientPublicKeysManager.class);
|
||||
dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
|
||||
final Executor clientPresenceExecutor = mock(Executor.class);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
final Runnable runnable = invocation.getArgument(0);
|
||||
runnable.run();
|
||||
|
||||
return null;
|
||||
}).when(clientPresenceExecutor).execute(any());
|
||||
|
||||
//noinspection unchecked
|
||||
asyncCommands = mock(RedisAsyncCommands.class);
|
||||
when(asyncCommands.set(any(), any(), any())).thenReturn(MockRedisFuture.completedFuture("OK"));
|
||||
@@ -250,6 +238,9 @@ class AccountsManagerTest {
|
||||
.stringAsyncCommands(asyncClusterCommands)
|
||||
.build();
|
||||
|
||||
when(pubSubClientEventManager.requestDisconnection(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -261,12 +252,10 @@ class AccountsManagerTest {
|
||||
profilesManager,
|
||||
storageClient,
|
||||
svr2Client,
|
||||
clientPresenceManager,
|
||||
pubSubClientEventManager,
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
mock(Executor.class),
|
||||
clientPresenceExecutor,
|
||||
CLOCK,
|
||||
LINK_DEVICE_SECRET,
|
||||
dynamicConfigurationManager);
|
||||
@@ -802,7 +791,6 @@ class AccountsManagerTest {
|
||||
verify(keysManager, times(2)).deleteSingleUsePreKeys(account.getUuid(), linkedDevice.getId());
|
||||
verify(keysManager).buildWriteItemsForRemovedDevice(account.getUuid(), account.getPhoneNumberIdentifier(), linkedDevice.getId());
|
||||
verify(clientPublicKeysManager).buildTransactWriteItemForDeletion(account.getUuid(), linkedDevice.getId());
|
||||
verify(clientPresenceManager).disconnectPresence(account.getUuid(), linkedDevice.getId());
|
||||
verify(pubSubClientEventManager).requestDisconnection(account.getUuid(), List.of(linkedDevice.getId()));
|
||||
}
|
||||
|
||||
@@ -821,7 +809,6 @@ class AccountsManagerTest {
|
||||
assertDoesNotThrow(account::getPrimaryDevice);
|
||||
verify(messagesManager, never()).clear(any(), anyByte());
|
||||
verify(keysManager, never()).deleteSingleUsePreKeys(any(), anyByte());
|
||||
verify(clientPresenceManager, never()).disconnectPresence(any(), anyByte());
|
||||
verify(pubSubClientEventManager, never()).requestDisconnection(any(), any());
|
||||
}
|
||||
|
||||
@@ -891,7 +878,6 @@ class AccountsManagerTest {
|
||||
verify(keysManager, times(2)).deleteSingleUsePreKeys(phoneNumberIdentifiersByE164.get(e164));
|
||||
verify(messagesManager, times(2)).clear(existingUuid);
|
||||
verify(profilesManager, times(2)).deleteAll(existingUuid);
|
||||
verify(clientPresenceManager).disconnectAllPresencesForUuid(existingUuid);
|
||||
verify(pubSubClientEventManager).requestDisconnection(existingUuid);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -35,7 +35,6 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.mockito.Mockito;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
@@ -135,6 +134,9 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
when(messageManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(profileManager.deleteAll(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PubSubClientEventManager pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
when(pubSubClientEventManager.requestDisconnection(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -146,12 +148,10 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
profileManager,
|
||||
mock(SecureStorageClient.class),
|
||||
mock(SecureValueRecovery2Client.class),
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
pubSubClientEventManager,
|
||||
mock(RegistrationRecoveryPasswordsManager.class),
|
||||
mock(ClientPublicKeysManager.class),
|
||||
Executors.newSingleThreadExecutor(),
|
||||
Executors.newSingleThreadExecutor(),
|
||||
mock(Clock.class),
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
|
||||
-9
@@ -33,7 +33,6 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
@@ -70,7 +69,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
|
||||
private ExecutorService accountLockExecutor;
|
||||
private ExecutorService clientPresenceExecutor;
|
||||
|
||||
private KeysManager keysManager;
|
||||
private ClientPublicKeysManager clientPublicKeysManager;
|
||||
@@ -107,7 +105,6 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
DynamoDbExtensionSchema.Tables.USED_LINK_DEVICE_TOKENS.tableName());
|
||||
|
||||
accountLockExecutor = Executors.newSingleThreadExecutor();
|
||||
clientPresenceExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
final AccountLockManager accountLockManager = new AccountLockManager(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DynamoDbExtensionSchema.Tables.DELETED_ACCOUNTS_LOCK.tableName());
|
||||
@@ -152,12 +149,10 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
profilesManager,
|
||||
secureStorageClient,
|
||||
svr2Client,
|
||||
mock(ClientPresenceManager.class),
|
||||
mock(PubSubClientEventManager.class),
|
||||
registrationRecoveryPasswordsManager,
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
CLOCK,
|
||||
"link-device-secret".getBytes(StandardCharsets.UTF_8),
|
||||
dynamicConfigurationManager);
|
||||
@@ -170,13 +165,9 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
accountsManager.stop();
|
||||
|
||||
accountLockExecutor.shutdown();
|
||||
clientPresenceExecutor.shutdown();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
accountLockExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
clientPresenceExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+8
-1
@@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
@@ -32,6 +33,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
@@ -53,6 +55,7 @@ class MessagePersisterIntegrationTest {
|
||||
private ExecutorService messageDeletionExecutorService;
|
||||
private MessagesCache messagesCache;
|
||||
private MessagesManager messagesManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private MessagePersister messagePersister;
|
||||
private Account account;
|
||||
|
||||
@@ -82,8 +85,10 @@ class MessagePersisterIntegrationTest {
|
||||
messageDeliveryScheduler, messageDeletionExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
pubSubClientEventManager, dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
account = mock(Account.class);
|
||||
|
||||
@@ -178,6 +183,8 @@ class MessagePersisterIntegrationTest {
|
||||
.toList();
|
||||
|
||||
assertEquals(expectedMessages, persistedMessages);
|
||||
|
||||
verify(pubSubClientEventManager).handleMessagesPersisted(account.getUuid(), Device.PRIMARY_ID);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+10
-1
@@ -46,6 +46,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -66,6 +67,7 @@ class MessagePersisterTest {
|
||||
private MessagePersister messagePersister;
|
||||
private AccountsManager accountsManager;
|
||||
private MessagesManager messagesManager;
|
||||
private PubSubClientEventManager pubSubClientEventManager;
|
||||
private Account destinationAccount;
|
||||
|
||||
private static final UUID DESTINATION_ACCOUNT_UUID = UUID.randomUUID();
|
||||
@@ -100,7 +102,8 @@ class MessagePersisterTest {
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService,
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
pubSubClientEventManager = mock(PubSubClientEventManager.class);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, pubSubClientEventManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
@@ -154,6 +157,8 @@ class MessagePersisterTest {
|
||||
verify(messagesDynamoDb, atLeastOnce()).store(messagesCaptor.capture(), eq(DESTINATION_ACCOUNT_UUID),
|
||||
eq(DESTINATION_DEVICE));
|
||||
assertEquals(messageCount, messagesCaptor.getAllValues().stream().mapToInt(List::size).sum());
|
||||
|
||||
verify(pubSubClientEventManager).handleMessagesPersisted(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -223,6 +228,8 @@ class MessagePersisterTest {
|
||||
assertEquals(List.of(queueName),
|
||||
messagesCache.getQueuesToPersist(SlotHash.getSlot(queueName),
|
||||
Instant.now().plus(messagePersister.getPersistDelay()), 1));
|
||||
|
||||
verify(pubSubClientEventManager).handleMessagesPersisted(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -241,6 +248,8 @@ class MessagePersisterTest {
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () ->
|
||||
assertThrows(MessagePersistenceException.class,
|
||||
() -> messagePersister.persistQueue(destinationAccount, DESTINATION_DEVICE)));
|
||||
|
||||
verify(pubSubClientEventManager).handleMessagesPersisted(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-7
@@ -57,7 +57,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.push.PubSubClientEventManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
@@ -125,7 +124,7 @@ class WebSocketConnectionTest {
|
||||
new WebSocketAccountAuthenticator(accountAuthenticator, mock(PrincipalSupplier.class));
|
||||
AuthenticatedConnectListener connectListener = new AuthenticatedConnectListener(receiptSender, messagesManager,
|
||||
new MessageMetrics(), mock(PushNotificationManager.class), mock(PushNotificationScheduler.class),
|
||||
mock(ClientPresenceManager.class), mock(PubSubClientEventManager.class), retrySchedulingExecutor,
|
||||
mock(PubSubClientEventManager.class), retrySchedulingExecutor,
|
||||
messageDeliveryScheduler, clientReleaseManager, mock(MessageDeliveryLoopMonitor.class));
|
||||
WebSocketSessionContext sessionContext = mock(WebSocketSessionContext.class);
|
||||
|
||||
@@ -269,7 +268,7 @@ class WebSocketConnectionTest {
|
||||
// or wait for anything.
|
||||
connection.start();
|
||||
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
synchronized (sendCounter) {
|
||||
while (sendCounter.get() < 1) {
|
||||
@@ -277,7 +276,7 @@ class WebSocketConnectionTest {
|
||||
}
|
||||
}
|
||||
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
synchronized (sendCounter) {
|
||||
while (sendCounter.get() < 2) {
|
||||
@@ -694,7 +693,7 @@ class WebSocketConnectionTest {
|
||||
|
||||
when(client.sendRequest(eq("PUT"), eq("/api/v1/message"), any(List.class), any(Optional.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
return CompletableFuture.completedFuture(successResponse);
|
||||
});
|
||||
@@ -742,7 +741,7 @@ class WebSocketConnectionTest {
|
||||
|
||||
verify(messagesManager).getMessagesForDeviceReactive(account.getUuid(), device, false);
|
||||
|
||||
connection.handleNewMessagesAvailable();
|
||||
connection.handleNewMessageAvailable();
|
||||
|
||||
verify(messagesManager).getMessagesForDeviceReactive(account.getUuid(), device, true);
|
||||
}
|
||||
@@ -770,7 +769,7 @@ class WebSocketConnectionTest {
|
||||
// whenComplete method will get called immediately on THIS thread, so we don't need to synchronize or wait for
|
||||
// anything.
|
||||
connection.processStoredMessages();
|
||||
connection.handleMessagesPersisted();
|
||||
connection.handleMessagesPersistedPubSub();
|
||||
|
||||
verify(messagesManager, times(2)).getMessagesForDeviceReactive(account.getUuid(), device, false);
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ braintree:
|
||||
supportedCurrenciesByPaymentMethod:
|
||||
PAYPAL:
|
||||
- usd
|
||||
- xts
|
||||
pubSubPublisher:
|
||||
type: stub
|
||||
|
||||
@@ -155,9 +156,6 @@ dynamoDbTables:
|
||||
cacheCluster: # Redis server configuration for cache cluster
|
||||
type: local
|
||||
|
||||
clientPresenceCluster: # Redis server configuration for client presence cluster
|
||||
type: local
|
||||
|
||||
pubsub: # Redis server configuration for pubsub cluster
|
||||
type: local
|
||||
|
||||
@@ -375,7 +373,7 @@ subscription: # configuration for Stripe subscriptions
|
||||
prices: {}
|
||||
levels:
|
||||
500:
|
||||
badge: EXAMPLE
|
||||
badge: TEST
|
||||
prices:
|
||||
# list of ISO 4217 currency codes and amounts for the given badge level
|
||||
xts:
|
||||
@@ -389,11 +387,11 @@ oneTimeDonations:
|
||||
boost:
|
||||
level: 1
|
||||
expiration: P90D
|
||||
badge: EXAMPLE
|
||||
badge: TEST
|
||||
gift:
|
||||
level: 10
|
||||
expiration: P90D
|
||||
badge: EXAMPLE
|
||||
badge: TEST
|
||||
currencies:
|
||||
# ISO 4217 currency codes and amounts in those currencies
|
||||
xts:
|
||||
|
||||
+1
-1
Submodule spam-filter updated: d37dd5bde2...b08642def5.
Reference in new issue
Block a user