mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:26:50 +00:00
Compare commits
90
Commits
v20261015.1.0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ec51c1200 | ||
|
|
d0ef28cbfd | ||
|
|
cb8a3fb7d6 | ||
|
|
7ec705e616 | ||
|
|
9dfbb454d1 | ||
|
|
5de899da4b | ||
|
|
cbfc2720d5 | ||
|
|
0100901667 | ||
|
|
b3db95c3ea | ||
|
|
a9f87693ba | ||
|
|
b06709b63b | ||
|
|
99278dcd1f | ||
|
|
2d6eb7951a | ||
|
|
7e26b7fe0a | ||
|
|
2f955582a4 | ||
|
|
31bb5ff621 | ||
|
|
c21ad7a3aa | ||
|
|
4a48066d87 | ||
|
|
a0cdb5d3b6 | ||
|
|
3f1b678095 | ||
|
|
ffb821e344 | ||
|
|
d9bf32dd9c | ||
|
|
2fe70c89fa | ||
|
|
9d6589110e | ||
|
|
e67272033b | ||
|
|
0e7afd9f90 | ||
|
|
cbbfc3966a | ||
|
|
59f5adc934 | ||
|
|
67ab444604 | ||
|
|
5e44fbd4e9 | ||
|
|
8abb61ebe6 | ||
|
|
50634ae07e | ||
|
|
8d426b788d | ||
|
|
a57dd64196 | ||
|
|
451bbf1da9 | ||
|
|
358fb8e58a | ||
|
|
1a36eff391 | ||
|
|
cc487aa2ac | ||
|
|
21be842303 | ||
|
|
7af5bd4d2e | ||
|
|
f8e22ae674 | ||
|
|
a4a5c1bb29 | ||
|
|
2220f750dd | ||
|
|
27980ed25d | ||
|
|
ce75147186 | ||
|
|
9049a63038 | ||
|
|
d083eb0939 | ||
|
|
129cb9e765 | ||
|
|
5ed6c58c6b | ||
|
|
ecd881a280 | ||
|
|
ca7a105f15 | ||
|
|
8e37334d2a | ||
|
|
0e4ac57482 | ||
|
|
7df37fd815 | ||
|
|
db4ad89a5d | ||
|
|
56b7cdb179 | ||
|
|
b9cff94d24 | ||
|
|
685026dd39 | ||
|
|
fbb42763d9 | ||
|
|
d4467a1f6a | ||
|
|
718d5a60b1 | ||
|
|
faf9eff6e2 | ||
|
|
1a7be839cd | ||
|
|
e4c230fb75 | ||
|
|
b18e587093 | ||
|
|
f7e4f4b5db | ||
|
|
335c079f82 | ||
|
|
8edf3488f7 | ||
|
|
ad31cff2a4 | ||
|
|
9f146e6ad1 | ||
|
|
0688bdda6d | ||
|
|
9c5170d47c | ||
|
|
4c940f2a39 | ||
|
|
3f79eb32c3 | ||
|
|
1c4933e23c | ||
|
|
6e79823f74 | ||
|
|
b6e4349caa | ||
|
|
9830e147ff | ||
|
|
954be67307 | ||
|
|
1ca19fb02c | ||
|
|
48a5fa529d | ||
|
|
f9b490c24f | ||
|
|
faff0e1751 | ||
|
|
78ec09cc25 | ||
|
|
5318ef4562 | ||
|
|
746304935d | ||
|
|
4dd84f4fc8 | ||
|
|
578f96f426 | ||
|
|
94e412031a | ||
|
|
5f24e3f771 |
No files matched your search
@@ -26,14 +26,8 @@ updates:
|
||||
# https://github.com/dropwizard/dropwizard/pull/11273
|
||||
- dependency-name: "ch.qos.logback:*"
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.14"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.14"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt-get install -y protobuf-compiler gpg
|
||||
pip install sabledocs
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt update
|
||||
sudo apt install -y gpg
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
# ca-certificates: required for AWS CRT client
|
||||
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
temurin-26
|
||||
temurin-27
|
||||
@@ -8,6 +8,7 @@ package org.signal.integration;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.google.common.io.Resources;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.webauthn4j.data.AuthenticatorAssertionResponse;
|
||||
@@ -20,6 +21,7 @@ import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import com.webauthn4j.test.client.ClientPlatform;
|
||||
import io.dropwizard.configuration.ConfigurationValidationException;
|
||||
import io.dropwizard.jersey.validation.Validators;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.grpc.ChannelCredentials;
|
||||
import io.grpc.ClientInterceptor;
|
||||
import io.grpc.Grpc;
|
||||
@@ -51,17 +53,23 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.client.Request;
|
||||
import org.eclipse.jetty.http2.client.HTTP2Client;
|
||||
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
|
||||
import org.eclipse.jetty.io.ClientConnector;
|
||||
import org.eclipse.jetty.util.ssl.SslContextFactory;
|
||||
import org.eclipse.jetty.websocket.api.exceptions.UpgradeException;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.signal.integration.config.Config;
|
||||
@@ -82,6 +90,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
@@ -95,6 +104,7 @@ import org.whispersystems.textsecuregcm.storage.TotpManager;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.HttpUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingSupplier;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -113,14 +123,29 @@ public final class Operations {
|
||||
|
||||
private static final FaultTolerantHttpClient CLIENT = buildClient();
|
||||
|
||||
private static final FaultTolerantHttpClient NO_RETRY_CLIENT = buildNoRetryClient();
|
||||
|
||||
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
|
||||
|
||||
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
|
||||
|
||||
private static final Retry WEBSOCKET_CONNECT_RETRY = Retry.of("integration-test-websocket-connect",
|
||||
new RetryConfiguration().toRetryConfigBuilder()
|
||||
.retryOnException(Operations::isRetryableConnectFailure)
|
||||
.build());
|
||||
private Operations() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
static boolean isRetryableConnectFailure(final Throwable e) {
|
||||
final Throwable cause = e instanceof ExecutionException ? e.getCause() : e;
|
||||
if (cause instanceof UpgradeException upgradeException) {
|
||||
return upgradeException.getResponseStatusCode() >= 500
|
||||
|| ExceptionUtils.getRootCause(upgradeException) instanceof TimeoutException;
|
||||
}
|
||||
return cause instanceof IOException;
|
||||
}
|
||||
|
||||
public record Receipt(ReceiptSerial serial, ReceiptCredential credential) {}
|
||||
|
||||
public static Receipt getPrescribedReceipt() throws InvalidInputException {
|
||||
@@ -236,50 +261,66 @@ public final class Operations {
|
||||
Optional.empty()));
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
// Retry a 441 to 3 times. It's possible we burned a challenge on a 500 that actually succeeded, but we didn't see
|
||||
// the response, so we can retry on the new challenge.
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
attempt++;
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectSuccess(AccountIdentityResponse.class);
|
||||
final Pair<Integer, JsonNode> registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(JsonNode.class);
|
||||
|
||||
recoveredUser.setAciUuid(registrationResponse.uuid());
|
||||
return recoveredUser;
|
||||
if (registrationResponse.getLeft() == 441 && attempt < 3) {
|
||||
mfaFailureResponse = SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
|
||||
"Unexpected response code: %d, body: %s", registrationResponse.getLeft(), registrationResponse.getRight());
|
||||
recoveredUser.setAciUuid(SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), AccountIdentityResponse.class).uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static TestUser newRegisteredUser(final String number) {
|
||||
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -326,7 +367,24 @@ public final class Operations {
|
||||
}
|
||||
|
||||
public static void deleteUser(final TestUser user) {
|
||||
apiDelete("/v1/accounts/me").authorized(user).executeExpectSuccess();
|
||||
final AtomicInteger attempts = new AtomicInteger();
|
||||
final Retry retry = Retry.of("integration-test-delete-user",
|
||||
new RetryConfiguration().<Integer>toRetryConfigBuilder()
|
||||
.retryOnResult(statusCode -> statusCode >= 500)
|
||||
.build());
|
||||
final int statusCode = retry.executeSupplier(() -> {
|
||||
attempts.incrementAndGet();
|
||||
return apiDelete("/v1/accounts/me")
|
||||
.authorized(user)
|
||||
// disable retries, since this endpoint is not idempotent
|
||||
.withoutRetries()
|
||||
.execute()
|
||||
.getLeft();
|
||||
});
|
||||
|
||||
// If we had to retry a 500 where the account was already deleted, we would fail authorization
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(statusCode) || (attempts.get() > 1 && statusCode == 401),
|
||||
"Unexpected response code: %d", statusCode);
|
||||
}
|
||||
|
||||
public static String peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
@@ -442,6 +500,15 @@ public final class Operations {
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCertInputStream).build();
|
||||
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
|
||||
.userAgent(USER_AGENT)
|
||||
.defaultServiceConfig(Map.of("methodConfig", List.of(Map.of(
|
||||
"name", List.of(Map.of()),
|
||||
"retryPolicy", Map.of(
|
||||
"maxAttempts", 3.0,
|
||||
"initialBackoff", "0.5s",
|
||||
"maxBackoff", "2s",
|
||||
"backoffMultiplier", 2.0,
|
||||
"retryableStatusCodes", List.of("UNAVAILABLE"))))))
|
||||
.enableRetry()
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
@@ -456,6 +523,7 @@ public final class Operations {
|
||||
|
||||
private final List<String> queryParams = new ArrayList<>();
|
||||
|
||||
private boolean retryServerErrors = true;
|
||||
|
||||
private RequestBuilder(final HttpRequest.Builder builder, final String endpoint) {
|
||||
this.builder = builder;
|
||||
@@ -493,6 +561,12 @@ public final class Operations {
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Don't automatically retry 5xx responses, for requests that aren't safe to blindly retry
|
||||
public RequestBuilder withoutRetries() {
|
||||
retryServerErrors = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Pair<Integer, Void> execute() {
|
||||
return execute(Void.class);
|
||||
}
|
||||
@@ -542,7 +616,8 @@ public final class Operations {
|
||||
private RawResponse executeRaw() {
|
||||
builder.uri(serverUri(endpoint, queryParams))
|
||||
.header(HttpHeaders.USER_AGENT, USER_AGENT);
|
||||
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
return (retryServerErrors ? CLIENT : NO_RETRY_CLIENT)
|
||||
.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
.whenComplete((response, error) -> {
|
||||
if (error != null) {
|
||||
logger.error("request error", error);
|
||||
@@ -571,7 +646,23 @@ public final class Operations {
|
||||
|
||||
private static FaultTolerantHttpClient buildClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("integration-test", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.withRetry(null, Executors.newSingleThreadScheduledExecutor())
|
||||
.build();
|
||||
// FaultTolerantHttpClient doesn't expose its Retry; it's the only one registered in this JVM
|
||||
ResilienceUtil.getRetryRegistry().getAllRetries().forEach(retry -> retry.getEventPublisher()
|
||||
.onRetry(event -> logger.warn("Retrying {} after {} failed attempt(s)",
|
||||
event.getName(), event.getNumberOfRetryAttempts(), event.getLastThrowable())));
|
||||
return client;
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static FaultTolerantHttpClient buildNoRetryClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test-no-retry", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.build();
|
||||
} catch (final CertificateException e) {
|
||||
@@ -589,7 +680,17 @@ public final class Operations {
|
||||
connector.setSslContextFactory(sslContextFactory);
|
||||
|
||||
final HTTP2Client http2Client = new HTTP2Client(connector);
|
||||
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client));
|
||||
final HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client)) {
|
||||
// There is an upstream Jetty bug where an HTTP/2 reader can race against and beat a websocket connection in
|
||||
// reading the first websocket frame. See https://github.com/jetty/jetty.project/issues/15981 for more details.
|
||||
//
|
||||
// As a workaround, register a response content listener that never reads. This stops the HTTP client's default
|
||||
// response content consumer from reading websocket frames off the upgraded HTTP/2 stream.
|
||||
@Override
|
||||
public Request newRequest(final URI uri) {
|
||||
return super.newRequest(uri).onResponseContentSource((_, _) -> {});
|
||||
}
|
||||
};
|
||||
|
||||
final WebSocketClient wsClient = new WebSocketClient(httpClient);
|
||||
wsClient.start();
|
||||
@@ -614,16 +715,19 @@ public final class Operations {
|
||||
|
||||
final URI uri = URI.create("wss://" + GRPC_DOMAIN + path);
|
||||
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
|
||||
request.setTimeout(5, TimeUnit.SECONDS);
|
||||
headers.forEach(request::setHeader);
|
||||
|
||||
final WebsocketClientSession listener = new WebsocketClientSession();
|
||||
try {
|
||||
WEB_SOCKET_CLIENT.connect(listener, request).get(5, TimeUnit.SECONDS);
|
||||
return WEBSOCKET_CONNECT_RETRY.executeCallable(() -> {
|
||||
final WebsocketClientSession session = new WebsocketClientSession();
|
||||
WEB_SOCKET_CLIENT.connect(session, request).get();
|
||||
logger.info("Successfully connected to websocket on {}", uri);
|
||||
return session;
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
logger.info("Successfully connected to websocket on {}", uri);
|
||||
return listener;
|
||||
}
|
||||
|
||||
private static Config loadConfigFromClasspath(final String filename) {
|
||||
|
||||
+20
-12
@@ -5,6 +5,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -19,6 +20,7 @@ import org.eclipse.jetty.websocket.api.Callback;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.RetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.messages.WebSocketMessage;
|
||||
@@ -30,6 +32,10 @@ import org.whispersystems.websocket.messages.protobuf.ProtobufWebSocketMessageFa
|
||||
public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(WebsocketClientSession.class);
|
||||
private static final Retry REQUEST_RETRY = Retry.of("integration-test-websocket-request",
|
||||
new RetryConfiguration().<WebSocketResponseMessage>toRetryConfigBuilder()
|
||||
.retryOnResult(response -> response.getStatus() >= 500)
|
||||
.build());
|
||||
private final WebSocketMessageFactory messageFactory = new ProtobufWebSocketMessageFactory();
|
||||
private final AtomicLong requestId = new AtomicLong();
|
||||
private final ConcurrentHashMap<Long, CompletableFuture<WebSocketResponseMessage>> responseFutures = new ConcurrentHashMap<>();
|
||||
@@ -95,18 +101,20 @@ public class WebsocketClientSession implements Session.Listener.AutoDemanding {
|
||||
final String path,
|
||||
final List<String> headers,
|
||||
final T body) {
|
||||
final Session session = opened.join();
|
||||
final long id = requestId.incrementAndGet();
|
||||
final CompletableFuture<WebSocketResponseMessage> future = new CompletableFuture<>();
|
||||
responseFutures.put(id, future);
|
||||
final Optional<byte[]> maybeBody = Optional.ofNullable(body).map(Operations::encodeJsonBody);
|
||||
final byte[] bytes = messageFactory.createRequest(Optional.of(id), verb, path, headers, maybeBody).toByteArray();
|
||||
session.sendBinary(ByteBuffer.wrap(bytes), Callback.from(() -> {}, throwable -> {
|
||||
if (responseFutures.remove(id) != null) {
|
||||
future.completeExceptionally(throwable);
|
||||
}
|
||||
}));
|
||||
return future.join();
|
||||
return REQUEST_RETRY.executeSupplier(() -> {
|
||||
final Session session = opened.join();
|
||||
final long id = requestId.incrementAndGet();
|
||||
final CompletableFuture<WebSocketResponseMessage> future = new CompletableFuture<>();
|
||||
responseFutures.put(id, future);
|
||||
final Optional<byte[]> maybeBody = Optional.ofNullable(body).map(Operations::encodeJsonBody);
|
||||
final byte[] bytes = messageFactory.createRequest(Optional.of(id), verb, path, headers, maybeBody).toByteArray();
|
||||
session.sendBinary(ByteBuffer.wrap(bytes), Callback.from(() -> {}, throwable -> {
|
||||
if (responseFutures.remove(id) != null) {
|
||||
future.completeExceptionally(throwable);
|
||||
}
|
||||
}));
|
||||
return future.join();
|
||||
});
|
||||
}
|
||||
|
||||
public List<MessageProtos.Envelope> getReceivedEnvelopes() {
|
||||
|
||||
@@ -66,6 +66,7 @@ import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.internal.ByteArray;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -289,7 +290,10 @@ public class AccountTest {
|
||||
|
||||
// reserve a username
|
||||
final ReserveUsernameHashRequest reserveUsernameHashRequest = new ReserveUsernameHashRequest(
|
||||
candidates.stream().map(Username::getHash).toList());
|
||||
candidates.stream()
|
||||
.map(Username::getHash)
|
||||
.map(ByteArray::serialize)
|
||||
.toList());
|
||||
// try unauthorized
|
||||
Operations
|
||||
.apiPut("/v1/accounts/username_hash/reserve", reserveUsernameHashRequest)
|
||||
@@ -303,13 +307,13 @@ public class AccountTest {
|
||||
// find which one is the reserved username
|
||||
final byte[] reservedHash = reserveUsernameHashResponse.usernameHash();
|
||||
final Username reservedUsername = candidates.stream()
|
||||
.filter(u -> Arrays.equals(u.getHash(), reservedHash))
|
||||
.filter(u -> Arrays.equals(u.getHash().serialize(), reservedHash))
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
|
||||
// confirm a username
|
||||
final ConfirmUsernameHashRequest confirmUsernameHashRequest = new ConfirmUsernameHashRequest(
|
||||
reservedUsername.getHash(),
|
||||
reservedUsername.getHash().serialize(),
|
||||
reservedUsername.generateProof(),
|
||||
"cluck cluck i'm a parrot".getBytes()
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
|
||||
@@ -54,8 +55,13 @@ public class RegistrationTest {
|
||||
// verify code
|
||||
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest(
|
||||
params.verificationCode());
|
||||
final VerificationSessionResponse codeVerified = Operations
|
||||
final Pair<Integer, VerificationSessionResponse> codeVerified = Operations
|
||||
.apiPut("/v1/verification/session/%s/code".formatted(sessionId), submitVerificationCodeRequest)
|
||||
.executeExpectSuccess(VerificationSessionResponse.class);
|
||||
.execute(VerificationSessionResponse.class);
|
||||
|
||||
// If we succeeded but then retried a 500, we might have submitted a code when we were already verified
|
||||
Assertions.assertTrue(codeVerified.getLeft() == 200 || codeVerified.getLeft() == 409,
|
||||
"Unexpected response code: " + codeVerified.getLeft());
|
||||
Assertions.assertTrue(codeVerified.getRight().verified());
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,12 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.55.14</aws.sdk2.version>
|
||||
<braintree.version>3.54.0</braintree.version>
|
||||
<aws.sdk2.version>2.59.1</aws.sdk2.version>
|
||||
<braintree.version>3.56.0</braintree.version>
|
||||
<!-- Weird stuff happens with parameter annotation counts under Java 27 with versions of Byte Buddy older than
|
||||
1.18.9, so we need to pull in a newer version than we'd get via Dropwizard -> Mockito -> Byte Buddy. We can drop
|
||||
this when Dropwizard updates and pulls in a newer version of Byte Buddy. -->
|
||||
<byte-buddy.version>1.18.17-jdk5</byte-buddy.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
@@ -55,12 +59,12 @@
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.90.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.93.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<guava.version>33.7.2-jre</guava.version>
|
||||
<guava.version>33.8.0-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache httpclient transitively, and we need to align them -->
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.22.3</jackson.version>
|
||||
<jackson.version>2.23.0</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
@@ -69,30 +73,29 @@
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.8.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.41</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<lettuce.version>7.9.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.43</libphonenumber.version>
|
||||
<log4j-bom.version>2.26.1</log4j-bom.version>
|
||||
<luajava.version>4.1.0</luajava.version>
|
||||
<micrometer.version>1.17.1</micrometer.version>
|
||||
<netty.version>4.2.19.Final</netty.version>
|
||||
<micrometer.version>1.17.2</micrometer.version>
|
||||
<netty.version>4.2.20.Final</netty.version>
|
||||
<!-- netty-bom doesn't manage the BoringSSL uber-jar; keep in sync with netty's tcnative.version -->
|
||||
<netty-tcnative.version>2.0.84.Final</netty-tcnative.version>
|
||||
<netty-tcnative.version>2.0.85.Final</netty-tcnative.version>
|
||||
<!-- Instrumentation releases target upstream opentelemetry versions and include that BOM by reference -->
|
||||
<opentelemetry-instrumentation.version>2.32.0</opentelemetry-instrumentation.version>
|
||||
<opentelemetry-instrumentation.version>2.33.1</opentelemetry-instrumentation.version>
|
||||
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
|
||||
<protobuf.version>4.36.2</protobuf.version>
|
||||
<pushy.version>0.15.6</pushy.version>
|
||||
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2025.0.8</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<simple-grpc.version>0.3.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
<stripe.version>33.4.2</stripe.version>
|
||||
<stripe.version>34.1.0</stripe.version>
|
||||
<swagger.version>2.2.55</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
<webauthn4j.version>0.31.11.RELEASE</webauthn4j.version>
|
||||
<webauthn4j.version>0.32.0.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- Images to use in tests via testcontainers. See also: prepull-testcontainers-images <profile> -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
|
||||
@@ -100,7 +103,7 @@
|
||||
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:26-jre-resolute@sha256:c3b6e31e48772c98e8868654e5f21fb2c3670e67c055ddd76d8cf37e62113eb5</docker.image>
|
||||
<docker.image>eclipse-temurin:27-jre-resolute@sha256:16a0cae9bfb17ab4257ac64e3d7585fc49233e7bdf3d376c4545289eaf193929</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -176,6 +179,16 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.bytebuddy</groupId>
|
||||
<artifactId>byte-buddy-agent</artifactId>
|
||||
<version>${byte-buddy.version}</version>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
@@ -253,11 +266,6 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<version>${logstash.logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-csv</artifactId>
|
||||
@@ -307,13 +315,13 @@
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<version>3.0.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.105.0</version>
|
||||
<version>0.108.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -490,12 +498,12 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.6.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -515,12 +523,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.4</version>
|
||||
<version>3.7.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.1</version>
|
||||
<version>1.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -563,7 +571,7 @@
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.16.0</version>
|
||||
<configuration>
|
||||
<release>26</release>
|
||||
<release>27</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@@ -603,7 +611,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.6.3</version>
|
||||
<version>3.7.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
||||
@@ -230,11 +230,6 @@ svrb:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
messageCache: # Redis server configuration for message store cache
|
||||
persistDelayMinutes: 1
|
||||
cluster:
|
||||
configurationUri: redis://redis.example.com:6379/
|
||||
|
||||
attachments:
|
||||
maxAttachmentUploadSizeInBytes: 1024
|
||||
maxMessageBackupUploadSizeInBytes: 1024
|
||||
@@ -260,7 +255,8 @@ fcm: # FCM configuration
|
||||
credentials: secret://fcm.credentials
|
||||
|
||||
cdn:
|
||||
bucket: cdn # S3 Bucket name
|
||||
baseUrl: https://cdn.example.com # Public base URL for objects in the bucket
|
||||
bucket: cdn # S3 Bucket name
|
||||
credentials:
|
||||
accessKeyId: secret://cdn.accessKey
|
||||
secretAccessKey: secret://cdn.accessSecret
|
||||
|
||||
+4
-26
@@ -14,10 +14,10 @@
|
||||
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
|
||||
<commons-compress.version>1.28.0</commons-compress.version>
|
||||
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.11.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.41</libphonenumber-geocoder.version>
|
||||
<firebase-admin.version>9.12.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.43</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.6.1</java-jwt.version>
|
||||
<java-jwt.version>4.6.2</java-jwt.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
|
||||
<opentelemetry-logback-appender-1.0.version>${opentelemetry-instrumentation.version}-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
@@ -177,25 +177,6 @@
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<exclusions>
|
||||
<!-- conflicts with webauthn4j-appattest -->
|
||||
<exclusion>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- sentinel for dependency convergence -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
@@ -805,9 +786,6 @@
|
||||
<jvmFlag>-XX:MaxRAMPercentage=75</jvmFlag>
|
||||
<jvmFlag>-XX:+HeapDumpOnOutOfMemoryError</jvmFlag>
|
||||
<jvmFlag>-XX:HeapDumpPath=/tmp/heapdump.bin</jvmFlag>
|
||||
<!-- This will likely become the default in a future version of Java, and we can remove this flag when
|
||||
that happens. Please see https://openjdk.org/jeps/534 for details. -->
|
||||
<jvmFlag>-XX:+UseCompactObjectHeaders</jvmFlag>
|
||||
</jvmFlags>
|
||||
<ports>
|
||||
<port>8080</port>
|
||||
@@ -878,7 +856,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
-10
@@ -47,7 +47,6 @@ import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConf
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OpenTelemetryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PagedSingleUseKEMPreKeyStoreConfiguration;
|
||||
@@ -190,11 +189,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private FaultTolerantRedisClusterFactory rateLimitersCluster;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private MessageCacheConfiguration messageCache;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -481,10 +475,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return storageService;
|
||||
}
|
||||
|
||||
public MessageCacheConfiguration getMessageCacheConfiguration() {
|
||||
return messageCache;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getPushSchedulerCluster() {
|
||||
return pushSchedulerCluster;
|
||||
}
|
||||
|
||||
@@ -33,10 +33,11 @@ import io.lettuce.core.metrics.MicrometerOptions;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalIoHandler;
|
||||
import io.netty.channel.local.LocalServerChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.nio.NioDatagramChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
@@ -176,6 +177,7 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
|
||||
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcCompressionInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
@@ -184,6 +186,7 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerStreamTracer;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
|
||||
@@ -193,11 +196,14 @@ import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.H2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.PooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
|
||||
import org.whispersystems.textsecuregcm.grpc.net.UnpooledH2ConnectionFactory;
|
||||
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
|
||||
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
@@ -207,6 +213,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CallNotPermittedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
|
||||
@@ -240,7 +247,6 @@ import org.whispersystems.textsecuregcm.push.ProvisioningManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationScheduler;
|
||||
import org.whispersystems.textsecuregcm.push.ReceiptSender;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ConnectionEventLogger;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
@@ -268,7 +274,6 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesCache;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
@@ -328,6 +333,7 @@ import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.NoContextTakeoverPerMessageDeflateExtension;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
@@ -338,7 +344,6 @@ import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesC
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
import org.whispersystems.textsecuregcm.workers.MessagePersisterServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.NotifyIdleDevicesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ProcessScheduledJobsServiceCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.RegenerateSecondaryDynamoDbTableDataCommand;
|
||||
@@ -400,7 +405,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new SetUserDiscoverabilityCommand());
|
||||
bootstrap.addCommand(new UnlinkDeviceCommand());
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new RemoveExpiredAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new RemoveExpiredSandboxAccountsCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new SandboxAccountPoolCommand());
|
||||
@@ -564,7 +568,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
BlockingQueue<Runnable> messageDeletionQueue = new LinkedBlockingQueue<>();
|
||||
Metrics.gaugeCollectionSize(name(getClass(), "messageDeletionQueueSize"), Collections.emptyList(),
|
||||
messageDeletionQueue);
|
||||
ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor")
|
||||
final ExecutorService messageDeletionAsyncExecutor = ExecutorServiceBuilder.of(environment, "messageDeletionAsyncExecutor")
|
||||
.minThreads(2)
|
||||
.maxThreads(2)
|
||||
.allowCoreThreadTimeOut(true)
|
||||
@@ -637,9 +641,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
FaultTolerantRedisClusterClient cacheCluster = config.getCacheClusterConfiguration()
|
||||
.build("main_cache", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient messagesCluster =
|
||||
config.getMessageCacheConfiguration().getRedisClusterConfiguration()
|
||||
.build("messages", sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient pushSchedulerCluster = config.getPushSchedulerCluster().build("push_scheduler",
|
||||
sharedClientResources.mutate());
|
||||
FaultTolerantRedisClusterClient rateLimitersCluster = config.getRateLimitersCluster().build("rate_limiters",
|
||||
@@ -731,7 +732,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
|
||||
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
|
||||
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> dnsResolutionEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
|
||||
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
|
||||
.completeOncePreferredResolved(false)
|
||||
@@ -796,8 +798,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
disconnectionRequestListenerExecutor, retryExecutor);
|
||||
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
|
||||
config.getCdnConfiguration().bucket());
|
||||
MessagesCache messagesCache = new MessagesCache(messagesCluster, messageDeliveryScheduler,
|
||||
messageDeletionAsyncExecutor, retryExecutor, clock);
|
||||
final FoundationDbMessageStore foundationDbMessageStore = new FoundationDbMessageStore(messageDatabasesByEpoch,
|
||||
config.getFoundationDbMessagesConfiguration().activeEpoch(),
|
||||
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
|
||||
@@ -812,11 +812,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
Clock.systemUTC());
|
||||
ReportMessageManager reportMessageManager = new ReportMessageManager(reportMessageDynamoDb, rateLimitersCluster,
|
||||
config.getReportMessageConfiguration().getCounterTtl());
|
||||
RedisMessageAvailabilityManager redisMessageAvailabilityManager =
|
||||
new RedisMessageAvailabilityManager(messagesCluster, clientEventExecutor, asyncOperationQueueingExecutor);
|
||||
MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, messagesCache, foundationDbMessageStore, redisMessageAvailabilityManager,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC(), experimentEnrollmentManager);
|
||||
final MessagesManager messagesManager =
|
||||
new MessagesManager(messagesDynamoDb, foundationDbMessageStore,
|
||||
reportMessageManager, messageDeletionAsyncExecutor, Clock.systemUTC());
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods = new ChangeNumberWaitingPeriods(
|
||||
config.getDynamoDbTables().getChangeNumberWaitingPeriods().getTableName(), dynamoDbClient);
|
||||
final ChangeNumberWaitingPeriodManager changeNumberWaitingPeriodManager = new ChangeNumberWaitingPeriodManager(
|
||||
@@ -944,7 +942,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
environment.lifecycle().manage(pushNotificationScheduler);
|
||||
environment.lifecycle().manage(provisioningManager);
|
||||
environment.lifecycle().manage(disconnectionRequestManager);
|
||||
environment.lifecycle().manage(redisMessageAvailabilityManager);
|
||||
environment.lifecycle().manage(currencyManager);
|
||||
environment.lifecycle().manage(registrationServiceClient);
|
||||
environment.lifecycle().manage(keyTransparencyServiceClient);
|
||||
@@ -1107,6 +1104,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
|
||||
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
|
||||
final GrpcAllowListInterceptor grpcAllowListInterceptor = new GrpcAllowListInterceptor(dynamicConfigurationManager);
|
||||
final GrpcCompressionInterceptor grpcCompressionInterceptor = new GrpcCompressionInterceptor(dynamicConfigurationManager);
|
||||
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
|
||||
|
||||
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
|
||||
@@ -1122,7 +1120,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
|
||||
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager);
|
||||
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager, Clock.systemUTC());
|
||||
|
||||
final CertificateGenerator certificateGenerator =
|
||||
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
|
||||
@@ -1143,7 +1141,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator,
|
||||
config.getCdnConfiguration().baseUrl(), chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager),
|
||||
@@ -1163,6 +1162,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
@@ -1176,7 +1176,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
|
||||
new LoginPurchaseGrpcService(loginPurchaseManager, dynamicConfigurationManager),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator,
|
||||
config.getCdnConfiguration().baseUrl(), chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC()), rateLimiters),
|
||||
@@ -1195,6 +1196,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
validatingInterceptor,
|
||||
errorMappingInterceptor,
|
||||
errorConformanceInterceptor,
|
||||
grpcCompressionInterceptor,
|
||||
grpcAllowListInterceptor,
|
||||
remoteDeprecationFilter,
|
||||
metricServerInterceptor,
|
||||
@@ -1206,15 +1208,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
|
||||
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
|
||||
|
||||
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
|
||||
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusLocalEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory()));
|
||||
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusNioEventLoopGroup =
|
||||
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
|
||||
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
|
||||
final ServerBuilder<?> serverBuilder = NettyServerBuilder
|
||||
.forAddress(grpcLocalAddress)
|
||||
.channelType(LocalServerChannel.class)
|
||||
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
|
||||
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment));
|
||||
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment))
|
||||
.addStreamTracerFactory(new MetricServerStreamTracer.Factory());
|
||||
authenticatedServices.forEach(serverBuilder::addService);
|
||||
unauthenticatedServices.forEach(serverBuilder::addService);
|
||||
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
|
||||
@@ -1224,10 +1229,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final SocketAddress websocketAddress =
|
||||
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
|
||||
final H2ConnectionFactory grpcH2ConnectionFactory = new PooledH2ConnectionFactory(grpcLocalAddress,
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup());
|
||||
final H2ConnectionFactory websocketH2ConnectionFactory = new UnpooledH2ConnectionFactory(websocketAddress, omnibusNioEventLoopGroup.getEventLoopGroup());
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
websocketServletPath, websocketH2ConnectionFactory,
|
||||
provisioningWebsocketServletPath, websocketH2ConnectionFactory),
|
||||
grpcH2ConnectionFactory);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(),
|
||||
@@ -1236,7 +1244,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
|
||||
sniMapping,
|
||||
omnibusNioEventLoopGroup.getEventLoopGroup(),
|
||||
omnibusLocalEventLoopGroup.getEventLoopGroup(),
|
||||
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
|
||||
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
|
||||
config.getGrpc().idleTimeout());
|
||||
@@ -1289,13 +1296,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(accountsManager, receiptSender, messagesManager, messageMetrics, pushNotificationManager,
|
||||
pushNotificationScheduler, disconnectionRequestManager,
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, experimentEnrollmentManager
|
||||
messageDeliveryScheduler, asnInfoProviderSupplier, clientReleaseManager, dynamicConfigurationManager
|
||||
));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager, experimentEnrollmentManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController());
|
||||
webSocketEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
@@ -1357,9 +1364,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.getRequestLog(), Duration.ofMillis(60000));
|
||||
provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(provisioningManager, asnInfoProviderSupplier, clientReleaseManager, provisioningWebsocketTimeoutExecutor, Duration.ofSeconds(90)));
|
||||
provisioningEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController(redisMessageAvailabilityManager, experimentEnrollmentManager));
|
||||
provisioningEnvironment.jersey().register(new KeepAliveController());
|
||||
provisioningEnvironment.jersey().register(new TimestampResponseFilter());
|
||||
|
||||
WebSocketConnection.registerDroppedErrorHook();
|
||||
|
||||
registerExceptionMappers(environment, webSocketEnvironment, provisioningEnvironment);
|
||||
|
||||
environment.jersey().property(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE);
|
||||
@@ -1405,6 +1414,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new CallNotPermittedExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
|
||||
+10
-6
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.netty.resolver.dns.DnsNameResolver;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
@@ -14,10 +15,8 @@ import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -27,7 +26,6 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
public class CloudflareTurnCredentialsManager {
|
||||
@@ -133,10 +131,16 @@ public class CloudflareTurnCredentialsManager {
|
||||
|
||||
final HttpResponse<String> response;
|
||||
try {
|
||||
response = cloudflareTurnClient.sendAsync(getCredentialsRequest, HttpResponse.BodyHandlers.ofString()).join();
|
||||
} catch (CompletionException e) {
|
||||
response = cloudflareTurnClient.send(getCredentialsRequest, HttpResponse.BodyHandlers.ofString());
|
||||
} catch (Exception e) {
|
||||
|
||||
if (e instanceof CallNotPermittedException cnpe) {
|
||||
// the circuit breaker is open, and this can escape up to the exception mapper
|
||||
throw cnpe;
|
||||
}
|
||||
|
||||
logger.warn("failed to make http request to Cloudflare Turn: {}", e.getMessage());
|
||||
throw new IOException(ExceptionUtils.unwrap(e));
|
||||
throw new IOException(e);
|
||||
}
|
||||
|
||||
if (response.statusCode() != Response.Status.CREATED.getStatusCode()) {
|
||||
|
||||
+16
-17
@@ -27,7 +27,6 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClient;
|
||||
@@ -120,10 +119,6 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
/**
|
||||
* Adds a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to register
|
||||
*/
|
||||
public void addListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.compute(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
@@ -138,10 +133,6 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
|
||||
/**
|
||||
* Removes a listener for disconnection requests for a specific authenticated device.
|
||||
*
|
||||
* @param accountIdentifier TODO
|
||||
* @param deviceId TODO
|
||||
* @param listener the listener to remove
|
||||
*/
|
||||
public void removeListener(final UUID accountIdentifier, final byte deviceId, final DisconnectionRequestListener listener) {
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
@@ -218,14 +209,22 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
}
|
||||
|
||||
deviceIds.forEach(deviceId -> {
|
||||
listeners.getOrDefault(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), Collections.emptyList())
|
||||
.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
final ArrayList<DisconnectionRequestListener> listenersForDevice = new ArrayList<>();
|
||||
|
||||
// This is a little weird, but it's a thread-safe way to get an immutable copy of the list of listeners for a
|
||||
// given device
|
||||
listeners.computeIfPresent(new AccountIdentifierAndDeviceId(accountIdentifier, deviceId), (_, existingListeners) -> {
|
||||
listenersForDevice.addAll(existingListeners);
|
||||
return existingListeners;
|
||||
});
|
||||
|
||||
listenersForDevice.forEach(listener -> listenerEventExecutor.execute(() -> {
|
||||
try {
|
||||
listener.handleDisconnectionRequest();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Listener failed to handle disconnection request", e);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -15,7 +15,7 @@ public class BulkheadConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Min(1)
|
||||
private int maxConcurrentCalls = BulkheadConfig.DEFAULT_MAX_CONCURRENT_CALLS;
|
||||
private int maxConcurrentCalls = 256;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
|
||||
+1
@@ -12,6 +12,7 @@ import javax.annotation.Nullable;
|
||||
import java.net.URI;
|
||||
|
||||
public record CdnConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
|
||||
@NotBlank String baseUrl,
|
||||
@NotBlank String bucket,
|
||||
@NotBlank String region,
|
||||
@Nullable URI endpointOverride) {
|
||||
|
||||
+4
-2
@@ -14,7 +14,9 @@ import java.time.Duration;
|
||||
/// @param port The port to bind the omnibus server to
|
||||
/// @param websocketAddress The address of a listening websocket server for handling legacy requests
|
||||
/// @param websocketPort The port of a listening websocket server for handling legacy requests
|
||||
/// @param idleTimeout The duration after which an idle connection may be disconnected
|
||||
/// @param idleTimeout The duration after which a connection the client has not written to may be disconnected.
|
||||
/// Clients are expected to send some periodic write traffic (application-level or h2-level
|
||||
/// pings) to keep otherwise idle connections open
|
||||
/// @param h2c If true, listen for plaintext h2c with prior-knowledge
|
||||
/// @param sslProvider The TLS implementation used to terminate TLS. Defaults to `OPENSSL`.
|
||||
public record GrpcConfiguration(
|
||||
@@ -34,7 +36,7 @@ public record GrpcConfiguration(
|
||||
websocketAddress = "localhost";
|
||||
}
|
||||
if (idleTimeout == null) {
|
||||
idleTimeout = Duration.ofMinutes(5);
|
||||
idleTimeout = Duration.ofSeconds(60);
|
||||
}
|
||||
if (sslProvider == null) {
|
||||
sslProvider = SslProvider.OPENSSL;
|
||||
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2020 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class MessageCacheConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
private FaultTolerantRedisClusterFactory cluster;
|
||||
|
||||
@JsonProperty
|
||||
private int persistDelayMinutes = 10;
|
||||
|
||||
public FaultTolerantRedisClusterFactory getRedisClusterConfiguration() {
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public int getPersistDelayMinutes() {
|
||||
return persistDelayMinutes;
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -43,11 +43,11 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessagePersisterConfiguration messagePersister = new DynamicMessagePersisterConfiguration();
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
DynamicMessageDeliveryConfiguration messageDelivery = new DynamicMessageDeliveryConfiguration();
|
||||
DynamicNotificationConfiguration notifications = DynamicNotificationConfiguration.DEFAULT;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -77,6 +77,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicGrpcCompressionConfiguration grpcCompression = new DynamicGrpcCompressionConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
|
||||
@@ -115,14 +119,14 @@ public class DynamicConfiguration {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public DynamicMessagePersisterConfiguration getMessagePersisterConfiguration() {
|
||||
return messagePersister;
|
||||
}
|
||||
|
||||
public DynamicMessageDeliveryConfiguration getMessageDeliveryConfiguration() {
|
||||
return messageDelivery;
|
||||
}
|
||||
|
||||
public DynamicNotificationConfiguration getNotificationConfiguration() {
|
||||
return notifications;
|
||||
}
|
||||
|
||||
public DynamicRegistrationConfiguration getRegistrationConfiguration() {
|
||||
return registrationConfiguration;
|
||||
}
|
||||
@@ -151,6 +155,10 @@ public class DynamicConfiguration {
|
||||
return grpcAllowList;
|
||||
}
|
||||
|
||||
public DynamicGrpcCompressionConfiguration getGrpcCompression() {
|
||||
return grpcCompression;
|
||||
}
|
||||
|
||||
public DynamicOmnibusConfiguration getOmnibus() {
|
||||
return omnibus;
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
/// Configure which gRPC methods may compress their responses
|
||||
///
|
||||
/// @param compressedServices A list of fully qualified service names for which all RPC responses should be compressed.
|
||||
/// For example, `kt_query.KeyTransparencyQueryService` would compress responses for all RPCs
|
||||
/// on that service.
|
||||
/// @param compressedMethods A list of fully qualified method names of RPCs whose responses should be compressed. For
|
||||
/// example, `kt_query.KeyTransparencyQueryService/Search` would compress responses for the
|
||||
/// `Search` RPC method
|
||||
public record DynamicGrpcCompressionConfiguration(
|
||||
Set<String> compressedServices,
|
||||
Set<String> compressedMethods) {
|
||||
|
||||
public DynamicGrpcCompressionConfiguration {
|
||||
if (compressedServices == null) {
|
||||
compressedServices = Collections.emptySet();
|
||||
}
|
||||
if (compressedMethods == null) {
|
||||
compressedMethods = Collections.emptySet();
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicGrpcCompressionConfiguration() {
|
||||
// By default, no gRPC responses are compressed
|
||||
this(Collections.emptySet(), Collections.emptySet());
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
|
||||
public class DynamicMessagePersisterConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
private boolean persistenceEnabled = true;
|
||||
|
||||
/**
|
||||
* If we have to trim a client's persisted queue to make room to persist from Redis to DynamoDB, how much extra room should we make
|
||||
*/
|
||||
@JsonProperty
|
||||
private double trimOversizedQueueExtraRoomRatio = 1.5;
|
||||
|
||||
@JsonProperty
|
||||
private Duration nodeClaimTtl = Duration.ofMinutes(5);
|
||||
|
||||
@JsonProperty
|
||||
private Duration sleepBetweenNodes = Duration.ofSeconds(5);
|
||||
|
||||
public DynamicMessagePersisterConfiguration() {}
|
||||
|
||||
@VisibleForTesting
|
||||
public DynamicMessagePersisterConfiguration(final boolean persistenceEnabled,
|
||||
final double trimOversizedQueueExtraRoomRatio,
|
||||
final Duration nodeClaimTtl,
|
||||
final Duration sleepBetweenNodes) {
|
||||
|
||||
this.persistenceEnabled = persistenceEnabled;
|
||||
this.trimOversizedQueueExtraRoomRatio = trimOversizedQueueExtraRoomRatio;
|
||||
this.nodeClaimTtl = nodeClaimTtl;
|
||||
this.sleepBetweenNodes = sleepBetweenNodes;
|
||||
}
|
||||
|
||||
public boolean isPersistenceEnabled() {
|
||||
return persistenceEnabled;
|
||||
}
|
||||
|
||||
public double getTrimOversizedQueueExtraRoomRatio() {
|
||||
return trimOversizedQueueExtraRoomRatio;
|
||||
}
|
||||
|
||||
public Duration getNodeClaimTtl() {
|
||||
return nodeClaimTtl;
|
||||
}
|
||||
|
||||
public Duration getSleepBetweenNodes() {
|
||||
return sleepBetweenNodes;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
public record DynamicNotificationConfiguration(boolean sendRemainingMessagesNotificationImmediately) {
|
||||
|
||||
public static final DynamicNotificationConfiguration DEFAULT =
|
||||
new DynamicNotificationConfiguration(false);
|
||||
}
|
||||
+19
-1
@@ -38,7 +38,9 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
@@ -97,6 +99,7 @@ public class AccountController {
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setGcmRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid GcmRegistrationId registrationId) {
|
||||
|
||||
@@ -118,6 +121,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ManagedAsync
|
||||
public void deleteGcmRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setGcmId(null);
|
||||
@@ -130,6 +134,7 @@ public class AccountController {
|
||||
@Path("/apn/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setApnRegistrationId(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid ApnRegistrationId registrationId) {
|
||||
|
||||
@@ -144,6 +149,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ManagedAsync
|
||||
public void deleteApnRegistrationId(@Auth AuthenticatedDevice auth) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(), d -> {
|
||||
d.setApnId(null);
|
||||
@@ -155,6 +161,7 @@ public class AccountController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
@ManagedAsync
|
||||
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
|
||||
|
||||
@@ -168,6 +175,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
@ManagedAsync
|
||||
public void removeRegistrationLock(@Auth AuthenticatedDevice auth) {
|
||||
accounts.update(auth.accountIdentifier(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
@@ -183,6 +191,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Device name changed successfully")
|
||||
@ApiResponse(responseCode = "404", description = "No device found with the given ID")
|
||||
@ApiResponse(responseCode = "403", description = "Not authorized to change the name of the device with the given ID")
|
||||
@ManagedAsync
|
||||
public void setName(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final DeviceName deviceName,
|
||||
|
||||
@@ -214,6 +223,7 @@ public class AccountController {
|
||||
@Path("/attributes/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public void setAccountAttributes(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
|
||||
@@ -260,6 +270,7 @@ public class AccountController {
|
||||
@GET
|
||||
@Path("/whoami")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public AccountIdentityResponse whoAmI(@Auth final AuthenticatedDevice auth) {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
@@ -278,6 +289,7 @@ public class AccountController {
|
||||
)
|
||||
@ApiResponse(responseCode = "204", description = "Username successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ManagedAsync
|
||||
public void deleteUsernameHash(@Auth final AuthenticatedDevice auth) {
|
||||
accounts.clearUsernameHash(auth.accountIdentifier());
|
||||
}
|
||||
@@ -298,6 +310,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "409", description = "All username hashes from the list are taken.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public ReserveUsernameHashResponse reserveUsernameHash(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ReserveUsernameHashRequest usernameRequest) throws RateLimitExceededException {
|
||||
@@ -337,13 +350,14 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "410", description = "Username hash not available (username can't be used).")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public UsernameHashResponse confirmUsernameHash(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final ConfirmUsernameHashRequest confirmRequest) throws RateLimitExceededException {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
@@ -417,6 +431,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "409", description = "Username is not set for the account.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public UsernameLinkHandle updateUsernameLink(
|
||||
@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final EncryptedUsername encryptedUsername) throws RateLimitExceededException {
|
||||
@@ -454,6 +469,7 @@ public class AccountController {
|
||||
@ApiResponse(responseCode = "204", description = "Username Link successfully deleted.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public void deleteUsernameLink(@Auth final AuthenticatedDevice auth) throws RateLimitExceededException {
|
||||
// check ratelimiter for username link operations
|
||||
rateLimiters.forDescriptor(RateLimiters.For.USERNAME_LINK_OPERATION).validate(auth.accountIdentifier());
|
||||
@@ -503,6 +519,7 @@ public class AccountController {
|
||||
@HEAD
|
||||
@Path("/account/{identifier}")
|
||||
@RateLimitedByIp(RateLimiters.For.CHECK_ACCOUNT_EXISTENCE)
|
||||
@ManagedAsync
|
||||
public Response accountExists(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@@ -519,6 +536,7 @@ public class AccountController {
|
||||
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
@ManagedAsync
|
||||
public void deleteAccount(@Auth AuthenticatedDevice auth) {
|
||||
accounts.delete(auth.accountIdentifier(), AccountsManager.DeletionReason.USER_REQUEST);
|
||||
}
|
||||
|
||||
+4
@@ -33,6 +33,7 @@ import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
@@ -84,6 +85,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final ChangeNumberRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@@ -151,6 +153,7 @@ public class AccountControllerV2 {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Sets whether the account should be discoverable by phone number in the directory.")
|
||||
@ApiResponse(responseCode = "204", description = "The setting was successfully updated.")
|
||||
@ManagedAsync
|
||||
public void setPhoneNumberDiscoverability(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
|
||||
@@ -171,6 +174,7 @@ public class AccountControllerV2 {
|
||||
@ApiResponse(responseCode = "200",
|
||||
description = "Response with data report. A plain text representation is a field in the response.",
|
||||
useReturnTypeSchema = true)
|
||||
@ManagedAsync
|
||||
public AccountDataReportResponse getAccountDataReport(@Auth final AuthenticatedDevice auth) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
|
||||
+12
-16
@@ -9,13 +9,11 @@ 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;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import jakarta.ws.rs.GET;
|
||||
@@ -27,9 +25,9 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
@@ -99,33 +97,31 @@ public class AttachmentControllerV4 {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public AttachmentDescriptorV3 getAttachmentUploadForm(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@Parameter(description = "The size of the attachment to upload in bytes")
|
||||
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
|
||||
@QueryParam("uploadLength") @Positive final long uploadLength,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
|
||||
if (uploadLength > maxUploadLength) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
|
||||
countRateLimiter.validate(auth.accountIdentifier());
|
||||
if (maybeUploadLength.isPresent()) {
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
|
||||
// However, just undoing the first modification if the second one fails is close enough for our purposes
|
||||
try {
|
||||
bytesRateLimiter.validate(auth.accountIdentifier(), uploadLength);
|
||||
} catch (RateLimitExceededException e) {
|
||||
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
|
||||
throw e;
|
||||
}
|
||||
|
||||
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(uploadLength);
|
||||
|
||||
|
||||
+2
@@ -14,6 +14,7 @@ import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -55,6 +56,7 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
@ManagedAsync
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedDevice auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
|
||||
|
||||
+2
@@ -18,6 +18,7 @@ import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.CloudflareTurnCredentialsManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -54,6 +55,7 @@ public class CallRoutingControllerV2 {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ManagedAsync
|
||||
public GetCallingRelaysResponse getCallingRelays(final @Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, IOException {
|
||||
|
||||
|
||||
+3
@@ -29,6 +29,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
@@ -77,6 +78,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
@ManagedAsync
|
||||
public DeliveryCertificate getDeliveryCertificate(@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164) {
|
||||
|
||||
@@ -96,6 +98,7 @@ public class CertificateController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
@ManagedAsync
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
|
||||
+3
@@ -31,6 +31,7 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
@@ -88,6 +89,7 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response handleChallengeResponse(@Auth final AuthenticatedDevice auth,
|
||||
@Valid final AnswerChallengeRequest answerRequest,
|
||||
@Context final ContainerRequestContext requestContext,
|
||||
@@ -182,6 +184,7 @@ public class ChallengeController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response requestPushChallenge(@Auth final AuthenticatedDevice auth,
|
||||
@Context ContainerRequestContext requestContext) {
|
||||
|
||||
|
||||
+6
@@ -47,6 +47,7 @@ import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesLinkedDevices;
|
||||
@@ -135,6 +136,7 @@ public class DeviceController {
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ManagedAsync
|
||||
public DeviceInfoList getDevices(@Auth AuthenticatedDevice auth) {
|
||||
// Devices may change their own names (and primary devices may change the names of linked devices) and so the device
|
||||
// state associated with the authenticated account may be stale. Fetch a fresh copy to compensate.
|
||||
@@ -149,6 +151,7 @@ public class DeviceController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@ChangesLinkedDevices
|
||||
@ManagedAsync
|
||||
public void removeDevice(@Auth AuthenticatedDevice auth, @PathParam("device_id") byte deviceId) {
|
||||
if (auth.deviceId() != Device.PRIMARY_ID && auth.deviceId() != deviceId) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
@@ -189,6 +192,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public LinkDeviceToken createDeviceToken(@Auth AuthenticatedDevice auth)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
@@ -223,6 +227,7 @@ public class DeviceController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public LinkDeviceResponse linkDevice(@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
|
||||
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
|
||||
@@ -391,6 +396,7 @@ public class DeviceController {
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
@ManagedAsync
|
||||
public void setCapabilities(@Auth final AuthenticatedDevice auth, @NotNull final Map<String, Boolean> capabilities) {
|
||||
accounts.updateDevice(auth.accountIdentifier(), auth.deviceId(),
|
||||
d -> d.setCapabilities(DeviceCapabilityAdapter.mapToSet(capabilities)));
|
||||
|
||||
+1
@@ -160,6 +160,7 @@ public class DonationController {
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited; reduce requested permit count and/or try again after the prescribed delay")
|
||||
@ManagedAsync
|
||||
public CreateDonationPermitResponse createPermits(@Auth final AuthenticatedDevice auth,
|
||||
@NotNull @Valid final CreateDonationPermitsRequest request) throws RateLimitExceededException {
|
||||
|
||||
|
||||
+1
-56
@@ -5,72 +5,18 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.websocket.session.WebSocketSession;
|
||||
import org.whispersystems.websocket.session.WebSocketSessionContext;
|
||||
|
||||
|
||||
@Path("/v1/keepalive")
|
||||
@Tag(name = "Keep Alive")
|
||||
public class KeepAliveController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(KeepAliveController.class);
|
||||
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private static final String CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME = name(KeepAliveController.class,
|
||||
"closedConnectionAge");
|
||||
|
||||
|
||||
public KeepAliveController(final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedDevice> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
|
||||
maybeAuth.ifPresent(auth -> {
|
||||
if (!(experimentEnrollmentManager.isEnrolled(auth.accountIdentifier(), MessagesManager.READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME) ||
|
||||
redisMessageAvailabilityManager.isLocallyPresent(auth.accountIdentifier(), auth.deviceId()))) {
|
||||
|
||||
final Duration age = Duration.between(context.getClient().getCreated(), Instant.now());
|
||||
|
||||
logger.debug("***** No local subscription found for {}::{}; age = {}ms, User-Agent = {}",
|
||||
auth.accountIdentifier(), auth.deviceId(), age.toMillis(),
|
||||
context.getClient().getUserAgent());
|
||||
|
||||
context.getClient().close(1000, "OK");
|
||||
|
||||
Timer.builder(CLOSED_CONNECTION_AGE_DISTRIBUTION_NAME)
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(context.getClient().getUserAgent())))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(age);
|
||||
}
|
||||
});
|
||||
|
||||
public Response getKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@@ -79,5 +25,4 @@ public class KeepAliveController {
|
||||
public Response getProvisioningKeepAlive() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
+2
@@ -463,6 +463,7 @@ public class MessageController {
|
||||
@ApiResponse(
|
||||
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
|
||||
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
|
||||
@ManagedAsync
|
||||
public Response sendMultiRecipientMessage(
|
||||
@Deprecated
|
||||
@Parameter(description="The bitwise xor of the unidentified access keys for every recipient of the message. Will be replaced with group send endorsements")
|
||||
@@ -729,6 +730,7 @@ public class MessageController {
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Path("/report/{source}/{messageGuid}")
|
||||
@ManagedAsync
|
||||
public Response reportSpamMessage(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@PathParam("source") UUID source,
|
||||
|
||||
+2
-5
@@ -168,8 +168,8 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
|
||||
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ManagedAsync
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid CreateProfileRequest request,
|
||||
@Context final ContainerRequestContext requestContext) {
|
||||
@@ -177,10 +177,6 @@ public class ProfileController {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return Response.status(Response.Status.PRECONDITION_FAILED).build();
|
||||
}
|
||||
|
||||
final Optional<VersionedProfileV1> currentProfile =
|
||||
profilesManager.getV1(auth.accountIdentifier(), request.version());
|
||||
|
||||
@@ -278,6 +274,7 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "401", description = "Not authorized to access this profile.")
|
||||
@ApiResponse(responseCode = "404", description = "Profile or account not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limit exceeded.")
|
||||
@ManagedAsync
|
||||
public ExpiringProfileKeyCredentialProfileResponse getProfile(
|
||||
@Auth Optional<AuthenticatedDevice> maybeAuthenticatedDevice,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
|
||||
+2
@@ -29,6 +29,7 @@ import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Base64;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.ProvisioningMessage;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -76,6 +77,7 @@ public class ProvisioningController {
|
||||
@ApiResponse(responseCode="204", description="The provisioning message was delivered to the given provisioning address")
|
||||
@ApiResponse(responseCode="400", description="The provisioning message was too large")
|
||||
@ApiResponse(responseCode="404", description="No device with the given provisioning address was connected at the time of the request")
|
||||
@ManagedAsync
|
||||
public void sendProvisioningMessage(@Auth final AuthenticatedDevice auth,
|
||||
|
||||
@Parameter(description = "The temporary provisioning address to which to send a provisioning message")
|
||||
|
||||
+2
@@ -45,6 +45,7 @@ import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
@@ -161,6 +162,7 @@ public class RegistrationController {
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = MfaFailureExceptionMapper.MfaFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
|
||||
@ManagedAsync
|
||||
public AccountCreationResponse register(
|
||||
@Parameter(
|
||||
in = ParameterIn.HEADER,
|
||||
|
||||
+2
@@ -24,6 +24,7 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
@@ -52,6 +53,7 @@ public class RemoteConfigController {
|
||||
@ApiResponse(responseCode = "304", description = "There is no change since the last fetch", content = {})
|
||||
@ApiResponse(responseCode = "401", description = "This request requires authentication", content = {})
|
||||
|
||||
@ManagedAsync
|
||||
public Response getAll(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
|
||||
|
||||
+2
@@ -32,6 +32,7 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
@@ -115,6 +116,7 @@ public class SecureValueRecovery2Controller {
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "422", description = "Provided list of SVR2 credentials could not be parsed")
|
||||
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
|
||||
@ManagedAsync
|
||||
public AuthCheckResponseV2 authCheck(
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final AuthCheckRequest request) {
|
||||
|
||||
+2
@@ -21,6 +21,7 @@ import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.StickerPackFormUploadAttributes.StickerPackFormUploadItem;
|
||||
@@ -49,6 +50,7 @@ public class StickerController {
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/pack/form/{count}")
|
||||
@ManagedAsync
|
||||
public StickerPackFormUploadAttributes getStickersForm(@Auth AuthenticatedDevice auth,
|
||||
@PathParam("count") @Min(1) @Max(201) int stickerCount)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
+6
@@ -60,6 +60,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
@@ -184,6 +185,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse createSession(@NotNull @Valid final CreateVerificationSessionRequest request,
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, ObsoletePhoneNumberFormatException {
|
||||
@@ -263,6 +265,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse updateSession(
|
||||
@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@@ -518,6 +521,7 @@ public class VerificationController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "404", description = "Session with the specified ID could not be found")
|
||||
@ApiResponse(responseCode = "422", description = "Malformed session ID encoding")
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse getSession(@PathParam("sessionId") final String encodedSessionId) {
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession = retrieveRegistrationServiceSession(encodedSessionId);
|
||||
@@ -564,6 +568,7 @@ public class VerificationController {
|
||||
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse requestVerificationCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@Parameter(in = ParameterIn.HEADER, description = "Ordered list of languages in which the client prefers to receive SMS or voice verification messages") @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE)
|
||||
@@ -700,6 +705,7 @@ public class VerificationController {
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed",
|
||||
schema = @Schema(implementation = Integer.class)))
|
||||
@ManagedAsync
|
||||
public VerificationSessionResponse verifyCode(@PathParam("sessionId") final String encodedSessionId,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final SubmitVerificationCodeRequest submitVerificationCodeRequest) {
|
||||
|
||||
+1
-1
@@ -263,7 +263,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("Could not verify proof");
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
final Account account = authenticatedAccount();
|
||||
final Device device = account
|
||||
.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest);
|
||||
return SetBackupIdResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -162,7 +162,7 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
private Account authenticatedAccount() {
|
||||
return accountManager
|
||||
.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
+6
-2
@@ -18,9 +18,11 @@ public class DeviceCapabilityUtil {
|
||||
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
|
||||
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
|
||||
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
|
||||
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
|
||||
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
|
||||
case DEVICE_CAPABILITY_REPLY_PRIVATELY -> DeviceCapability.REPLY_PRIVATELY;
|
||||
case DEVICE_CAPABILITY_CONTACT_DELETE -> DeviceCapability.CONTACT_DELETE;
|
||||
case DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE -> DeviceCapability.ADMIN_REMOVE_AND_DELETE;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
|
||||
throw GrpcExceptions.invalidArguments("unrecognized device capability");
|
||||
};
|
||||
@@ -32,9 +34,11 @@ public class DeviceCapabilityUtil {
|
||||
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
|
||||
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
|
||||
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
|
||||
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
|
||||
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
|
||||
case REPLY_PRIVATELY -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY;
|
||||
case CONTACT_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE;
|
||||
case ADMIN_REMOVE_AND_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE;
|
||||
};
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -12,6 +12,8 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.chat.device.ChangeDevicePasswordRequest;
|
||||
import org.signal.chat.device.ChangeDevicePasswordResponse;
|
||||
import org.signal.chat.device.ClearPushTokenRequest;
|
||||
import org.signal.chat.device.ClearPushTokenResponse;
|
||||
import org.signal.chat.device.GetDevicesRequest;
|
||||
@@ -28,7 +30,6 @@ import org.signal.chat.device.SimpleDevicesGrpc;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -184,6 +185,23 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
return SetCapabilitiesResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChangeDevicePasswordResponse changeDevicePassword(final ChangeDevicePasswordRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getNewPassword().isBlank()) {
|
||||
throw GrpcExceptions.fieldViolation("new_password", "password must not be blank");
|
||||
}
|
||||
|
||||
if (!accountsManager.updateDevicePassword(authenticatedDevice.accountIdentifier(), authenticatedDevice.deviceId(),
|
||||
request.getNewPassword())) {
|
||||
|
||||
throw GrpcExceptions.invalidCredentials("invalid credentials");
|
||||
}
|
||||
|
||||
return ChangeDevicePasswordResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount() {
|
||||
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
+10
-1
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import io.grpc.ForwardingServerCall;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
@@ -12,6 +13,7 @@ import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.lettuce.core.RedisException;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import org.slf4j.Logger;
|
||||
@@ -66,6 +68,13 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case CallNotPermittedException _ -> GrpcExceptions.unavailable();
|
||||
case RedisException e -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
log.warn("RPC {} encountered RedisException", call.getMethodDescriptor().getFullMethodName(), e);
|
||||
}
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
|
||||
@@ -73,7 +82,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
call.getMethodDescriptor().getFullMethodName(), cause);
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
};
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
/// Requests gzip compression of responses for configured gRPC methods. Compression is only applied if the client
|
||||
/// advertises gzip in its `grpc-accept-encoding` header; otherwise gRPC falls back to sending uncompressed responses.
|
||||
public class GrpcCompressionInterceptor implements ServerInterceptor {
|
||||
|
||||
private static final String GZIP = "gzip";
|
||||
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public GrpcCompressionInterceptor(
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
|
||||
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
|
||||
final DynamicGrpcCompressionConfiguration compressionConfiguration =
|
||||
this.dynamicConfigurationManager.getConfiguration().getGrpcCompression();
|
||||
final MethodDescriptor<ReqT, RespT> methodDescriptor = serverCall.getMethodDescriptor();
|
||||
if (compressionConfiguration.compressedServices().contains(methodDescriptor.getServiceName()) ||
|
||||
compressionConfiguration.compressedMethods().contains(methodDescriptor.getFullMethodName())) {
|
||||
// This does not necessarily enable compression. The implementation will handle negotiation with the client
|
||||
// and may fall back to no compression.
|
||||
serverCall.setCompression(GZIP);
|
||||
}
|
||||
return next.startCall(serverCall, metadata);
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
@@ -33,6 +34,8 @@ import reactor.util.function.Tuples;
|
||||
|
||||
public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonymousImplBase {
|
||||
|
||||
private static final int CHECK_KEYS_MAX_CONCURRENCY = 16;
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final KeysManager keysManager;
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
@@ -99,20 +102,22 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
|
||||
.map(request -> Tuples.of(GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
|
||||
request.getFingerprint().toByteArray()))
|
||||
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
.flatMapSequential(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
|
||||
.map(maybeAccount -> maybeAccount.flatMap(
|
||||
account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) {
|
||||
case ACI -> Optional.of(account.getAccountIdentityKey());
|
||||
case PNI -> account.getPhoneNumberIdentityKey();
|
||||
}))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.build())));
|
||||
.map(maybeIdentityKey -> {
|
||||
final CheckIdentityKeyResponse.Builder builder = CheckIdentityKeyResponse.newBuilder();
|
||||
|
||||
return maybeIdentityKey.map(identityKey ->
|
||||
fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2())
|
||||
? builder.setMatched(Empty.getDefaultInstance()).build()
|
||||
: builder.setIdentityKey(ByteString.copyFrom(identityKey.serialize())).build())
|
||||
.orElseGet(() -> builder.setTargetNotFound(NotFound.getDefaultInstance()).build());
|
||||
}), CHECK_KEYS_MAX_CONCURRENCY));
|
||||
}
|
||||
|
||||
private static boolean fingerprintMatches(final IdentityKey identityKey, final byte[] fingerprint) {
|
||||
|
||||
@@ -104,7 +104,7 @@ class KeysGrpcHelper {
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.ecSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
|
||||
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
|
||||
.setKemPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
|
||||
|
||||
+29
-15
@@ -8,8 +8,10 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.signal.chat.messages.GetMessagesStreamClosed;
|
||||
@@ -18,7 +20,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
@@ -38,7 +39,6 @@ import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Signal;
|
||||
import reactor.core.publisher.Sinks;
|
||||
|
||||
/// A MessageDispatcher is used to stream messages to an authenticated device and coordinates message acknowledgement,
|
||||
@@ -48,13 +48,12 @@ public class MessageDispatcher {
|
||||
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_UNACKED_MESSAGES = 256;
|
||||
static final int DEFAULT_MAX_UNACKED_MESSAGES = 256;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
|
||||
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
|
||||
|
||||
public static final GetMessagesResponse QUEUE_EMPTY_RESPONSE =
|
||||
GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).build();
|
||||
private static final StatusRuntimeException CONFLICTING_STREAM_EXCEPTION =
|
||||
GrpcExceptions.streamClosed(GetMessagesStreamClosed.newBuilder()
|
||||
.setConflictingStream(Empty.getDefaultInstance())
|
||||
@@ -69,6 +68,7 @@ public class MessageDispatcher {
|
||||
private final PushNotificationScheduler pushNotificationScheduler;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final Clock clock;
|
||||
|
||||
public MessageDispatcher(final ReceiptSender receiptSender,
|
||||
final MessagesManager messagesManager,
|
||||
@@ -76,7 +76,8 @@ public class MessageDispatcher {
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final PushNotificationScheduler pushNotificationScheduler,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
final ClientReleaseManager clientReleaseManager,
|
||||
final Clock clock) {
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageMetrics = messageMetrics;
|
||||
@@ -84,6 +85,7 @@ public class MessageDispatcher {
|
||||
this.pushNotificationScheduler = pushNotificationScheduler;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Retrieve messages for the device.
|
||||
@@ -132,10 +134,21 @@ public class MessageDispatcher {
|
||||
|
||||
pushNotificationManager.handleMessagesRetrieved(account, device, userAgentString);
|
||||
|
||||
final Flux<GetMessagesResponse> messages = JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
final AtomicInteger maxUnacknowledgedMessages = new AtomicInteger(DEFAULT_MAX_UNACKED_MESSAGES);
|
||||
|
||||
final Flux<GetMessagesResponse> messages = Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(account.getAccountIdentifier(), device.getId()))
|
||||
.flatMapMany(hasSuspectedDeliveryLoop -> {
|
||||
if (hasSuspectedDeliveryLoop) {
|
||||
maxUnacknowledgedMessages.set(1);
|
||||
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.GRPC_CHANNEL, userAgent, clientReleaseManager);
|
||||
}
|
||||
|
||||
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(maxUnacknowledgedMessages.get());
|
||||
})
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
|
||||
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
|
||||
@@ -149,13 +162,13 @@ public class MessageDispatcher {
|
||||
final MessageProtos.Envelope stripped = envelope.toBuilder().clearEphemeral().build();
|
||||
messageMetrics.measureAccountEnvelopeUuidMismatches(account, envelope);
|
||||
messageMetrics.measureMessageSent(stripped.getSerializedSize());
|
||||
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).build());
|
||||
yield Mono.just(GetMessagesResponse.newBuilder().setEnvelope(stripped).setServerTimeEpochMillis(clock.millis()).build());
|
||||
}
|
||||
case MessageStreamEntry.QueueEmpty _ -> {
|
||||
pendingAcknowledgementTracker.markEndOfQueue();
|
||||
yield Mono.empty();
|
||||
}
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
}, maxUnacknowledgedMessages.get())
|
||||
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
|
||||
return CONFLICTING_STREAM_EXCEPTION;
|
||||
@@ -164,7 +177,7 @@ public class MessageDispatcher {
|
||||
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
|
||||
// after that a permit is emitted every time we receive an ack.
|
||||
final Sinks.Many<Boolean> ackPermits = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final Flux<Boolean> permits = Flux.range(0, MAX_UNACKED_MESSAGES)
|
||||
final Flux<Boolean> permits = Flux.range(0, maxUnacknowledgedMessages.get())
|
||||
.map(_ -> true)
|
||||
.concatWith(ackPermits.asFlux());
|
||||
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
|
||||
@@ -184,7 +197,7 @@ public class MessageDispatcher {
|
||||
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
|
||||
// Just have to emit some value that indicates we can release a permit
|
||||
.thenReturn(true);
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
}, maxUnacknowledgedMessages.get())
|
||||
.doOnNext(_ -> ackPermits.tryEmitNext(true))
|
||||
.ignoreElements()
|
||||
.cast(GetMessagesResponse.class);
|
||||
@@ -195,7 +208,8 @@ public class MessageDispatcher {
|
||||
// Will only emit errors, but those should terminate the stream
|
||||
ackCompletions,
|
||||
// Emits a queue empty once all messages prior to the queueEmpty signal have been acked
|
||||
pendingAcknowledgementTracker.queueDrained(),
|
||||
pendingAcknowledgementTracker.queueDrained().map(
|
||||
_ -> GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).setServerTimeEpochMillis(clock.millis()).build()),
|
||||
// Emit an invalid credentials error if we receive a disconnection request
|
||||
disconnectionSignal(account, device, userAgent))
|
||||
.doFinally(_ -> maybeSchedulePush(account, device));
|
||||
|
||||
+4
-6
@@ -59,6 +59,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes");
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
|
||||
/// Response bytes as written to the wire (i.e. after compression), as reported by [MetricServerStreamTracer]
|
||||
@VisibleForTesting
|
||||
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes");
|
||||
@VisibleForTesting
|
||||
@@ -113,15 +114,16 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
|
||||
|
||||
private final Counter responseMessageCounter;
|
||||
private final Counter responseBytesCounter;
|
||||
private final Tags tags;
|
||||
private @Nullable String reason = null;
|
||||
|
||||
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
|
||||
super(delegate);
|
||||
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
|
||||
this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags);
|
||||
this.tags = tags;
|
||||
|
||||
MetricServerStreamTracer.current().ifPresent(tracer ->
|
||||
tracer.setResponseBytesCounter(meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -143,10 +145,6 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
public void sendMessage(final RespT responseMessage) {
|
||||
this.responseMessageCounter.increment();
|
||||
|
||||
if (responseMessage instanceof GeneratedMessage generatedMessage) {
|
||||
this.responseBytesCounter.increment(generatedMessage.getSerializedSize());
|
||||
}
|
||||
|
||||
// Extract the annotated reason (if any) from the message
|
||||
final String messageReason = MetricServerCall.reason(responseMessage);
|
||||
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Context;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerStreamTracer;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/// Records on-the-wire (i.e. possibly compressed) sizes of response messages.
|
||||
///
|
||||
/// Stream tracers are created before the method being called has been resolved. The tracer makes itself available
|
||||
/// via the call's [Context], and [MetricServerInterceptor] (which only runs for registered methods) supplies the
|
||||
/// counter to increment; without it, nothing is recorded.
|
||||
public class MetricServerStreamTracer extends ServerStreamTracer {
|
||||
|
||||
private static final Context.Key<MetricServerStreamTracer> CONTEXT_KEY = Context.key("metricServerStreamTracer");
|
||||
|
||||
@Nullable
|
||||
private volatile Counter responseBytesCounter;
|
||||
|
||||
public static class Factory extends ServerStreamTracer.Factory {
|
||||
|
||||
@Override
|
||||
public ServerStreamTracer newServerStreamTracer(final String fullMethodName, final Metadata headers) {
|
||||
return new MetricServerStreamTracer();
|
||||
}
|
||||
}
|
||||
|
||||
/// @return the tracer for the current call, if a [Factory] is installed on the server
|
||||
static Optional<MetricServerStreamTracer> current() {
|
||||
return Optional.ofNullable(CONTEXT_KEY.get());
|
||||
}
|
||||
|
||||
void setResponseBytesCounter(final Counter responseBytesCounter) {
|
||||
this.responseBytesCounter = responseBytesCounter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Context filterContext(final Context context) {
|
||||
return context.withValue(CONTEXT_KEY, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void outboundWireSize(final long bytes) {
|
||||
final Counter counter = responseBytesCounter;
|
||||
if (counter != null) {
|
||||
counter.increment(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -9,7 +9,6 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -39,9 +38,8 @@ class PendingAcknowledgementTracker {
|
||||
private final ConcurrentHashMap<UUID, UnacknowledgedEnvelope> unacknowledgedEnvelopes = new ConcurrentHashMap<>();
|
||||
private final AtomicLong sentMessageCounter = new AtomicLong();
|
||||
|
||||
private final Sinks.One<GetMessagesResponse> queueDrained = Sinks.one();
|
||||
private final ClosableEpoch queueDrainEpoch = new ClosableEpoch(() ->
|
||||
queueDrained.tryEmitValue(MessageDispatcher.QUEUE_EMPTY_RESPONSE));
|
||||
private final Sinks.One<Boolean> queueDrained = Sinks.one();
|
||||
private final ClosableEpoch queueDrainEpoch = new ClosableEpoch(() -> queueDrained.tryEmitValue(true));
|
||||
private final Timer.Sample queueDrainStart = Timer.start();
|
||||
|
||||
private final MessageMetrics messageMetrics;
|
||||
@@ -92,7 +90,7 @@ class PendingAcknowledgementTracker {
|
||||
///
|
||||
/// @return A mono that completes with a QueueEmpty response when all messages tracked before [#markEndOfQueue] have
|
||||
/// been acknowledged.
|
||||
Mono<GetMessagesResponse> queueDrained() {
|
||||
Mono<Boolean> queueDrained() {
|
||||
return queueDrained.asMono();
|
||||
}
|
||||
|
||||
|
||||
+8
-2
@@ -11,6 +11,7 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -56,6 +57,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
private final String cdnBaseUrl;
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
@@ -66,6 +68,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final String cdnBaseUrl,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ServerSecretParams serverSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
@@ -74,6 +77,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
profilesManager,
|
||||
profileBadgeConverter,
|
||||
policyGenerator,
|
||||
cdnBaseUrl,
|
||||
genericServerSecretParams,
|
||||
rateLimiters,
|
||||
clock,
|
||||
@@ -86,6 +90,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final String cdnBaseUrl,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final RateLimiters rateLimiters,
|
||||
final Clock clock,
|
||||
@@ -95,6 +100,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
this.profilesManager = profilesManager;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.cdnBaseUrl = Strings.CS.removeEnd(cdnBaseUrl, "/");
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.clock = clock;
|
||||
@@ -133,7 +139,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
|
||||
// If we didn't find a v2 profile, try a v1 profile
|
||||
.or(() -> ProfileGrpcHelper
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, cdnBaseUrl, version)
|
||||
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
|
||||
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
|
||||
@@ -238,7 +244,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
|
||||
return profilesManager.extendAvatarTtlForIdentity(identity)
|
||||
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setPath(extendedPath)
|
||||
.setUrl(ProfileGrpcHelper.cdnUrl(cdnBaseUrl, extendedPath))
|
||||
.build())
|
||||
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
|
||||
+12
-14
@@ -14,6 +14,7 @@ import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.bouncycastle.crypto.digests.TupleHash;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
@@ -32,7 +33,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
@@ -47,9 +47,14 @@ public class ProfileGrpcHelper {
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
static String cdnUrl(final String cdnBaseUrl, final String path) {
|
||||
return Strings.CS.removeEnd(cdnBaseUrl, "/") + "/" + Strings.CS.removeStart(path, "/");
|
||||
}
|
||||
|
||||
static Optional<LegacyProfileResult> getProfileV1(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final String cdnBaseUrl,
|
||||
final byte[] requestVersion) {
|
||||
final Optional<VersionedProfileV1> maybeV1Profile =
|
||||
profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(requestVersion));
|
||||
@@ -74,7 +79,7 @@ public class ProfileGrpcHelper {
|
||||
builder.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
}
|
||||
if (v1Profile.avatar() != null) {
|
||||
builder.setAvatar(v1Profile.avatar());
|
||||
builder.setAvatarUrl(cdnUrl(cdnBaseUrl, v1Profile.avatar()));
|
||||
}
|
||||
|
||||
// If present, include the payment address if the version matches the latest version on Account or the latest
|
||||
@@ -91,9 +96,7 @@ public class ProfileGrpcHelper {
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final byte[] requestVersion) {
|
||||
|
||||
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
|
||||
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
|
||||
: Optional.empty();
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getAccountIdentifier(), requestVersion);
|
||||
if (maybeProfile.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -135,14 +138,8 @@ public class ProfileGrpcHelper {
|
||||
final ProfilesManager profilesManager,
|
||||
final ServerZkProfileOperations zkProfileOperations) {
|
||||
|
||||
final Optional<VersionedProfile> versionedProfile;
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
versionedProfile = profilesManager.get(account.getAccountIdentifier(), version);
|
||||
} else {
|
||||
versionedProfile = Optional.empty();
|
||||
}
|
||||
|
||||
return versionedProfile.map(VersionedProfile::commitment)
|
||||
return profilesManager.get(account.getAccountIdentifier(), version)
|
||||
.map(VersionedProfile::commitment)
|
||||
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
|
||||
.map(VersionedProfileV1::commitment))
|
||||
.map(commitment -> {
|
||||
@@ -151,7 +148,8 @@ public class ProfileGrpcHelper {
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
|
||||
new ProfileKeyCredentialRequest(encodedCredentialRequest),
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()),
|
||||
zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential request");
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -73,6 +74,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final String cdnBaseUrl;
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
@@ -86,6 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final String cdnBaseUrl,
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final RateLimiters rateLimiters) {
|
||||
@@ -97,6 +100,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.cdnBaseUrl = Strings.CS.removeEnd(cdnBaseUrl, "/");
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -268,7 +272,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
// If we didn't find a v2 profile, try a v1 profile
|
||||
.or(() -> ProfileGrpcHelper
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, cdnBaseUrl, version)
|
||||
.map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build())))
|
||||
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.netty.handler.ssl.OpenSsl;
|
||||
import java.net.Socket;
|
||||
import java.security.Principal;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import javax.net.ssl.ExtendedSSLSession;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.SSLEngine;
|
||||
import javax.net.ssl.X509ExtendedKeyManager;
|
||||
|
||||
/// A server key manager for netty's BoringSSL provider that uses a client's signature algorithm preferences, enabling
|
||||
/// support for ed25519.
|
||||
///
|
||||
/// This works around [netty#17690](https://github.com/netty/netty/issues/17690):
|
||||
/// netty’s engine only asks the key manager for RSA- and EC-family key types, so it never selects an Ed25519 key.
|
||||
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
|
||||
|
||||
private final X509ExtendedKeyManager delegate;
|
||||
|
||||
@VisibleForTesting
|
||||
BoringSslServerKeyManager(final X509ExtendedKeyManager delegate) {
|
||||
if (!"BoringSSL".equals(OpenSsl.versionString())) {
|
||||
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
|
||||
}
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
/// @throws IllegalArgumentException if `keyManagers` contains no [X509ExtendedKeyManager]
|
||||
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
|
||||
return Arrays.stream(keyManagers)
|
||||
.filter(X509ExtendedKeyManager.class::isInstance)
|
||||
.map(X509ExtendedKeyManager.class::cast)
|
||||
.findFirst()
|
||||
.map(BoringSslServerKeyManager::new)
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509ExtendedKeyManager found"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseEngineServerAlias(final String keyType, final Principal[] issuers, final SSLEngine engine) {
|
||||
if (!(engine.getHandshakeSession() instanceof ExtendedSSLSession session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Netty will only call this with EC/RSA key types (https://github.com/netty/netty/issues/17690).
|
||||
// We can safely ignore `keyType` and loop through the peer's signature algorithms to find the best matching key.
|
||||
for (final String signatureAlgorithm : session.getPeerSupportedSignatureAlgorithms()) {
|
||||
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
|
||||
.map(jdkKeyType -> delegate.chooseEngineServerAlias(jdkKeyType, issuers, engine));
|
||||
|
||||
if (maybeAlias.isPresent()) {
|
||||
return maybeAlias.get();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Maps a JDK signature algorithm name to the JDK key type that can produce it
|
||||
@VisibleForTesting
|
||||
static Optional<String> getJdkKeyType(final String signatureAlgorithm) {
|
||||
if (signatureAlgorithm.equals("Ed25519")) {
|
||||
return Optional.of("EdDSA");
|
||||
} else if (signatureAlgorithm.endsWith("withECDSA")) {
|
||||
return Optional.of("EC");
|
||||
} else if (signatureAlgorithm.endsWith("withRSA")) {
|
||||
return Optional.of("RSA");
|
||||
}
|
||||
|
||||
// We don't need to be exhaustive, because we require TLS 1.3 and only use a limited number of key types.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
|
||||
return delegate.chooseServerAlias(keyType, issuers, socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getServerAliases(final String keyType, final Principal[] issuers) {
|
||||
return delegate.getServerAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) {
|
||||
return delegate.chooseClientAlias(keyTypes, issuers, socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
|
||||
return delegate.getClientAliases(keyType, issuers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getCertificateChain(final String alias) {
|
||||
return delegate.getCertificateChain(alias);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrivateKey getPrivateKey(final String alias) {
|
||||
return delegate.getPrivateKey(alias);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.EventLoop;
|
||||
import java.net.SocketAddress;
|
||||
|
||||
/// A factory that creates h2 connections to some configured target address
|
||||
public interface H2ConnectionFactory {
|
||||
|
||||
/// Retrieve a h2 connection to [#address()]
|
||||
///
|
||||
/// @param callerEventLoop The event loop of the channel making this call
|
||||
ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop);
|
||||
|
||||
/// Release a connection previously acquired via [#getConnectionChannelFuture]
|
||||
void release(final Channel connection);
|
||||
|
||||
/// @return The [SocketAddress] that this factory targets
|
||||
SocketAddress address();
|
||||
}
|
||||
+8
-12
@@ -14,9 +14,9 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.SimpleUserEventChannelHandler;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.DecoderException;
|
||||
@@ -67,8 +67,7 @@ public class OmnibusH2Server implements Managed {
|
||||
private final OmnibusRouter router;
|
||||
private final Supplier<DynamicOmnibusConfiguration> configurationSupplier;
|
||||
private final Duration idleTimeout;
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
private final EventLoopGroup nioEventLoopGroup;
|
||||
private final SocketAddress bindAddress;
|
||||
|
||||
private Channel serverChannel;
|
||||
@@ -77,16 +76,14 @@ public class OmnibusH2Server implements Managed {
|
||||
///
|
||||
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
|
||||
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
|
||||
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
|
||||
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
|
||||
/// @param nioEventLoopGroup An Event loop with a [NioIoHandler#newFactory()] to use for all NIO channel pipelines
|
||||
/// @param bindAddress The address the server should listen on
|
||||
/// @param router How the server should select backends based on request paths
|
||||
/// @param configurationSupplier Dynamic configuration supplier
|
||||
/// @param idleTimeout How long to wait before terminating idle TCP connections
|
||||
/// @param idleTimeout How long to wait since the last data was received from the client before terminating TCP connections
|
||||
public OmnibusH2Server(
|
||||
final @Nullable Mapping<String, SslContext> sslContextBySni,
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final EventLoopGroup nioEventLoopGroup,
|
||||
final SocketAddress bindAddress,
|
||||
final OmnibusRouter router,
|
||||
final Supplier<DynamicOmnibusConfiguration> configurationSupplier,
|
||||
@@ -94,7 +91,6 @@ public class OmnibusH2Server implements Managed {
|
||||
this.sslContextBySni = sslContextBySni;
|
||||
this.configurationSupplier = configurationSupplier;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.bindAddress = bindAddress;
|
||||
this.router = router;
|
||||
this.idleTimeout = idleTimeout;
|
||||
@@ -113,7 +109,7 @@ public class OmnibusH2Server implements Managed {
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final SocketChannel ch) {
|
||||
ch.pipeline().addLast(new IdleStateHandler(0, 0, idleTimeout.toMillis(), TimeUnit.MILLISECONDS));
|
||||
ch.pipeline().addLast(new IdleStateHandler(idleTimeout.toMillis(), 0, 0, TimeUnit.MILLISECONDS));
|
||||
ch.pipeline().addLast(new SimpleUserEventChannelHandler<IdleStateEvent>() {
|
||||
@Override
|
||||
protected void eventReceived(final ChannelHandlerContext ctx, final IdleStateEvent evt) {
|
||||
@@ -184,7 +180,7 @@ public class OmnibusH2Server implements Managed {
|
||||
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
|
||||
@Override
|
||||
protected void initChannel(final Http2StreamChannel ch) {
|
||||
ch.pipeline().addLast(new OmnibusH2StreamHandler(nioEventLoopGroup, localEventLoopGroup, router));
|
||||
ch.pipeline().addLast(new OmnibusH2StreamHandler(router));
|
||||
}
|
||||
}));
|
||||
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
|
||||
|
||||
+15
-85
@@ -7,36 +7,22 @@ package org.whispersystems.textsecuregcm.grpc.net;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.DefaultEventLoopGroup;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2Headers;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
|
||||
import io.netty.handler.codec.http2.Http2Error;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2HeadersFrame;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannel;
|
||||
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import io.netty.util.ReferenceCounted;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -46,7 +32,7 @@ import org.slf4j.LoggerFactory;
|
||||
///
|
||||
/// When this handler receives an H2 header for a new stream-id=X on our parent H2 connection it will
|
||||
/// - Receive the stream-id=X header and check the path to determine the correct backend
|
||||
/// - Make a new H2 connection to the backend
|
||||
/// - Get or create an H2 connection to the backend
|
||||
/// - Forward the header with stream-id=Y to the backend
|
||||
/// - Install a [H2FrameProxyHandler] on the backend stream pipeline that forwards the received stream-id=Y frames from
|
||||
/// the backend back to the client on stream-id=X
|
||||
@@ -56,25 +42,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OmnibusH2StreamHandler.class);
|
||||
|
||||
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("backend-connection", List.of());
|
||||
private static final String BACKEND_STREAM_COUNTER_NAME = name(OmnibusH2StreamHandler.class, "backendStream");
|
||||
private static final String BACKEND_CONNECT_DURATION_NAME = name(OmnibusH2StreamHandler.class,
|
||||
"backendConnectDuration");
|
||||
private static final String BACKEND_TAG = "backend";
|
||||
|
||||
private final OmnibusRouter router;
|
||||
|
||||
private final DefaultEventLoopGroup localEventLoopGroup;
|
||||
private final NioEventLoopGroup nioEventLoopGroup;
|
||||
|
||||
public OmnibusH2StreamHandler(
|
||||
final NioEventLoopGroup nioEventLoopGroup,
|
||||
final DefaultEventLoopGroup localEventLoopGroup,
|
||||
final OmnibusRouter router) {
|
||||
public OmnibusH2StreamHandler(final OmnibusRouter router) {
|
||||
this.router = router;
|
||||
this.localEventLoopGroup = localEventLoopGroup;
|
||||
this.nioEventLoopGroup = nioEventLoopGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,8 +70,8 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
// Select the target backend based on the path
|
||||
final String path = Optional.ofNullable(headersFrame.headers().path()).map(CharSequence::toString).orElse("");
|
||||
final SocketAddress target = router.match(path);
|
||||
final String backendTag = target.toString();
|
||||
final H2ConnectionFactory connectionFactory = router.match(path);
|
||||
final String backendTag = connectionFactory.address().toString();
|
||||
|
||||
Metrics.counter(BACKEND_STREAM_COUNTER_NAME, BACKEND_TAG, backendTag).increment();
|
||||
|
||||
@@ -109,55 +83,38 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
? proxyRemoteAddress.getHostAddress()
|
||||
: ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
|
||||
|
||||
// Make a new H2 connection to the target backend
|
||||
final Timer.Sample connectSample = Timer.start();
|
||||
new Bootstrap()
|
||||
.group(selectEventLoop(ctx, target))
|
||||
.channel(target instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class)
|
||||
.handler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
|
||||
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
|
||||
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
|
||||
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
|
||||
}
|
||||
})
|
||||
.connect(target)
|
||||
// Make an H2 connection to the target backend
|
||||
connectionFactory.getConnectionChannelFuture(ctx.channel().eventLoop())
|
||||
.addListener((ChannelFuture connectFuture) -> {
|
||||
connectSample.stop(Timer.builder(BACKEND_CONNECT_DURATION_NAME)
|
||||
.tag(BACKEND_TAG, backendTag)
|
||||
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
|
||||
.register(Metrics.globalRegistry));
|
||||
|
||||
if (!connectFuture.isSuccess()) {
|
||||
// Close the client stream with a 502: Bad Gateway if the backend wasn't available
|
||||
logger.warn("Failed to connect to backend {}", target, connectFuture.cause());
|
||||
logger.warn("Failed to connect to backend {}", backendTag, connectFuture.cause());
|
||||
ctx.channel()
|
||||
.writeAndFlush(new DefaultHttp2HeadersFrame(
|
||||
new DefaultHttp2Headers().status("502"), true))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
connectionFactory.release(connectFuture.channel());
|
||||
return;
|
||||
}
|
||||
|
||||
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
|
||||
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
|
||||
logger.trace("Opening a HTTP/2 stream to the backend {}", backendTag);
|
||||
final Channel backendConnection = connectFuture.channel();
|
||||
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
|
||||
createBackendProxyStream(ctx, connectionFactory, backendConnection, headersFrame, backendTag);
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a proxy stream on the provided `backendConnection` that forwards H2 frames to/from the client H2 stream.
|
||||
///
|
||||
/// @param clientStreamCtx The context for a client H2 stream that targets the backend
|
||||
/// @param connectionFactory The factory `backendConnection` came from
|
||||
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
|
||||
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
|
||||
/// backend stream
|
||||
/// @param backendTag The backend this stream targets, for metrics
|
||||
private void createBackendProxyStream(
|
||||
final ChannelHandlerContext clientStreamCtx,
|
||||
final H2ConnectionFactory connectionFactory,
|
||||
final Channel backendConnection,
|
||||
final Http2HeadersFrame headersFrame,
|
||||
final String backendTag) {
|
||||
@@ -171,15 +128,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
clientStreamCtx.channel()
|
||||
.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.INTERNAL_ERROR))
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
backendConnection.close();
|
||||
connectionFactory.release(backendConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
final Http2StreamChannel backendStream = streamFuture.getNow();
|
||||
|
||||
// Close the entire H2 connection whenever the stream we just opened closes. We only plan on using
|
||||
// a single stream on this connection.
|
||||
backendStream.closeFuture().addListener(_ -> backendConnection.close());
|
||||
backendStream.closeFuture().addListener(_ -> connectionFactory.release(backendConnection));
|
||||
|
||||
// We're going to modify the inbound H2 stream channel, which runs on a different eventloop than the
|
||||
// outbound channel we've made to the backend. We have to submit our updates back to the inbound
|
||||
@@ -188,7 +143,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
|
||||
if (!clientStreamCtx.channel().isActive()) {
|
||||
// The client disconnected already and the client pipeline is already torn down.
|
||||
backendConnection.close();
|
||||
backendStream.close();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -204,29 +159,4 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private EventLoopGroup selectEventLoop(final ChannelHandlerContext inboundCtx, SocketAddress target) {
|
||||
final boolean localInbound = inboundCtx.channel() instanceof LocalChannel;
|
||||
final boolean localTarget = target instanceof LocalAddress;
|
||||
|
||||
// If the inbound eventloop matches the target type, we can just reuse the inbound's event loop
|
||||
if (localInbound == localTarget) {
|
||||
return inboundCtx.channel().eventLoop();
|
||||
}
|
||||
|
||||
return localTarget ? this.localEventLoopGroup : this.nioEventLoopGroup;
|
||||
}
|
||||
|
||||
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelRegistered(final ChannelHandlerContext ctx) {
|
||||
logger.error("Inbound stream handler was registered when no inbound streams expected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
|
||||
super.channelRead(ctx, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,22 +4,21 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Map;
|
||||
|
||||
public class OmnibusRouter {
|
||||
|
||||
private final Map<String, SocketAddress> routes;
|
||||
private final SocketAddress defaultBackend;
|
||||
private final Map<String, H2ConnectionFactory> routesByPath;
|
||||
private final H2ConnectionFactory defaultBackend;
|
||||
|
||||
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
|
||||
this.routes = routes;
|
||||
public OmnibusRouter(final Map<String, H2ConnectionFactory> routesByPath, final H2ConnectionFactory defaultBackend) {
|
||||
this.routesByPath = routesByPath;
|
||||
this.defaultBackend = defaultBackend;
|
||||
}
|
||||
|
||||
SocketAddress match(final String fullPath) {
|
||||
H2ConnectionFactory match(final String fullPath) {
|
||||
final int queryIndex = fullPath.indexOf('?');
|
||||
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
|
||||
return routes.getOrDefault(path, defaultBackend);
|
||||
return routesByPath.getOrDefault(path, defaultBackend);
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
|
||||
import io.netty.handler.codec.http2.Http2CodecUtil;
|
||||
import io.netty.handler.codec.http2.Http2GoAwayFrame;
|
||||
import io.netty.util.AttributeKey;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import java.net.SocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.whispersystems.textsecuregcm.util.ClosableEpoch;
|
||||
|
||||
/// An [H2ConnectionFactory] that creates one shared h2 connection per calling event loop.
|
||||
///
|
||||
/// A connection is replaced the next time it's requested if it failed to connect, has closed, has received a GOAWAY, or
|
||||
/// is older than `retireAfterNanos`. Retiring connections bounds how many stream IDs a connection uses since eventually
|
||||
/// stream-ids are exhausted.
|
||||
///
|
||||
/// A replaced connection is never handed out again, and is closed once every stream it was handed out for has been
|
||||
/// [#release]ed.
|
||||
public class PooledH2ConnectionFactory implements H2ConnectionFactory {
|
||||
|
||||
private static final AttributeKey<Boolean> GOAWAY_RECEIVED =
|
||||
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "goawayReceived");
|
||||
|
||||
// Key for a [ClosableEpoch] attached to every new connection's channel. When the connection is replaced,
|
||||
// [ClosableEpoch#close] is called, and when all streams are released the underlying netty channel is closed.
|
||||
private static final AttributeKey<ClosableEpoch> CONNECTION_EPOCH =
|
||||
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "connection_epoch");
|
||||
|
||||
private static final PooledConnectionHandler POOLED_CONNECTION_HANDLER = new PooledConnectionHandler();
|
||||
|
||||
private static final String CONNECTION_REPLACED_COUNTER_NAME =
|
||||
name(PooledH2ConnectionFactory.class, "connectionReplaced");
|
||||
private static final String OPEN_CONNECTIONS_GAUGE_NAME = name(PooledH2ConnectionFactory.class, "openConnections");
|
||||
|
||||
// How long to use a pooled connection for
|
||||
private static final Duration RETIRE_AFTER = Duration.ofMinutes(30);
|
||||
|
||||
private final UnpooledH2ConnectionFactory connectionFactory;
|
||||
private final long retireAfterNanos;
|
||||
|
||||
private final ConcurrentHashMap<EventLoop, PooledConnection> connectionsByCallerEventLoop = new ConcurrentHashMap<>();
|
||||
// Count of all open connections (including replaced ones waiting for outstanding streams to terminate)
|
||||
private final AtomicInteger openConnections;
|
||||
|
||||
private record PooledConnection(ChannelFuture connectFuture, long createdNanos) {}
|
||||
|
||||
/// Create a pooled H2 connection factory
|
||||
///
|
||||
/// @param targetAddress The [SocketAddress] connections should target
|
||||
/// @param eventLoopGroup The eventLoopGroup on which connections will be made. Must match the type of the [SocketAddress]
|
||||
public PooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
|
||||
this(targetAddress, eventLoopGroup, RETIRE_AFTER);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
PooledH2ConnectionFactory(final SocketAddress targetAddress,
|
||||
final EventLoopGroup eventLoopGroup,
|
||||
final Duration retireAfter) {
|
||||
this.connectionFactory = new UnpooledH2ConnectionFactory(targetAddress, eventLoopGroup, POOLED_CONNECTION_HANDLER);
|
||||
this.retireAfterNanos = retireAfter.toNanos();
|
||||
this.openConnections = Metrics.gauge(OPEN_CONNECTIONS_GAUGE_NAME, Tags.of("backend", targetAddress.toString()),
|
||||
new AtomicInteger());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
|
||||
assert callerEventLoop.inEventLoop();
|
||||
|
||||
final ChannelFuture connection = connectionsByCallerEventLoop.compute(callerEventLoop, (_, existing) -> {
|
||||
if (existing == null) {
|
||||
return newConnection(callerEventLoop);
|
||||
} else if (!isUsable(existing)) {
|
||||
existing.connectFuture().channel().attr(CONNECTION_EPOCH).get().close();
|
||||
return newConnection(callerEventLoop);
|
||||
} else {
|
||||
return existing;
|
||||
}
|
||||
})
|
||||
.connectFuture();
|
||||
|
||||
// Compute always hands us a connection with an open epoch and we can't race with anyone because we're in
|
||||
// callerEventLoop, so we should always be able to enter the epoch
|
||||
final boolean arrived = connection.channel().attr(CONNECTION_EPOCH).get().tryArrive();
|
||||
assert arrived;
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
private PooledConnection newConnection(final EventLoop callerEventLoop) {
|
||||
final ChannelFuture connectFuture = connectionFactory.getConnectionChannelFuture(callerEventLoop);
|
||||
final Channel channel = connectFuture.channel();
|
||||
channel.attr(CONNECTION_EPOCH).set(new ClosableEpoch(channel::close));
|
||||
openConnections.incrementAndGet();
|
||||
channel.closeFuture().addListener(_ -> openConnections.decrementAndGet());
|
||||
return new PooledConnection(connectFuture, System.nanoTime());
|
||||
}
|
||||
|
||||
/// Whether a pooled connection can still be handed out
|
||||
private boolean isUsable(final PooledConnection pooledConnection) {
|
||||
final ChannelFuture connectionFuture = pooledConnection.connectFuture();
|
||||
if (!connectionFuture.isDone()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final Channel connection = connectionFuture.channel();
|
||||
|
||||
// We know the future is done, see if we actually connected or if we've since disconnected
|
||||
final boolean active = connection.isActive();
|
||||
|
||||
// We might still be connected but have gotten a GOAWAY indicating we shouldn't open new streams
|
||||
final boolean goawayReceived = Boolean.TRUE.equals(connection.attr(GOAWAY_RECEIVED).get());
|
||||
|
||||
// The connection might be fine but old enough that we want a fresh one
|
||||
final boolean retired = System.nanoTime() - pooledConnection.createdNanos() > retireAfterNanos;
|
||||
|
||||
final boolean usable = active && !goawayReceived && !retired;
|
||||
if (!usable) {
|
||||
Metrics.counter(CONNECTION_REPLACED_COUNTER_NAME,
|
||||
"backend", address().toString(),
|
||||
"active", String.valueOf(active),
|
||||
"goaway", String.valueOf(goawayReceived),
|
||||
"retired", String.valueOf(retired))
|
||||
.increment();
|
||||
}
|
||||
return usable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(final Channel connection) {
|
||||
connection.attr(CONNECTION_EPOCH).get().depart();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress address() {
|
||||
return connectionFactory.address();
|
||||
}
|
||||
|
||||
/// Initializes the connection with a large window, and marks a connection as draining when the backend sends a GOAWAY
|
||||
@ChannelHandler.Sharable
|
||||
private static class PooledConnectionHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelActive(final ChannelHandlerContext ctx) {
|
||||
// Every new H2 connection starts with a connection flow-control window of 64K. Each stream on the connection also
|
||||
// starts with a per-stream window of 64K. See https://www.rfc-editor.org/rfc/rfc9113.html#section-6.9.2.
|
||||
//
|
||||
// Because we're pooling many distinct, h2 streams from different remote clients may share this single h2
|
||||
// connection to the backend. So, by default, if a single stream is slow to receive a large response from the
|
||||
// backend, they could consume the entire connection window.
|
||||
//
|
||||
// To avoid this, as soon as we open the connection tell the server we're willing to accept more at the connection
|
||||
// level. We update the connection window to the max value by sending a WINDOW_UPDATE (6.9) to add enough credit
|
||||
// to reach the max connection window size of INT_MAX. The individual streams still retain the default window-size
|
||||
// of 64K.
|
||||
ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE));
|
||||
ctx.fireChannelActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
|
||||
if (msg instanceof Http2GoAwayFrame) {
|
||||
ctx.channel().attr(GOAWAY_RECEIVED).set(true);
|
||||
ReferenceCountUtil.release(msg);
|
||||
return;
|
||||
}
|
||||
ctx.fireChannelRead(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,12 +100,7 @@ public class SniMapper {
|
||||
private static SslContext buildSslContext(final KeyManagerFactory kmf, final SslProvider sslProvider)
|
||||
throws SSLException {
|
||||
|
||||
final SslContextBuilder sslContextBuilder = sslProvider == SslProvider.OPENSSL
|
||||
// work around netty's OpenSSL provider not selecting Ed25519 certificates on its own
|
||||
? SslContextBuilder.forServer(BoringSslServerKeyManager.wrap(kmf.getKeyManagers()))
|
||||
: SslContextBuilder.forServer(kmf);
|
||||
|
||||
return sslContextBuilder
|
||||
return SslContextBuilder.forServer(kmf)
|
||||
.sslProvider(sslProvider)
|
||||
.applicationProtocolConfig(new ApplicationProtocolConfig(
|
||||
ApplicationProtocolConfig.Protocol.ALPN,
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoop;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.local.LocalAddress;
|
||||
import io.netty.channel.local.LocalChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
|
||||
import io.netty.handler.codec.http2.Http2MultiplexHandler;
|
||||
import io.netty.handler.codec.http2.Http2Settings;
|
||||
import io.netty.util.concurrent.EventExecutor;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
|
||||
private static final Logger logger = LoggerFactory.getLogger(UnpooledH2ConnectionFactory.class);
|
||||
|
||||
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
|
||||
new OmnibusExceptionHandler("backend-connection", List.of());
|
||||
private static final String BACKEND_CONNECT_TIMER_NAME = name(UnpooledH2ConnectionFactory.class,
|
||||
"backendConnectDuration");
|
||||
private static final String BACKEND_TAG = "backend";
|
||||
|
||||
|
||||
private final SocketAddress targetAddress;
|
||||
private final Class<? extends Channel> channelClass;
|
||||
private final EventLoopGroup eventLoopGroup;
|
||||
private final Set<EventExecutor> eventLoops;
|
||||
@Nullable
|
||||
private final ChannelHandler connectionHandler;
|
||||
|
||||
public UnpooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
|
||||
this(targetAddress, eventLoopGroup, null);
|
||||
}
|
||||
|
||||
UnpooledH2ConnectionFactory(
|
||||
final SocketAddress targetAddress,
|
||||
final EventLoopGroup eventLoopGroup,
|
||||
@Nullable final ChannelHandler connectionHandler) {
|
||||
this.targetAddress = targetAddress;
|
||||
this.channelClass = targetAddress instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class;
|
||||
this.eventLoopGroup = eventLoopGroup;
|
||||
this.eventLoops = ImmutableSet.copyOf(eventLoopGroup);
|
||||
this.connectionHandler = connectionHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
|
||||
// Make a new H2 connection to the target backend
|
||||
final Timer.Sample connectSample = Timer.start();
|
||||
|
||||
return new Bootstrap()
|
||||
// If the caller is already on one of our event loops, connect on that loop so this connection runs on the
|
||||
// caller's thread
|
||||
.group(eventLoops.contains(callerEventLoop) ? callerEventLoop : eventLoopGroup)
|
||||
.channel(channelClass)
|
||||
.handler(new ChannelInitializer<>() {
|
||||
@Override
|
||||
protected void initChannel(final Channel ch) {
|
||||
ch.pipeline()
|
||||
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
|
||||
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
|
||||
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
|
||||
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
|
||||
if (connectionHandler != null) {
|
||||
ch.pipeline().addLast(connectionHandler);
|
||||
}
|
||||
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
|
||||
}
|
||||
})
|
||||
.connect(targetAddress)
|
||||
.addListener((ChannelFuture connectFuture) ->
|
||||
connectSample.stop(Timer.builder(BACKEND_CONNECT_TIMER_NAME)
|
||||
.tag(BACKEND_TAG, targetAddress.toString())
|
||||
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
|
||||
.register(Metrics.globalRegistry)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(final Channel connection) {
|
||||
// Each connection only ever carries one stream
|
||||
connection.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress address() {
|
||||
return targetAddress;
|
||||
}
|
||||
|
||||
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
|
||||
@Override
|
||||
public void channelRegistered(final ChannelHandlerContext ctx) {
|
||||
logger.error("Inbound stream handler was registered when no inbound streams expected");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
|
||||
super.channelRead(ctx, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -184,7 +184,8 @@ public class KeyTransparencyServiceClient implements Managed {
|
||||
channel = Grpc.newChannelBuilderForAddress(host, port, tlsChannelCredentials)
|
||||
.idleTimeout(1, TimeUnit.MINUTES)
|
||||
.build();
|
||||
stub = KeyTransparencyQueryServiceGrpc.newBlockingStub(channel);
|
||||
stub = KeyTransparencyQueryServiceGrpc.newBlockingStub(channel)
|
||||
.withCompression("gzip");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
|
||||
public class CallNotPermittedExceptionMapper implements ExceptionMapper<CallNotPermittedException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final CallNotPermittedException exception) {
|
||||
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ public final class MessageMetrics {
|
||||
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
|
||||
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
|
||||
|
||||
private static final String SUSPECTED_DELIVERY_LOOP_COUNTER_NAME = name(MessageMetrics.class, "suspectedDeliveryLoop");
|
||||
|
||||
private final MeterRegistry metricRegistry;
|
||||
private final Counter sendMessageCounter;
|
||||
private final Counter bytesSentCounter;
|
||||
@@ -145,4 +147,16 @@ public final class MessageMetrics {
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
|
||||
.register(metricRegistry));
|
||||
}
|
||||
|
||||
public static void recordSuspectedDeliveryLoop(final String channel,
|
||||
@Nullable final UserAgent userAgent,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
final Tags tags = UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
|
||||
.map(Tags::of)
|
||||
.orElseGet(Tags::empty)
|
||||
.and(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
Metrics.counter(SUSPECTED_DELIVERY_LOOP_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.logging.common.AbstractAppenderFactory;
|
||||
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
|
||||
@@ -19,9 +18,6 @@ import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppen
|
||||
@JsonTypeName("otlp")
|
||||
public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
|
||||
|
||||
@JsonProperty
|
||||
private String destination;
|
||||
|
||||
@Override
|
||||
public Appender<ILoggingEvent> build(
|
||||
final LoggerContext context,
|
||||
@@ -32,8 +28,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
|
||||
|
||||
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
|
||||
appender.setCaptureCodeAttributes(true);
|
||||
appender.setCaptureLoggerContext(true);
|
||||
appender.setCaptureLogstashMarkerAttributes(true);
|
||||
appender.setKeyValuePairAttributesIncluded("*");
|
||||
|
||||
// The installation of an OpenTelemetry configuration happens in
|
||||
// WhisperServerService (or CommandDependencies), in order to let us tie
|
||||
|
||||
+4
-6
@@ -8,10 +8,8 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -49,10 +47,10 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
|
||||
accountsManager.getByAccountIdentifier(reporterUuid).ifPresent(reporter -> {
|
||||
final String destinationCountryCode = Util.getCountryCode(reporter);
|
||||
|
||||
logger.info(Markers.appendEntries(Map.of(
|
||||
"sourceCountry", sourceCountryCode,
|
||||
"destinationCountry", destinationCountryCode)),
|
||||
"Message reported");
|
||||
logger.atInfo()
|
||||
.addKeyValue("sourceCountry", sourceCountryCode)
|
||||
.addKeyValue("destinationCountry", destinationCountryCode)
|
||||
.log("Message reported");
|
||||
|
||||
Metrics.counter(REPORTER_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, destinationCountryCode).increment();
|
||||
});
|
||||
|
||||
+19
-3
@@ -15,6 +15,7 @@ import com.apple.itunes.storekit.model.StatusResponse;
|
||||
import com.apple.itunes.storekit.model.TransactionInfoResponse;
|
||||
import com.apple.itunes.storekit.verification.SignedDataVerifier;
|
||||
import com.apple.itunes.storekit.verification.VerificationException;
|
||||
import com.apple.itunes.storekit.verification.VerificationStatus;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
@@ -27,6 +28,7 @@ import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -113,10 +115,10 @@ public class AppleAppStoreClient {
|
||||
default -> throw new IllegalStateException("Unexpected environment: " + environment);
|
||||
};
|
||||
try {
|
||||
return new AppleAppStoreDecodedTransaction(
|
||||
return verifyWithRetry(() -> new AppleAppStoreDecodedTransaction(
|
||||
tx,
|
||||
signedDataVerifier.verifyAndDecodeTransaction(tx.getSignedTransactionInfo()),
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo()));
|
||||
signedDataVerifier.verifyAndDecodeRenewalInfo(tx.getSignedRenewalInfo())));
|
||||
} catch (VerificationException e) {
|
||||
throw new UncheckedIOException(new IOException("Failed to verify payload from App Store Server", e));
|
||||
}
|
||||
@@ -146,7 +148,8 @@ public class AppleAppStoreClient {
|
||||
return Optional.of(lookupByTransactionId(transactionId, errorTags, (environment, txId) -> {
|
||||
try {
|
||||
final TransactionInfoResponse transactionInfo = client(environment).getTransactionInfo(txId);
|
||||
return verifier(environment).verifyAndDecodeTransaction(transactionInfo.getSignedTransactionInfo());
|
||||
return verifyWithRetry(() ->
|
||||
verifier(environment).verifyAndDecodeTransaction(transactionInfo.getSignedTransactionInfo()));
|
||||
} catch (VerificationException e) {
|
||||
throw new IOException("Failed to verify payload from App Store Server", e);
|
||||
}
|
||||
@@ -217,6 +220,16 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T verifyWithRetry(final Callable<T> verification) throws VerificationException {
|
||||
try {
|
||||
return retry.executeCallable(verification);
|
||||
} catch (VerificationException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private AppStoreServerAPIClient client(final Environment environment) {
|
||||
return switch (environment) {
|
||||
case SANDBOX -> sandboxApiClient;
|
||||
@@ -247,6 +260,9 @@ public class AppleAppStoreClient {
|
||||
}
|
||||
|
||||
private static boolean shouldRetry(Throwable e) {
|
||||
if (e instanceof VerificationException verificationException) {
|
||||
return verificationException.getStatus() == VerificationStatus.RETRYABLE_VERIFICATION_FAILURE;
|
||||
}
|
||||
return e instanceof APIException apiException && switch (apiException.getApiError()) {
|
||||
case ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE, GENERAL_INTERNAL_RETRYABLE, APP_NOT_FOUND_RETRYABLE, ACCOUNT_NOT_FOUND_RETRYABLE -> true;
|
||||
case null, default -> false;
|
||||
|
||||
@@ -365,7 +365,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated
|
||||
.setProrationBehavior(ProrationBehavior.NONE)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.builder().setType(BillingCycleAnchor.Type.NOW).build())
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addAllItem(items)
|
||||
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A message availability listener handles message availability and presence events related to a client's open message
|
||||
* stream. Handler methods are run on dedicated threads and may safely perform blocking operations.
|
||||
*
|
||||
* @see RedisMessageAvailabilityManager#handleClientConnected(UUID, byte, MessageAvailabilityListener)
|
||||
*/
|
||||
public interface MessageAvailabilityListener {
|
||||
|
||||
/**
|
||||
* Indicates that a new message is available in the connected client's message queue.
|
||||
*/
|
||||
void handleNewMessageAvailable();
|
||||
|
||||
/**
|
||||
* Indicates that messages for the client have been persisted from short-term storage to long-term storage.
|
||||
*/
|
||||
void handleMessagesPersisted();
|
||||
|
||||
/**
|
||||
* Indicates a newer instance of this client has started reading messages and the listener should close this client's
|
||||
* underlying network connection.
|
||||
*/
|
||||
void handleConflictingMessageConsumer();
|
||||
}
|
||||
+6
-2
@@ -35,9 +35,10 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@@ -99,7 +100,10 @@ public class PushNotificationScheduler implements Managed {
|
||||
Util.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("Exception while processing scheduled notifications", e);
|
||||
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Exception while processing scheduled notifications", e);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(EXCEPTION_PAUSE);
|
||||
|
||||
-358
@@ -1,358 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.push;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.event.ClusterTopologyChangedEvent;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.lettuce.core.cluster.pubsub.RedisClusterPubSubAdapter;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubClusterConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.RedisClusterUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* The Redis message availability manager distributes events related to client presence and message availability to
|
||||
* registered listeners. In the current Signal server implementation, clients generally interact with the service by
|
||||
* opening a dual-purpose WebSocket. The WebSocket serves as both a delivery mechanism for messages and as a channel
|
||||
* for the client to issue API requests to the server. Clients are considered "present" if they have an open WebSocket
|
||||
* connection and are therefore likely to receive messages as soon as they're delivered to the server. Redis message
|
||||
* availability managers ensure that clients have at most one active message delivery channel at a time on a
|
||||
* best-effort basis.
|
||||
*
|
||||
* @implNote The Redis message availability manager uses the Redis 7 sharded pub/sub system to distribute events. This
|
||||
* system makes a best effort to ensure that a given client has only a single open connection across the fleet of
|
||||
* servers, but cannot guarantee at-most-one behavior.
|
||||
*
|
||||
* @see MessageAvailabilityListener
|
||||
* @see org.whispersystems.textsecuregcm.storage.MessagesManager#insert(UUID, Map)
|
||||
*/
|
||||
public class RedisMessageAvailabilityManager extends RedisClusterPubSubAdapter<byte[], byte[]> implements Managed {
|
||||
|
||||
private final FaultTolerantRedisClusterClient clusterClient;
|
||||
private final Executor listenerEventExecutor;
|
||||
|
||||
// Note that this MUST be a single-threaded executor; its function is to process tasks that should usually be
|
||||
// non-blocking, but can rarely block, and do so in the order in which those tasks were submitted.
|
||||
private final Executor asyncOperationQueueingExecutor;
|
||||
|
||||
@Nullable
|
||||
private FaultTolerantPubSubClusterConnection<byte[], byte[]> pubSubConnection;
|
||||
|
||||
private final Map<AccountAndDeviceIdentifier, MessageAvailabilityListener> listenersByAccountAndDeviceIdentifier;
|
||||
|
||||
private final UUID serverId = UUID.randomUUID();
|
||||
|
||||
private final byte[] CLIENT_CONNECTED_EVENT_BYTES = ClientEvent.newBuilder()
|
||||
.setClientConnected(ClientConnectedEvent.newBuilder()
|
||||
.setServerId(UUIDUtil.toByteString(serverId))
|
||||
.build())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
private static final Counter PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "publishClientConnectionEventError"));
|
||||
|
||||
private static final Counter UNSUBSCRIBE_ERROR_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "unsubscribeError"));
|
||||
|
||||
private static final Counter PUB_SUB_EVENT_WITHOUT_LISTENER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "pubSubEventWithoutListener"));
|
||||
|
||||
private static final Counter MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(RedisMessageAvailabilityManager.class, "messageAvailableWithoutListener"));
|
||||
|
||||
private static final String LISTENER_GAUGE_NAME =
|
||||
MetricsUtil.name(RedisMessageAvailabilityManager.class, "listeners");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RedisMessageAvailabilityManager.class);
|
||||
|
||||
@VisibleForTesting
|
||||
record AccountAndDeviceIdentifier(UUID accountIdentifier, byte deviceId) {
|
||||
}
|
||||
|
||||
public RedisMessageAvailabilityManager(final FaultTolerantRedisClusterClient clusterClient,
|
||||
final Executor listenerEventExecutor,
|
||||
final Executor asyncOperationQueueingExecutor) {
|
||||
|
||||
this.clusterClient = clusterClient;
|
||||
this.listenerEventExecutor = listenerEventExecutor;
|
||||
this.asyncOperationQueueingExecutor = asyncOperationQueueingExecutor;
|
||||
|
||||
this.listenersByAccountAndDeviceIdentifier =
|
||||
Metrics.gaugeMapSize(LISTENER_GAUGE_NAME, Tags.empty(), new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start() {
|
||||
this.pubSubConnection = clusterClient.createBinaryPubSubConnection();
|
||||
this.pubSubConnection.usePubSubConnection(connection -> connection.addListener(this));
|
||||
|
||||
pubSubConnection.subscribeToClusterTopologyChangedEvents(this::resubscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
if (pubSubConnection != null) {
|
||||
pubSubConnection.usePubSubConnection(connection -> {
|
||||
connection.removeListener(this);
|
||||
connection.close();
|
||||
});
|
||||
}
|
||||
|
||||
pubSubConnection = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the given device as "present" for message delivery and registers a listener for new messages and conflicting
|
||||
* connections. If the given device already has a presence registered with this manager, that presence is displaced
|
||||
* immediately and the listener's {@link MessageAvailabilityListener#handleConflictingMessageConsumer()} method is called.
|
||||
*
|
||||
* @param accountIdentifier the account identifier for the newly-connected device
|
||||
* @param deviceId the ID of the newly-connected device within the given account
|
||||
* @param listener the listener to notify when new messages or conflicting connections arrive for the newly-connected
|
||||
* device
|
||||
*
|
||||
* @return a future that completes when the new device's presence has been registered; the future may fail if a
|
||||
* pub/sub subscription could not be established, in which case callers should close the client's connection to the
|
||||
* server
|
||||
*/
|
||||
public CompletionStage<Void> handleClientConnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("WebSocket connection event manager not started");
|
||||
}
|
||||
|
||||
final byte[] eventChannel = getClientEventChannel(accountIdentifier, deviceId);
|
||||
final AtomicReference<MessageAvailabilityListener> displacedListener = new AtomicReference<>();
|
||||
final AtomicReference<CompletionStage<Void>> subscribeFuture = new AtomicReference<>();
|
||||
|
||||
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
|
||||
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
|
||||
//
|
||||
// > The entire method invocation is performed atomically. The supplied function is invoked exactly once per
|
||||
// > invocation of this method. Some attempted update operations on this map by other threads may be blocked while
|
||||
// > computation is in progress, so the computation should be short and simple.
|
||||
//
|
||||
// This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order
|
||||
// as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued
|
||||
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
|
||||
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
|
||||
(key, existingListener) -> {
|
||||
subscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().ssubscribe(eventChannel)), asyncOperationQueueingExecutor)
|
||||
.thenCompose(Function.identity()));
|
||||
|
||||
if (existingListener != null) {
|
||||
displacedListener.set(existingListener);
|
||||
}
|
||||
|
||||
return listener;
|
||||
});
|
||||
|
||||
if (displacedListener.get() != null) {
|
||||
listenerEventExecutor.execute(() -> displacedListener.get().handleConflictingMessageConsumer());
|
||||
}
|
||||
|
||||
return subscribeFuture.get()
|
||||
.thenCompose(_ -> clusterClient.withBinaryCluster(connection -> connection.async()
|
||||
.spublish(eventChannel, CLIENT_CONNECTED_EVENT_BYTES))
|
||||
.handle((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
PUBLISH_CLIENT_CONNECTION_EVENT_ERROR_COUNTER.increment();
|
||||
}
|
||||
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a "presence" and event listener for the given device if it is still the active listener. Callers should call this method when the client's
|
||||
* underlying network connection has closed.
|
||||
*
|
||||
* @param accountIdentifier the identifier of the account for the disconnected device
|
||||
* @param deviceId the ID of the disconnected device within the given account
|
||||
*
|
||||
* @return a future that completes when the presence and event listener have been removed
|
||||
*/
|
||||
public CompletionStage<Void> handleClientDisconnected(final UUID accountIdentifier, final byte deviceId, final MessageAvailabilityListener listener) {
|
||||
if (pubSubConnection == null) {
|
||||
throw new IllegalStateException("WebSocket connection event manager not started");
|
||||
}
|
||||
|
||||
final AtomicReference<CompletionStage<Void>> unsubscribeFuture = new AtomicReference<>(CompletableFuture.completedFuture(null));
|
||||
|
||||
// Note that we're relying on some specific implementation details of `ConcurrentHashMap#compute(...)`. In
|
||||
// particular, the behavioral contract for `ConcurrentHashMap#compute(...)` says:
|
||||
//
|
||||
// > The entire method invocation is performed atomically. The supplied function is invoked exactly once per
|
||||
// > invocation of this method. Some attempted update operations on this map by other threads may be blocked while
|
||||
// > computation is in progress, so the computation should be short and simple.
|
||||
//
|
||||
// This provides a mechanism to make sure that we enqueue subscription/unsubscription operations in the same order
|
||||
// as adding/removing listeners from the map and helps us avoid races and conflicts. Note that the enqueued
|
||||
// operation is asynchronous; we're not blocking on it in the scope of the `compute` operation.
|
||||
listenersByAccountAndDeviceIdentifier.compute(new AccountAndDeviceIdentifier(accountIdentifier, deviceId),
|
||||
(ignored, existingListener) -> {
|
||||
if (listener != existingListener) {
|
||||
// the listener was already replaced, ignore this event completely
|
||||
return existingListener;
|
||||
}
|
||||
|
||||
unsubscribeFuture.set(CompletableFuture.supplyAsync(() -> pubSubConnection.withPubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountIdentifier, deviceId)))
|
||||
.thenRun(Util.NOOP), asyncOperationQueueingExecutor)
|
||||
.thenCompose(Function.identity()));
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return unsubscribeFuture.get().whenComplete((ignored, throwable) -> {
|
||||
if (throwable != null) {
|
||||
UNSUBSCRIBE_ERROR_COUNTER.increment();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether a client with the given account/device is connected to this manager instance.
|
||||
*
|
||||
* @param accountUuid the account identifier for the client to check
|
||||
* @param deviceId the ID of the device within the given account
|
||||
*
|
||||
* @return {@code true} if a client with the given account/device is connected to this manager instance or
|
||||
* {@code false} if the client is not connected at all or is connected to a different manager instance
|
||||
*/
|
||||
public boolean isLocallyPresent(final UUID accountUuid, final byte deviceId) {
|
||||
return listenersByAccountAndDeviceIdentifier.containsKey(new AccountAndDeviceIdentifier(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void resubscribe(final ClusterTopologyChangedEvent clusterTopologyChangedEvent) {
|
||||
final boolean[] changedSlots = RedisClusterUtil.getChangedSlots(clusterTopologyChangedEvent);
|
||||
|
||||
final Map<Integer, List<byte[]>> eventChannelsBySlot = new HashMap<>();
|
||||
|
||||
// Organize subscriptions by slot so we can issue a smaller number of larger resubscription commands
|
||||
listenersByAccountAndDeviceIdentifier.keySet()
|
||||
.stream()
|
||||
.map(accountAndDeviceIdentifier -> getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(), accountAndDeviceIdentifier.deviceId()))
|
||||
.forEach(clientEventChannel -> {
|
||||
final int slot = SlotHash.getSlot(clientEventChannel);
|
||||
|
||||
if (changedSlots[slot]) {
|
||||
eventChannelsBySlot.computeIfAbsent(slot, ignored -> new ArrayList<>()).add(clientEventChannel);
|
||||
}
|
||||
});
|
||||
|
||||
// Issue one resubscription command per affected slot
|
||||
eventChannelsBySlot.forEach((slot, eventChannels) -> {
|
||||
if (pubSubConnection != null) {
|
||||
pubSubConnection.usePubSubConnection(connection ->
|
||||
connection.sync().ssubscribe(eventChannels.toArray(byte[][]::new)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribes for notifications for the given account and device identifier if and only if no listener is registered
|
||||
* for that account and device identifier.
|
||||
*
|
||||
* @param accountAndDeviceIdentifier the account and device identifier for which to stop receiving notifications
|
||||
*/
|
||||
void unsubscribeIfMissingListener(final AccountAndDeviceIdentifier accountAndDeviceIdentifier) {
|
||||
listenersByAccountAndDeviceIdentifier.compute(accountAndDeviceIdentifier, (ignored, existingListener) -> {
|
||||
if (existingListener == null && pubSubConnection != null) {
|
||||
// Enqueue, but do not block on, an "unsubscribe" operation
|
||||
asyncOperationQueueingExecutor.execute(() -> pubSubConnection.usePubSubConnection(connection ->
|
||||
connection.async().sunsubscribe(getClientEventChannel(accountAndDeviceIdentifier.accountIdentifier(),
|
||||
accountAndDeviceIdentifier.deviceId()))));
|
||||
}
|
||||
|
||||
// Make no change to the existing listener whether present or absent
|
||||
return existingListener;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void smessage(final RedisClusterNode node, final byte[] shardChannel, final byte[] message) {
|
||||
final ClientEvent clientEvent;
|
||||
|
||||
try {
|
||||
clientEvent = ClientEvent.parseFrom(message);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.error("Failed to parse pub/sub event protobuf", e);
|
||||
return;
|
||||
}
|
||||
|
||||
final AccountAndDeviceIdentifier accountAndDeviceIdentifier = parseClientEventChannel(shardChannel);
|
||||
|
||||
@Nullable final MessageAvailabilityListener listener =
|
||||
listenersByAccountAndDeviceIdentifier.get(accountAndDeviceIdentifier);
|
||||
|
||||
if (listener != null) {
|
||||
switch (clientEvent.getEventCase()) {
|
||||
case NEW_MESSAGE_AVAILABLE -> listener.handleNewMessageAvailable();
|
||||
|
||||
case CLIENT_CONNECTED -> {
|
||||
// Only act on new connections to other event manager instances; we'll learn about displacements in THIS
|
||||
// instance when we update the listener map in `handleClientConnected`
|
||||
if (!this.serverId.equals(UUIDUtil.fromByteString(clientEvent.getClientConnected().getServerId()))) {
|
||||
listenerEventExecutor.execute(listener::handleConflictingMessageConsumer);
|
||||
}
|
||||
}
|
||||
|
||||
case MESSAGES_PERSISTED -> listenerEventExecutor.execute(listener::handleMessagesPersisted);
|
||||
|
||||
default -> logger.warn("Unexpected client event type: {}", clientEvent.getClass());
|
||||
}
|
||||
} else {
|
||||
PUB_SUB_EVENT_WITHOUT_LISTENER_COUNTER.increment();
|
||||
|
||||
listenerEventExecutor.execute(() -> unsubscribeIfMissingListener(accountAndDeviceIdentifier));
|
||||
|
||||
if (clientEvent.getEventCase() == ClientEvent.EventCase.NEW_MESSAGE_AVAILABLE) {
|
||||
MESSAGE_AVAILABLE_WITHOUT_LISTENER_COUNTER.increment();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] getClientEventChannel(final UUID accountIdentifier, final byte deviceId) {
|
||||
return ("client_presence::{" + accountIdentifier + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static AccountAndDeviceIdentifier parseClientEventChannel(final byte[] eventChannelBytes) {
|
||||
final String eventChannel = new String(eventChannelBytes, StandardCharsets.UTF_8);
|
||||
final int uuidStart = "client_presence::{".length();
|
||||
|
||||
final UUID accountIdentifier = UUID.fromString(eventChannel.substring(uuidStart, uuidStart + 36));
|
||||
final byte deviceId = Byte.parseByte(eventChannel.substring(uuidStart + 38, eventChannel.length() - 1));
|
||||
|
||||
return new AccountAndDeviceIdentifier(accountIdentifier, deviceId);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ClusterLuaScript {
|
||||
@@ -109,7 +110,9 @@ public class ClusterLuaScript {
|
||||
return connection.sync().eval(script, scriptOutputType, keys, args);
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to execute script", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
log.warn("Failed to execute script", e);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -123,7 +126,9 @@ public class ClusterLuaScript {
|
||||
return connection.async().eval(script, scriptOutputType, keys, args);
|
||||
}
|
||||
|
||||
log.warn("Failed to execute script", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
log.warn("Failed to execute script", throwable);
|
||||
}
|
||||
throw new RedisException(throwable);
|
||||
}).toCompletableFuture();
|
||||
}
|
||||
@@ -133,6 +138,10 @@ public class ClusterLuaScript {
|
||||
|
||||
return connection.reactive().evalsha(sha, scriptOutputType, keys, args)
|
||||
.onErrorResume(RedisNoScriptException.class, _ -> connection.reactive().eval(script, scriptOutputType, keys, args))
|
||||
.doOnError(throwable -> log.warn("Failed to execute script", throwable));
|
||||
.doOnError(throwable -> {
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
log.warn("Failed to execute script", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -170,22 +170,22 @@ public class RegistrationServiceClient implements Managed {
|
||||
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED ->
|
||||
throw RegistrationServiceSenderException.rejected(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.rejected(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
|
||||
throw new RegistrationFraudException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
|
||||
RegistrationServiceSenderException.rejected(!response.getError().getMayRetry()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT ->
|
||||
throw RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.illegalArgument(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED ->
|
||||
throw RegistrationServiceSenderException.unknown(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.unknown(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED ->
|
||||
throw new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE ->
|
||||
throw RegistrationServiceSenderException.unavailable(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.unavailable(!response.getError().getMayRetry());
|
||||
|
||||
default -> throw new RuntimeException("Failed to send verification code: " + response.getError().getErrorType());
|
||||
}
|
||||
|
||||
+62
-8
@@ -71,6 +71,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyResult;
|
||||
@@ -818,7 +819,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
connection.async().set(key, deviceInfoJson, SetArgs.Builder.ex(RECENTLY_ADDED_DEVICE_TTL))))
|
||||
.whenComplete((_, pubSubThrowable) -> {
|
||||
if (pubSubThrowable != null) {
|
||||
logger.warn("Failed to record recently-created device", pubSubThrowable);
|
||||
if (!ExceptionUtils.isBreakerOpen(pubSubThrowable)) {
|
||||
logger.warn("Failed to record recently-created device", pubSubThrowable);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1375,6 +1378,43 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets a new password for the given device and requests disconnection for all authenticated device connections.
|
||||
///
|
||||
///
|
||||
/// @return `true` if the password was changed or `false` if the device no longer exists or its credentials
|
||||
/// have been locked
|
||||
public boolean updateDevicePassword(final UUID accountIdentifier, final byte deviceId, final String newPassword) {
|
||||
|
||||
final SaltedTokenHash newCredentials = SaltedTokenHash.generateFor(newPassword);
|
||||
|
||||
final Account updatedAccount = update(accountIdentifier, a -> {
|
||||
|
||||
final Optional<Device> maybeDevice = a.getDevice(deviceId);
|
||||
|
||||
return maybeDevice.map(d -> {
|
||||
|
||||
if (d.hasLockedCredentials()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
d.setAuthTokenHash(newCredentials);
|
||||
|
||||
return true;
|
||||
|
||||
}).orElse(false);
|
||||
});
|
||||
|
||||
final boolean passwordChanged = updatedAccount.getDevice(deviceId)
|
||||
.map(d -> d.getAuthTokenHash().equals(newCredentials))
|
||||
.orElse(false);
|
||||
|
||||
if (passwordChanged) {
|
||||
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
|
||||
}
|
||||
|
||||
return passwordChanged;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param accountIdentifier identifier of account to update
|
||||
* @param updater must return {@code true} if the account was actually updated
|
||||
@@ -1565,7 +1605,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
DELETION_REASON_TAG_NAME, deletionReason.tagValue)
|
||||
.increment();
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Failed to delete account", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to delete account", e);
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
sample.stop(deleteTimer);
|
||||
@@ -1658,7 +1700,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
try {
|
||||
account.ifPresent(this::redisSet);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return account;
|
||||
@@ -1679,7 +1723,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
.thenCompose(maybeAccountFromAccounts -> maybeAccountFromAccounts
|
||||
.map(account -> redisSetAsync(account)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(RedisException.class, e -> {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved account", e);
|
||||
}
|
||||
return null;
|
||||
}))
|
||||
.thenApply(ignored -> maybeAccountFromAccounts))
|
||||
@@ -1697,7 +1743,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
logger.warn("Deserialization error", e);
|
||||
return Optional.empty();
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed fetching account from cache by secondary key", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed fetching account from cache by secondary key", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
@@ -1715,7 +1763,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
}
|
||||
})
|
||||
.exceptionally(throwable -> {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
}
|
||||
return Optional.empty();
|
||||
})
|
||||
.whenComplete((_, _) -> sample.stop(timer))
|
||||
@@ -1729,7 +1779,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
|
||||
return parseAccountJson(json, uuid);
|
||||
} catch (final RedisException e) {
|
||||
logger.warn("Failed to retrieve account from cache", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to retrieve account from cache", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
});
|
||||
@@ -1739,7 +1791,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
return cacheCluster.withCluster(connection -> connection.async().get(getAccountEntityKey(uuid)))
|
||||
.thenApply(accountJson -> parseAccountJson(accountJson, uuid))
|
||||
.exceptionally(throwable -> {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to retrieve account from Redis", throwable);
|
||||
}
|
||||
return Optional.empty();
|
||||
})
|
||||
.toCompletableFuture();
|
||||
|
||||
+18
-8
@@ -7,34 +7,42 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
|
||||
public class ConcatenatingMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final DynamoDbMessageStream dynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
|
||||
private final AtomicBoolean shouldDeleteFromDynamoDb = new AtomicBoolean(false);
|
||||
|
||||
private static final Counter CONFLICTING_CONSUMER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(ConcatenatingMessageStream.class, "conflictingConsumer"));
|
||||
|
||||
public ConcatenatingMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
public ConcatenatingMessageStream(final DynamoDbMessageStream dynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.dynamoDbMessageStream = dynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Flux.concat(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages()),
|
||||
JdkFlowAdapter.flowPublisherToFlux(dynamoDbMessageStream.getMessages())
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
|
||||
shouldDeleteFromDynamoDb.set(true);
|
||||
}
|
||||
}),
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages()))
|
||||
.doOnError(throwable -> {
|
||||
if (ExceptionUtils.unwrap(throwable) instanceof ConflictingMessageConsumerException) {
|
||||
@@ -46,7 +54,9 @@ public class ConcatenatingMessageStream implements MessageStream {
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
return CompletableFuture.allOf(
|
||||
redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp),
|
||||
shouldDeleteFromDynamoDb.get()
|
||||
? dynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
: CompletableFuture.completedFuture(null),
|
||||
messageGuid.version() == 8
|
||||
? foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
: CompletableFuture.completedFuture(null));
|
||||
|
||||
+4
-2
@@ -17,9 +17,11 @@ public enum DeviceCapability {
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SELF, false, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, true, true),
|
||||
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, false, false),
|
||||
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false),
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false);
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false),
|
||||
REPLY_PRIVATELY("replyPrivately", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
|
||||
CONTACT_DELETE("contactDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
|
||||
ADMIN_REMOVE_AND_DELETE("adminRemoveAndDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false);
|
||||
|
||||
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
|
||||
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
/// A [MessageStream] implementation that produces messages from a DynamoDB message store.
|
||||
public class DynamoDbMessageStream implements MessageStream {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
private static final String MESSAGE_READ_COUNTER_NAME =
|
||||
name(DynamoDbMessageStream.class, "messagesRead");
|
||||
|
||||
private static final String MESSAGE_ACKNOWLEDGED_COUNTER_NAME =
|
||||
name(DynamoDbMessageStream.class, "messagesAcknowledged");
|
||||
|
||||
private static final String UUID_VERSION_TAG = "uuidVersion";
|
||||
|
||||
public DynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
|
||||
final UUID accountIdentifier,
|
||||
final Device device) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Flux.from(messagesDynamoDb.load(accountIdentifier, device, null))
|
||||
.doOnNext(envelope -> {
|
||||
final UUID messageGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
|
||||
|
||||
Metrics.counter(MESSAGE_READ_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
|
||||
.increment();
|
||||
})
|
||||
.map(MessageStreamEntry.Envelope::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
Metrics.counter(MESSAGE_ACKNOWLEDGED_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
|
||||
.increment();
|
||||
|
||||
return messagesDynamoDb.deleteMessage(accountIdentifier, device, messageGuid, serverTimestamp)
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
/*
|
||||
* Copyright 2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
public class MessagePersistenceException extends Exception {
|
||||
|
||||
public MessagePersistenceException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,405 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.LongTaskTimer;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.util.function.Tuples;
|
||||
import reactor.util.retry.Retry;
|
||||
import reactor.util.retry.RetryBackoffSpec;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
|
||||
|
||||
public class MessagePersister implements Managed {
|
||||
|
||||
private final MessagesCache messagesCache;
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Scheduler persistQueueScheduler;
|
||||
private final Clock clock;
|
||||
|
||||
private final Duration persistDelay;
|
||||
private final int maxConcurrency;
|
||||
private final int scanCount;
|
||||
|
||||
private final RetryBackoffSpec retryBackoffSpec;
|
||||
|
||||
private final String persisterId = UUID.randomUUID().toString();
|
||||
|
||||
private volatile boolean running;
|
||||
|
||||
@Nullable
|
||||
private Thread workerThread;
|
||||
|
||||
private static final String INSPECTED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "inspectedQueue");
|
||||
|
||||
private static final String OVERSIZED_QUEUE_COUNTER_NAME = name(MessagePersister.class, "persistQueueOversized");
|
||||
private static final String PERSISTED_MESSAGE_COUNTER_NAME = name(MessagePersister.class, "persistMessage");
|
||||
private static final String PERSISTED_BYTES_COUNTER_NAME = name(MessagePersister.class, "persistBytes");
|
||||
|
||||
private static final Timer PERSIST_QUEUE_TIMER = Metrics.timer(name(MessagePersister.class, "persistQueue"));
|
||||
private static final Counter TRIMMED_MESSAGE_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessage"));
|
||||
private static final Counter TRIMMED_MESSAGE_BYTES_COUNTER = Metrics.counter(name(MessagePersister.class, "trimmedMessageBytes"));
|
||||
|
||||
private static final Counter PERSIST_NODE_COUNTER = Metrics.counter(name(MessagePersister.class, "persistNodeCount"));
|
||||
private static final LongTaskTimer PERSIST_NODE_TIMER = Metrics.more().longTaskTimer(name(MessagePersister.class, "persistNode"));
|
||||
|
||||
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(MessagePersister.class, "queueSize");
|
||||
|
||||
static final int QUEUE_BATCH_LIMIT = 100;
|
||||
static final int MESSAGE_BATCH_LIMIT = 100;
|
||||
|
||||
private static final DistributionSummary QUEUE_COUNT_DISTRIBUTION_SUMMARY =
|
||||
DistributionSummary.builder(name(MessagePersister.class, "queueCount"))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final long EXCEPTION_PAUSE_MILLIS = Duration.ofSeconds(3).toMillis();
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int maxConcurrency,
|
||||
final int scanCount) {
|
||||
|
||||
this(messagesCache,
|
||||
messagesManager,
|
||||
accountsManager,
|
||||
dynamicConfigurationManager,
|
||||
persistQueueScheduler,
|
||||
clock,
|
||||
persistDelay,
|
||||
maxConcurrency,
|
||||
scanCount,
|
||||
Retry.backoff(3, Duration.ofSeconds(1)));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessagePersister(final MessagesCache messagesCache,
|
||||
final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Scheduler persistQueueScheduler,
|
||||
final Clock clock,
|
||||
final Duration persistDelay,
|
||||
final int maxConcurrency,
|
||||
final int scanCount,
|
||||
final RetryBackoffSpec retryBackoffSpec) {
|
||||
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.clock = clock;
|
||||
this.persistDelay = persistDelay;
|
||||
this.maxConcurrency = maxConcurrency;
|
||||
this.scanCount = scanCount;
|
||||
this.retryBackoffSpec = retryBackoffSpec;
|
||||
this.persistQueueScheduler = persistQueueScheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start() {
|
||||
running = true;
|
||||
|
||||
workerThread = new Thread(() -> {
|
||||
while (running) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().isPersistenceEnabled()) {
|
||||
try {
|
||||
final int queuesPersisted = persistNextNode();
|
||||
QUEUE_COUNT_DISTRIBUTION_SUMMARY.record(queuesPersisted);
|
||||
|
||||
if (queuesPersisted == 0) {
|
||||
Util.sleep(100);
|
||||
}
|
||||
} catch (final Throwable t) {
|
||||
logger.warn("Failed to persist queues", t);
|
||||
Util.sleep(EXCEPTION_PAUSE_MILLIS);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Persisters work through nodes quickly, and running in a hot loop taxes Redis nodes unnecessarily
|
||||
Thread.sleep(dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getSleepBetweenNodes());
|
||||
} catch (final InterruptedException _) {
|
||||
}
|
||||
}
|
||||
}, "MessagePersister");
|
||||
|
||||
workerThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
|
||||
if (workerThread != null) {
|
||||
try {
|
||||
workerThread.join();
|
||||
} catch (final InterruptedException e) {
|
||||
logger.warn("Interrupted while waiting for worker thread to complete current operation");
|
||||
}
|
||||
|
||||
workerThread = null;
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int persistNextNode() {
|
||||
final RedisClusterNode node;
|
||||
{
|
||||
final Duration nodeClaimTtl =
|
||||
dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration().getNodeClaimTtl();
|
||||
|
||||
final Optional<RedisClusterNode> maybeNode = messagesCache.claimNextNodeToPersist(persisterId, nodeClaimTtl);
|
||||
|
||||
if (maybeNode.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
node = maybeNode.get();
|
||||
}
|
||||
|
||||
try {
|
||||
return persistNode(node);
|
||||
} finally {
|
||||
messagesCache.releaseNodeClaim(node, persisterId);
|
||||
}
|
||||
}
|
||||
|
||||
int persistNode(final RedisClusterNode node) {
|
||||
final LongTaskTimer.Sample sample = PERSIST_NODE_TIMER.start();
|
||||
|
||||
try {
|
||||
final Tags tags = Tags.of("node", node.getUri().getHost());
|
||||
|
||||
return messagesCache.getQueues(node, scanCount)
|
||||
.filter(_ -> dynamicConfigurationManager.getConfiguration().getMessagePersisterConfiguration()
|
||||
.isPersistenceEnabled())
|
||||
.flatMap(queueKey -> Mono.defer(() -> shouldPersistQueue(queueKey))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to determine whether queue {} should be persisted", queueKey, e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.mapNotNull(shouldPersist -> shouldPersist ? queueKey : null)
|
||||
.doOnTerminate(() -> Metrics.counter(INSPECTED_QUEUE_COUNTER_NAME, tags).increment()), maxConcurrency)
|
||||
.distinct()
|
||||
.flatMap(queueKey -> {
|
||||
final UUID accountIdentifier = MessagesCache.getAccountUuidFromQueueName(queueKey);
|
||||
final byte deviceId = MessagesCache.getDeviceIdFromQueueName(queueKey);
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(accountIdentifier))
|
||||
.map(maybeAccount -> maybeAccount
|
||||
.flatMap(account -> account.getDevice(deviceId))
|
||||
.map(device -> Tuples.of(maybeAccount.get(), device)))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to fetch account/device for queue: {}", queueKey, e);
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.flatMap(accountAndDevice -> {
|
||||
final Account account = accountAndDevice.getT1();
|
||||
final Device device = accountAndDevice.getT2();
|
||||
|
||||
return persistQueue(account, device, tags)
|
||||
.thenReturn(1)
|
||||
.retryWhen(retryBackoffSpec
|
||||
// Don't retry with backoff for persistence exceptions
|
||||
.filter(e -> !(e instanceof MessagePersistenceException)))
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry",
|
||||
account.getAccountIdentifier(), device.getId(), node.getUri().getHost(), e);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
}, maxConcurrency)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Unhandled error while persisting messages", e);
|
||||
return Mono.empty();
|
||||
})
|
||||
.count()
|
||||
.blockOptional()
|
||||
.map(Math::toIntExact)
|
||||
.orElse(0);
|
||||
} finally {
|
||||
sample.stop();
|
||||
PERSIST_NODE_COUNTER.increment();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Mono<Void> persistQueue(final Account account, final Device device, final Tags baseTags) {
|
||||
final UUID accountUuid = account.getAccountIdentifier();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device)
|
||||
.map(platform -> platform.name().toLowerCase(Locale.ROOT))
|
||||
.orElse("unknown"));
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final Tags tags = baseTags.and(platformTag);
|
||||
|
||||
return Flux.usingWhen(
|
||||
messagesCache.lockQueueForPersistence(accountUuid, deviceId)
|
||||
.thenReturn(true),
|
||||
_ -> Flux.from(messagesCache.getMessagesToPersist(accountUuid, deviceId))
|
||||
.buffer(MESSAGE_BATCH_LIMIT)
|
||||
.flatMap(messages -> {
|
||||
final int urgentMessageCount = (int) messages.stream().filter(MessageProtos.Envelope::getUrgent).count();
|
||||
final int nonUrgentMessageCount = messages.size() - urgentMessageCount;
|
||||
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "true")).increment(urgentMessageCount);
|
||||
Metrics.counter(PERSISTED_MESSAGE_COUNTER_NAME, tags.and("urgent", "false")).increment(nonUrgentMessageCount);
|
||||
Metrics.counter(PERSISTED_BYTES_COUNTER_NAME, tags)
|
||||
.increment(messages.stream().mapToInt(MessageProtos.Envelope::getSerializedSize).sum());
|
||||
|
||||
return Mono.fromRunnable(() -> messagesManager.persistMessages(accountUuid, device, messages))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.thenReturn(messages.size());
|
||||
}, 1)
|
||||
.reduce(0, Integer::sum)
|
||||
.onErrorResume(ItemCollectionSizeLimitExceededException.class, _ -> {
|
||||
final boolean isPrimary = deviceId == Device.PRIMARY_ID;
|
||||
Metrics.counter(OVERSIZED_QUEUE_COUNTER_NAME, "primary", String.valueOf(isPrimary)).increment();
|
||||
// may throw, in which case we'll retry later by the usual mechanism
|
||||
if (isPrimary) {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
|
||||
account.getAccountIdentifier(), deviceId);
|
||||
|
||||
return trimQueue(account, device)
|
||||
.then(Mono.error(new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed")));
|
||||
} else {
|
||||
logger.warn("Failed to persist queue {}::{} due to overfull queue; will unlink device", accountUuid, deviceId);
|
||||
|
||||
return Mono.fromRunnable(() -> accountsManager.removeDevice(accountUuid, deviceId))
|
||||
.subscribeOn(persistQueueScheduler)
|
||||
.then(Mono.empty());
|
||||
}
|
||||
})
|
||||
.doOnSuccess(messagesPersisted -> {
|
||||
if (messagesPersisted != null) {
|
||||
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
|
||||
.tags(Tags.of(platformTag))
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(messagesPersisted);
|
||||
}
|
||||
})
|
||||
.doOnTerminate(() -> sample.stop(PERSIST_QUEUE_TIMER)),
|
||||
_ -> messagesCache.unlockQueueForPersistence(accountUuid, deviceId))
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Void> trimQueue(final Account account, final Device device) {
|
||||
final UUID aci = account.getAccountIdentifier();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
|
||||
.getMessagePersisterConfiguration()
|
||||
.getTrimOversizedQueueExtraRoomRatio();
|
||||
|
||||
final AtomicLong oldestMessage = new AtomicLong(0L);
|
||||
final AtomicLong newestMessage = new AtomicLong(0L);
|
||||
final AtomicLong bytesDeleted = new AtomicLong(0L);
|
||||
|
||||
final AtomicLong cachedMessageBytes = new AtomicLong(0L);
|
||||
final AtomicLong targetDeleteBytes = new AtomicLong(0L);
|
||||
|
||||
return Mono.fromFuture(() -> messagesCache.estimatePersistedQueueSizeBytes(aci, deviceId))
|
||||
.flatMap(estimatedPersistedQueueSize -> {
|
||||
cachedMessageBytes.set(estimatedPersistedQueueSize);
|
||||
targetDeleteBytes.set(Math.round(estimatedPersistedQueueSize * extraRoomRatio));
|
||||
|
||||
return Flux.from(messagesManager.getMessagesForDevice(aci, device))
|
||||
.concatMap(envelope -> {
|
||||
if (bytesDeleted.getAndAdd(envelope.getSerializedSize()) >= targetDeleteBytes.get()) {
|
||||
return Mono.just(Optional.<MessageProtos.Envelope>empty());
|
||||
}
|
||||
oldestMessage.compareAndSet(0L, envelope.getServerTimestamp());
|
||||
newestMessage.set(envelope.getServerTimestamp());
|
||||
return Mono.just(Optional.of(envelope));
|
||||
})
|
||||
.takeWhile(Optional::isPresent)
|
||||
.flatMap(maybeEnvelope -> {
|
||||
// We know this must be present because we `takeWhile` values are present
|
||||
final MessageProtos.Envelope envelope = maybeEnvelope.orElseThrow(AssertionError::new);
|
||||
TRIMMED_MESSAGE_COUNTER.increment();
|
||||
TRIMMED_MESSAGE_BYTES_COUNTER.increment(envelope.getSerializedSize());
|
||||
return Mono
|
||||
.fromCompletionStage(() -> messagesManager
|
||||
.delete(aci, device, UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()))
|
||||
.retryWhen(retryBackoffSpec)
|
||||
.map(Optional::isPresent);
|
||||
})
|
||||
.reduce(Pair.of(0L, 0L), (acc, deleted) -> deleted
|
||||
? Pair.of(acc.getLeft() + 1, acc.getRight())
|
||||
: Pair.of(acc.getLeft(), acc.getRight() + 1));
|
||||
})
|
||||
.doOnSuccess(outcomes -> {
|
||||
if (outcomes != null) {
|
||||
logger.warn(
|
||||
"Finished trimming {}:{}. Oldest message = {}, newest message = {}. Attempted to delete {} persisted bytes to make room for {} cached message bytes. Delete outcomes: {} present, {} missing.",
|
||||
aci, deviceId,
|
||||
Instant.ofEpochMilli(oldestMessage.get()), Instant.ofEpochMilli(newestMessage.get()),
|
||||
targetDeleteBytes, cachedMessageBytes,
|
||||
outcomes.getLeft(), outcomes.getRight());
|
||||
}
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Mono<Boolean> shouldPersistQueue(final String queueKey) {
|
||||
return messagesCache.getEarliestUndeliveredTimestamp(
|
||||
MessagesCache.getAccountUuidFromQueueName(queueKey),
|
||||
MessagesCache.getDeviceIdFromQueueName(queueKey))
|
||||
.map(oldestMessageTimestamp ->
|
||||
Duration.between(Instant.ofEpochMilli(oldestMessageTimestamp), clock.instant()).compareTo(persistDelay) > 0)
|
||||
.switchIfEmpty(Mono.just(false));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getPersisterId() {
|
||||
return persisterId;
|
||||
}
|
||||
}
|
||||
@@ -1,783 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.resilience4j.reactor.retry.RetryOperator;
|
||||
import io.lettuce.core.Limit;
|
||||
import io.lettuce.core.Range;
|
||||
import io.lettuce.core.ScanArgs;
|
||||
import io.lettuce.core.ScanStream;
|
||||
import io.lettuce.core.ScoredValue;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
/**
|
||||
* Manages short-term storage of messages in Redis. Messages are frequently delivered to their destination and deleted
|
||||
* shortly after they reach the server, and this cache acts as a low-latency holding area for new messages, reducing
|
||||
* load on higher-latency, longer-term storage systems.
|
||||
* <p>
|
||||
* The following structures are used:
|
||||
* <dl>
|
||||
* <dt>{@code queueKey}</code></dt>
|
||||
* <dd>A sorted set of messages in a device’s queue. A message’s score is its queue-local message ID. See
|
||||
* <a href="https://redis.io/docs/latest/develop/use/patterns/twitter-clone/#the-sorted-set-data-type">Redis.io: The
|
||||
* Sorted Set data type</a> for background on scores and this data structure.</dd>
|
||||
* <dt>{@code queueMetadataKey}</dt>
|
||||
* <dd>A hash containing message guids and their queue-local message ID. It also contains a {@code counter} key, which is
|
||||
* incremented to supply the next message ID. This is used to remove a message by GUID from {@code queueKey} by its
|
||||
* local messageId.</dd>
|
||||
* <dt>{@code sharedMrmKey}</dt>
|
||||
* <dd>A hash containing a single multi-recipient message pending delivery. It contains:
|
||||
* <ul>
|
||||
* <li>{@code data} - the serialized SealedSenderMultiRecipientMessage data</li>
|
||||
* <li>fields with each recipient device's “view” into the payload ({@link SealedSenderMultiRecipientMessage#serializedRecipientView(SealedSenderMultiRecipientMessage.Recipient)}</li>
|
||||
* </ul>
|
||||
* Note: this is shared among all of the message's recipients, and it may be located in any Redis shard. As each recipient’s
|
||||
* message is delivered, its corresponding view is idempotently removed. When {@code data} is the only remaining
|
||||
* field, the hash will be deleted.
|
||||
* </dd>
|
||||
* <dt>{@code queueLockKey}</dt>
|
||||
* <dd>Used to indicate that a queue is being modified by the {@link MessagePersister} and that {@code get_items} should
|
||||
* return an empty list.</dd>
|
||||
* </dl>
|
||||
* <p>
|
||||
* At a high level, the process is:
|
||||
* <ol>
|
||||
* <li>Insert: the queue metadata is queried for the next incremented message ID. The message data is inserted into
|
||||
* the queue at that ID, and the message GUID is inserted in the queue metadata.</li>
|
||||
* <li>Get: a batch of messages are retrieved from the queue, potentially with an after-message-ID offset.</li>
|
||||
* <li>Remove: a set of messages are remove by GUID. For each GUID, the message ID is retrieved from the queue metadata,
|
||||
* and then that single-value range is removed from the queue.</li>
|
||||
* </ol>
|
||||
* For multi-recipient messages (sometimes abbreviated “MRM”), there are similar operations on the common data during
|
||||
* insert, get, and remove. MRM inserts must occur before individual queue inserts, while removal is considered
|
||||
* best-effort, and uses key expiration as back-stop garbage collection.
|
||||
* <p>
|
||||
* For atomicity, many operations are implemented as Lua scripts that are executed on the Redis server using
|
||||
* {@code EVAL}/{@code EVALSHA}.
|
||||
*
|
||||
* @see MessagesCacheInsertScript
|
||||
* @see MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript
|
||||
* @see MessagesCacheGetItemsScript
|
||||
* @see MessagesCacheRemoveByGuidScript
|
||||
* @see MessagesCacheRemoveRecipientViewFromMrmDataScript
|
||||
* @see MessagesCacheRemoveQueueScript
|
||||
*/
|
||||
public class MessagesCache {
|
||||
|
||||
private final FaultTolerantRedisClusterClient redisCluster;
|
||||
private final Clock clock;
|
||||
|
||||
private final Scheduler messageDeliveryScheduler;
|
||||
private final ExecutorService messageDeletionExecutorService;
|
||||
// messageDeletionExecutorService wrapped into a reactor Scheduler
|
||||
private final Scheduler messageDeletionScheduler;
|
||||
|
||||
private final MessagesCacheInsertScript insertScript;
|
||||
private final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript;
|
||||
private final MessagesCacheRemoveByGuidScript removeByGuidScript;
|
||||
private final MessagesCacheGetItemsScript getItemsScript;
|
||||
private final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript;
|
||||
private final MessagesCacheRemoveQueueScript removeQueueScript;
|
||||
private final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript;
|
||||
private final MessagesCacheUnlockQueueScript unlockQueueScript;
|
||||
|
||||
private int nextNodeRotateDistance = 0;
|
||||
|
||||
private final Timer insertTimer = Metrics.timer(name(MessagesCache.class, "insert"));
|
||||
private final Timer insertSharedMrmPayloadTimer = Metrics.timer(name(MessagesCache.class, "insertSharedMrmPayload"));
|
||||
private final Timer removeByGuidTimer = Metrics.timer(name(MessagesCache.class, "removeByGuid"));
|
||||
private final Timer removeRecipientViewTimer = Metrics.timer(name(MessagesCache.class, "removeRecipientView"));
|
||||
private final Timer clearQueueTimer = Metrics.timer(name(MessagesCache.class, "clear"));
|
||||
private final Counter removeMessageCounter = Metrics.counter(name(MessagesCache.class, "remove"));
|
||||
private final Counter staleEphemeralMessagesCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "staleEphemeralMessages"));
|
||||
private final Counter staleMrmMessagesCounter = Metrics.counter(name(MessagesCache.class, "staleMrmMessages"));
|
||||
private final Counter mrmContentRetrievedCounter = Metrics.counter(name(MessagesCache.class, "mrmViewRetrieved"));
|
||||
private final String MRM_RETRIEVAL_ERROR_COUNTER_NAME = name(MessagesCache.class, "mrmRetrievalError");
|
||||
private final String EPHEMERAL_TAG_NAME = "ephemeral";
|
||||
private final String MISSING_MRM_DATA_TAG_NAME = "missingMrmData";
|
||||
private final Counter skippedStaleEphemeralMrmCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "skippedStaleEphemeralMrm"));
|
||||
private final Counter sharedMrmDataKeyRemovedCounter = Metrics.counter(
|
||||
name(MessagesCache.class, "sharedMrmKeyRemoved"));
|
||||
|
||||
static final String RETRY_NAME = ResilienceUtil.name(MessagesCache.class);
|
||||
|
||||
private static final byte[] LOCK_VALUE = "1".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@VisibleForTesting
|
||||
static final ByteString STALE_MRM_KEY = ByteString.copyFromUtf8("stale");
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration MAX_EPHEMERAL_MESSAGE_DELAY = Duration.ofSeconds(10);
|
||||
|
||||
private static final String GET_FLUX_NAME = MetricsUtil.name(MessagesCache.class, "get");
|
||||
|
||||
@VisibleForTesting
|
||||
static final int PAGE_SIZE = 100;
|
||||
|
||||
private static final int REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY = 8;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesCache.class);
|
||||
|
||||
public MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService,
|
||||
final ScheduledExecutorService retryExecutor,
|
||||
final Clock clock) throws IOException {
|
||||
|
||||
this(
|
||||
redisCluster,
|
||||
messageDeliveryScheduler,
|
||||
messageDeletionExecutorService,
|
||||
clock,
|
||||
new MessagesCacheInsertScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheGetItemsScript(redisCluster),
|
||||
new MessagesCacheReleaseNodeClaimScript(redisCluster),
|
||||
new MessagesCacheRemoveByGuidScript(redisCluster, retryExecutor),
|
||||
new MessagesCacheRemoveQueueScript(redisCluster),
|
||||
new MessagesCacheRemoveRecipientViewFromMrmDataScript(redisCluster),
|
||||
new MessagesCacheUnlockQueueScript(redisCluster)
|
||||
);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
MessagesCache(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final Scheduler messageDeliveryScheduler,
|
||||
final ExecutorService messageDeletionExecutorService, final Clock clock,
|
||||
final MessagesCacheInsertScript insertScript,
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript,
|
||||
final MessagesCacheGetItemsScript getItemsScript,
|
||||
final MessagesCacheReleaseNodeClaimScript releaseNodeClaimScript,
|
||||
final MessagesCacheRemoveByGuidScript removeByGuidScript,
|
||||
final MessagesCacheRemoveQueueScript removeQueueScript,
|
||||
final MessagesCacheRemoveRecipientViewFromMrmDataScript removeRecipientViewFromMrmDataScript,
|
||||
final MessagesCacheUnlockQueueScript unlockQueueScript) throws IOException {
|
||||
|
||||
this.redisCluster = redisCluster;
|
||||
this.clock = clock;
|
||||
|
||||
this.messageDeliveryScheduler = messageDeliveryScheduler;
|
||||
this.messageDeletionExecutorService = messageDeletionExecutorService;
|
||||
this.messageDeletionScheduler = Schedulers.fromExecutorService(messageDeletionExecutorService, "messageDeletion");
|
||||
|
||||
this.insertScript = insertScript;
|
||||
this.insertMrmScript = insertMrmScript;
|
||||
this.removeByGuidScript = removeByGuidScript;
|
||||
this.getItemsScript = getItemsScript;
|
||||
this.releaseNodeClaimScript = releaseNodeClaimScript;
|
||||
this.removeQueueScript = removeQueueScript;
|
||||
this.removeRecipientViewFromMrmDataScript = removeRecipientViewFromMrmDataScript;
|
||||
this.unlockQueueScript = unlockQueueScript;
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> insert(final UUID messageGuid,
|
||||
final UUID destinationAccountIdentifier,
|
||||
final byte destinationDeviceId,
|
||||
final MessageProtos.Envelope message) {
|
||||
|
||||
final MessageProtos.Envelope messageWithGuid = message.toBuilder().setServerGuid(UUIDUtil.toByteString(messageGuid)).build();
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return insertScript.executeAsync(destinationAccountIdentifier, destinationDeviceId, messageWithGuid)
|
||||
.toCompletableFuture()
|
||||
.whenComplete((_, _) -> sample.stop(insertTimer));
|
||||
}
|
||||
|
||||
public CompletableFuture<byte[]> insertSharedMultiRecipientMessagePayload(
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage,
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> resolvedRecipients) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID());
|
||||
|
||||
return insertMrmScript.executeAsync(sharedMrmKey, sealedSenderMultiRecipientMessage, resolvedRecipients)
|
||||
.thenApply(_ -> sharedMrmKey)
|
||||
.toCompletableFuture()
|
||||
.whenComplete((_, _) -> sample.stop(insertSharedMrmPayloadTimer));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
|
||||
final UUID messageGuid) {
|
||||
|
||||
return remove(destinationUuid, destinationDevice, List.of(messageGuid))
|
||||
.thenApply(removed -> removed.isEmpty() ? Optional.empty() : Optional.of(removed.getFirst()));
|
||||
}
|
||||
|
||||
public CompletableFuture<List<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<UUID> messageGuids) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return removeByGuidScript.execute(destinationUuid, destinationDevice, messageGuids)
|
||||
.thenApplyAsync(serialized -> {
|
||||
|
||||
final List<RemovedMessage> removedMessages = new ArrayList<>(serialized.size());
|
||||
final Map<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
|
||||
for (final byte[] bytes : serialized) {
|
||||
try {
|
||||
final MessageProtos.Envelope envelope = parseEnvelope(bytes);
|
||||
removedMessages.add(RemovedMessage.fromEnvelope(envelope));
|
||||
if (envelope.hasSharedMrmKey()) {
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(
|
||||
ServiceIdentifier.fromByteString(envelope.getDestinationServiceId()), _ -> new ArrayList<>())
|
||||
.add(envelope.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
serviceIdentifierToMrmKeys.forEach(
|
||||
(serviceId, keysToUpdate) -> removeRecipientViewFromMrmData(keysToUpdate, serviceId, destinationDevice));
|
||||
|
||||
return removedMessages;
|
||||
}, messageDeletionExecutorService)
|
||||
.toCompletableFuture()
|
||||
.whenComplete((removedMessages, _) -> {
|
||||
if (removedMessages != null) {
|
||||
removeMessageCounter.increment(removedMessages.size());
|
||||
}
|
||||
|
||||
sample.stop(removeByGuidTimer);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> hasMessagesAsync(final UUID destinationUuid, final byte destinationDevice) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.async().zcard(getMessageQueueKey(destinationUuid, destinationDevice))
|
||||
.thenApply(cardinality -> cardinality > 0))
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return get(destinationUuid,
|
||||
destinationDeviceId,
|
||||
clock.instant().minus(MAX_EPHEMERAL_MESSAGE_DELAY),
|
||||
false);
|
||||
}
|
||||
|
||||
Publisher<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDeviceId) {
|
||||
return Flux.from(get(accountUuid,
|
||||
destinationDeviceId,
|
||||
// Discard all ephemeral messages when persisting
|
||||
Instant.ofEpochMilli(Long.MAX_VALUE),
|
||||
true));
|
||||
}
|
||||
|
||||
private Publisher<MessageProtos.Envelope> get(final UUID destinationUuid,
|
||||
final byte destinationDeviceId,
|
||||
final Instant earliestAllowableEphemeralTimestamp,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final long earliestAllowableEphemeralTimestampMillis = earliestAllowableEphemeralTimestamp.toEpochMilli();
|
||||
|
||||
final Flux<MessageProtos.Envelope> allMessages = getAllMessages(destinationUuid, destinationDeviceId,
|
||||
earliestAllowableEphemeralTimestampMillis, PAGE_SIZE, bypassLock)
|
||||
.publish()
|
||||
// We expect exactly three subscribers to this base flux:
|
||||
// 1. the websocket that delivers messages to clients
|
||||
// 2. an internal processes to discard stale ephemeral messages
|
||||
// 3. an internal process to discard stale MRM messages
|
||||
// The discard subscribers will subscribe immediately, but we don’t want to do any work if the
|
||||
// websocket never subscribes.
|
||||
.autoConnect(3);
|
||||
|
||||
final Flux<MessageProtos.Envelope> messagesToPublish = allMessages
|
||||
.filter(Predicate.not(envelope ->
|
||||
isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis) || isStaleMrmMessage(envelope)));
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleEphemeralMessages = allMessages
|
||||
.filter(envelope -> isStaleEphemeralMessage(envelope, earliestAllowableEphemeralTimestampMillis));
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleEphemeralMessages, staleEphemeralMessagesCounter, "ephemeral");
|
||||
|
||||
final Flux<MessageProtos.Envelope> staleMrmMessages = allMessages.filter(MessagesCache::isStaleMrmMessage)
|
||||
// clearing the sharedMrmKey prevents unnecessary calls to update the shared MRM data
|
||||
.map(envelope -> envelope.toBuilder().clearSharedMrmKey().build());
|
||||
discardStaleMessages(destinationUuid, destinationDeviceId, staleMrmMessages, staleMrmMessagesCounter, "mrm");
|
||||
|
||||
return messagesToPublish.name(GET_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
/// Returns the server-issued timestamp of the earliest message in the queue for the given account/device, regardless
|
||||
/// of the type of message. Note that this method may return a timestamp for a message that would ultimately be
|
||||
/// discarded were a caller to actually fetch messages (i.e. an expired ephemeral message).
|
||||
///
|
||||
/// @param destinationUuid the account identifier for the queue for which to get a timestamp
|
||||
/// @param destinationDeviceId the device identifier for the queue for which to get a timestamp
|
||||
///
|
||||
/// @return a `Mono` that publishes the timestamp (in milliseconds since the epoch) of the earliest message in the
|
||||
/// given queue or yields no value if the queue is empty or does not exist
|
||||
public Mono<Long> getEarliestUndeliveredTimestamp(final UUID destinationUuid, final byte destinationDeviceId) {
|
||||
return redisCluster.withBinaryCluster(connection ->
|
||||
connection.reactive().zrange(getMessageQueueKey(destinationUuid, destinationDeviceId), 0, 0))
|
||||
.next()
|
||||
.flatMap(serializedEnvelope -> {
|
||||
try {
|
||||
return Mono.just(parseEnvelope(serializedEnvelope).getServerTimestamp());
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
return Mono.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isStaleEphemeralMessage(final MessageProtos.Envelope message,
|
||||
long earliestAllowableTimestamp) {
|
||||
return message.getEphemeral() && message.getClientTimestamp() < earliestAllowableTimestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given message is a stale MRM message
|
||||
*
|
||||
* @see #getMessageWithSharedMrmData(MessageProtos.Envelope, byte)
|
||||
*/
|
||||
private static boolean isStaleMrmMessage(final MessageProtos.Envelope message) {
|
||||
return message.hasSharedMrmKey() && STALE_MRM_KEY.equals(message.getSharedMrmKey());
|
||||
}
|
||||
|
||||
private void discardStaleMessages(final UUID destinationUuid, final byte destinationDevice,
|
||||
Flux<MessageProtos.Envelope> staleMessages, final Counter counter, final String context) {
|
||||
staleMessages
|
||||
.map(e -> UUIDUtil.fromByteString(e.getServerGuid()))
|
||||
.buffer(PAGE_SIZE)
|
||||
.subscribeOn(messageDeletionScheduler)
|
||||
.subscribe(messageGuids ->
|
||||
remove(destinationUuid, destinationDevice, messageGuids)
|
||||
.thenAccept(removedMessages -> counter.increment(removedMessages.size())),
|
||||
e -> logger.warn("Could not remove stale {} messages from cache", context, e));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Flux<MessageProtos.Envelope> getAllMessages(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final long earliestAllowableEphemeralTimestamp,
|
||||
final int pageSize,
|
||||
final boolean bypassLock) {
|
||||
|
||||
// fetch messages by page
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, -1, pageSize, bypassLock)
|
||||
.expand(queueItemsAndLastMessageId -> {
|
||||
// expand() is breadth-first, so each page will be published in order
|
||||
if (queueItemsAndLastMessageId.first().isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
return getNextMessagePage(destinationUuid, destinationDevice, queueItemsAndLastMessageId.second(), pageSize, bypassLock);
|
||||
})
|
||||
.limitRate(1)
|
||||
// we want to ensure we don’t accidentally block the Lettuce/netty i/o executors
|
||||
.publishOn(messageDeliveryScheduler)
|
||||
.map(Pair::first)
|
||||
.concatMap(queueItems -> {
|
||||
|
||||
final List<Mono<MessageProtos.Envelope>> envelopes = new ArrayList<>(queueItems.size() / 2);
|
||||
|
||||
for (int i = 0; i < queueItems.size() - 1; i += 2) {
|
||||
try {
|
||||
final MessageProtos.Envelope message = parseEnvelope(queueItems.get(i));
|
||||
|
||||
final Mono<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
|
||||
if (isStaleEphemeralMessage(message, earliestAllowableEphemeralTimestamp)) {
|
||||
// skip fetching content for message that will be discarded
|
||||
messageMono = Mono.just(message.toBuilder().clearSharedMrmKey().build());
|
||||
skippedStaleEphemeralMrmCounter.increment();
|
||||
} else {
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
}
|
||||
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
}
|
||||
|
||||
envelopes.add(messageMono);
|
||||
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
return Flux.mergeSequential(envelopes);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given message with its shared MRM data. There are three possible cases:
|
||||
* <ol>
|
||||
* <li>The reconstructed message for delivery with {@code content} set and {@code sharedMrmKey} cleared</li>
|
||||
* <li>The input with {@code sharedMrmKey} set to a static value, indicating that the shared MRM data is no longer available, and the message should be
|
||||
* discarded from the queue</li>
|
||||
* <li>An empty {@code Mono}, if an unexpected error occurred</li>
|
||||
* </ol>
|
||||
*/
|
||||
private Mono<MessageProtos.Envelope> getMessageWithSharedMrmData(final MessageProtos.Envelope mrmMessage,
|
||||
final byte destinationDevice) {
|
||||
|
||||
assert mrmMessage.hasSharedMrmKey();
|
||||
|
||||
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
|
||||
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
|
||||
// the message might be addressed to the account's PNI, so use the service ID from the envelope
|
||||
ServiceIdentifier.fromByteString(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
|
||||
return Mono.from(redisCluster.withBinaryCluster(
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
.collectList()
|
||||
.publishOn(messageDeliveryScheduler)))
|
||||
.transformDeferred(RetryOperator.of(ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)))
|
||||
.<MessageProtos.Envelope>handle((mrmDataAndView, sink) -> {
|
||||
try {
|
||||
assert mrmDataAndView.size() == 2;
|
||||
|
||||
if (mrmDataAndView.getFirst().isEmpty()) {
|
||||
// shared data is missing
|
||||
//noinspection ReactiveStreamsThrowInOperator
|
||||
throw new MrmDataMissingException(MrmDataMissingException.Type.SHARED);
|
||||
}
|
||||
|
||||
if (mrmDataAndView.getLast().isEmpty()) {
|
||||
// recipient's view is missing
|
||||
//noinspection ReactiveStreamsThrowInOperator
|
||||
throw new MrmDataMissingException(MrmDataMissingException.Type.RECIPIENT_VIEW);
|
||||
}
|
||||
|
||||
final byte[] content = SealedSenderMultiRecipientMessage.messageForRecipient(
|
||||
mrmDataAndView.getFirst().getValue(),
|
||||
mrmDataAndView.getLast().getValue());
|
||||
|
||||
sink.next(mrmMessage.toBuilder()
|
||||
.clearSharedMrmKey()
|
||||
.setContent(ByteString.copyFrom(content))
|
||||
.build());
|
||||
|
||||
mrmContentRetrievedCounter.increment();
|
||||
} catch (Exception e) {
|
||||
sink.error(e);
|
||||
}
|
||||
})
|
||||
.onErrorResume(throwable -> {
|
||||
|
||||
final List<Tag> tags = new ArrayList<>();
|
||||
tags.add(Tag.of(EPHEMERAL_TAG_NAME, String.valueOf(mrmMessage.getEphemeral())));
|
||||
|
||||
final Mono<MessageProtos.Envelope> result;
|
||||
if (throwable instanceof MrmDataMissingException mdme) {
|
||||
tags.add(Tag.of(MISSING_MRM_DATA_TAG_NAME, mdme.getType().name()));
|
||||
// MRM data may be missing if either of the two non-transactional writes (delete from queue, update shared
|
||||
// MRM data) fails after it has been delivered. We return it so that it may be discarded from the queue.
|
||||
result = Mono.just(mrmMessage.toBuilder().setSharedMrmKey(STALE_MRM_KEY).build());
|
||||
} else {
|
||||
logger.warn("Failed to retrieve shared mrm data", throwable);
|
||||
// For unexpected errors, return empty. The message will remain in the queue and be retried in the future.
|
||||
result = Mono.empty();
|
||||
}
|
||||
|
||||
Metrics.counter(MRM_RETRIEVAL_ERROR_COUNTER_NAME, tags).increment();
|
||||
|
||||
return result;
|
||||
})
|
||||
.share();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a best-effort attempt at asynchronously updating (and removing when empty) the MRM data structure
|
||||
*/
|
||||
void removeRecipientViewFromMrmData(final List<byte[]> sharedMrmKeys, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
if (sharedMrmKeys.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
Flux.fromIterable(sharedMrmKeys)
|
||||
.collectMultimap(SlotHash::getSlot)
|
||||
.flatMapMany(slotsAndKeys -> Flux.fromIterable(slotsAndKeys.values()))
|
||||
.flatMap(
|
||||
keys -> removeRecipientViewFromMrmDataScript.execute(keys, serviceIdentifier, deviceId),
|
||||
REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY)
|
||||
.doOnNext(sharedMrmDataKeyRemovedCounter::increment)
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Error removing recipient view", e);
|
||||
return Mono.just(0L);
|
||||
})
|
||||
.then()
|
||||
.doOnTerminate(() -> sample.stop(removeRecipientViewTimer))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final long messageId,
|
||||
final int pageSize,
|
||||
final boolean bypassLock) {
|
||||
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, pageSize, messageId, bypassLock)
|
||||
.map(queueItems -> {
|
||||
logger.trace("Processing page: {}", messageId);
|
||||
|
||||
if (queueItems.isEmpty()) {
|
||||
return new Pair<>(Collections.emptyList(), null);
|
||||
}
|
||||
|
||||
if (queueItems.size() % 2 != 0) {
|
||||
logger.error("\"Get messages\" operation returned a list with a non-even number of elements.");
|
||||
return new Pair<>(Collections.emptyList(), null);
|
||||
}
|
||||
|
||||
final long lastMessageId = Long.parseLong(
|
||||
new String(queueItems.getLast(), StandardCharsets.UTF_8));
|
||||
|
||||
return new Pair<>(queueItems, lastMessageId);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the size of the cached queue if it were to be persisted
|
||||
* @param accountUuid The account identifier
|
||||
* @param destinationDevice The destination device id
|
||||
* @return A future that completes with the approximate size of stored messages that need to be persisted
|
||||
*/
|
||||
CompletableFuture<Long> estimatePersistedQueueSizeBytes(final UUID accountUuid, final byte destinationDevice) {
|
||||
final Function<Optional<Long>, Mono<List<ScoredValue<byte[]>>>> getNextPage = (Optional<Long> start) ->
|
||||
Mono.fromCompletionStage(() -> redisCluster.withBinaryCluster(connection ->
|
||||
connection.async().zrangebyscoreWithScores(
|
||||
getMessageQueueKey(accountUuid, destinationDevice),
|
||||
Range.from(
|
||||
start.map(Range.Boundary::excluding).orElse(Range.Boundary.unbounded()),
|
||||
Range.Boundary.unbounded()),
|
||||
Limit.from(PAGE_SIZE))));
|
||||
final Flux<byte[]> allSerializedMessages = getNextPage.apply(Optional.empty())
|
||||
.expand(scoredValues -> {
|
||||
if (scoredValues.isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
long lastTimestamp = (long) scoredValues.getLast().getScore();
|
||||
return getNextPage.apply(Optional.of(lastTimestamp));
|
||||
})
|
||||
.concatMap(scoredValues -> Flux.fromStream(scoredValues.stream().map(ScoredValue::getValue)));
|
||||
|
||||
return parseAndFetchMrms(allSerializedMessages, destinationDevice)
|
||||
.filter(Predicate.not(envelope -> envelope.getEphemeral() || isStaleMrmMessage(envelope)))
|
||||
.reduce(0L, (acc, envelope) -> acc + envelope.getSerializedSize())
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
private Flux<MessageProtos.Envelope> parseAndFetchMrms(final Flux<byte[]> serializedMessages, final byte destinationDevice) {
|
||||
return serializedMessages
|
||||
.mapNotNull(message -> {
|
||||
try {
|
||||
return parseEnvelope(message);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.concatMap(message -> {
|
||||
final Mono<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
messageMono = getMessageWithSharedMrmData(message, destinationDevice);
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
}
|
||||
|
||||
return messageMono;
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
return CompletableFuture.allOf(
|
||||
Device.ALL_POSSIBLE_DEVICE_IDS.stream()
|
||||
.map(deviceId -> clear(destinationUuid, deviceId))
|
||||
.toList()
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final byte deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return removeQueueScript.execute(destinationUuid, deviceId, Collections.emptyList())
|
||||
.publishOn(messageDeletionScheduler)
|
||||
.expand(messagesToProcess -> {
|
||||
if (messagesToProcess.isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
final Map<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
final List<String> processedMessages = new ArrayList<>(messagesToProcess.size());
|
||||
for (byte[] serialized : messagesToProcess) {
|
||||
try {
|
||||
final MessageProtos.Envelope message = parseEnvelope(serialized);
|
||||
|
||||
processedMessages.add(UUIDUtil.fromByteString(message.getServerGuid()).toString());
|
||||
|
||||
if (message.hasSharedMrmKey()) {
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.fromByteString(message.getDestinationServiceId()),
|
||||
_ -> new ArrayList<>())
|
||||
.add(message.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
serviceIdentifierToMrmKeys.forEach((serviceId, keysToUpdate) ->
|
||||
removeRecipientViewFromMrmData(keysToUpdate, serviceId, deviceId));
|
||||
|
||||
return removeQueueScript.execute(destinationUuid, deviceId, processedMessages);
|
||||
})
|
||||
.then()
|
||||
.toFuture()
|
||||
.thenRun(() -> sample.stop(clearQueueTimer));
|
||||
}
|
||||
|
||||
Optional<RedisClusterNode> claimNextNodeToPersist(final String persisterId, final Duration ttl) {
|
||||
final List<RedisClusterNode> primaryNodes = redisCluster.withCluster(connection -> connection.getPartitions().stream()
|
||||
.filter(node -> node.is(RedisClusterNode.NodeFlag.UPSTREAM))
|
||||
.collect(Collectors.toCollection(ArrayList::new)));
|
||||
|
||||
Collections.rotate(primaryNodes, Math.abs(nextNodeRotateDistance++) % primaryNodes.size());
|
||||
|
||||
return primaryNodes.stream()
|
||||
.filter(node -> claimNode(node, persisterId, ttl))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
boolean claimNode(final RedisClusterNode node, final String persisterId, final Duration claimTtl) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
"OK".equals(connection.sync().set(getPersisterNodeClaimKey(node), persisterId, SetArgs.Builder.nx().ex(claimTtl))));
|
||||
}
|
||||
|
||||
void releaseNodeClaim(final RedisClusterNode node, final String persisterId) {
|
||||
releaseNodeClaimScript.execute(node, persisterId);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getPersisterNodeClaimKey(final RedisClusterNode node) {
|
||||
return "persister_node_claim::" + node.getNodeId();
|
||||
}
|
||||
|
||||
Flux<String> getQueues(final RedisClusterNode node, final int scanCount) {
|
||||
return redisCluster.withCluster(connection ->
|
||||
ScanStream.scan(connection.getConnection(node.getNodeId()).reactive(),
|
||||
ScanArgs.Builder.matches("user_queue::*").limit(scanCount)));
|
||||
}
|
||||
|
||||
Mono<Void> lockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return redisCluster.withBinaryCluster(
|
||||
connection -> connection.reactive().setex(getPersistInProgressKey(accountUuid, deviceId), 30, LOCK_VALUE))
|
||||
.then();
|
||||
}
|
||||
|
||||
Mono<Void> unlockQueueForPersistence(final UUID accountUuid, final byte deviceId) {
|
||||
return unlockQueueScript.execute(accountUuid, deviceId);
|
||||
}
|
||||
|
||||
static byte[] getMessageQueueKey(final UUID accountUuid, final byte deviceId) {
|
||||
return ("user_queue::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getMessageQueueMetadataKey(final UUID accountUuid, final byte deviceId) {
|
||||
return ("user_queue_metadata::{" + accountUuid.toString() + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmKey(final UUID mrmGuid) {
|
||||
return ("mrm::{" + mrmGuid.toString() + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getPersistInProgressKey(final UUID accountUuid, final byte deviceId) {
|
||||
return ("user_queue_persisting::{" + accountUuid + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmViewKey(final ServiceId serviceId, final byte deviceId) {
|
||||
return getSharedMrmViewKey(serviceId.toServiceIdFixedWidthBinary(), deviceId);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmViewKey(final ServiceIdentifier serviceIdentifier, final byte deviceId) {
|
||||
return getSharedMrmViewKey(serviceIdentifier.toFixedWidthByteArray(), deviceId);
|
||||
}
|
||||
|
||||
private static byte[] getSharedMrmViewKey(final byte[] fixedWithServiceId, final byte deviceId) {
|
||||
assert fixedWithServiceId.length == 17;
|
||||
|
||||
final ByteBuffer keyBb = ByteBuffer.allocate(18);
|
||||
keyBb.put(fixedWithServiceId);
|
||||
keyBb.put(deviceId);
|
||||
assert !keyBb.hasRemaining();
|
||||
return keyBb.array();
|
||||
}
|
||||
|
||||
static UUID getAccountUuidFromQueueName(final String queueName) {
|
||||
final int startOfHashTag = queueName.indexOf('{');
|
||||
|
||||
return UUID.fromString(queueName.substring(startOfHashTag + 1, queueName.indexOf("::", startOfHashTag)));
|
||||
}
|
||||
|
||||
static byte getDeviceIdFromQueueName(final String queueName) {
|
||||
return Byte.parseByte(queueName.substring(queueName.lastIndexOf("::") + 2, queueName.lastIndexOf('}')));
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope parseEnvelope(final byte[] envelopeBytes)
|
||||
throws InvalidProtocolBufferException {
|
||||
|
||||
return MessageProtos.Envelope.parseFrom(envelopeBytes);
|
||||
}
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.github.resilience4j.reactor.retry.RetryOperator;
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Retrieves a list of messages and their corresponding queue-local IDs for the device. To support streaming processing,
|
||||
* the last queue-local message ID from a previous call may be used as the {@code afterMessageId}.
|
||||
*/
|
||||
class MessagesCacheGetItemsScript {
|
||||
|
||||
private final ClusterLuaScript getItemsScript;
|
||||
|
||||
MessagesCacheGetItemsScript(FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.getItemsScript = ClusterLuaScript.fromResource(redisCluster, "lua/get_items.lua", ScriptOutputType.OBJECT);
|
||||
}
|
||||
|
||||
Mono<List<byte[]>> execute(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
final int limit,
|
||||
final long afterMessageId,
|
||||
final boolean bypassLock) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getPersistInProgressKey(destinationUuid, destinationDevice) // queueLockKey
|
||||
);
|
||||
final List<byte[]> args = List.of(
|
||||
String.valueOf(limit).getBytes(StandardCharsets.UTF_8), // limit
|
||||
String.valueOf(afterMessageId).getBytes(StandardCharsets.UTF_8), // afterMessageId
|
||||
String.valueOf(bypassLock).getBytes(StandardCharsets.UTF_8) // bypassLock
|
||||
);
|
||||
//noinspection unchecked
|
||||
return getItemsScript.executeBinaryReactive(keys, args)
|
||||
.transformDeferred(RetryOperator.of(ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)))
|
||||
.map(result -> (List<byte[]>) result)
|
||||
.next();
|
||||
}
|
||||
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.NewMessageAvailableEvent;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
/**
|
||||
* Inserts an envelope into the message queue for a destination device and publishes a "new message available" event.
|
||||
*/
|
||||
class MessagesCacheInsertScript {
|
||||
|
||||
private final ClusterLuaScript insertScript;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
|
||||
private static final byte[] NEW_MESSAGE_EVENT_BYTES = ClientEvent.newBuilder()
|
||||
.setNewMessageAvailable(NewMessageAvailableEvent.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray();
|
||||
|
||||
MessagesCacheInsertScript(FaultTolerantRedisClusterClient redisCluster,
|
||||
final ScheduledExecutorService retryExecutor) throws IOException {
|
||||
|
||||
this.insertScript = ClusterLuaScript.fromResource(redisCluster, "lua/insert_item.lua", ScriptOutputType.BOOLEAN);
|
||||
this.retryExecutor = retryExecutor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a message into the given device's message queue and publishes a "new message available" event.
|
||||
*
|
||||
* @param destinationUuid the account identifier for the receiving account
|
||||
* @param destinationDevice the ID of the receiving device within the given account
|
||||
* @param envelope the message to insert
|
||||
* @return {@code true} if the destination device had a registered "presence"/event subscriber or {@code false}
|
||||
* otherwise
|
||||
*/
|
||||
CompletionStage<Boolean> executeAsync(final UUID destinationUuid, final byte destinationDevice, final MessageProtos.Envelope envelope) {
|
||||
assert envelope.hasServerGuid();
|
||||
assert envelope.hasServerTimestamp();
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice), // queueMetadataKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(destinationUuid, destinationDevice) // eventChannelKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>(Arrays.asList(
|
||||
envelope.toByteArray(), // message
|
||||
UUIDUtil.fromByteString(envelope.getServerGuid()).toString().getBytes(StandardCharsets.UTF_8), // guid
|
||||
NEW_MESSAGE_EVENT_BYTES // eventPayload
|
||||
));
|
||||
|
||||
return ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)
|
||||
.executeCompletionStage(retryExecutor, () -> insertScript.executeBinaryAsync(keys, args))
|
||||
.thenApply(result -> (boolean) result);
|
||||
}
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* Inserts the shared multi-recipient message payload into the cache. The list of recipients and views will be set as
|
||||
* fields in the hash.
|
||||
*
|
||||
* @see SealedSenderMultiRecipientMessage#serializedRecipientView(SealedSenderMultiRecipientMessage.Recipient)
|
||||
*/
|
||||
class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
|
||||
|
||||
private final ClusterLuaScript script;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
|
||||
static final String ERROR_KEY_EXISTS = "ERR key exists";
|
||||
|
||||
MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(FaultTolerantRedisClusterClient redisCluster,
|
||||
final ScheduledExecutorService retryExecutor) throws IOException {
|
||||
|
||||
this.script = ClusterLuaScript.fromResource(redisCluster, "lua/insert_shared_multirecipient_message_data.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
|
||||
this.retryExecutor = retryExecutor;
|
||||
}
|
||||
|
||||
CompletionStage<Void> executeAsync(final byte[] sharedMrmKey,
|
||||
final SealedSenderMultiRecipientMessage message,
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> resolvedRecipients) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
sharedMrmKey // sharedMrmKey
|
||||
);
|
||||
|
||||
final int deviceCount = message.getRecipients().values().stream()
|
||||
.filter(resolvedRecipients::contains)
|
||||
.mapToInt(recipient -> recipient.getDevices().length)
|
||||
.sum();
|
||||
|
||||
// Pre-allocate capacity for the most fields we expect -- the shared data field plus one for each device
|
||||
final List<byte[]> args = new ArrayList<>(1 + deviceCount);
|
||||
args.add(message.serialized());
|
||||
|
||||
message.getRecipients().forEach((serviceId, recipient) -> {
|
||||
if (!resolvedRecipients.contains(recipient)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (final byte deviceId : recipient.getDevices()) {
|
||||
args.add(MessagesCache.getSharedMrmViewKey(serviceId, deviceId));
|
||||
args.add(message.serializedRecipientView(recipient));
|
||||
}
|
||||
});
|
||||
|
||||
return ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)
|
||||
.executeCompletionStage(retryExecutor, () -> script.executeBinaryAsync(keys, args))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
class MessagesCacheReleaseNodeClaimScript {
|
||||
|
||||
private final ClusterLuaScript releaseNodeClaimScript;
|
||||
|
||||
MessagesCacheReleaseNodeClaimScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.releaseNodeClaimScript =
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/release_node_claim.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
void execute(final RedisClusterNode node, final String persisterId) {
|
||||
final List<String> keys = List.of(MessagesCache.getPersisterNodeClaimKey(node));
|
||||
final List<String> arguments = List.of(persisterId);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(getClass().getSimpleName())
|
||||
.executeRunnable(() -> releaseNodeClaimScript.execute(keys, arguments));
|
||||
}
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
/**
|
||||
* Removes a list of message GUIDs from the queue of a destination device.
|
||||
*/
|
||||
class MessagesCacheRemoveByGuidScript {
|
||||
|
||||
private final ClusterLuaScript removeByGuidScript;
|
||||
private final ScheduledExecutorService retryExecutor;
|
||||
|
||||
MessagesCacheRemoveByGuidScript(final FaultTolerantRedisClusterClient redisCluster,
|
||||
final ScheduledExecutorService retryExecutor) throws IOException {
|
||||
|
||||
this.removeByGuidScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_item_by_guid.lua",
|
||||
ScriptOutputType.OBJECT);
|
||||
this.retryExecutor = retryExecutor;
|
||||
}
|
||||
|
||||
CompletionStage<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<UUID> messageGuids) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
final List<byte[]> args = messageGuids.stream().map(guid -> guid.toString().getBytes(StandardCharsets.UTF_8))
|
||||
.toList();
|
||||
|
||||
//noinspection unchecked
|
||||
return ResilienceUtil.getGeneralRedisRetry(MessagesCache.RETRY_NAME)
|
||||
.executeCompletionStage(retryExecutor, () -> removeByGuidScript.executeBinaryAsync(keys, args))
|
||||
.thenApply(result -> (List<byte[]>) result);
|
||||
}
|
||||
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Removes a device's queue from the cache. For a non-empty queue, this script must be executed multiple times.
|
||||
* <ol>
|
||||
* <li>The first call will return a list of messages to check for {@code sharedMrmKeys}. If a {@code sharedMrmKey} is present, {@link MessagesCacheRemoveRecipientViewFromMrmDataScript} must be called.</li>
|
||||
* <li>Once theses messages have been processed, this script should be called again, confirming that the messages have been processed.</li>
|
||||
* <li>This should be repeated until the script returns an empty list, as the script only returns a page ({@value PAGE_SIZE}) of messages at a time.</li>
|
||||
* </ol>
|
||||
*/
|
||||
class MessagesCacheRemoveQueueScript {
|
||||
|
||||
private static final int PAGE_SIZE = 100;
|
||||
|
||||
private final ClusterLuaScript removeQueueScript;
|
||||
|
||||
MessagesCacheRemoveQueueScript(FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.removeQueueScript = ClusterLuaScript.fromResource(redisCluster, "lua/remove_queue.lua",
|
||||
ScriptOutputType.MULTI);
|
||||
}
|
||||
|
||||
Mono<List<byte[]>> execute(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<String> processedMessageGuids) {
|
||||
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getMessageQueueKey(destinationUuid, destinationDevice), // queueKey
|
||||
MessagesCache.getMessageQueueMetadataKey(destinationUuid, destinationDevice) // queueMetadataKey
|
||||
);
|
||||
|
||||
final List<byte[]> args = new ArrayList<>();
|
||||
|
||||
args.addFirst(String.valueOf(PAGE_SIZE).getBytes(StandardCharsets.UTF_8)); // limit
|
||||
args.addAll(processedMessageGuids.stream().map(guid -> guid.getBytes(StandardCharsets.UTF_8))
|
||||
.toList()); // processedMessageGuids
|
||||
|
||||
//noinspection unchecked
|
||||
return removeQueueScript.executeBinaryReactive(keys, args)
|
||||
.map(result -> (List<byte[]>) result)
|
||||
.next();
|
||||
}
|
||||
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Removes the given destination device from the given {@code sharedMrmKeys}. If there are no devices remaining in the
|
||||
* hash as a result, the shared payload is deleted.
|
||||
* <p>
|
||||
* NOTE: Callers are responsible for ensuring that all keys are in the same slot.
|
||||
*/
|
||||
class MessagesCacheRemoveRecipientViewFromMrmDataScript {
|
||||
|
||||
private final ClusterLuaScript removeRecipientViewFromMrmDataScript;
|
||||
|
||||
MessagesCacheRemoveRecipientViewFromMrmDataScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.removeRecipientViewFromMrmDataScript = ClusterLuaScript.fromResource(redisCluster,
|
||||
"lua/remove_recipient_view_from_mrm_data.lua", ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
Mono<Long> execute(final Collection<byte[]> keysCollection, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
final List<byte[]> keys = keysCollection instanceof List<byte[]>
|
||||
? (List<byte[]>) keysCollection
|
||||
: new ArrayList<>(keysCollection);
|
||||
|
||||
return removeRecipientViewFromMrmDataScript.executeBinaryReactive(keys,
|
||||
List.of(MessagesCache.getSharedMrmViewKey(serviceIdentifier, deviceId)))
|
||||
.map(o -> (long) o)
|
||||
.next();
|
||||
}
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import io.lettuce.core.ScriptOutputType;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.whispersystems.textsecuregcm.push.ClientEvent;
|
||||
import org.whispersystems.textsecuregcm.push.MessagesPersistedEvent;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
/**
|
||||
* Unlocks a message queue for persistence/message retrieval.
|
||||
*/
|
||||
class MessagesCacheUnlockQueueScript {
|
||||
|
||||
private final ClusterLuaScript unlockQueueScript;
|
||||
|
||||
private final List<byte[]> MESSAGES_PERSISTED_EVENT_ARGS = List.of(ClientEvent.newBuilder()
|
||||
.setMessagesPersisted(MessagesPersistedEvent.getDefaultInstance())
|
||||
.build()
|
||||
.toByteArray()); // eventPayload
|
||||
|
||||
MessagesCacheUnlockQueueScript(final FaultTolerantRedisClusterClient redisCluster) throws IOException {
|
||||
this.unlockQueueScript =
|
||||
ClusterLuaScript.fromResource(redisCluster, "lua/unlock_queue.lua", ScriptOutputType.STATUS);
|
||||
}
|
||||
|
||||
Mono<Void> execute(final UUID accountIdentifier, final byte deviceId) {
|
||||
final List<byte[]> keys = List.of(
|
||||
MessagesCache.getPersistInProgressKey(accountIdentifier, deviceId), // persistInProgressKey
|
||||
RedisMessageAvailabilityManager.getClientEventChannel(accountIdentifier, deviceId) // eventChannelKey
|
||||
);
|
||||
|
||||
return unlockQueueScript.executeBinaryReactive(keys, MESSAGES_PERSISTED_EVENT_ARGS)
|
||||
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+107
-293
@@ -4,105 +4,58 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class MessagesManager {
|
||||
|
||||
final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME = name(MessagesManager.class, "getMessagesForDevice");
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagesManager.class);
|
||||
|
||||
private static final Counter PERSIST_MESSAGE_COUNTER = Metrics.counter(
|
||||
name(MessagesManager.class, "persistMessage"));
|
||||
|
||||
private static final Counter PERSIST_MESSAGE_BYTES_COUNTER = Metrics.counter(
|
||||
name(MessagesManager.class, "persistMessageBytes"));
|
||||
|
||||
private static final String MAY_HAVE_MESSAGES_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "mayHaveMessages");
|
||||
|
||||
private static final String PRESENCE_MATCH_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "presenceMatch");
|
||||
|
||||
private static final String INSERT_FDB_EXCEPTIONS_COUNTER_NAME = name(MessagesManager.class, "insertExceptions");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
public static final String READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME = "foundationDbReadLiveMessages";
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
@VisibleForTesting
|
||||
static final long DELIVERY_LOOP_READ_THRESHOLD = 10;
|
||||
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final ReportMessageManager reportMessageManager,
|
||||
final ExecutorService messageDeletionExecutor,
|
||||
final Clock clock,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager) {
|
||||
final Clock clock) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.reportMessageManager = reportMessageManager;
|
||||
this.messageDeletionExecutor = messageDeletionExecutor;
|
||||
this.clock = clock;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,95 +64,44 @@ public class MessagesManager {
|
||||
* @param accountIdentifier the account identifier for the destination queue
|
||||
* @param messagesByDeviceId a map of device IDs to messages
|
||||
*
|
||||
* @return a map of device IDs to a device's presence state (i.e. if the device has an active event listener)
|
||||
*
|
||||
* @see RedisMessageAvailabilityManager
|
||||
* @return a map of device IDs to a device's presence state
|
||||
*/
|
||||
public Map<Byte, Boolean> insert(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
return insertAsync(accountIdentifier, messagesByDeviceId).join();
|
||||
}
|
||||
|
||||
private CompletableFuture<Map<Byte, Boolean>> insertAsync(final UUID accountIdentifier, final Map<Byte, Envelope> messagesByDeviceId) {
|
||||
final Map<Byte, Boolean> devicePresenceById = new ConcurrentHashMap<>();
|
||||
return foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), messagesByDeviceId)
|
||||
.thenApply(insertResultsByDeviceId -> {
|
||||
messagesByDeviceId.forEach((deviceId, message) -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
final CompletableFuture<Map<Byte, FoundationDbMessageStore.InsertResult>> foundationDbInsertFuture;
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier, MIRROR_INSERTS_EXPERIMENT_NAME)) {
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only need/want the
|
||||
// latter for FoundationDB
|
||||
final Map<Byte, Envelope> minimizedMessagesByDeviceId = messagesByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(
|
||||
Map.Entry::getKey,
|
||||
entry -> entry.getValue().toBuilder().clearSharedMrmKey().build()));
|
||||
|
||||
foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.exceptionally(e -> {
|
||||
if (ExceptionUtils.unwrap(e) instanceof final FDBException fdbException) {
|
||||
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
|
||||
.increment();
|
||||
} else {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
|
||||
throw ExceptionUtils.wrap(e);
|
||||
});
|
||||
} else {
|
||||
foundationDbInsertFuture = CompletableFuture.completedFuture(Collections.emptyMap());
|
||||
}
|
||||
|
||||
return foundationDbInsertFuture.thenCompose(foundationDbInsertResults -> {
|
||||
final boolean useFoundationDbPresence =
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME);
|
||||
|
||||
if (useFoundationDbPresence) {
|
||||
foundationDbInsertResults.forEach((deviceId, insertResult) ->
|
||||
devicePresenceById.put(deviceId, insertResult.present()));
|
||||
}
|
||||
|
||||
return CompletableFuture.allOf(messagesByDeviceId.entrySet().stream()
|
||||
.map(deviceIdAndMessage -> {
|
||||
final byte deviceId = deviceIdAndMessage.getKey();
|
||||
|
||||
// Multi-recipient messages will have both a "shared MRM key" and actual message content; we only
|
||||
// need/want the former for Redis
|
||||
final Envelope message = deviceIdAndMessage.getValue().hasSharedMrmKey()
|
||||
? deviceIdAndMessage.getValue().toBuilder().clearContent().build()
|
||||
: deviceIdAndMessage.getValue();
|
||||
|
||||
final UUID messageGuid = Optional.ofNullable(foundationDbInsertResults.get(deviceId))
|
||||
.flatMap(FoundationDbMessageStore.InsertResult::messageGuid)
|
||||
.orElseGet(UUID::randomUUID);
|
||||
|
||||
return messagesCache.insert(messageGuid, accountIdentifier, deviceId, message)
|
||||
.thenAccept(present -> {
|
||||
if (message.hasSourceServiceId()) {
|
||||
final ServiceIdentifier sourceServiceIdentifier =
|
||||
ServiceIdentifier.fromByteString(message.getSourceServiceId());
|
||||
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid()) && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
}
|
||||
}
|
||||
|
||||
if (!useFoundationDbPresence) {
|
||||
devicePresenceById.put(deviceId, present);
|
||||
}
|
||||
|
||||
if (foundationDbInsertResults.containsKey(deviceId)) {
|
||||
Metrics.counter(PRESENCE_MATCH_COUNTER_NAME,
|
||||
"match", String.valueOf(present == foundationDbInsertResults.get(deviceId).present()))
|
||||
.increment();
|
||||
}
|
||||
if (!accountIdentifier.equals(sourceServiceIdentifier.uuid()) && message.getType() != Envelope.Type.SERVER_DELIVERY_RECEIPT) {
|
||||
insertResultsByDeviceId.get(deviceId).messageGuid().ifPresent(messageGuid -> {
|
||||
// Note that this is an asynchronous, best-effort, fire-and-forget operation
|
||||
reportMessageManager.store(sourceServiceIdentifier.toServiceIdentifierString(), messageGuid);
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return insertResultsByDeviceId.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().present()));
|
||||
})
|
||||
.thenApply(ignored -> devicePresenceById);
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(ExceptionUtils.unwrap(throwable) instanceof FDBException) && !ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
messagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,10 +116,7 @@ public class MessagesManager {
|
||||
* connections to a Signal server or {@code false} otherwise
|
||||
* @param isUrgent {@code true} if the given message is urgent or {@code false} otherwise
|
||||
*
|
||||
* @return a map of accounts to maps of device IDs to a device's presence state (i.e. if the device has an active
|
||||
* event listener)
|
||||
*
|
||||
* @see RedisMessageAvailabilityManager
|
||||
* @return a map of accounts to maps of device IDs to a device's presence state
|
||||
*/
|
||||
public CompletableFuture<Map<Account, Map<Byte, Boolean>>> insertMultiRecipientMessage(
|
||||
final SealedSenderMultiRecipientMessage multiRecipientMessage,
|
||||
@@ -229,201 +128,116 @@ public class MessagesManager {
|
||||
|
||||
final long serverTimestamp = clock.millis();
|
||||
|
||||
return insertSharedMultiRecipientMessagePayload(multiRecipientMessage, resolvedRecipients.keySet())
|
||||
.thenCompose(maybeSharedMrmKey -> {
|
||||
final Envelope.Builder envelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp == 0 ? serverTimestamp : clientTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent);
|
||||
final Envelope.Builder envelopeBuilder = Envelope.newBuilder()
|
||||
.setType(Envelope.Type.UNIDENTIFIED_SENDER)
|
||||
.setClientTimestamp(clientTimestamp == 0 ? serverTimestamp : clientTimestamp)
|
||||
.setServerTimestamp(serverTimestamp)
|
||||
.setEphemeral(isEphemeral)
|
||||
.setUrgent(isUrgent);
|
||||
|
||||
maybeSharedMrmKey
|
||||
.ifPresent(sharedMrmKey -> envelopeBuilder.setSharedMrmKey(ByteString.copyFrom(sharedMrmKey)));
|
||||
if (isStory) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
|
||||
if (isStory) {
|
||||
// Avoid sending this field if it's false.
|
||||
envelopeBuilder.setStory(true);
|
||||
}
|
||||
final Envelope prototypeMessage = envelopeBuilder.build();
|
||||
|
||||
final Envelope prototypeMessage = envelopeBuilder.build();
|
||||
final Map<Account, Map<Byte, Boolean>> clientPresenceByAccountAndDevice = new ConcurrentHashMap<>();
|
||||
|
||||
final Map<Account, Map<Byte, Boolean>> clientPresenceByAccountAndDevice = new ConcurrentHashMap<>();
|
||||
return CompletableFuture.allOf(multiRecipientMessage.getRecipients().entrySet().stream()
|
||||
.filter(serviceIdAndRecipient -> resolvedRecipients.containsKey(serviceIdAndRecipient.getValue()))
|
||||
.map(serviceIdAndRecipient -> {
|
||||
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = serviceIdAndRecipient.getValue();
|
||||
final byte[] devices = recipient.getDevices();
|
||||
|
||||
return CompletableFuture.allOf(multiRecipientMessage.getRecipients().entrySet().stream()
|
||||
.filter(serviceIdAndRecipient -> resolvedRecipients.containsKey(serviceIdAndRecipient.getValue()))
|
||||
.map(serviceIdAndRecipient -> {
|
||||
final ServiceIdentifier serviceIdentifier = ServiceIdentifier.fromLibsignal(serviceIdAndRecipient.getKey());
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = serviceIdAndRecipient.getValue();
|
||||
final byte[] devices = recipient.getDevices();
|
||||
|
||||
return insertAsync(resolvedRecipients.get(recipient).getAccountIdentifier(),
|
||||
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(serviceIdAndRecipient.getValue())))
|
||||
.setDestinationServiceId(serviceIdentifier.toCompactByteString())
|
||||
.build())))
|
||||
.thenAccept(clientPresenceByDeviceId ->
|
||||
clientPresenceByAccountAndDevice.put(resolvedRecipients.get(recipient),
|
||||
clientPresenceByDeviceId));
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> clientPresenceByAccountAndDevice);
|
||||
});
|
||||
return insertAsync(resolvedRecipients.get(recipient).getAccountIdentifier(),
|
||||
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(serviceIdAndRecipient.getValue())))
|
||||
.setDestinationServiceId(serviceIdentifier.toCompactByteString())
|
||||
.build())))
|
||||
.thenAccept(clientPresenceByDeviceId ->
|
||||
clientPresenceByAccountAndDevice.put(resolvedRecipients.get(recipient),
|
||||
clientPresenceByDeviceId));
|
||||
})
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> clientPresenceByAccountAndDevice);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHavePersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice);
|
||||
return foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
.thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice), (a, b) -> a || b);
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesCache.hasMessagesAsync(destinationUuid, destinationDevice.getId())
|
||||
.thenCombine(messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice),
|
||||
(mayHaveCachedMessages, mayHavePersistedMessages) -> {
|
||||
final String outcome;
|
||||
@SuppressWarnings("unchecked") final CompletableFuture<Boolean>[] mayHaveMessagesFutures = new CompletableFuture[] {
|
||||
foundationDbMessageStore.hasMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
messagesDynamoDb.mayHaveMessages(destinationUuid, destinationDevice)
|
||||
};
|
||||
|
||||
if (mayHaveCachedMessages && mayHavePersistedMessages) {
|
||||
outcome = "both";
|
||||
} else if (mayHaveCachedMessages) {
|
||||
outcome = "cached";
|
||||
} else if (mayHavePersistedMessages) {
|
||||
outcome = "persisted";
|
||||
} else {
|
||||
outcome = "none";
|
||||
}
|
||||
|
||||
Metrics.counter(MAY_HAVE_MESSAGES_COUNTER_NAME, "outcome", outcome).increment();
|
||||
|
||||
return mayHaveCachedMessages || mayHavePersistedMessages;
|
||||
});
|
||||
return CompletableFuture.allOf(mayHaveMessagesFutures)
|
||||
.thenApply(_ -> Arrays.stream(mayHaveMessagesFutures).anyMatch(CompletableFuture::resultNow));
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveUrgentPersistedMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice);
|
||||
return foundationDbMessageStore.mayHaveUrgentMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
.thenCombine(messagesDynamoDb.mayHaveUrgentMessages(destinationUuid, destinationDevice), (a, b) -> a || b);
|
||||
}
|
||||
|
||||
public MessageStream getMessages(final UUID destinationUuid, final Device destinationDevice) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, READ_LIVE_MESSAGES_FROM_FOUNDATIONDB_EXPERIMENT_NAME)) {
|
||||
return new ConcatenatingMessageStream(
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice, true),
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
);
|
||||
}
|
||||
|
||||
final RedisDynamoDbMessageStream redisDynamoDbMessageStream =
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice, false);
|
||||
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
}
|
||||
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
return Flux.concat(
|
||||
messagesDynamoDb.load(destinationUuid, destinationDevice, null),
|
||||
messagesCache.get(destinationUuid, destinationDevice.getId()))
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
return new ConcatenatingMessageStream(
|
||||
new DynamoDbMessageStream(messagesDynamoDb, destinationUuid, destinationDevice),
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId())
|
||||
);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid));
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}", destinationUuid, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return messagesCache.clear(destinationUuid);
|
||||
}
|
||||
}, messageDeletionExecutor);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final byte deviceId) {
|
||||
if (experimentEnrollmentManager.isEnrolled(destinationUuid, MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
messageDeletionExecutor.execute(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
foundationDbMessageStore.clearAll(new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
} catch (final Exception e) {
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to clear messages for {}:{}", destinationUuid, deviceId, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return messagesCache.clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RemovedMessage>> delete(final UUID destinationUuid,
|
||||
final Device destinationDevice,
|
||||
final UUID guid,
|
||||
final long serverTimestamp) {
|
||||
|
||||
return messagesCache.remove(destinationUuid, destinationDevice.getId(), guid)
|
||||
.thenComposeAsync(removed -> removed
|
||||
.map(_ -> CompletableFuture.completedFuture(removed))
|
||||
.orElseGet(() -> messagesDynamoDb.deleteMessage(destinationUuid, destinationDevice, guid, serverTimestamp)
|
||||
.thenApply(maybeEnvelope -> maybeEnvelope.map(RemovedMessage::fromEnvelope))
|
||||
), messageDeletionExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the number of messages successfully removed from the cache.
|
||||
*/
|
||||
public int persistMessages(
|
||||
final UUID destinationUuid,
|
||||
final Device destinationDevice,
|
||||
final List<Envelope> messages) {
|
||||
|
||||
messagesDynamoDb.store(messages, destinationUuid, destinationDevice);
|
||||
|
||||
final List<UUID> messageGuids = messages.stream().map(message -> UUIDUtil.fromByteString(message.getServerGuid()))
|
||||
.collect(Collectors.toList());
|
||||
int messagesRemovedFromCache = 0;
|
||||
try {
|
||||
messagesRemovedFromCache = messagesCache.remove(destinationUuid, destinationDevice.getId(), messageGuids)
|
||||
.get(30, TimeUnit.SECONDS).size();
|
||||
PERSIST_MESSAGE_COUNTER.increment(messages.size());
|
||||
PERSIST_MESSAGE_BYTES_COUNTER.increment(messages.stream()
|
||||
.mapToInt(Envelope::getSerializedSize)
|
||||
.sum());
|
||||
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
logger.warn("Failed to remove messages from cache", e);
|
||||
}
|
||||
return messagesRemovedFromCache;
|
||||
}
|
||||
}, messageDeletionExecutor);
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<Instant>> getEarliestUndeliveredTimestampForDevice(UUID destinationUuid, Device destinationDevice) {
|
||||
// If there's any message in the persisted layer, return the oldest
|
||||
return Mono.from(messagesDynamoDb.load(destinationUuid, destinationDevice, 1)).map(Envelope::getServerTimestamp)
|
||||
// If not, return the oldest message in the cache
|
||||
.switchIfEmpty(messagesCache.getEarliestUndeliveredTimestamp(destinationUuid, destinationDevice.getId()))
|
||||
// And if there are none there, then check FoundationDB
|
||||
.switchIfEmpty(Mono.fromFuture(() -> foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
|
||||
.mapNotNull(maybeTimestamp -> maybeTimestamp.map(Instant::toEpochMilli).orElse(null)))
|
||||
.map(epochMilli -> Optional.of(Instant.ofEpochMilli(epochMilli)))
|
||||
.switchIfEmpty(Mono.just(Optional.empty()))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/// Inserts the shared multi-recipient message payload to storage.
|
||||
/// Checks whether the given device is in a suspected "delivery loop" where it is repeatedly requesting but not
|
||||
/// acknowledging messages.
|
||||
///
|
||||
/// @return a future that yields a key where the shared data is stored or empty if the resolved recipient set is empty
|
||||
/// @param accountIdentifier the identifier of the account to check for a delivery loop
|
||||
/// @param deviceId the ID of the device to check for a delivery loop
|
||||
///
|
||||
/// @see MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript
|
||||
private CompletableFuture<Optional<byte[]>> insertSharedMultiRecipientMessagePayload(
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage,
|
||||
final Set<SealedSenderMultiRecipientMessage.Recipient> resolvedRecipients) {
|
||||
|
||||
if (resolvedRecipients.isEmpty()) {
|
||||
return CompletableFuture.completedFuture(Optional.empty());
|
||||
}
|
||||
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage, resolvedRecipients)
|
||||
.thenApply(Optional::of);
|
||||
/// @return a future that yields `true` if the identified device is suspected of being stuck in a message delivery
|
||||
/// loop or `false` otherwise
|
||||
public CompletableFuture<Boolean> hasSuspectedDeliveryLoop(final UUID accountIdentifier, final byte deviceId) {
|
||||
return foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(new AciServiceIdentifier(accountIdentifier), deviceId)
|
||||
.thenApply(readsSinceLastAcknowledgedMessage -> readsSinceLastAcknowledgedMessage >= DELIVERY_LOOP_READ_THRESHOLD);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
@@ -467,7 +281,7 @@ public class MessagesManager {
|
||||
final long rangeSplitChunkSizeBytes,
|
||||
final boolean dryRun) {
|
||||
// All trims will be considered successful during a dry run
|
||||
final UnaryOperator<Mono<Boolean>> deleteModifier = dryRun ? _ -> Mono.just(true) : UnaryOperator.identity();
|
||||
final Function<Mono<Boolean>, Mono<Boolean>> deleteModifier = dryRun ? _ -> Mono.just(true) : Function.identity();
|
||||
return foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, deleteModifier);
|
||||
}
|
||||
}
|
||||
-335
@@ -1,335 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import jakarta.annotation.Nullable;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.SignalType;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Counter CONFLICTING_CONSUMER_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "conflictingConsumer"));
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
private static final Counter MESSAGE_MISMATCHES_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "messageMismatches"));
|
||||
|
||||
private static final String STREAM_AGREEMENTS = MetricsUtil.name(MirroringMessageStream.class, "streamAgreements");
|
||||
|
||||
private static final String MISSING_MESSAGES_COUNTER =
|
||||
MetricsUtil.name(MirroringMessageStream.class, "missingMessages");
|
||||
|
||||
private static final DistributionSummary MISSING_MESSAGE_AGE_DISTRIBUTION =
|
||||
DistributionSummary.builder(MetricsUtil.name(MirroringMessageStream.class, "missingMessageAge"))
|
||||
.register(Metrics.globalRegistry);
|
||||
|
||||
private static final int MAX_WINDOW_SIZE = 1024;
|
||||
|
||||
private final Map<UUID, HashCode> redisDynamoMessageWindow = new HashMap<>();
|
||||
private final Map<UUID, HashCode> foundationDbMessageWindow = new HashMap<>();
|
||||
|
||||
private boolean stopAgreementVerification = false;
|
||||
|
||||
@Nullable
|
||||
private Tags agreementFailureTags;
|
||||
|
||||
private final Set<UUID> recentFoundationDbUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private final Set<UUID> recentRedisDynamoEphemeralUuids = Collections.newSetFromMap(new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(final Map.Entry<UUID, Boolean> eldest) {
|
||||
return size() > MAX_WINDOW_SIZE;
|
||||
}
|
||||
});
|
||||
|
||||
private enum Stream {
|
||||
REDIS_DYNAMO("redisDynamo"),
|
||||
FOUNDATION_DB("foundationDb");
|
||||
|
||||
private final String name;
|
||||
|
||||
Stream(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
private final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
|
||||
|
||||
private class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case final MessageStreamEntry.Envelope envelopeEntry -> {
|
||||
final boolean isUUIDv8 = UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
if (isUUIDv8) {
|
||||
verifyMessageAgreement(envelopeEntry, Stream.REDIS_DYNAMO);
|
||||
}
|
||||
yield isUUIDv8;
|
||||
}
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> true;
|
||||
};
|
||||
|
||||
if (isMirroredMessage) {
|
||||
request(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnError(final Throwable throwable) {
|
||||
switch (ExceptionUtils.unwrap(throwable)) {
|
||||
case ConflictingMessageConsumerException _ -> CONFLICTING_CONSUMER_COUNTER.increment();
|
||||
case FDBException _ -> {
|
||||
// FDBExceptions are already instrumented by metrics, so do nothing
|
||||
}
|
||||
default -> super.hookOnError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
protected void hookOnNext(final MessageStreamEntry messageStreamEntry) {
|
||||
if (messageStreamEntry instanceof final MessageStreamEntry.Envelope envelope) {
|
||||
verifyMessageAgreement(envelope, Stream.FOUNDATION_DB);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookFinally(final SignalType type) {
|
||||
super.hookFinally(type);
|
||||
publishStreamAgreementMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
subscriber.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(),
|
||||
MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)
|
||||
&&
|
||||
messageNotDeliveredOnFoundationDbStream(messageGuid)) {
|
||||
foundationDbMessageStream.acknowledgeAndGetMessage(messageGuid)
|
||||
.thenAccept(deleteMessage -> {
|
||||
if (deleteMessage.isEmpty()) {
|
||||
handleMissingFoundationDbMessage(messageGuid, serverTimestamp);
|
||||
return;
|
||||
}
|
||||
verifyMessageAgreement(deleteMessage.get(), Stream.FOUNDATION_DB);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private synchronized void verifyMessageAgreement(final MessageStreamEntry.Envelope envelope,
|
||||
final Stream stream) {
|
||||
|
||||
if (stopAgreementVerification) {
|
||||
return;
|
||||
}
|
||||
|
||||
final UUID messageUUID = UUIDUtil.fromByteString(envelope.message().getServerGuid());
|
||||
|
||||
if (envelope.message().getEphemeral()) {
|
||||
// We don't compare ephemeral messages across streams because the two systems have different ways of handling and
|
||||
// delivering ephemeral messages. However, we track recently seen ephemeral UUIDs on the Redis/Dynamo stream
|
||||
// to answer whether a message missing from FoundationDB was ephemeral or not.
|
||||
if (stream == Stream.REDIS_DYNAMO) {
|
||||
recentRedisDynamoEphemeralUuids.add(messageUUID);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// There could be a race where a FoundationDB message is delivered on the stream right after it was acknowledged,
|
||||
// so we don't want to add it to the window again; check it against a set of recently seen UUIDs before adding.
|
||||
if (Stream.FOUNDATION_DB == stream && !recentFoundationDbUuids.add(messageUUID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Map<UUID, HashCode> thisStreamWindow;
|
||||
final Map<UUID, HashCode> otherStreamWindow;
|
||||
if (Stream.REDIS_DYNAMO == stream) {
|
||||
thisStreamWindow = redisDynamoMessageWindow;
|
||||
otherStreamWindow = foundationDbMessageWindow;
|
||||
} else {
|
||||
thisStreamWindow = foundationDbMessageWindow;
|
||||
otherStreamWindow = redisDynamoMessageWindow;
|
||||
}
|
||||
|
||||
final HashCode thisStreamMessageHashCode = hashCode(envelope.message());
|
||||
|
||||
final HashCode otherStreamMessageHashCode = otherStreamWindow.remove(messageUUID);
|
||||
if (otherStreamMessageHashCode != null) {
|
||||
if (!otherStreamMessageHashCode.equals(thisStreamMessageHashCode)) {
|
||||
MESSAGE_MISMATCHES_COUNTER.increment();
|
||||
}
|
||||
} else {
|
||||
thisStreamWindow.put(messageUUID, thisStreamMessageHashCode);
|
||||
if (thisStreamWindow.size() >= MAX_WINDOW_SIZE) {
|
||||
// Stream is way ahead of the other, stop comparing further
|
||||
stopAgreementVerification = true;
|
||||
thisStreamWindow.clear();
|
||||
otherStreamWindow.clear();
|
||||
recentFoundationDbUuids.clear();
|
||||
setAgreementFailure(Tags.of("reason", "overflow", "stream", stream.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean messageNotDeliveredOnFoundationDbStream(final UUID messageGuid) {
|
||||
return redisDynamoMessageWindow.containsKey(messageGuid);
|
||||
}
|
||||
|
||||
private synchronized void setAgreementFailure(final Tags tags) {
|
||||
if (agreementFailureTags == null) {
|
||||
agreementFailureTags = tags;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void publishStreamAgreementMetrics() {
|
||||
|
||||
Tags tags = Tags.of("success", String.valueOf(agreementFailureTags == null));
|
||||
if (agreementFailureTags != null) {
|
||||
tags = tags.and(agreementFailureTags);
|
||||
}
|
||||
|
||||
Metrics.counter(STREAM_AGREEMENTS, tags).increment();
|
||||
}
|
||||
|
||||
private synchronized void handleMissingFoundationDbMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
final Boolean ephemeral;
|
||||
if (redisDynamoMessageWindow.containsKey(messageGuid)) {
|
||||
// The comparison window always contains non-ephemeral messages since we ignore ephemeral messages for comparison
|
||||
ephemeral = false;
|
||||
} else if (recentRedisDynamoEphemeralUuids.contains(messageGuid)) {
|
||||
ephemeral = true;
|
||||
} else {
|
||||
ephemeral = null;
|
||||
}
|
||||
setAgreementFailure(Tags.of("reason", "missingMessages"));
|
||||
Metrics.counter(MISSING_MESSAGES_COUNTER, "ephemeral", ephemeral == null ? "unknown" : ephemeral.toString())
|
||||
.increment();
|
||||
MISSING_MESSAGE_AGE_DISTRIBUTION.record(System.currentTimeMillis() - serverTimestamp);
|
||||
}
|
||||
|
||||
private static HashCode hashCode(final MessageProtos.Envelope envelope) {
|
||||
final byte[] serialized = new byte[envelope.getSerializedSize()];
|
||||
final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(serialized);
|
||||
codedOutputStream.useDeterministicSerialization();
|
||||
try {
|
||||
envelope.writeTo(codedOutputStream);
|
||||
codedOutputStream.flush();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return Hashing.murmur3_128().hashBytes(serialized);
|
||||
}
|
||||
|
||||
}
|
||||
+14
-9
@@ -27,6 +27,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -101,11 +102,7 @@ public class ProfilesManager {
|
||||
redisSet(uuid, null, versionedProfile);
|
||||
|
||||
try {
|
||||
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
|
||||
// downgrades to v1, all v2 profiles are stale
|
||||
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
|
||||
|
||||
profilesV2.deleteAll(uuid);
|
||||
profilesV2.deleteAll(uuid).join();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
|
||||
}
|
||||
@@ -177,7 +174,9 @@ public class ProfilesManager {
|
||||
try {
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, null, versionedProfile));
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
@@ -190,7 +189,9 @@ public class ProfilesManager {
|
||||
try {
|
||||
profile.ifPresent(versionedProfile -> redisSet(uuid, versionedProfile, null));
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to cache retrieved profile", e);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
@@ -239,7 +240,9 @@ public class ProfilesManager {
|
||||
|
||||
return parseProfileJson(json, VersionedProfile.class);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Redis exception", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Redis exception", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -255,7 +258,9 @@ public class ProfilesManager {
|
||||
|
||||
return parseProfileJson(json, VersionedProfileV1.class);
|
||||
} catch (RedisException e) {
|
||||
logger.warn("Failed to retrieve profile from cache", e);
|
||||
if (!ExceptionUtils.isBreakerOpen(e)) {
|
||||
logger.warn("Failed to retrieve profile from cache", e);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
-412
@@ -1,412 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Flow;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.MessageAvailabilityListener;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
/// A Redis/DynamoDB message publisher produces an optionally-terminating stream of messages for a specific device. It
|
||||
/// listens for message availability signals from [RedisMessageAvailabilityManager] and emits new messages to its
|
||||
/// subscriber when available.
|
||||
///
|
||||
/// This publisher supports only a single subscriber. It assumes that subscribers acknowledge (delete) messages as they
|
||||
/// read the messages, and may emit duplicate messages if subscribers do not acknowledge messages before requesting more
|
||||
/// messages.
|
||||
class RedisDynamoDbMessagePublisher implements MessageAvailabilityListener, Flow.Publisher<MessageStreamEntry> {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
private final RedisMessageAvailabilityManager redisMessageAvailabilityManager;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
// Indicates which data source(s) we think might contain messages for the destination device. Messages initially land
|
||||
// in Redis, but are eventually "persisted" to DynamoDB. This state changes in response to signals this publisher
|
||||
// receives as a MessageAvailabilityListener. As an initial state, we assume that we have messages in both DynamoDB
|
||||
// and Redis.
|
||||
private StoredMessageState storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
|
||||
// Indicates whether we've sent an "initial queue drain complete" signal to subscribers. This state will transition
|
||||
// from "not ready" to "pending" as soon as the initial message source subscription completes, and then from "pending"
|
||||
// to "send" when the signal has been sent. This state will never roll backwards.
|
||||
private QueueEmptySignalState queueEmptySignalState = QueueEmptySignalState.NOT_READY;
|
||||
|
||||
// The total requested demand from the subscriber across the whole lifetime of this publisher
|
||||
private long requestedDemand = 0;
|
||||
|
||||
// The total number of signals (new messages or "queue empty" signals) published during the lifetime of this
|
||||
// publisher. Must not exceed `requestedDemand`.
|
||||
private long publishedEntries = 0;
|
||||
|
||||
// The total number of published signals that have been acknowledged by the subscriber; to avoid re-reading messages,
|
||||
// we should never start a new message source subscriber until `acknowledgedEntries` is equal to `publishedEntries`
|
||||
private long acknowledgedEntries = 0;
|
||||
|
||||
// Although technically nullable, operation of this publisher really begins once we get a subscriber. This publisher
|
||||
// supports only a single subscriber.
|
||||
@Nullable private Flow.Subscriber<? super MessageStreamEntry> subscriber;
|
||||
|
||||
// If terminated (i.e. by an error or by downstream cancellation), this publisher will stop emitting signals. Once
|
||||
// terminated, a publisher cannot be un-terminated.
|
||||
private boolean terminated = false;
|
||||
|
||||
// A message source subscriber subscribes to messages from upstream data sources (i.e. DynamoDB and Redis), and this
|
||||
// publisher relays signals the message source subscriber to the downstream subscriber. The message source subscriber
|
||||
// may be null if we're not actively fetching messages from an upstream source and changes every time an upstream
|
||||
// publisher completes.
|
||||
@Nullable private MessageSourceSubscriber messageSourceSubscriber;
|
||||
|
||||
private static final String GET_MESSAGES_FOR_DEVICE_FLUX_NAME =
|
||||
name(RedisDynamoDbMessagePublisher.class, "getMessagesForDevice");
|
||||
|
||||
private enum StoredMessageState {
|
||||
// Indicates that stored messages are available in at least DynamoDB and possibly also Redis
|
||||
PERSISTED_NEW_MESSAGES_AVAILABLE,
|
||||
|
||||
// Indicates that messages are available in Redis, but have not yet been persisted to DynamoDB
|
||||
CACHED_NEW_MESSAGES_AVAILABLE,
|
||||
|
||||
// Indicates that no new messages are available in either Redis or DynamoDB
|
||||
EMPTY
|
||||
}
|
||||
|
||||
private enum QueueEmptySignalState {
|
||||
// Indicates that we are not yet ready to send the "initial queue drain complete" signal regardless of outstanding
|
||||
// demand
|
||||
NOT_READY,
|
||||
|
||||
// Indicates that we are ready to send the "queue empty" signal as soon as demand is available
|
||||
PENDING,
|
||||
|
||||
// Indicates that we have sent the "queue empty" signal and must never send it again
|
||||
SENT
|
||||
}
|
||||
|
||||
/// A message source subscriber subscribes to upstream message source publishers and relays signals to the downstream
|
||||
/// subscriber via the parent `RedisDynamoDbMessagePublisher`.
|
||||
private static class MessageSourceSubscriber extends BaseSubscriber<MessageProtos.Envelope> {
|
||||
|
||||
private final RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher;
|
||||
|
||||
private MessageSourceSubscriber(RedisDynamoDbMessagePublisher redisDynamoDbMessagePublisher) {
|
||||
this.redisDynamoDbMessagePublisher = redisDynamoDbMessagePublisher;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceSubscribed(subscription);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnNext(final MessageProtos.Envelope message) {
|
||||
redisDynamoDbMessagePublisher.handleNextMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnComplete() {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnError(final Throwable throwable) {
|
||||
redisDynamoDbMessagePublisher.handleMessageSourceError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
RedisDynamoDbMessagePublisher(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final UUID accountIdentifier,
|
||||
final Device device,
|
||||
final boolean terminateOnQueueEmpty) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.redisMessageAvailabilityManager = redisMessageAvailabilityManager;
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
this.terminateOnQueueEmpty = terminateOnQueueEmpty;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void subscribe(final Flow.Subscriber<? super MessageStreamEntry> subscriber) {
|
||||
if (this.subscriber != null) {
|
||||
subscriber.onError(new IllegalStateException("Redis/DynamoDB message publisher only allows one subscriber"));
|
||||
return;
|
||||
}
|
||||
|
||||
this.subscriber = subscriber;
|
||||
|
||||
@Nullable final CompletionStage<Void> clientConnectedFuture;
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// If we're trying to follow a live stream of messages, then listen for signals indicating that new messages are
|
||||
// available in Redis, that messages have been persisted from Redis to DynamoDB, or that there's a conflicting
|
||||
// message reader connected somewhere else
|
||||
clientConnectedFuture = redisMessageAvailabilityManager.handleClientConnected(accountIdentifier, device.getId(), this);
|
||||
} else {
|
||||
clientConnectedFuture = null;
|
||||
}
|
||||
|
||||
subscriber.onSubscribe(new Flow.Subscription() {
|
||||
@Override
|
||||
public void request(final long n) {
|
||||
addDemand(n);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
terminate();
|
||||
}
|
||||
});
|
||||
|
||||
// Defer the client connected handling until after onSubscribe() is called. Otherwise, onError() might be called
|
||||
// first, which violates the Reactive Streams spec.
|
||||
if (clientConnectedFuture != null) {
|
||||
clientConnectedFuture.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
handleMessageSourceError(throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleNewMessageAvailable() {
|
||||
// We only need to take action if we think there aren't already messages to pass downstream. Any other stored
|
||||
// message state implies that we're either actively sending messages downstream or we're waiting for demand from the
|
||||
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
|
||||
// we receive a request for more messages or when the current upstream publisher completes.
|
||||
if (storedMessageState == StoredMessageState.EMPTY) {
|
||||
storedMessageState = StoredMessageState.CACHED_NEW_MESSAGES_AVAILABLE;
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleMessagesPersisted() {
|
||||
// We only need to take action if we think there aren't already messages in DynamoDB. If we're already aware of
|
||||
// messages in DynamoDB, then we're either actively sending messages downstream or we're waiting for demand from the
|
||||
// downstream subscriber and don't need to take any action now. We'll call `maybeGenerateMessageSource` either when
|
||||
// we receive a request for more messages or when the current upstream publisher completes.
|
||||
if (storedMessageState != StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE) {
|
||||
storedMessageState = StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE;
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void handleConflictingMessageConsumer() {
|
||||
// We don't register as a listener for conflicting consumer signals until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
terminate();
|
||||
subscriber.onError(new ConflictingMessageConsumerException());
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void handleMessageAcknowledged() {
|
||||
acknowledgedEntries += 1;
|
||||
assert acknowledgedEntries <= publishedEntries;
|
||||
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
|
||||
private synchronized boolean maybeSendQueueEmptySignal() {
|
||||
// Regardless of any other state, don't do anything if terminated
|
||||
if (terminated) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't send a "queue empty" signal if we're supposed to terminate when the queue is empty
|
||||
if (terminateOnQueueEmpty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (queueEmptySignalState == QueueEmptySignalState.PENDING && publishedEntries < requestedDemand) {
|
||||
queueEmptySignalState = QueueEmptySignalState.SENT;
|
||||
publishedEntries += 1;
|
||||
|
||||
// Subscribers don't explicitly acknowledge "queue empty" signals, and we can consider them automatically
|
||||
// acknowledged
|
||||
acknowledgedEntries += 1;
|
||||
|
||||
subscriber.onNext(new MessageStreamEntry.QueueEmpty());
|
||||
|
||||
assert publishedEntries <= requestedDemand;
|
||||
assert acknowledgedEntries <= publishedEntries;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private synchronized void maybeGenerateMessageSource() {
|
||||
if (terminated) {
|
||||
// Regardless of any other state, don't do anything if terminated
|
||||
return;
|
||||
}
|
||||
|
||||
if (messageSourceSubscriber != null) {
|
||||
// We're still working through a previous message source; wait until it completes before starting a new one.
|
||||
return;
|
||||
}
|
||||
|
||||
if (acknowledgedEntries < publishedEntries) {
|
||||
// To avoid double-reading messages from data stores that don't support cursors, don't get a new message source
|
||||
// unless all previously-published signals have been acknowledged (when messages are acknowledged, we'll come back
|
||||
// to this point with a higher value for `acknowledgedEntries` via `handleMessageAcknowledged`)
|
||||
return;
|
||||
}
|
||||
|
||||
if (terminateOnQueueEmpty && queueEmptySignalState == QueueEmptySignalState.PENDING) {
|
||||
// If we've acknowledged everything we've published and we're ready to send a "queue empty" signal, we can use the
|
||||
// "ready to send a 'queue empty' signal" state as our cue to terminate the subscription
|
||||
assert subscriber != null;
|
||||
|
||||
subscriber.onComplete();
|
||||
terminate();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (storedMessageState == StoredMessageState.EMPTY) {
|
||||
// We don't think there are any messages in either message source; don't do anything until the situation changes
|
||||
// (when new messages arrive, we'll come back to this point with a non-empty stored message state)
|
||||
return;
|
||||
}
|
||||
|
||||
if (publishedEntries == requestedDemand) {
|
||||
// Even if there are messages available, there's no demand for them yet (when there's new demand, we'll come back
|
||||
// to this point with a higher value for `requestedDemand` via `addDemand`)
|
||||
return;
|
||||
}
|
||||
|
||||
// We maybe be able to skip reading from DynamoDB entirely if we think messages are only stored in Redis
|
||||
final Publisher<MessageProtos.Envelope> dynamoPublisher =
|
||||
storedMessageState == StoredMessageState.PERSISTED_NEW_MESSAGES_AVAILABLE
|
||||
? messagesDynamoDb.load(accountIdentifier, device, null)
|
||||
: Flux.empty();
|
||||
|
||||
final Publisher<MessageProtos.Envelope> redisPublisher = messagesCache.get(accountIdentifier, device.getId());
|
||||
|
||||
final Flux<MessageProtos.Envelope> messageSource = Flux.concat(dynamoPublisher, redisPublisher)
|
||||
.name(GET_MESSAGES_FOR_DEVICE_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
|
||||
messageSourceSubscriber = new MessageSourceSubscriber(this);
|
||||
messageSource.subscribe(messageSourceSubscriber);
|
||||
|
||||
// If nothing else happens before the DynamoDB/Redis publisher completes, then we'll have emptied all stored
|
||||
// messages; new signals about persisted messages or newly-arrived messages will change this state
|
||||
storedMessageState = StoredMessageState.EMPTY;
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceSubscribed(final Subscription subscription) {
|
||||
if (!terminated) {
|
||||
// If we already have some unmet demand, pass that on to the upstream publisher immediately on subscribing
|
||||
if (requestedDemand > publishedEntries) {
|
||||
subscription.request(requestedDemand - publishedEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void handleNextMessage(final MessageProtos.Envelope message) {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
// We only pass along unfulfilled demand to the message source subscriber, so if the message source subscriber
|
||||
// emits a new signal, it should fit within the unfulfilled demand from the downstream subscriber
|
||||
assert publishedEntries < requestedDemand;
|
||||
|
||||
publishedEntries += 1;
|
||||
subscriber.onNext(new MessageStreamEntry.Envelope(message));
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceComplete() {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
messageSourceSubscriber = null;
|
||||
|
||||
if (queueEmptySignalState == QueueEmptySignalState.NOT_READY) {
|
||||
queueEmptySignalState = QueueEmptySignalState.PENDING;
|
||||
maybeSendQueueEmptySignal();
|
||||
}
|
||||
|
||||
// New messages may have arrived already; fetch them if possible
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
|
||||
private synchronized void handleMessageSourceError(final Throwable throwable) {
|
||||
// The machinery that produces messages won't activate until we have a subscriber
|
||||
assert subscriber != null;
|
||||
|
||||
if (!terminated) {
|
||||
terminate();
|
||||
subscriber.onError(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void addDemand(final long demand) {
|
||||
if (demand <= 0) {
|
||||
throw new IllegalArgumentException("Demand must be positive");
|
||||
}
|
||||
|
||||
requestedDemand += demand;
|
||||
|
||||
final boolean sentQueueEmptySignal = maybeSendQueueEmptySignal();
|
||||
|
||||
// This is a little tricky; if we already have a subscriber, we only want to request NEW demand, not the total
|
||||
// outstanding demand. On top of that, we may have consumed some demand by sending a "queue empty" message.
|
||||
final long newDemand = demand - (sentQueueEmptySignal ? 1 : 0);
|
||||
|
||||
if (newDemand > 0) {
|
||||
if (messageSourceSubscriber != null) {
|
||||
messageSourceSubscriber.request(newDemand);
|
||||
} else {
|
||||
maybeGenerateMessageSource();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void terminate() {
|
||||
if (!terminated) {
|
||||
terminated = true;
|
||||
|
||||
if (messageSourceSubscriber != null) {
|
||||
messageSourceSubscriber.dispose();
|
||||
messageSourceSubscriber = null;
|
||||
}
|
||||
|
||||
// Stop receiving signals about new messages/conflicting consumers
|
||||
redisMessageAvailabilityManager.handleClientDisconnected(accountIdentifier, device.getId(), this);
|
||||
}
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
/// A [MessageStream] implementation that produces message from a joint DynamoDB/Redis message store.
|
||||
public class RedisDynamoDbMessageStream implements MessageStream {
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
|
||||
private final UUID accountIdentifier;
|
||||
private final Device device;
|
||||
|
||||
private final RedisDynamoDbMessagePublisher messagePublisher;
|
||||
|
||||
private static final String MESSAGE_READ_COUNTER_NAME =
|
||||
name(RedisDynamoDbMessageStream.class, "messagesRead");
|
||||
|
||||
private static final String MESSAGE_ACKNOWLEDGED_COUNTER_NAME =
|
||||
name(RedisDynamoDbMessageStream.class, "messagesAcknowledged");
|
||||
|
||||
private static final String UUID_VERSION_TAG = "uuidVersion";
|
||||
|
||||
public RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final RedisMessageAvailabilityManager redisMessageAvailabilityManager,
|
||||
final UUID accountIdentifier,
|
||||
final Device device,
|
||||
final boolean terminateOnQueueEmpty) {
|
||||
|
||||
this(messagesDynamoDb, messagesCache, accountIdentifier, device, new RedisDynamoDbMessagePublisher(messagesDynamoDb,
|
||||
messagesCache,
|
||||
redisMessageAvailabilityManager,
|
||||
accountIdentifier,
|
||||
device,
|
||||
terminateOnQueueEmpty));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
RedisDynamoDbMessageStream(final MessagesDynamoDb messagesDynamoDb,
|
||||
final MessagesCache messagesCache,
|
||||
final UUID accountIdentifier,
|
||||
final Device device,
|
||||
final RedisDynamoDbMessagePublisher messagePublisher) {
|
||||
|
||||
this.messagesDynamoDb = messagesDynamoDb;
|
||||
this.messagesCache = messagesCache;
|
||||
this.accountIdentifier = accountIdentifier;
|
||||
this.device = device;
|
||||
this.messagePublisher = messagePublisher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(messagePublisher)
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope(org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope message)) {
|
||||
final UUID messageGuid = UUIDUtil.fromByteString(message.getServerGuid());
|
||||
|
||||
Metrics.counter(MESSAGE_READ_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
|
||||
.increment();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
Metrics.counter(MESSAGE_ACKNOWLEDGED_COUNTER_NAME, UUID_VERSION_TAG, String.valueOf(messageGuid.version()))
|
||||
.increment();
|
||||
|
||||
return messagesCache.remove(accountIdentifier, device.getId(), messageGuid)
|
||||
.thenCompose(removed -> removed.map(_ -> CompletableFuture.<Void>completedFuture(null))
|
||||
.orElseGet(() ->
|
||||
messagesDynamoDb.deleteMessage(accountIdentifier, device, messageGuid, serverTimestamp)
|
||||
.thenRun(Util.NOOP)))
|
||||
.whenComplete((_, _) -> messagePublisher.handleMessageAcknowledged());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -138,7 +138,8 @@ public class AppleDeviceCheckManager {
|
||||
final DCAttestationData dcAttestationData;
|
||||
try {
|
||||
dcAttestationData = deviceCheckManager.validate(dcAttestationRequest,
|
||||
new DCAttestationParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(challenge))));
|
||||
new DCAttestationParameters(new DCServerProperty(teamId, bundleId,
|
||||
new DefaultChallenge(challenge.getBytes(StandardCharsets.UTF_8)))));
|
||||
} catch (VerificationException e) {
|
||||
logger.info("Failed to verify attestation", e);
|
||||
throw new DeviceCheckVerificationFailedException(e);
|
||||
|
||||
+3
@@ -171,6 +171,9 @@ public class FaultTolerantDatabase {
|
||||
READ_STATUS("readStatus"),
|
||||
READ_VERSIONSTAMP("readVersionstamp"),
|
||||
RECORD_VERSIONSTAMP_AND_TIME("recordVersionstampAndTime"),
|
||||
GET_HAS_MESSAGES("hasMessages"),
|
||||
GET_HAS_URGENT_MESSAGES("hasUrgentMessages"),
|
||||
GET_EARLIEST_TIMESTAMP("getEarliestTimestamp"),
|
||||
TEST("test");
|
||||
|
||||
private final String name;
|
||||
|
||||
+78
-15
@@ -1,6 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
@@ -8,6 +9,8 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -42,6 +45,8 @@ class FoundationDbMessagePublisher {
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
private final byte[] readsSinceLastAcknowledgedMessageKey;
|
||||
|
||||
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
|
||||
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
|
||||
@Nullable private final byte[] presenceKey;
|
||||
@@ -87,6 +92,12 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
private static final int STREAM_ID_UNASSIGNED = -1;
|
||||
|
||||
// FoundationDB's `ADD` mutation operate on little-endian, 64-bit integers rather than on tuple-encoded integers
|
||||
private static final byte[] ONE_LITTLE_ENDIAN = ByteBuffer.allocate(Long.BYTES)
|
||||
.order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putLong(1L)
|
||||
.array();
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
private static final String WATCHES_COUNTER = MetricsUtil.name(FoundationDbMessagePublisher.class, "watches");
|
||||
@@ -131,6 +142,7 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int streamId,
|
||||
final byte[] readsSinceLastAcknowledgedMessageKey,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@@ -141,6 +153,7 @@ class FoundationDbMessagePublisher {
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.streamId = streamId;
|
||||
this.readsSinceLastAcknowledgedMessageKey = readsSinceLastAcknowledgedMessageKey;
|
||||
this.presenceKey = presenceKey;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
@@ -176,13 +189,15 @@ class FoundationDbMessagePublisher {
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive) {
|
||||
final KeySelector endKeyExclusive,
|
||||
final byte[] readsSinceHeadAcknowledgedKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
STREAM_ID_UNASSIGNED,
|
||||
readsSinceHeadAcknowledgedKey,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -198,6 +213,7 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int streamId,
|
||||
final byte[] readsSinceHeadAcknowledgedKey,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
@@ -207,6 +223,7 @@ class FoundationDbMessagePublisher {
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
streamId,
|
||||
readsSinceHeadAcknowledgedKey,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
@@ -316,7 +333,22 @@ class FoundationDbMessagePublisher {
|
||||
// This is an unbounded publisher and we've established presence, so we should check for conflicts
|
||||
checkPresenceFuture = transaction.get(presenceKey)
|
||||
.thenAccept(presenceValue -> {
|
||||
if (presenceValue == null) {
|
||||
// We wrote a presence key earlier, but now it is gone. Two possibilities:
|
||||
// 1. The queue was cleared by an account/device delete. We should eventually get a disconnection
|
||||
// request so we should stay present until then.
|
||||
// 2. Someone else connected, wrote their own presence key, and then disconnected (nulling the key),
|
||||
// without us ever noticing an update to messagesAvailableWatchKey. Though we briefly did
|
||||
// conflict, we're not conflicting any more so we can continue.
|
||||
// In either case, we can try to re-establish our presence (unless we've already been disposed)
|
||||
if (!isTerminated()) {
|
||||
setPresence(transaction);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPresenceContested(presenceValue)) {
|
||||
// Someone else established presence over us
|
||||
throw new CompletionException(new ConflictingMessageConsumerException());
|
||||
}
|
||||
});
|
||||
@@ -330,7 +362,14 @@ class FoundationDbMessagePublisher {
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList(),
|
||||
(_, keyValues) -> keyValues)
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
|
||||
final int keyValuesSize = keyValues.size();
|
||||
|
||||
if (keyValuesSize > 0 && !hasEmittedEntry()) {
|
||||
// We're about to emit our first message; increment the "sent head of queue since last ACK" counter
|
||||
incrementReadsSinceHeadAcknowledged(transaction);
|
||||
}
|
||||
|
||||
if (keyValuesSize < maxMessages && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
@@ -383,6 +422,10 @@ class FoundationDbMessagePublisher {
|
||||
return (int) Math.min(totalRequested - totalEmitted, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
private synchronized boolean hasEmittedEntry() {
|
||||
return totalEmitted > 0;
|
||||
}
|
||||
|
||||
/// Fetch and publish messages. Messages are fetched in batches to avoid excessive memory consumption. After each
|
||||
/// fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading from. If the fetch
|
||||
/// operation returns fewer items than the batch size, we infer that we have fetched all available messages and
|
||||
@@ -411,12 +454,23 @@ class FoundationDbMessagePublisher {
|
||||
return this.messagePublisher;
|
||||
}
|
||||
|
||||
private void incrementReadsSinceHeadAcknowledged(final Transaction transaction) {
|
||||
transaction.mutate(MutationType.ADD, readsSinceLastAcknowledgedMessageKey, ONE_LITTLE_ENDIAN);
|
||||
}
|
||||
|
||||
private synchronized void setWatch(final Transaction transaction) {
|
||||
assert messagesAvailableWatchKey != null;
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
if (isTerminated()) {
|
||||
// If we're already in a terminal state, we don't want to set a watch that would leak
|
||||
return;
|
||||
}
|
||||
|
||||
if (watchFuture != null && !watchFuture.isDone()) {
|
||||
LOGGER.warn("Setting a watch before previous watch future is done");
|
||||
}
|
||||
|
||||
cancelWatch();
|
||||
|
||||
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
|
||||
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
|
||||
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
|
||||
@@ -451,7 +505,9 @@ class FoundationDbMessagePublisher {
|
||||
final ScheduledFuture<?> scheduledFuture = presenceRenewalExecutorService.schedule(() -> {
|
||||
renewPresence().whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence", throwable);
|
||||
if (!ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to renew presence", throwable);
|
||||
}
|
||||
renewPresenceFuture.completeExceptionally(throwable);
|
||||
} else {
|
||||
renewPresenceFuture.complete(null);
|
||||
@@ -481,16 +537,20 @@ class FoundationDbMessagePublisher {
|
||||
}
|
||||
|
||||
private synchronized CompletableFuture<Void> renewPresence() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
if (isTerminated()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
|
||||
}
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}, FaultTolerantDatabase.Context.SET_PRESENCE);
|
||||
}
|
||||
|
||||
private void setPresence(final Transaction transaction) {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void clearPresence() {
|
||||
if (renewPresenceFuture != null) {
|
||||
@@ -498,31 +558,34 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
renewPresenceFuture.whenComplete((_, _) ->
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
if (!isPresenceContested(presenceValue)) {
|
||||
if (presenceValue == null || !isPresenceContested(presenceValue)) {
|
||||
// Note: we still try to set the value to null even if it is already null. This way we would still
|
||||
// cause a FoundationDB transaction conflict with a concurrent presence renewal that was updating
|
||||
// from null to something else.
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}), FaultTolerantDatabase.Context.CLEAR_PRESENCE)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
if (throwable != null && !ExceptionUtils.isBreakerOpen(throwable)) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// @return true if a publisher other than us has claimed presence
|
||||
private boolean isPresenceContested(final byte[] presenceValue) {
|
||||
if (presenceValue == null) {
|
||||
// Some other process has cleared our presence key, so we must assume a conflict somewhere
|
||||
return true;
|
||||
}
|
||||
|
||||
return streamId != FoundationDbMessageStore.getPresenceStreamId(presenceValue) ||
|
||||
!Arrays.equals(FoundationDbMessageStore.getPresenceServerId(presenceValue), FoundationDbMessageStore.getServerId());
|
||||
}
|
||||
|
||||
private synchronized boolean isTerminated() {
|
||||
return state == State.TERMINATED || state == State.ERROR;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void terminateWithError(final Throwable throwable) {
|
||||
if (state != State.TERMINATED && state != State.ERROR && !emitter.isCancelled()) {
|
||||
if (!isTerminated() && !emitter.isCancelled()) {
|
||||
setState(State.ERROR, Event.INTERNAL_TRIGGER);
|
||||
emitter.error(throwable);
|
||||
}
|
||||
@@ -531,7 +594,7 @@ class FoundationDbMessagePublisher {
|
||||
private synchronized void onDispose() {
|
||||
// Unless the state machine is an already terminal state, directly set state to "terminated", since there's no point
|
||||
// in evaluating the state machine when there's no live subscription.
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
if (!isTerminated()) {
|
||||
setState(State.TERMINATED, Event.INTERNAL_TRIGGER);
|
||||
}
|
||||
cancelWatch();
|
||||
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user