mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 12:36:47 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50a54136e8 | ||
|
|
a1d9c4c062 | ||
|
|
4acb3b5ac7 | ||
|
|
b76eaa1098 | ||
|
|
c883cd8148 | ||
|
|
1e77d0471e | ||
|
|
a94ce72894 | ||
|
|
0f2a4d02e0 | ||
|
|
4d521cea42 |
No files matched your search
+1
-1
@@ -316,7 +316,7 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration(Duration.ofMillis(1));
|
||||
private VirtualThreadConfiguration virtualThread = new VirtualThreadConfiguration();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
|
||||
@@ -258,6 +258,7 @@ import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import org.whispersystems.textsecuregcm.util.VirtualExecutorServiceProvider;
|
||||
@@ -395,8 +396,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.lifecycle().manage(new ManagedAwsCrt());
|
||||
|
||||
final ExecutorService awsSdkMetricsExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "awsSdkMetrics-%d"));
|
||||
final ExecutorService awsSdkMetricsExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"awsSdkMetrics",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient = config.getDynamoDbClientConfiguration()
|
||||
.buildAsyncClient(awsCredentialsProvider, new MicrometerAwsSdkMetricPublisher(awsSdkMetricsExecutor, "dynamoDbAsync"));
|
||||
@@ -449,8 +452,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDynamoDbTables().getPagedKemKeys().getTableName(),
|
||||
config.getPagedSingleUseKEMPreKeyStore().bucket()),
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getEcSignedPreKeys().getTableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemLastResortKeys().getTableName()),
|
||||
experimentEnrollmentManager);
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, config.getDynamoDbTables().getKemLastResortKeys().getTableName()));
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getMessages().getTableName(),
|
||||
config.getDynamoDbTables().getMessages().getExpiration(),
|
||||
@@ -562,14 +564,23 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
ExecutorService googlePlayBillingExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "googlePlayBilling-%d"));
|
||||
ExecutorService appleAppStoreExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "appleAppStore-%d"));
|
||||
ExecutorService clientEventExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "clientEvent-%d"));
|
||||
ExecutorService disconnectionRequestListenerExecutor = environment.lifecycle()
|
||||
.virtualExecutorService(name(getClass(), "disconnectionRequest-%d"));
|
||||
|
||||
ExecutorService googlePlayBillingExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"googlePlayBilling",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
ExecutorService appleAppStoreExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"appleAppStore",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
ExecutorService clientEventExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"clientEvent",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
ExecutorService disconnectionRequestListenerExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"disconnectionRequest",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor(),
|
||||
environment);
|
||||
|
||||
ScheduledExecutorService appleAppStoreRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "appleAppStoreRetry").threads(1).build();
|
||||
ScheduledExecutorService subscriptionProcessorRetryExecutor = ScheduledExecutorServiceBuilder.of(environment, "subscriptionProcessorRetry").threads(1).build();
|
||||
@@ -977,7 +988,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.jersey().register(new BufferingInterceptor());
|
||||
environment.jersey().register(new RestDeprecationFilter(dynamicConfigurationManager, experimentEnrollmentManager));
|
||||
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider(
|
||||
"managed-async-virtual-thread",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
|
||||
environment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
@@ -988,15 +1001,16 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
///
|
||||
WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment = new WebSocketEnvironment<>(environment,
|
||||
config.getWebSocketConfiguration(), Duration.ofMillis(90000));
|
||||
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider("managed-async-websocket-virtual-thread-"));
|
||||
webSocketEnvironment.jersey().register(new VirtualExecutorServiceProvider(
|
||||
"managed-async-websocket-virtual-thread",
|
||||
config.getVirtualThreadConfiguration().maxConcurrentThreadsPerExecutor()));
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
|
||||
webSocketEnvironment.setAuthenticatedWebSocketUpgradeFilter(new IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter(
|
||||
config.idlePrimaryDeviceReminderConfiguration().minIdleDuration(), Clock.systemUTC()));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager
|
||||
));
|
||||
pushNotificationScheduler, redisMessageAvailabilityManager, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, clientReleaseManager, messageDeliveryLoopMonitor, experimentEnrollmentManager));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
|
||||
+17
-1
@@ -6,4 +6,20 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public record VirtualThreadConfiguration(Duration pinEventThreshold) {}
|
||||
public record VirtualThreadConfiguration(
|
||||
Duration pinEventThreshold,
|
||||
Integer maxConcurrentThreadsPerExecutor) {
|
||||
|
||||
public VirtualThreadConfiguration() {
|
||||
this(null, null);
|
||||
}
|
||||
|
||||
public VirtualThreadConfiguration {
|
||||
if (maxConcurrentThreadsPerExecutor == null) {
|
||||
maxConcurrentThreadsPerExecutor = 1_000_000;
|
||||
}
|
||||
if (pinEventThreshold == null) {
|
||||
pinEventThreshold = Duration.ofMillis(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-4
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -371,9 +370,8 @@ public class KeysController {
|
||||
final Account target = maybeTarget.orElseThrow(NotFoundException::new);
|
||||
|
||||
if (account.isPresent()) {
|
||||
rateLimiters.getPreKeysLimiter().validate(
|
||||
account.get().getUuid() + "." + maybeAuthenticatedDevice.get().deviceId() + "__" + targetIdentifier.uuid()
|
||||
+ "." + deviceId);
|
||||
rateLimiters.getPreKeysLimiter().validate(getPreKeysLimiterKey(account.get(), maybeAuthenticatedDevice.get(),
|
||||
targetIdentifier, target, deviceId));
|
||||
}
|
||||
|
||||
final List<Device> devices = parseDeviceId(deviceId, target);
|
||||
@@ -409,4 +407,24 @@ public class KeysController {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
}
|
||||
|
||||
private String getPreKeysLimiterKey(
|
||||
final Account account,
|
||||
final AuthenticatedDevice authenticatedDevice,
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final Account targetAccount,
|
||||
final String targetDeviceId) {
|
||||
final String targetRegistrationId = targetDeviceId.equals("*")
|
||||
? "*"
|
||||
: String.valueOf(
|
||||
parseDeviceId(targetDeviceId, targetAccount).getFirst().getRegistrationId(targetIdentifier.identityType()));
|
||||
|
||||
return String.format("%s.%s__%s.%s.%s",
|
||||
account.getUuid(),
|
||||
authenticatedDevice.deviceId(),
|
||||
targetIdentifier.uuid(),
|
||||
targetDeviceId,
|
||||
targetRegistrationId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import org.whispersystems.textsecuregcm.controllers.KeysController;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
@@ -36,9 +35,6 @@ public class KeysManager {
|
||||
private final PagedSingleUseKEMPreKeyStore pagedPqPreKeys;
|
||||
private final RepeatedUseECSignedPreKeyStore ecSignedPreKeys;
|
||||
private final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
public static String PAGED_KEYS_EXPERIMENT_NAME = "pagedPreKeys";
|
||||
|
||||
private static final String TAKE_PQ_NAME = MetricsUtil.name(KeysManager.class, "takePq");
|
||||
|
||||
@@ -47,14 +43,12 @@ public class KeysManager {
|
||||
final SingleUseKEMPreKeyStore pqPreKeys,
|
||||
final PagedSingleUseKEMPreKeyStore pagedPqPreKeys,
|
||||
final RepeatedUseECSignedPreKeyStore ecSignedPreKeys,
|
||||
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
final RepeatedUseKEMSignedPreKeyStore pqLastResortKeys) {
|
||||
this.ecPreKeys = ecPreKeys;
|
||||
this.pqPreKeys = pqPreKeys;
|
||||
this.pagedPqPreKeys = pagedPqPreKeys;
|
||||
this.ecSignedPreKeys = ecSignedPreKeys;
|
||||
this.pqLastResortKeys = pqLastResortKeys;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
public TransactWriteItem buildWriteItemForEcSignedPreKey(final UUID identifier,
|
||||
@@ -116,13 +110,9 @@ public class KeysManager {
|
||||
|
||||
public CompletableFuture<Void> storeKemOneTimePreKeys(final UUID identifier, final byte deviceId,
|
||||
final List<KEMSignedPreKey> preKeys) {
|
||||
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
|
||||
final CompletableFuture<Void> deleteOtherKeys = enrolledInPagedKeys
|
||||
? pqPreKeys.delete(identifier, deviceId)
|
||||
: pagedPqPreKeys.delete(identifier, deviceId);
|
||||
return deleteOtherKeys.thenCompose(ignored -> enrolledInPagedKeys
|
||||
? pagedPqPreKeys.store(identifier, deviceId, preKeys)
|
||||
: pqPreKeys.store(identifier, deviceId, preKeys));
|
||||
// Unconditionally delete keys in old format keystore, then write to the pagedPqPreKeys store
|
||||
return pqPreKeys.delete(identifier, deviceId)
|
||||
.thenCompose(_ -> pagedPqPreKeys.store(identifier, deviceId, preKeys));
|
||||
|
||||
}
|
||||
|
||||
@@ -133,14 +123,13 @@ public class KeysManager {
|
||||
|
||||
@VisibleForTesting
|
||||
CompletableFuture<Optional<KEMSignedPreKey>> takePQ(final UUID identifier, final byte deviceId) {
|
||||
final boolean enrolledInPagedKeys = experimentEnrollmentManager.isEnrolled(identifier, PAGED_KEYS_EXPERIMENT_NAME);
|
||||
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE, enrolledInPagedKeys)
|
||||
return tagTakePQ(pagedPqPreKeys.take(identifier, deviceId), PQSource.PAGE)
|
||||
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
|
||||
.map(ignored -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
|
||||
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW, enrolledInPagedKeys)))
|
||||
.orElseGet(() -> tagTakePQ(pqPreKeys.take(identifier, deviceId), PQSource.ROW)))
|
||||
.thenCompose(maybeSingleUsePreKey -> maybeSingleUsePreKey
|
||||
.map(singleUsePreKey -> CompletableFuture.completedFuture(maybeSingleUsePreKey))
|
||||
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT, enrolledInPagedKeys)));
|
||||
.orElseGet(() -> tagTakePQ(pqLastResortKeys.find(identifier, deviceId), PQSource.LAST_RESORT)));
|
||||
}
|
||||
|
||||
private enum PQSource {
|
||||
@@ -148,7 +137,7 @@ public class KeysManager {
|
||||
ROW,
|
||||
LAST_RESORT
|
||||
}
|
||||
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source, final boolean enrolledInPagedKeys) {
|
||||
private CompletableFuture<Optional<KEMSignedPreKey>> tagTakePQ(CompletableFuture<Optional<KEMSignedPreKey>> prekey, final PQSource source) {
|
||||
return prekey.thenApply(maybeSingleUsePreKey -> {
|
||||
final Optional<String> maybeSourceTag = maybeSingleUsePreKey
|
||||
// If we found a PK, use this source tag
|
||||
@@ -156,10 +145,7 @@ public class KeysManager {
|
||||
// If we didn't and this is our last resort, we didn't find a PK
|
||||
.or(() -> source == PQSource.LAST_RESORT ? Optional.of("absent") : Optional.empty());
|
||||
maybeSourceTag.ifPresent(sourceTag -> {
|
||||
Metrics.counter(TAKE_PQ_NAME,
|
||||
"source", sourceTag,
|
||||
"enrolled", Boolean.toString(enrolledInPagedKeys))
|
||||
.increment();
|
||||
Metrics.counter(TAKE_PQ_NAME, "source", sourceTag).increment();
|
||||
});
|
||||
return maybeSingleUsePreKey;
|
||||
});
|
||||
@@ -178,9 +164,9 @@ public class KeysManager {
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> getPqCount(final UUID identifier, final byte deviceId) {
|
||||
return pagedPqPreKeys.getCount(identifier, deviceId).thenCompose(count -> count == 0
|
||||
? pqPreKeys.getCount(identifier, deviceId)
|
||||
: CompletableFuture.completedFuture(count));
|
||||
// We only return the paged prekey count to encourage clients to upload more prekeys if they only have prekeys
|
||||
// stored in the previous key store format
|
||||
return pagedPqPreKeys.getCount(identifier, deviceId);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteSingleUsePreKeys(final UUID identifier) {
|
||||
|
||||
+85
-25
@@ -8,63 +8,106 @@ import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.hash.Hashing;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
/// An implementation of a message store backed by FoundationDB.
|
||||
///
|
||||
/// @implNote The layout of elements in FoundationDB is as follows:
|
||||
/// * messages
|
||||
/// * {aci}
|
||||
/// * last => versionstamp
|
||||
/// * messageAvailableWatch => versionstamp
|
||||
/// * {deviceId}
|
||||
/// * presence => server_id | last_seen_seconds_since_epoch
|
||||
/// * queue
|
||||
/// * {versionstamp_1} => envelope_1
|
||||
/// * {versionstamp_2} => envelope_2
|
||||
public class FoundationDbMessageStore {
|
||||
|
||||
private final Database[] databases;
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private final Executor executor;
|
||||
private final Clock clock;
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor) {
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
private static final int MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE = 300;
|
||||
|
||||
public FoundationDbMessageStore(final Database[] databases, final Executor executor, final Clock clock) {
|
||||
this.databases = databases;
|
||||
this.executor = executor;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a message bundle for a set of devices belonging to a single recipient
|
||||
*
|
||||
* @param aci destination account identifier
|
||||
* @param messagesByDeviceId a map of deviceId => message envelope
|
||||
* @return a future that completes with a {@link Versionstamp} of the committed transaction
|
||||
*/
|
||||
public CompletableFuture<Versionstamp> insert(final AciServiceIdentifier aci,
|
||||
/// Insert a message bundle for a set of devices belonging to a single recipient. A message may not be inserted if the
|
||||
/// device is not present (as determined from its presence key) and the message is ephemeral. If all messages in the
|
||||
/// bundle don't end up being inserted, we won't return a versionstamp since the transaction was read-only.
|
||||
///
|
||||
/// @param aci destination account identifier
|
||||
/// @param messagesByDeviceId a map of deviceId => message envelope
|
||||
/// @return a future that completes with a [Versionstamp] of the committed transaction if at least one message was
|
||||
/// inserted
|
||||
public CompletableFuture<Optional<Versionstamp>> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId) {
|
||||
// We use Database#runAsync and not Database#run here because the latter would commit the transaction synchronously
|
||||
// and we would like to avoid any potential blocking in native code that could unexpectedly pin virtual threads. See https://forums.foundationdb.org/t/fdbdatabase-usage-from-java-api/593/2
|
||||
// for details.
|
||||
return getShardForAci(aci).runAsync(transaction -> {
|
||||
insert(aci, messagesByDeviceId, transaction);
|
||||
return CompletableFuture.completedFuture(transaction.getVersionstamp());
|
||||
})
|
||||
return getShardForAci(aci).runAsync(transaction -> insert(aci, messagesByDeviceId, transaction)
|
||||
.thenApply(hasMutations -> {
|
||||
if (hasMutations) {
|
||||
return transaction.getVersionstamp();
|
||||
}
|
||||
return CompletableFuture.completedFuture((byte[]) null);
|
||||
}))
|
||||
.thenComposeAsync(Function.identity(), executor)
|
||||
.thenApply(Versionstamp::complete);
|
||||
.thenApply(versionstampBytes -> Optional.ofNullable(versionstampBytes).map(Versionstamp::complete));
|
||||
}
|
||||
|
||||
private void insert(final AciServiceIdentifier aci, final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
private CompletableFuture<Boolean> insert(final AciServiceIdentifier aci,
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId,
|
||||
final Transaction transaction) {
|
||||
messagesByDeviceId.forEach((deviceId, message) -> {
|
||||
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY, deviceQueueSubspace.packWithVersionstamp(Tuple.from(
|
||||
Versionstamp.incomplete())), message.toByteArray());
|
||||
});
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getLastMessageKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
final List<CompletableFuture<Pair<Boolean, Boolean>>> messageInsertFutures = messagesByDeviceId.entrySet()
|
||||
.stream()
|
||||
.map(e -> {
|
||||
final byte deviceId = e.getKey();
|
||||
final MessageProtos.Envelope message = e.getValue();
|
||||
final byte[] presenceKey = getPresenceKey(aci, deviceId);
|
||||
return transaction.get(presenceKey)
|
||||
.thenApply(this::isClientPresent)
|
||||
.thenApply(isPresent -> {
|
||||
boolean hasMutations = false;
|
||||
if (isPresent || !message.getEphemeral()) {
|
||||
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, deviceId);
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_KEY,
|
||||
deviceQueueSubspace.packWithVersionstamp(Tuple.from(
|
||||
Versionstamp.incomplete())), message.toByteArray());
|
||||
hasMutations = true;
|
||||
}
|
||||
return new Pair<>(isPresent, hasMutations);
|
||||
});
|
||||
})
|
||||
.toList();
|
||||
return CompletableFuture.allOf(messageInsertFutures.toArray(CompletableFuture[]::new))
|
||||
.thenApply(_ -> {
|
||||
final boolean anyClientPresent = messageInsertFutures
|
||||
.stream()
|
||||
.anyMatch(future -> future.join().first());
|
||||
final boolean hasMutations = messageInsertFutures
|
||||
.stream()
|
||||
.anyMatch(future -> future.join().second());
|
||||
if (anyClientPresent && hasMutations) {
|
||||
transaction.mutate(MutationType.SET_VERSIONSTAMPED_VALUE, getMessagesAvailableWatchKey(aci),
|
||||
Tuple.from(Versionstamp.incomplete()).packWithVersionstamp());
|
||||
}
|
||||
return hasMutations;
|
||||
});
|
||||
}
|
||||
|
||||
private Database getShardForAci(final AciServiceIdentifier aci) {
|
||||
@@ -90,8 +133,25 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getLastMessageKey(final AciServiceIdentifier aci) {
|
||||
byte[] getMessagesAvailableWatchKey(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(aci).pack("l");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
byte[] getPresenceKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceQueueSubspace(aci, deviceId).pack("p");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean isClientPresent(final byte[] presenceValueBytes) {
|
||||
if (presenceValueBytes == null) {
|
||||
return false;
|
||||
}
|
||||
final long presenceValue = Conversions.byteArrayToLong(presenceValueBytes);
|
||||
// The presence value is a long with the higher order 16 bits containing a server id, and the lower 48 bits
|
||||
// containing the timestamp (seconds since epoch) that the client updates periodically.
|
||||
final long lastSeenSecondsSinceEpoch = presenceValue & 0x0000ffffffffffffL;
|
||||
return (clock.instant().getEpochSecond() - lastSeenSecondsSinceEpoch) <= MAX_SECONDS_SINCE_UPDATE_FOR_PRESENCE;
|
||||
}
|
||||
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
/**
|
||||
* A thread factory that creates virtual threads but limits the total number of virtual threads created.
|
||||
*/
|
||||
public class BoundedVirtualThreadFactory implements ThreadFactory {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BoundedVirtualThreadFactory.class);
|
||||
|
||||
private final AtomicInteger runningThreads = new AtomicInteger();
|
||||
private final ThreadFactory delegate;
|
||||
private final int maxConcurrentThreads;
|
||||
|
||||
private final Counter created;
|
||||
private final Counter completed;
|
||||
|
||||
public BoundedVirtualThreadFactory(final String threadPoolName, final int maxConcurrentThreads) {
|
||||
this.maxConcurrentThreads = maxConcurrentThreads;
|
||||
|
||||
final Tags tags = Tags.of("pool", threadPoolName);
|
||||
Metrics.gauge(
|
||||
MetricsUtil.name(BoundedVirtualThreadFactory.class, "active"),
|
||||
tags, runningThreads, (rt) -> (double) rt.get());
|
||||
this.created = Metrics.counter(MetricsUtil.name(BoundedVirtualThreadFactory.class, "created"), tags);
|
||||
this.completed = Metrics.counter(MetricsUtil.name(BoundedVirtualThreadFactory.class, "completed"), tags);
|
||||
|
||||
// The virtual thread factory will initialize thread names by appending the thread index to the provided prefix
|
||||
this.delegate = Thread.ofVirtual().name(threadPoolName + "-", 0).factory();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Thread newThread(final Runnable r) {
|
||||
if (!tryAcquire()) {
|
||||
return null;
|
||||
}
|
||||
Thread thread = null;
|
||||
try {
|
||||
final Runnable wrapped = () -> {
|
||||
try {
|
||||
r.run();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
};
|
||||
thread = delegate.newThread(wrapped);
|
||||
} finally {
|
||||
if (thread == null) {
|
||||
release();
|
||||
}
|
||||
}
|
||||
return thread;
|
||||
}
|
||||
|
||||
|
||||
@VisibleForTesting
|
||||
int getRunningThreads() {
|
||||
return runningThreads.get();
|
||||
}
|
||||
|
||||
private boolean tryAcquire() {
|
||||
int old;
|
||||
do {
|
||||
old = runningThreads.get();
|
||||
if (old >= maxConcurrentThreads) {
|
||||
return false;
|
||||
}
|
||||
} while (!runningThreads.compareAndSet(old, old + 1));
|
||||
created.increment();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void release() {
|
||||
int updated = runningThreads.decrementAndGet();
|
||||
if (updated < 0) {
|
||||
logger.error("Released a thread and count was {}, which should never happen", updated);
|
||||
}
|
||||
completed.increment();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.lifecycle.ExecutorServiceManager;
|
||||
import io.dropwizard.util.Duration;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Build Executor Services managed by dropwizard, supplementing executors provided by
|
||||
* {@link io.dropwizard.lifecycle.setup.LifecycleEnvironment#executorService}
|
||||
*/
|
||||
public class ManagedExecutors {
|
||||
|
||||
private static final Duration SHUTDOWN_DURATION = Duration.seconds(5);
|
||||
|
||||
private ManagedExecutors() {
|
||||
}
|
||||
|
||||
public static ExecutorService newVirtualThreadPerTaskExecutor(
|
||||
final String threadNamePrefix,
|
||||
final int maxConcurrentThreads,
|
||||
final Environment environment) {
|
||||
|
||||
final BoundedVirtualThreadFactory threadFactory =
|
||||
new BoundedVirtualThreadFactory(threadNamePrefix, maxConcurrentThreads);
|
||||
final ExecutorService virtualThreadExecutor = Executors.newThreadPerTaskExecutor(threadFactory);
|
||||
environment.lifecycle()
|
||||
.manage(new ExecutorServiceManager(virtualThreadExecutor, SHUTDOWN_DURATION, threadNamePrefix));
|
||||
return virtualThreadExecutor;
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -15,6 +15,7 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
@ManagedAsyncExecutor
|
||||
public class VirtualExecutorServiceProvider implements ExecutorServiceProvider {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(VirtualExecutorServiceProvider.class);
|
||||
|
||||
|
||||
@@ -22,17 +23,24 @@ public class VirtualExecutorServiceProvider implements ExecutorServiceProvider {
|
||||
* Default thread pool executor termination timeout in milliseconds.
|
||||
*/
|
||||
public static final int TERMINATION_TIMEOUT = 5000;
|
||||
private final String virtualThreadNamePrefix;
|
||||
|
||||
public VirtualExecutorServiceProvider(final String virtualThreadNamePrefix) {
|
||||
private final String virtualThreadNamePrefix;
|
||||
private final int maxConcurrentThreads;
|
||||
|
||||
public VirtualExecutorServiceProvider(
|
||||
final String virtualThreadNamePrefix,
|
||||
final int maxConcurrentThreads) {
|
||||
this.virtualThreadNamePrefix = virtualThreadNamePrefix;
|
||||
this.maxConcurrentThreads = maxConcurrentThreads;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ExecutorService getExecutorService() {
|
||||
logger.info("Creating executor service with virtual thread per task");
|
||||
return Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name(virtualThreadNamePrefix, 0).factory());
|
||||
final ExecutorService executor = Executors.newThreadPerTaskExecutor(
|
||||
new BoundedVirtualThreadFactory(virtualThreadNamePrefix, maxConcurrentThreads));
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+61
-51
@@ -7,11 +7,10 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -24,12 +23,12 @@ import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
import org.whispersystems.websocket.setup.WebSocketConnectListener;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -46,18 +45,21 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthenticatedConnectListener.class);
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final ReceiptSender receiptSender;
|
||||
private final MessagesManager messagesManager;
|
||||
private final MessageMetrics messageMetrics;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final WebSocketConnectionBuilder webSocketConnectionBuilder;
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final OpenWebSocketCounter openAuthenticatedWebSocketCounter;
|
||||
private final OpenWebSocketCounter openUnauthenticatedWebSocketCounter;
|
||||
|
||||
@VisibleForTesting
|
||||
@FunctionalInterface
|
||||
interface WebSocketConnectionBuilder {
|
||||
WebSocketConnection buildWebSocketConnection(Account account, Device device, WebSocketClient client);
|
||||
}
|
||||
|
||||
public AuthenticatedConnectListener(
|
||||
final AccountsManager accountsManager,
|
||||
final ReceiptSender receiptSender,
|
||||
@@ -65,63 +67,47 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final MessageMetrics messageMetrics,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this(accountsManager,
|
||||
disconnectionRequestManager,
|
||||
(account, device, client) -> new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
account,
|
||||
device,
|
||||
client,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager),
|
||||
authenticated -> new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME,
|
||||
NEW_CONNECTION_COUNTER_NAME,
|
||||
CONNECTED_DURATION_TIMER_NAME,
|
||||
Duration.ofHours(3),
|
||||
Tags.of(AUTHENTICATED_TAG_NAME, String.valueOf(authenticated)))
|
||||
);
|
||||
}
|
||||
|
||||
@VisibleForTesting AuthenticatedConnectListener(
|
||||
final AccountsManager accountsManager,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final WebSocketConnectionBuilder webSocketConnectionBuilder,
|
||||
final Function<Boolean, OpenWebSocketCounter> openWebSocketCounterBuilder) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageMetrics = messageMetrics;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.webSocketConnectionBuilder = webSocketConnectionBuilder;
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
openAuthenticatedWebSocketCounter = openWebSocketCounterBuilder.apply(true);
|
||||
openUnauthenticatedWebSocketCounter = openWebSocketCounterBuilder.apply(false);
|
||||
openAuthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Duration.ofHours(3), Tags.of(AUTHENTICATED_TAG_NAME, "true"));
|
||||
|
||||
openUnauthenticatedWebSocketCounter =
|
||||
new OpenWebSocketCounter(OPEN_WEBSOCKET_GAUGE_NAME, NEW_CONNECTION_COUNTER_NAME, CONNECTED_DURATION_TIMER_NAME, Duration.ofHours(3), Tags.of(AUTHENTICATED_TAG_NAME, "false"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWebSocketConnect(final WebSocketSessionContext context) {
|
||||
|
||||
final boolean authenticated = (context.getAuthenticated() != null);
|
||||
final OpenWebSocketCounter openWebSocketCounter =
|
||||
authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter;
|
||||
|
||||
(authenticated ? openAuthenticatedWebSocketCounter : openUnauthenticatedWebSocketCounter).countOpenWebSocket(context);
|
||||
openWebSocketCounter.countOpenWebSocket(context);
|
||||
|
||||
if (authenticated) {
|
||||
final AuthenticatedDevice auth = context.getAuthenticated(AuthenticatedDevice.class);
|
||||
|
||||
final Optional<Account> maybeAuthenticatedAccount =
|
||||
accountsManager.getByAccountIdentifier(auth.accountIdentifier());
|
||||
|
||||
final Optional<Device> maybeAuthenticatedDevice =
|
||||
maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
|
||||
final Optional<Account> maybeAuthenticatedAccount = accountsManager.getByAccountIdentifier(auth.accountIdentifier());
|
||||
final Optional<Device> maybeAuthenticatedDevice = maybeAuthenticatedAccount.flatMap(account -> account.getDevice(auth.deviceId()));
|
||||
|
||||
if (maybeAuthenticatedAccount.isEmpty() || maybeAuthenticatedDevice.isEmpty()) {
|
||||
log.warn("{}:{} not found when opening authenticated WebSocket", auth.accountIdentifier(), auth.deviceId());
|
||||
@@ -130,10 +116,18 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
return;
|
||||
}
|
||||
|
||||
final WebSocketConnection connection =
|
||||
webSocketConnectionBuilder.buildWebSocketConnection(maybeAuthenticatedAccount.get(),
|
||||
maybeAuthenticatedDevice.get(),
|
||||
context.getClient());
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
maybeAuthenticatedAccount.get(),
|
||||
maybeAuthenticatedDevice.get(),
|
||||
context.getClient(),
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager);
|
||||
|
||||
disconnectionRequestManager.addListener(maybeAuthenticatedAccount.get().getIdentifier(IdentityType.ACI),
|
||||
maybeAuthenticatedDevice.get().getId(),
|
||||
@@ -144,11 +138,27 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
maybeAuthenticatedDevice.get().getId(),
|
||||
connection);
|
||||
|
||||
// We begin the shutdown process by removing this client's "presence," which means it will again begin to
|
||||
// receive push notifications for inbound messages. We should do this first because, at this point, the
|
||||
// connection has already closed and attempts to actually deliver a message via the connection will not succeed.
|
||||
// It's preferable to start sending push notifications as soon as possible.
|
||||
redisMessageAvailabilityManager.handleClientDisconnected(auth.accountIdentifier(), auth.deviceId());
|
||||
|
||||
// Finally, stop trying to deliver messages and send a push notification if the connection is aware of any
|
||||
// undelivered messages.
|
||||
connection.stop();
|
||||
});
|
||||
|
||||
try {
|
||||
// Once we "start" the websocket connection, we'll cancel any scheduled "you may have new messages" push
|
||||
// notifications and begin delivering any stored messages for the connected device. We have not yet declared the
|
||||
// client as "present" yet. If a message arrives at this point, we will update the message availability state
|
||||
// correctly, but we may also send a spurious push notification.
|
||||
connection.start();
|
||||
|
||||
// Finally, we register this client's presence, which suppresses push notifications. We do this last because
|
||||
// receiving extra push notifications is generally preferable to missing out on a push notification.
|
||||
redisMessageAvailabilityManager.handleClientConnected(auth.accountIdentifier(), auth.deviceId(), connection);
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
|
||||
+206
-155
@@ -14,17 +14,22 @@ import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.eclipse.jetty.util.StaticException;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
@@ -37,28 +42,26 @@ import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.WebSocketResourceProvider;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
public class WebSocketConnection implements MessageAvailabilityListener, DisconnectionRequestListener {
|
||||
|
||||
private static final Counter sendMessageCounter = Metrics.counter(name(WebSocketConnection.class, "sendMessage"));
|
||||
private static final Counter bytesSentCounter = Metrics.counter(name(WebSocketConnection.class, "bytesSent"));
|
||||
@@ -75,15 +78,17 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
"sendMessages");
|
||||
private static final String SEND_MESSAGE_ERROR_COUNTER = MetricsUtil.name(WebSocketConnection.class,
|
||||
"sendMessageError");
|
||||
private static final String MESSAGE_AVAILABLE_COUNTER_NAME = name(WebSocketConnection.class, "messagesAvailable");
|
||||
private static final String MESSAGES_PERSISTED_COUNTER_NAME = name(WebSocketConnection.class, "messagesPersisted");
|
||||
private static final String SEND_MESSAGE_DURATION_TIMER_NAME = name(WebSocketConnection.class, "sendMessageDuration");
|
||||
|
||||
private static final String PRESENCE_MANAGER_TAG = "presenceManager";
|
||||
private static final String STATUS_CODE_TAG = "status";
|
||||
private static final String STATUS_MESSAGE_TAG = "message";
|
||||
private static final String ERROR_TYPE_TAG = "errorType";
|
||||
private static final String EXCEPTION_TYPE_TAG = "exceptionType";
|
||||
private static final String CONNECTED_ELSEWHERE_TAG = "connectedElsewhere";
|
||||
|
||||
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
|
||||
private static final long SLOW_DRAIN_THRESHOLD = 10_000;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
|
||||
@@ -103,21 +108,28 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
private final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final Retry retrySpec;
|
||||
|
||||
private final Account authenticatedAccount;
|
||||
private final Device authenticatedDevice;
|
||||
private final MessageStream messageStream;
|
||||
private final WebSocketClient client;
|
||||
private final Tags platformTag;
|
||||
|
||||
private final Semaphore processStoredMessagesSemaphore = new Semaphore(1);
|
||||
private final AtomicReference<StoredMessageState> storedMessageState = new AtomicReference<>(
|
||||
StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
private final AtomicBoolean sentInitialQueueEmptyMessage = new AtomicBoolean(false);
|
||||
private final LongAdder sentMessageCounter = new LongAdder();
|
||||
private final AtomicLong queueDrainStartNanoTime = new AtomicLong();
|
||||
private final AtomicReference<Disposable> messageSubscription = new AtomicReference<>();
|
||||
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private enum StoredMessageState {
|
||||
EMPTY,
|
||||
CACHED_NEW_MESSAGES_AVAILABLE,
|
||||
PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
}
|
||||
|
||||
public WebSocketConnection(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
final MessageMetrics messageMetrics,
|
||||
@@ -131,38 +143,6 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
|
||||
this(receiptSender,
|
||||
messagesManager,
|
||||
messageMetrics,
|
||||
pushNotificationManager,
|
||||
pushNotificationScheduler,
|
||||
authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
client,
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
messageDeliveryLoopMonitor,
|
||||
experimentEnrollmentManager,
|
||||
Retry.backoff(4, Duration.ofSeconds(1))
|
||||
.maxBackoff(Duration.ofSeconds(2))
|
||||
.filter(throwable -> !isConnectionClosedException(throwable)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
WebSocketConnection(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
final MessageMetrics messageMetrics,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final Account authenticatedAccount,
|
||||
final Device authenticatedDevice,
|
||||
final WebSocketClient client,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final MessageDeliveryLoopMonitor messageDeliveryLoopMonitor,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final Retry retrySpec) {
|
||||
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageMetrics = messageMetrics;
|
||||
@@ -175,83 +155,12 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.messageDeliveryLoopMonitor = messageDeliveryLoopMonitor;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.retrySpec = retrySpec;
|
||||
|
||||
this.messageStream =
|
||||
messagesManager.getMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice);
|
||||
|
||||
this.platformTag = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
}
|
||||
|
||||
public void start() {
|
||||
pushNotificationManager.handleMessagesRetrieved(authenticatedAccount, authenticatedDevice, client.getUserAgent());
|
||||
|
||||
final long queueDrainStartNanos = System.nanoTime();
|
||||
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
|
||||
|
||||
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
// We want to handle conflicting connections as soon as possible, and so do this before we start processing
|
||||
// messages in the `flatMapSequential` stage below. If we didn't do this first, then we'd wait for clients to
|
||||
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
|
||||
// it's also not ideal.
|
||||
.doOnError(ConflictingMessageConsumerException.class, _ -> {
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, platformTag.and(CONNECTED_ELSEWHERE_TAG, "true")).increment();
|
||||
client.close(4409, "Connected elsewhere");
|
||||
})
|
||||
.doOnNext(entry -> {
|
||||
if (entry instanceof MessageStreamEntry.Envelope(final Envelope message)) {
|
||||
if (hasSentFirstMessage.compareAndSet(false, true)) {
|
||||
messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI),
|
||||
authenticatedDevice.getId(),
|
||||
UUID.fromString(message.getServerGuid()),
|
||||
client.getUserAgent(),
|
||||
"websocket");
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope envelope -> Mono.fromFuture(() -> sendMessage(envelope.message()))
|
||||
.retryWhen(retrySpec)
|
||||
.thenReturn(entry);
|
||||
case MessageStreamEntry.QueueEmpty _ -> Mono.just(entry);
|
||||
}, MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
entry -> {
|
||||
if (entry instanceof MessageStreamEntry.QueueEmpty) {
|
||||
final Duration drainDuration = Duration.ofNanos(System.nanoTime() - queueDrainStartNanos);
|
||||
|
||||
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, platformTag).record(sentMessageCounter.sum());
|
||||
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, platformTag).record(drainDuration);
|
||||
|
||||
if (drainDuration.compareTo(SLOW_DRAIN_THRESHOLD) > 0) {
|
||||
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, platformTag).increment();
|
||||
}
|
||||
|
||||
client.sendRequest("PUT", "/api/v1/queue/empty",
|
||||
Collections.singletonList(HeaderUtils.getTimestampHeader()), Optional.empty());
|
||||
}
|
||||
},
|
||||
throwable -> {
|
||||
// `ConflictingMessageConsumerException` is handled before processing messages
|
||||
if (throwable instanceof ConflictingMessageConsumerException) {
|
||||
return;
|
||||
}
|
||||
|
||||
measureSendMessageErrors(throwable);
|
||||
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
}
|
||||
));
|
||||
queueDrainStartNanoTime.set(System.nanoTime());
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
@@ -262,22 +171,16 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
|
||||
client.close(1000, "OK");
|
||||
|
||||
messagesManager.mayHaveMessages(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice)
|
||||
.thenAccept(mayHaveMessages -> {
|
||||
if (mayHaveMessages) {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
}
|
||||
});
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount,
|
||||
authenticatedDevice,
|
||||
CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY);
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessage(final Envelope message) {
|
||||
if (message.getStory() && !client.shouldDeliverStories()) {
|
||||
return messageStream.acknowledgeMessage(message);
|
||||
}
|
||||
|
||||
final Optional<byte[]> body = Optional.of(serializeMessage(message));
|
||||
private CompletableFuture<Void> sendMessage(final Envelope message, StoredMessageInfo storedMessageInfo) {
|
||||
// clear ephemeral field from the envelope
|
||||
final Optional<byte[]> body = Optional.ofNullable(message.toBuilder().clearEphemeral().build().toByteArray());
|
||||
|
||||
sendMessageCounter.increment();
|
||||
sentMessageCounter.increment();
|
||||
@@ -305,39 +208,40 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
final CompletableFuture<Void> result;
|
||||
if (isSuccessResponse(response)) {
|
||||
|
||||
result = messageStream.acknowledgeMessage(message);
|
||||
result = messagesManager.delete(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice,
|
||||
storedMessageInfo.guid(), storedMessageInfo.serverTimestamp())
|
||||
.thenApply(ignored -> null);
|
||||
|
||||
if (message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
sendDeliveryReceiptFor(message);
|
||||
}
|
||||
} else {
|
||||
Tags tags = platformTag.and(STATUS_CODE_TAG, String.valueOf(response.getStatus()));
|
||||
final List<Tag> tags = new ArrayList<>(
|
||||
List.of(
|
||||
Tag.of(STATUS_CODE_TAG, String.valueOf(response.getStatus())),
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent())
|
||||
));
|
||||
|
||||
// TODO Remove this once we've identified the cause of message rejections from desktop clients
|
||||
if (StringUtils.isNotBlank(response.getMessage())) {
|
||||
tags = tags.and(Tag.of(STATUS_MESSAGE_TAG, response.getMessage()));
|
||||
// TODO Remove this once we've identified the cause of message rejections from desktop clients
|
||||
if (StringUtils.isNotBlank(response.getMessage())) {
|
||||
tags.add(Tag.of(STATUS_MESSAGE_TAG, response.getMessage()));
|
||||
}
|
||||
|
||||
Metrics.counter(NON_SUCCESS_RESPONSE_COUNTER_NAME, tags).increment();
|
||||
|
||||
result = CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
Metrics.counter(NON_SUCCESS_RESPONSE_COUNTER_NAME, tags).increment();
|
||||
|
||||
result = CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
return result;
|
||||
})
|
||||
.thenRun(() -> sample.stop(Timer.builder(SEND_MESSAGE_DURATION_TIMER_NAME)
|
||||
.publishPercentileHistogram(true)
|
||||
.minimumExpectedValue(Duration.ofMillis(100))
|
||||
.maximumExpectedValue(Duration.ofDays(1))
|
||||
.tags(platformTag)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent())))
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] serializeMessage(final Envelope message) {
|
||||
return message.toBuilder().clearEphemeral().build().toByteArray();
|
||||
}
|
||||
|
||||
private void sendDeliveryReceiptFor(Envelope message) {
|
||||
if (!message.hasSourceServiceId()) {
|
||||
return;
|
||||
@@ -347,17 +251,110 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
receiptSender.sendReceipt(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
authenticatedDevice.getId(), AciServiceIdentifier.valueOf(message.getSourceServiceId()),
|
||||
message.getClientTimestamp());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("Could not parse UUID: {}", message.getSourceServiceId());
|
||||
} catch (final Exception e) {
|
||||
} catch (Exception e) {
|
||||
logger.warn("Failed to send receipt", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isSuccessResponse(final WebSocketResponseMessage response) {
|
||||
private boolean isSuccessResponse(WebSocketResponseMessage response) {
|
||||
return response != null && response.getStatus() >= 200 && response.getStatus() < 300;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void processStoredMessages() {
|
||||
if (processStoredMessagesSemaphore.tryAcquire()) {
|
||||
final StoredMessageState state = storedMessageState.getAndSet(StoredMessageState.EMPTY);
|
||||
final boolean cachedMessagesOnly = state != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
sendMessages(cachedMessagesOnly)
|
||||
// Update our state with the outcome, send the empty queue message if we need to, and release the semaphore
|
||||
.whenComplete((ignored, cause) -> {
|
||||
try {
|
||||
if (cause != null) {
|
||||
// We failed, if the state is currently EMPTY, set it to what it was before we tried
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, state);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cleared the queue! Send a queue empty message if we need to
|
||||
if (sentInitialQueueEmptyMessage.compareAndSet(false, true)) {
|
||||
final Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(client.getUserAgent()));
|
||||
final long drainDurationNanos = System.nanoTime() - queueDrainStartNanoTime.get();
|
||||
|
||||
Metrics.summary(INITIAL_QUEUE_LENGTH_DISTRIBUTION_NAME, tags).record(sentMessageCounter.sum());
|
||||
Metrics.timer(INITIAL_QUEUE_DRAIN_TIMER_NAME, tags).record(drainDurationNanos, TimeUnit.NANOSECONDS);
|
||||
|
||||
if (drainDurationNanos > SLOW_DRAIN_THRESHOLD) {
|
||||
Metrics.counter(SLOW_QUEUE_DRAIN_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
|
||||
client.sendRequest("PUT", "/api/v1/queue/empty",
|
||||
Collections.singletonList(HeaderUtils.getTimestampHeader()), Optional.empty());
|
||||
}
|
||||
} finally {
|
||||
processStoredMessagesSemaphore.release();
|
||||
}
|
||||
})
|
||||
// Potentially kick off more work, must happen after we release the semaphore
|
||||
.whenComplete((ignored, cause) -> {
|
||||
if (cause != null) {
|
||||
if (!client.isOpen()) {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
return;
|
||||
}
|
||||
|
||||
client.close(1011, "Failed to retrieve messages");
|
||||
return;
|
||||
}
|
||||
|
||||
// Success, but check if more messages came in while we were processing
|
||||
if (storedMessageState.get() != StoredMessageState.EMPTY) {
|
||||
processStoredMessages();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessages(final boolean cachedMessagesOnly) {
|
||||
final CompletableFuture<Void> queueCleared = new CompletableFuture<>();
|
||||
|
||||
final Publisher<Envelope> messages =
|
||||
messagesManager.getMessagesForDeviceReactive(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice, cachedMessagesOnly);
|
||||
|
||||
final AtomicBoolean hasSentFirstMessage = new AtomicBoolean();
|
||||
|
||||
final Disposable subscription = Flux.from(messages)
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
.doOnNext(envelope -> {
|
||||
if (hasSentFirstMessage.compareAndSet(false, true)) {
|
||||
messageDeliveryLoopMonitor.recordDeliveryAttempt(authenticatedAccount.getIdentifier(IdentityType.ACI),
|
||||
authenticatedDevice.getId(),
|
||||
UUID.fromString(envelope.getServerGuid()),
|
||||
client.getUserAgent(),
|
||||
"websocket");
|
||||
}
|
||||
})
|
||||
.flatMapSequential(envelope -> Mono.fromFuture(() -> sendMessage(envelope))
|
||||
.retryWhen(Retry.backoff(4, Duration.ofSeconds(1)).filter(throwable -> !isConnectionClosedException(throwable))),
|
||||
MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
.doOnError(this::measureSendMessageErrors)
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
// no additional consumer of values - it is Flux<Void> by now
|
||||
null,
|
||||
// this first error will terminate the stream, but we may get multiple errors from in-flight messages
|
||||
queueCleared::completeExceptionally,
|
||||
// completion
|
||||
() -> queueCleared.complete(null)
|
||||
);
|
||||
|
||||
messageSubscription.set(subscription);
|
||||
return queueCleared;
|
||||
}
|
||||
|
||||
private void measureSendMessageErrors(final Throwable e) {
|
||||
final String errorType;
|
||||
|
||||
@@ -370,22 +367,76 @@ public class WebSocketConnection implements DisconnectionRequestListener {
|
||||
errorType = "other";
|
||||
}
|
||||
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER,
|
||||
platformTag.and(ERROR_TYPE_TAG, errorType, EXCEPTION_TYPE_TAG, e.getClass().getSimpleName()))
|
||||
Metrics.counter(SEND_MESSAGE_ERROR_COUNTER, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
Tag.of(ERROR_TYPE_TAG, errorType),
|
||||
Tag.of(EXCEPTION_TYPE_TAG, e.getClass().getSimpleName())))
|
||||
.increment();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static boolean isConnectionClosedException(final Throwable throwable) {
|
||||
private static boolean isConnectionClosedException(final Throwable throwable) {
|
||||
return throwable instanceof java.nio.channels.ClosedChannelException ||
|
||||
throwable == WebSocketResourceProvider.CONNECTION_CLOSED_EXCEPTION ||
|
||||
throwable instanceof org.eclipse.jetty.io.EofException ||
|
||||
(throwable instanceof StaticException staticException && "Closed".equals(staticException.getMessage()));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMessage(Envelope envelope) {
|
||||
final UUID messageGuid = UUID.fromString(envelope.getServerGuid());
|
||||
|
||||
if (envelope.getStory() && !client.shouldDeliverStories()) {
|
||||
messagesManager.delete(authenticatedAccount.getIdentifier(IdentityType.ACI), authenticatedDevice, messageGuid, envelope.getServerTimestamp());
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
} else {
|
||||
return sendMessage(envelope, new StoredMessageInfo(messageGuid, envelope.getServerTimestamp()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleNewMessageAvailable() {
|
||||
Metrics.counter(MESSAGE_AVAILABLE_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.compareAndSet(StoredMessageState.EMPTY, StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessagesPersisted() {
|
||||
Metrics.counter(MESSAGES_PERSISTED_COUNTER_NAME,
|
||||
PRESENCE_MANAGER_TAG, "pubsub")
|
||||
.increment();
|
||||
|
||||
storedMessageState.set(StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE);
|
||||
|
||||
processStoredMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleConflictingMessageConsumer() {
|
||||
closeConnection(4409, "Connected elsewhere");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleDisconnectionRequest() {
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, platformTag.and(CONNECTED_ELSEWHERE_TAG, "false")).increment();
|
||||
client.close(4401, "Reauthentication required");
|
||||
closeConnection(4401, "Reauthentication required");
|
||||
}
|
||||
|
||||
private void closeConnection(final int code, final String message) {
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(client.getUserAgent()),
|
||||
// TODO We should probably just use the status code directly
|
||||
Tag.of("connectedElsewhere", String.valueOf(code == 4409)));
|
||||
|
||||
Metrics.counter(DISPLACEMENT_COUNTER_NAME, tags).increment();
|
||||
|
||||
client.close(code, message);
|
||||
}
|
||||
|
||||
private record StoredMessageInfo(UUID guid, long serverTimestamp) {
|
||||
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -231,8 +231,7 @@ record CommandDependencies(
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getEcSignedPreKeys().getTableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName()),
|
||||
experimentEnrollmentManager);
|
||||
configuration.getDynamoDbTables().getKemLastResortKeys().getTableName()));
|
||||
MessagesDynamoDb messagesDynamoDb = new MessagesDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
configuration.getDynamoDbTables().getMessages().getTableName(),
|
||||
configuration.getDynamoDbTables().getMessages().getExpiration(),
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ public class BufferingInterceptorIntegrationTest {
|
||||
final TestController testController = new TestController();
|
||||
environment.jersey().register(testController);
|
||||
environment.jersey().register(new BufferingInterceptor());
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("virtual-thread-"));
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("virtual-thread-", 10));
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,17 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.api.StatusCode;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -34,6 +41,7 @@ import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.websocket.messages.WebSocketResponseMessage;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
+8
@@ -371,8 +371,16 @@ class KeysControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get();
|
||||
|
||||
final String expectedRatelimitKey = String.format("%s.%s__%s.%s.%s",
|
||||
AuthHelper.VALID_UUID,
|
||||
AuthHelper.VALID_DEVICE.getId(),
|
||||
EXISTS_PNI,
|
||||
"*",
|
||||
"*");
|
||||
|
||||
assertThat(result.getStatus()).isEqualTo(429);
|
||||
assertThat(result.getHeaderString("Retry-After")).isEqualTo(String.valueOf(retryAfter.toSeconds()));
|
||||
verify(rateLimiter).validate(expectedRatelimitKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-2
@@ -109,8 +109,7 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()));
|
||||
|
||||
final ClientPublicKeys clientPublicKeys = new ClientPublicKeys(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.CLIENT_PUBLIC_KEYS.tableName());
|
||||
|
||||
+1
-3
@@ -37,7 +37,6 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
@@ -99,8 +98,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()));
|
||||
|
||||
final ClientPublicKeys clientPublicKeys = new ClientPublicKeys(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.CLIENT_PUBLIC_KEYS.tableName());
|
||||
|
||||
+1
-3
@@ -39,7 +39,6 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.mockito.Mockito;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
@@ -112,8 +111,7 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()));
|
||||
|
||||
accounts = Mockito.spy(new Accounts(
|
||||
Clock.systemUTC(),
|
||||
|
||||
+1
-3
@@ -37,7 +37,6 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceInfo;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisServerExtension;
|
||||
@@ -107,8 +106,7 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient,
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()),
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
DynamoDbExtensionSchema.Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()));
|
||||
|
||||
final ClientPublicKeys clientPublicKeys = new ClientPublicKeys(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
DynamoDbExtensionSchema.Tables.CLIENT_PUBLIC_KEYS.tableName());
|
||||
|
||||
+19
-52
@@ -8,9 +8,6 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -20,12 +17,10 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
@@ -34,7 +29,6 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
class KeysManagerTest {
|
||||
|
||||
private KeysManager keysManager;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private SingleUseKEMPreKeyStore singleUseKEMPreKeyStore;
|
||||
private PagedSingleUseKEMPreKeyStore pagedSingleUseKEMPreKeyStore;
|
||||
@@ -56,7 +50,6 @@ class KeysManagerTest {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient();
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
singleUseKEMPreKeyStore = new SingleUseKEMPreKeyStore(dynamoDbAsyncClient, Tables.PQ_KEYS.tableName());
|
||||
pagedSingleUseKEMPreKeyStore = new PagedSingleUseKEMPreKeyStore(dynamoDbAsyncClient,
|
||||
S3_EXTENSION.getS3Client(),
|
||||
@@ -68,8 +61,7 @@ class KeysManagerTest {
|
||||
singleUseKEMPreKeyStore,
|
||||
pagedSingleUseKEMPreKeyStore,
|
||||
new RepeatedUseECSignedPreKeyStore(dynamoDbAsyncClient, Tables.REPEATED_USE_EC_SIGNED_PRE_KEYS.tableName()),
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()),
|
||||
experimentEnrollmentManager);
|
||||
new RepeatedUseKEMSignedPreKeyStore(dynamoDbAsyncClient, Tables.REPEATED_USE_KEM_SIGNED_PRE_KEYS.tableName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -85,55 +77,38 @@ class KeysManagerTest {
|
||||
"Repeatedly storing same key should have no effect");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void storeKemOneTimePreKeysClearsOld(boolean inPagedExperiment) {
|
||||
@Test
|
||||
void storeKemOneTimePreKeysClearsOld() {
|
||||
final List<KEMSignedPreKey> oldPreKeys = List.of(generateTestKEMSignedPreKey(1));
|
||||
|
||||
// Leave a key in the 'other' key store
|
||||
(inPagedExperiment
|
||||
? singleUseKEMPreKeyStore.store(ACCOUNT_UUID, DEVICE_ID, oldPreKeys)
|
||||
: pagedSingleUseKEMPreKeyStore.store(ACCOUNT_UUID, DEVICE_ID, oldPreKeys))
|
||||
.join();
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(ACCOUNT_UUID, KeysManager.PAGED_KEYS_EXPERIMENT_NAME))
|
||||
.thenReturn(inPagedExperiment);
|
||||
|
||||
// Leave a key in the 'old' key store
|
||||
singleUseKEMPreKeyStore.store(ACCOUNT_UUID, DEVICE_ID, oldPreKeys).join();
|
||||
|
||||
final List<KEMSignedPreKey> newPreKeys = List.of(generateTestKEMSignedPreKey(2));
|
||||
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, newPreKeys).join();
|
||||
|
||||
final int expectedPagedKeyCount = inPagedExperiment ? 1 : 0;
|
||||
final int expectedUnpagedKeyCount = 1 - expectedPagedKeyCount;
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(expectedPagedKeyCount, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(expectedUnpagedKeyCount, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(1, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(0, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
|
||||
final KEMSignedPreKey key = keysManager.takePQ(ACCOUNT_UUID, DEVICE_ID).join().orElseThrow();
|
||||
assertEquals(2, key.keyId());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void storeKemOneTimePreKeys(boolean inPagedExperiment) {
|
||||
@Test
|
||||
void storeKemOneTimePreKeys() {
|
||||
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join(),
|
||||
"Initial pre-key count for an account should be zero");
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(ACCOUNT_UUID, KeysManager.PAGED_KEYS_EXPERIMENT_NAME))
|
||||
.thenReturn(inPagedExperiment);
|
||||
|
||||
final int expectedPagedKeyCount = inPagedExperiment ? 1 : 0;
|
||||
final int expectedUnpagedKeyCount = 1 - expectedPagedKeyCount;
|
||||
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestKEMSignedPreKey(1))).join();
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(1, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(0, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
|
||||
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestKEMSignedPreKey(1))).join();
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(expectedPagedKeyCount, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(expectedUnpagedKeyCount, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
|
||||
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestKEMSignedPreKey(1))).join();
|
||||
assertEquals(1, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(expectedPagedKeyCount, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(expectedUnpagedKeyCount, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(1, pagedSingleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
assertEquals(0, singleUseKEMPreKeyStore.getCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
}
|
||||
|
||||
|
||||
@@ -196,14 +171,10 @@ class KeysManagerTest {
|
||||
assertEquals(0, keysManager.getPqCount(ACCOUNT_UUID, DEVICE_ID).join());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testDeleteSingleUsePreKeysByAccount(final boolean inPagedExperiment) {
|
||||
@Test
|
||||
void testDeleteSingleUsePreKeysByAccount() {
|
||||
int keyId = 1;
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(ACCOUNT_UUID, KeysManager.PAGED_KEYS_EXPERIMENT_NAME))
|
||||
.thenReturn(inPagedExperiment);
|
||||
|
||||
for (byte deviceId : new byte[] {DEVICE_ID, DEVICE_ID + 1}) {
|
||||
keysManager.storeEcOneTimePreKeys(ACCOUNT_UUID, deviceId, List.of(generateTestPreKey(keyId++))).join();
|
||||
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, deviceId, List.of(generateTestKEMSignedPreKey(keyId++))).join();
|
||||
@@ -228,14 +199,10 @@ class KeysManagerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testDeleteSingleUsePreKeysByAccountAndDevice(final boolean inPagedExperiment) {
|
||||
@Test
|
||||
void testDeleteSingleUsePreKeysByAccountAndDevice() {
|
||||
int keyId = 1;
|
||||
|
||||
when(experimentEnrollmentManager.isEnrolled(ACCOUNT_UUID, KeysManager.PAGED_KEYS_EXPERIMENT_NAME))
|
||||
.thenReturn(inPagedExperiment);
|
||||
|
||||
for (byte deviceId : new byte[] {DEVICE_ID, DEVICE_ID + 1}) {
|
||||
keysManager.storeEcOneTimePreKeys(ACCOUNT_UUID, deviceId, List.of(generateTestPreKey(keyId++))).join();
|
||||
keysManager.storeKemOneTimePreKeys(ACCOUNT_UUID, deviceId, List.of(generateTestKEMSignedPreKey(keyId++))).join();
|
||||
|
||||
+146
-25
@@ -1,7 +1,9 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
@@ -9,21 +11,32 @@ import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@@ -34,50 +47,139 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.ofEpochSecond(500), ZoneId.of("UTC"));
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
new Database[]{FOUNDATION_DB_EXTENSION.getDatabase()},
|
||||
Executors.newVirtualThreadPerTaskExecutor());
|
||||
Executors.newVirtualThreadPerTaskExecutor(),
|
||||
CLOCK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insert() {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void insert(final long presenceUpdatedBeforeSeconds, final boolean ephemeral, final boolean expectMessagesInserted,
|
||||
final boolean expectVersionstampUpdated) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
deviceIds.forEach(deviceId -> writePresenceKey(aci, deviceId, 1, presenceUpdatedBeforeSeconds));
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage()));
|
||||
final Versionstamp versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Optional<Versionstamp> versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
|
||||
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), deviceId -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
if (expectMessagesInserted) {
|
||||
assertTrue(versionstamp.isPresent());
|
||||
final Map<Byte, MessageProtos.Envelope> storedMessagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), deviceId -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(getMessageByVersionstamp(aci, deviceId, versionstamp.get()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
|
||||
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
|
||||
assertEquals(versionstamp, getLastMessageVersionstamp(aci),
|
||||
"last message versionstamp should be the versionstamp of the last insert transaction");
|
||||
assertEquals(messagesByDeviceId, storedMessagesByDeviceId);
|
||||
} else {
|
||||
assertTrue(versionstamp.isEmpty());
|
||||
}
|
||||
|
||||
if (expectVersionstampUpdated) {
|
||||
assertEquals(versionstamp, getMessagesAvailableWatch(aci),
|
||||
"messages available versionstamp should be the versionstamp of the last insert transaction");
|
||||
} else {
|
||||
assertTrue(getMessagesAvailableWatch(aci).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> insert() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Non-ephemeral messages with all devices online",
|
||||
10L, false, true, true),
|
||||
Arguments.argumentSet(
|
||||
"Ephemeral messages with presence updated exactly at the second before which the device would be considered offline",
|
||||
300L, true, true, true),
|
||||
Arguments.argumentSet("Non-ephemeral messages for with all devices offline",
|
||||
310L, false, true, false),
|
||||
Arguments.argumentSet("Ephemeral messages with all devices offline",
|
||||
310L, true, false, false)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionstampCorrectlyUpdatedOnMultipleInserts() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
final Versionstamp secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
assertEquals(secondMessageVersionstamp, getLastMessageVersionstamp(aci));
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
final Optional<Versionstamp> secondMessageVersionstamp = foundationDbMessageStore.insert(aci,
|
||||
Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
assertEquals(secondMessageVersionstamp, getMessagesAvailableWatch(aci));
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void insertOnlyOneDevicePresent(final boolean ephemeral) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Byte> deviceIds = IntStream.range(Device.PRIMARY_ID, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
// Only 1 device has a recent presence, the others do not have presence keys present.
|
||||
writePresenceKey(aci, Device.PRIMARY_ID, 1, 10L);
|
||||
final Map<Byte, MessageProtos.Envelope> messagesByDeviceId = deviceIds.stream()
|
||||
.collect(Collectors.toMap(Function.identity(), _ -> generateRandomMessage(ephemeral)));
|
||||
final Optional<Versionstamp> versionstamp = foundationDbMessageStore.insert(aci, messagesByDeviceId).join();
|
||||
assertNotNull(versionstamp);
|
||||
assertTrue(versionstamp.isPresent(),
|
||||
"versionstamp should be present since at least one message should be inserted");
|
||||
|
||||
assertArrayEquals(
|
||||
messagesByDeviceId.get(Device.PRIMARY_ID).toByteArray(),
|
||||
getMessageByVersionstamp(aci, Device.PRIMARY_ID, versionstamp.get()),
|
||||
"Message for primary should always be stored since it has a recently updated presence");
|
||||
|
||||
if (ephemeral) {
|
||||
assertTrue(IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID + 6)
|
||||
.mapToObj(deviceId -> getMessageByVersionstamp(aci, (byte) deviceId, versionstamp.get()))
|
||||
.allMatch(Objects::isNull), "Ephemeral messages for non-present devices must not be stored");
|
||||
} else {
|
||||
IntStream.range(Device.PRIMARY_ID + 1, Device.PRIMARY_ID)
|
||||
.forEach(deviceId -> {
|
||||
final byte[] messageBytes = getMessageByVersionstamp(aci, (byte) deviceId, versionstamp.get());
|
||||
assertEquals(messagesByDeviceId.get((byte) deviceId).toByteArray(), messageBytes,
|
||||
"Non-ephemeral messages must always be stored");
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isClientPresent(final byte[] presenceValueBytes, final boolean expectPresent) {
|
||||
assertEquals(expectPresent, foundationDbMessageStore.isClientPresent(presenceValueBytes));
|
||||
}
|
||||
|
||||
static Stream<Arguments> isClientPresent() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Presence value doesn't exist",
|
||||
null, false),
|
||||
Arguments.argumentSet("Presence updated recently",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(5))), true),
|
||||
Arguments.argumentSet("Presence updated same second as current time",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(0))), true),
|
||||
Arguments.argumentSet("Presence updated exactly at the second before which it would have been considered offline",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(300))), true),
|
||||
Arguments.argumentSet("Presence expired",
|
||||
Conversions.longToByteArray(constructPresenceValue(42, getEpochSecondsBeforeClock(400))), false)
|
||||
);
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral) {
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setContent(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.setEphemeral(ephemeral)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -90,12 +192,31 @@ class FoundationDbMessageStoreTest {
|
||||
}).join();
|
||||
}
|
||||
|
||||
private Versionstamp getLastMessageVersionstamp(final AciServiceIdentifier aci) {
|
||||
private Optional<Versionstamp> getMessagesAvailableWatch(final AciServiceIdentifier aci) {
|
||||
return FOUNDATION_DB_EXTENSION.getDatabase()
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getLastMessageKey(aci))
|
||||
.thenApply(Tuple::fromBytes)
|
||||
.thenApply(t -> t.getVersionstamp(0)))
|
||||
.read(transaction -> transaction.get(foundationDbMessageStore.getMessagesAvailableWatchKey(aci))
|
||||
.thenApply(value -> value == null ? null : Tuple.fromBytes(value).getVersionstamp(0))
|
||||
.thenApply(Optional::ofNullable))
|
||||
.join();
|
||||
}
|
||||
|
||||
private void writePresenceKey(final AciServiceIdentifier aci, final byte deviceId, final int serverId,
|
||||
final long secondsBeforeCurrentTime) {
|
||||
FOUNDATION_DB_EXTENSION.getDatabase().run(transaction -> {
|
||||
final byte[] presenceKey = foundationDbMessageStore.getPresenceKey(aci, deviceId);
|
||||
final long presenceUpdateEpochSeconds = getEpochSecondsBeforeClock(secondsBeforeCurrentTime);
|
||||
final long presenceValue = constructPresenceValue(serverId, presenceUpdateEpochSeconds);
|
||||
transaction.set(presenceKey, Conversions.longToByteArray(presenceValue));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private static long getEpochSecondsBeforeClock(final long secondsBefore) {
|
||||
return CLOCK.instant().minusSeconds(secondsBefore).getEpochSecond();
|
||||
}
|
||||
|
||||
private static long constructPresenceValue(final int serverId, final long presenceUpdateEpochSeconds) {
|
||||
return (long) (serverId & 0x0ffff) << 48 | (presenceUpdateEpochSeconds & 0x0000ffffffffffffL);
|
||||
}
|
||||
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BoundedVirtualThreadFactoryTest {
|
||||
|
||||
private final static int MAX_THREADS = 10;
|
||||
|
||||
private BoundedVirtualThreadFactory factory;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
factory = new BoundedVirtualThreadFactory("test", MAX_THREADS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseWhenTaskThrows() throws InterruptedException {
|
||||
final UncaughtExceptionHolder uncaughtExceptionHolder = new UncaughtExceptionHolder();
|
||||
final Thread t = submit(() -> {
|
||||
throw new IllegalArgumentException("test");
|
||||
}, uncaughtExceptionHolder);
|
||||
assertThat(t).isNotNull();
|
||||
t.join(Duration.ofSeconds(1));
|
||||
assertThat(uncaughtExceptionHolder.exception).isNotNull().isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
submitUntilRejected();
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseWhenRejected() throws InterruptedException {
|
||||
submitUntilRejected();
|
||||
submitUntilRejected();
|
||||
}
|
||||
|
||||
@Test
|
||||
void executorServiceRejectsAtLimit() throws InterruptedException {
|
||||
try (final ExecutorService executor = Executors.newThreadPerTaskExecutor(factory)) {
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
for (int i = 0; i < MAX_THREADS; i++) {
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
latch.await();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
assertThatExceptionOfType(RejectedExecutionException.class).isThrownBy(() -> executor.submit(Util.NOOP));
|
||||
latch.countDown();
|
||||
|
||||
executor.shutdown();
|
||||
assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stressTest() throws InterruptedException {
|
||||
for (int iteration = 0; iteration < 50; iteration++) {
|
||||
final CountDownLatch latch = new CountDownLatch(MAX_THREADS);
|
||||
|
||||
// submit a task that submits a task maxThreads/2 times
|
||||
final Thread[] threads = new Thread[MAX_THREADS];
|
||||
for (int i = 0; i < MAX_THREADS; i+=2) {
|
||||
int outerThreadIndex = i;
|
||||
int innerThreadIndex = i + 1;
|
||||
|
||||
threads[outerThreadIndex] = submit(() -> {
|
||||
latch.countDown();
|
||||
threads[innerThreadIndex] = submit(latch::countDown);
|
||||
});
|
||||
}
|
||||
latch.await();
|
||||
|
||||
// All threads must be created at this point, wait for them all to complete
|
||||
for (Thread thread : threads) {
|
||||
assertThat(thread).isNotNull();
|
||||
thread.join();
|
||||
}
|
||||
|
||||
assertThat(factory.getRunningThreads()).isEqualTo(0);
|
||||
}
|
||||
|
||||
submitUntilRejected();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify we can submit up to the concurrency limit (and no more)
|
||||
*/
|
||||
private void submitUntilRejected() throws InterruptedException {
|
||||
final CountDownLatch finish = new CountDownLatch(1);
|
||||
final List<Thread> threads = IntStream.range(0, MAX_THREADS).mapToObj(_ -> submit(() -> {
|
||||
try {
|
||||
finish.await();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})).toList();
|
||||
|
||||
assertThat(submit(Util.NOOP)).isNull();
|
||||
|
||||
finish.countDown();
|
||||
|
||||
for (Thread thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
assertThat(factory.getRunningThreads()).isEqualTo(0);
|
||||
}
|
||||
|
||||
private Thread submit(final Runnable runnable) {
|
||||
return submit(runnable, (t, e) ->
|
||||
fail("Uncaught exception on thread {} : {}", t, e));
|
||||
}
|
||||
|
||||
private Thread submit(final Runnable runnable, final Thread.UncaughtExceptionHandler handler) {
|
||||
final Thread thread = factory.newThread(runnable);
|
||||
if (thread == null) {
|
||||
return null;
|
||||
}
|
||||
if (handler != null) {
|
||||
thread.setUncaughtExceptionHandler(handler);
|
||||
}
|
||||
thread.start();
|
||||
return thread;
|
||||
}
|
||||
|
||||
private static class UncaughtExceptionHolder implements Thread.UncaughtExceptionHandler {
|
||||
Throwable exception = null;
|
||||
|
||||
@Override
|
||||
public void uncaughtException(final Thread t, final Throwable e) {
|
||||
exception = e;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+59
-3
@@ -13,20 +13,37 @@ import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.Principal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class VirtualExecutorServiceProviderTest {
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
private final TestController testController = new TestController();
|
||||
private final ResourceExtension resources = ResourceExtension.builder()
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addProvider(new VirtualExecutorServiceProvider("virtual-thread-"))
|
||||
.addResource(new TestController())
|
||||
.addProvider(new VirtualExecutorServiceProvider( "virtual-thread-", 2))
|
||||
.addResource(testController)
|
||||
.build();
|
||||
|
||||
@AfterEach
|
||||
void setUp() {
|
||||
testController.release();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testManagedAsyncThread() {
|
||||
final Response response = resources.getJerseyTest()
|
||||
@@ -37,6 +54,22 @@ class VirtualExecutorServiceProviderTest {
|
||||
assertThat(threadName).startsWith("virtual-thread-");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConcurrencyLimit() throws InterruptedException, TimeoutException {
|
||||
final BlockingQueue<Response> responses = new LinkedBlockingQueue<>();
|
||||
final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
executor.submit(() -> responses.offer(resources.getJerseyTest().target("/v1/test/await").request().get()));
|
||||
}
|
||||
final Response rejectedResponse = responses.poll(10, TimeUnit.SECONDS);
|
||||
assertThat(rejectedResponse).isNotNull().extracting(Response::getStatus).isEqualTo(500);
|
||||
|
||||
assertThat(responses.isEmpty()).isTrue();
|
||||
assertThat(testController.release()).isEqualTo(2);
|
||||
assertThat(responses.poll(1, TimeUnit.SECONDS)).isNotNull().extracting(Response::getStatus).isEqualTo(200);
|
||||
assertThat(responses.poll(1, TimeUnit.SECONDS)).isNotNull().extracting(Response::getStatus).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnmanagedThread() {
|
||||
final Response response = resources.getJerseyTest()
|
||||
@@ -49,6 +82,7 @@ class VirtualExecutorServiceProviderTest {
|
||||
|
||||
@Path("/v1/test")
|
||||
public static class TestController {
|
||||
private List<CountDownLatch> latches = new ArrayList<>();
|
||||
|
||||
@GET
|
||||
@Path("/managed-async")
|
||||
@@ -57,12 +91,34 @@ class VirtualExecutorServiceProviderTest {
|
||||
return Response.ok().entity(Thread.currentThread().getName()).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/await")
|
||||
@ManagedAsync
|
||||
public Response await() throws InterruptedException {
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
synchronized (this) {
|
||||
latches.add(latch);
|
||||
}
|
||||
latch.await();
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/unmanaged")
|
||||
public Response unmanaged() {
|
||||
return Response.ok().entity(Thread.currentThread().getName()).build();
|
||||
}
|
||||
|
||||
synchronized int release() {
|
||||
final Iterator<CountDownLatch> iterator = latches.iterator();
|
||||
int count;
|
||||
for (count = 0; iterator.hasNext(); count++) {
|
||||
iterator.next().countDown();
|
||||
iterator.remove();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class TestPrincipal implements Principal {
|
||||
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.OpenWebSocketCounter;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.websocket.WebSocketClient;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
class AuthenticatedConnectListenerTest {
|
||||
|
||||
private AccountsManager accountsManager;
|
||||
private DisconnectionRequestManager disconnectionRequestManager;
|
||||
|
||||
private WebSocketConnection authenticatedWebSocketConnection;
|
||||
private AuthenticatedConnectListener authenticatedConnectListener;
|
||||
|
||||
private Account authenticatedAccount;
|
||||
private WebSocketClient webSocketClient;
|
||||
private WebSocketSessionContext webSocketSessionContext;
|
||||
|
||||
private static final UUID ACCOUNT_IDENTIFIER = UUID.randomUUID();
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUpBeforeEach() {
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
disconnectionRequestManager = mock(DisconnectionRequestManager.class);
|
||||
|
||||
authenticatedWebSocketConnection = mock(WebSocketConnection.class);
|
||||
|
||||
authenticatedConnectListener = new AuthenticatedConnectListener(accountsManager,
|
||||
disconnectionRequestManager,
|
||||
(_, _, _) -> authenticatedWebSocketConnection,
|
||||
_ -> mock(OpenWebSocketCounter.class));
|
||||
|
||||
final Device device = mock(Device.class);
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
|
||||
authenticatedAccount = mock(Account.class);
|
||||
when(authenticatedAccount.getIdentifier(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTIFIER);
|
||||
when(authenticatedAccount.getDevice(DEVICE_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
webSocketClient = mock(WebSocketClient.class);
|
||||
|
||||
webSocketSessionContext = mock(WebSocketSessionContext.class);
|
||||
when(webSocketSessionContext.getClient()).thenReturn(webSocketClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectAuthenticated() {
|
||||
when(webSocketSessionContext.getAuthenticated()).thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
when(webSocketSessionContext.getAuthenticated(AuthenticatedDevice.class))
|
||||
.thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER)).thenReturn(Optional.of(authenticatedAccount));
|
||||
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(disconnectionRequestManager).addListener(ACCOUNT_IDENTIFIER, DEVICE_ID, authenticatedWebSocketConnection);
|
||||
verify(webSocketSessionContext).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectAuthenticatedAccountNotFound() {
|
||||
when(webSocketSessionContext.getAuthenticated()).thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
when(webSocketSessionContext.getAuthenticated(AuthenticatedDevice.class))
|
||||
.thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER)).thenReturn(Optional.empty());
|
||||
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(webSocketClient).close(eq(1011), anyString());
|
||||
|
||||
verify(disconnectionRequestManager, never()).addListener(any(), anyByte(), any());
|
||||
verify(webSocketSessionContext, never()).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection, never()).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectAuthenticatedStartException() {
|
||||
when(webSocketSessionContext.getAuthenticated()).thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
when(webSocketSessionContext.getAuthenticated(AuthenticatedDevice.class))
|
||||
.thenReturn(new AuthenticatedDevice(ACCOUNT_IDENTIFIER, DEVICE_ID, Instant.now()));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(ACCOUNT_IDENTIFIER)).thenReturn(Optional.of(authenticatedAccount));
|
||||
doThrow(new RuntimeException()).when(authenticatedWebSocketConnection).start();
|
||||
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(disconnectionRequestManager).addListener(ACCOUNT_IDENTIFIER, DEVICE_ID, authenticatedWebSocketConnection);
|
||||
verify(webSocketSessionContext).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection).start();
|
||||
|
||||
verify(webSocketClient).close(eq(1011), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWebSocketConnectUnauthenticated() {
|
||||
authenticatedConnectListener.onWebSocketConnect(webSocketSessionContext);
|
||||
|
||||
verify(disconnectionRequestManager, never()).addListener(any(), anyByte(), any());
|
||||
verify(webSocketSessionContext, never()).addWebsocketClosedListener(any());
|
||||
verify(authenticatedWebSocketConnection, never()).start();
|
||||
}
|
||||
}
|
||||
+32
-24
@@ -15,7 +15,6 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atMost;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -33,6 +32,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -42,6 +42,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
@@ -89,18 +90,16 @@ class WebSocketConnectionIntegrationTest {
|
||||
private Scheduler messageDeliveryScheduler;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private long serialTimestamp = System.currentTimeMillis();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
sharedExecutorService = Executors.newSingleThreadExecutor();
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(new DynamicConfiguration());
|
||||
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(),
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC());
|
||||
messagesDynamoDb = new MessagesDynamoDb(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
@@ -116,14 +115,10 @@ class WebSocketConnectionIntegrationTest {
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(UUID.randomUUID());
|
||||
when(device.getId()).thenReturn(Device.PRIMARY_ID);
|
||||
|
||||
redisMessageAvailabilityManager.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
redisMessageAvailabilityManager.stop();
|
||||
|
||||
sharedExecutorService.shutdown();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
sharedExecutorService.awaitTermination(2, TimeUnit.SECONDS);
|
||||
@@ -148,8 +143,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class)
|
||||
);
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
|
||||
final List<MessageProtos.Envelope> expectedMessages = new ArrayList<>(persistedMessageCount + cachedMessageCount);
|
||||
|
||||
@@ -177,21 +171,36 @@ class WebSocketConnectionIntegrationTest {
|
||||
}
|
||||
|
||||
final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class);
|
||||
final AtomicBoolean queueCleared = new AtomicBoolean(false);
|
||||
|
||||
when(successResponse.getStatus()).thenReturn(200);
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(successResponse));
|
||||
|
||||
webSocketConnection.start();
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), any())).thenAnswer(
|
||||
(Answer<CompletableFuture<WebSocketResponseMessage>>) invocation -> {
|
||||
synchronized (queueCleared) {
|
||||
queueCleared.set(true);
|
||||
queueCleared.notifyAll();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Optional<byte[]>> messageBodyCaptor =
|
||||
ArgumentCaptor.forClass(Optional.class);
|
||||
return CompletableFuture.completedFuture(successResponse);
|
||||
});
|
||||
|
||||
verify(webSocketClient, timeout(10_000))
|
||||
.sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty()));
|
||||
webSocketConnection.processStoredMessages();
|
||||
|
||||
verify(webSocketClient, times(persistedMessageCount + cachedMessageCount))
|
||||
.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
synchronized (queueCleared) {
|
||||
while (!queueCleared.get()) {
|
||||
queueCleared.wait();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(
|
||||
Optional.class);
|
||||
|
||||
verify(webSocketClient, times(persistedMessageCount + cachedMessageCount)).sendRequest(eq("PUT"),
|
||||
eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
verify(webSocketClient).sendRequest(eq("PUT"), eq("/api/v1/queue/empty"), anyList(), eq(Optional.empty()));
|
||||
|
||||
final List<MessageProtos.Envelope> sentMessages = new ArrayList<>();
|
||||
|
||||
@@ -223,8 +232,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
messageDeliveryScheduler,
|
||||
clientReleaseManager,
|
||||
mock(MessageDeliveryLoopMonitor.class),
|
||||
mock(ExperimentEnrollmentManager.class)
|
||||
);
|
||||
mock(ExperimentEnrollmentManager.class));
|
||||
|
||||
final int persistedMessageCount = 207;
|
||||
final int cachedMessageCount = 173;
|
||||
@@ -256,10 +264,10 @@ class WebSocketConnectionIntegrationTest {
|
||||
when(webSocketClient.sendRequest(eq("PUT"), eq("/api/v1/message"), anyList(), any())).thenReturn(
|
||||
CompletableFuture.failedFuture(new IOException("Connection closed")));
|
||||
|
||||
webSocketConnection.start();
|
||||
webSocketConnection.processStoredMessages();
|
||||
|
||||
//noinspection unchecked
|
||||
final ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(Optional.class);
|
||||
ArgumentCaptor<Optional<byte[]>> messageBodyCaptor = ArgumentCaptor.forClass(Optional.class);
|
||||
|
||||
verify(webSocketClient, atMost(persistedMessageCount + cachedMessageCount)).sendRequest(eq("PUT"),
|
||||
eq("/api/v1/message"), anyList(), messageBodyCaptor.capture());
|
||||
@@ -267,7 +275,7 @@ class WebSocketConnectionIntegrationTest {
|
||||
eq(Optional.empty()));
|
||||
|
||||
final List<MessageProtos.Envelope> sentMessages = messageBodyCaptor.getAllValues().stream()
|
||||
.map(Optional::orElseThrow)
|
||||
.map(Optional::get)
|
||||
.map(messageBytes -> {
|
||||
try {
|
||||
return Envelope.parseFrom(messageBytes);
|
||||
|
||||
+719
-423
File diff suppressed because it is too large.
Load diff
+1
-1
Submodule spam-filter updated: 6ef5efd1e1...bda357b6a4.
Reference in new issue
Block a user