mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:26:47 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdd461b8f4 | ||
|
|
d9a54a0d42 | ||
|
|
3f3aa89b0f | ||
|
|
55fa60dd4e | ||
|
|
b539df8e48 | ||
|
|
0cd0716eb5 | ||
|
|
6386aada73 | ||
|
|
5c44398bb5 | ||
|
|
54736bb117 | ||
|
|
aed8e60789 | ||
|
|
5fa50e8ad7 | ||
|
|
fdaba751bd | ||
|
|
0eebb58956 | ||
|
|
6bb85d77a7 | ||
|
|
9e3844ee5a | ||
|
|
7ee8e349e2 | ||
|
|
4d9e252697 | ||
|
|
222e5a033b | ||
|
|
8c6fbbfa65 | ||
|
|
b0b2122d8c | ||
|
|
d7711e235b | ||
|
|
5174550ef3 | ||
|
|
d0fcb9ab54 |
No files matched your search
@@ -17,6 +17,7 @@ jobs:
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
@@ -35,3 +36,11 @@ jobs:
|
||||
echo "${INTEGRATION_TEST_CONFIG}" > integration-tests/src/main/resources/config.yml
|
||||
- name: Run and verify integration tests
|
||||
run: ./mvnw clean compile test-compile failsafe:integration-test failsafe:verify -P aws-sso
|
||||
- name: Open an issue on failure
|
||||
if: ${{ failure() && github.event_name == 'schedule' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh issue create \
|
||||
--title "Failed server integration tests ($(date +'%Y-%m-%d'))" \
|
||||
--body "Workflow **${{ github.workflow }}** failed. See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
@@ -67,7 +67,7 @@
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<logback.version>1.5.32</logback.version>
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.12</logback-access-common.version>
|
||||
<lettuce.version>7.5.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.21</libphonenumber.version>
|
||||
|
||||
@@ -365,8 +365,6 @@ badges:
|
||||
svgs:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
badgeIdsEnabledForAll:
|
||||
- TEST
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
|
||||
|
||||
@@ -178,6 +178,7 @@ import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
@@ -316,6 +317,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
@@ -391,6 +393,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
|
||||
bootstrap.addCommand(new CopyToS3Command());
|
||||
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -1067,7 +1070,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().embedSigner());
|
||||
|
||||
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC()),
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
@@ -1080,7 +1083,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters))
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
List.of(stripeManager, braintreeManager), profileBadgeConverter,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()))
|
||||
.map(bindableService -> ServerInterceptors.intercept(bindableService,
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
|
||||
+1
-18
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.badges;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -31,7 +30,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
|
||||
private final Clock clock;
|
||||
private final Map<String, BadgeConfiguration> knownBadges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
|
||||
|
||||
public ConfiguredProfileBadgeConverter(
|
||||
@@ -41,7 +39,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
this.clock = clock;
|
||||
this.knownBadges = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.badgeIdsEnabledForAll = badgesConfiguration.getBadgeIdsEnabledForAll();
|
||||
this.headerControlledResourceBundleLookup = headerControlledResourceBundleLookup;
|
||||
}
|
||||
|
||||
@@ -73,7 +70,7 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
final List<Locale> acceptableLanguages,
|
||||
final List<AccountBadge> accountBadges,
|
||||
final boolean isSelf) {
|
||||
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
|
||||
if (accountBadges.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -99,20 +96,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
accountBadge.visible());
|
||||
})
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
|
||||
BadgeConfiguration configuration = knownBadges.get(id);
|
||||
return newBadge(
|
||||
isSelf,
|
||||
id,
|
||||
configuration.getCategory(),
|
||||
resourceBundle.getString(id + "_name"),
|
||||
resourceBundle.getString(id + "_description"),
|
||||
configuration.getSprites(),
|
||||
configuration.getSvg(),
|
||||
configuration.getSvgs(),
|
||||
now.plus(Duration.ofDays(1)),
|
||||
true);
|
||||
}).collect(Collectors.toList()));
|
||||
return badges;
|
||||
}
|
||||
|
||||
|
||||
-9
@@ -21,16 +21,13 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class BadgesConfiguration {
|
||||
private final List<BadgeConfiguration> badges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final Map<Long, String> receiptLevels;
|
||||
|
||||
@JsonCreator
|
||||
public BadgesConfiguration(
|
||||
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
|
||||
@JsonProperty("badgeIdsEnabledForAll") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<String> badgeIdsEnabledForAll,
|
||||
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
|
||||
this.badges = Objects.requireNonNull(badges);
|
||||
this.badgeIdsEnabledForAll = Objects.requireNonNull(badgeIdsEnabledForAll);
|
||||
this.receiptLevels = Objects.requireNonNull(receiptLevels);
|
||||
}
|
||||
|
||||
@@ -40,12 +37,6 @@ public class BadgesConfiguration {
|
||||
return badges;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public List<String> getBadgeIdsEnabledForAll() {
|
||||
return badgeIdsEnabledForAll;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public Map<Long, String> getReceiptLevels() {
|
||||
|
||||
+34
-1
@@ -7,6 +7,8 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
@@ -26,6 +28,8 @@ import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -70,16 +74,19 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final Clock clock;
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final Clock clock) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -103,6 +110,32 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetEntitlementsResponse getEntitlements(final GetEntitlementsRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final GetEntitlementsResponse.Builder builder = GetEntitlementsResponse.newBuilder();
|
||||
|
||||
final Instant now = clock.instant();
|
||||
|
||||
final Account.BackupVoucher backupVoucher = account.getBackupVoucher();
|
||||
if (backupVoucher != null && backupVoucher.expiration().isAfter(now)) {
|
||||
builder.setBackup(GetEntitlementsResponse.BackupEntitlement.newBuilder()
|
||||
.setExpirationEpochSeconds(backupVoucher.expiration().getEpochSecond())
|
||||
.setLevel(backupVoucher.receiptLevel()));
|
||||
}
|
||||
|
||||
builder.addAllBadges(account.getBadges().stream()
|
||||
.filter(badge -> badge.expiration().isAfter(now))
|
||||
.map(badge -> GetEntitlementsResponse.BadgeEntitlement.newBuilder()
|
||||
.setBadgeId(badge.id())
|
||||
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
|
||||
.setVisible(badge.visible())
|
||||
.build())
|
||||
.toList());
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
|
||||
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
|
||||
public class BadgeGrpcHelper {
|
||||
|
||||
public static Badge toGrpcBadge(final org.whispersystems.textsecuregcm.entities.Badge badge) {
|
||||
final Badge.Builder builder = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg());
|
||||
|
||||
badge.getSvgs().stream()
|
||||
.map(badgeSvg -> BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build())
|
||||
.forEach(builder::addSvgs);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -138,7 +138,9 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
final Device device = account.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally if it's an APNS request
|
||||
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
|
||||
+12
@@ -30,6 +30,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -65,12 +66,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@VisibleForTesting
|
||||
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME =
|
||||
MetricsUtil.name(MetricServerInterceptor.class, "activeRequests");
|
||||
|
||||
private final MeterRegistry meterRegistry;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -194,6 +202,8 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
|
||||
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
|
||||
this.sample = Timer.start(meterRegistry);
|
||||
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -210,12 +220,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public void onComplete() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
+5
-17
@@ -13,8 +13,6 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
import org.signal.chat.purchase.AmountList;
|
||||
import org.signal.chat.purchase.BackupConfiguration;
|
||||
import org.signal.chat.purchase.BackupLevelConfiguration;
|
||||
@@ -158,22 +156,12 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
|
||||
|
||||
private static LevelConfiguration toProtoLevelConfiguration(
|
||||
final org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration levelConfiguration) {
|
||||
final org.whispersystems.textsecuregcm.entities.Badge badge = levelConfiguration.badge();
|
||||
final Badge commonBadge = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(badge.getSvgs().stream()
|
||||
.map(s -> BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
|
||||
.toList())
|
||||
.build();
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder().setBadge(commonBadge);
|
||||
if (badge instanceof final PurchasableBadge purchasableBadge) {
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder();
|
||||
if (levelConfiguration.badge() instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder.build();
|
||||
return builder
|
||||
.setBadge(BadgeGrpcHelper.toGrpcBadge(levelConfiguration.badge()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -129,7 +129,6 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
return targetAccount.map(account ->
|
||||
GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
null,
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build())
|
||||
@@ -142,7 +141,21 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthenticationCase()) {
|
||||
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
|
||||
case UNIDENTIFIED_ACCESS_KEY ->
|
||||
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
|
||||
.orElse(false);
|
||||
default -> throw GrpcExceptions.invalidArguments("invalid authentication");
|
||||
};
|
||||
|
||||
if (!authorized) {
|
||||
return GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return targetAccount.flatMap(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account,
|
||||
|
||||
@@ -10,14 +10,11 @@ import com.google.protobuf.ByteString;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
@@ -33,6 +30,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -129,23 +127,6 @@ public class ProfileGrpcHelper {
|
||||
return Optional.of(responseBuilder.build());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<Badge> buildBadges(final List<org.whispersystems.textsecuregcm.entities.Badge> badges) {
|
||||
final ArrayList<Badge> grpcBadges = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.Badge badge : badges) {
|
||||
grpcBadges.add(Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(buildBadgeSvgs(badge.getSvgs()))
|
||||
.build());
|
||||
}
|
||||
return grpcBadges;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<org.signal.chat.common.DeviceCapability> buildAccountCapabilities(final Account account) {
|
||||
return Arrays.stream(DeviceCapability.values())
|
||||
@@ -155,20 +136,8 @@ public class ProfileGrpcHelper {
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<BadgeSvg> buildBadgeSvgs(final List<org.whispersystems.textsecuregcm.entities.BadgeSvg> badgeSvgs) {
|
||||
ArrayList<BadgeSvg> grpcBadgeSvgs = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.BadgeSvg badgeSvg : badgeSvgs) {
|
||||
grpcBadgeSvgs.add(BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build());
|
||||
}
|
||||
return grpcBadgeSvgs;
|
||||
}
|
||||
|
||||
static GetUnversionedProfileResult buildUnversionedProfileResult(
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final UUID requesterUuid,
|
||||
final Account targetAccount,
|
||||
final ProfileBadgeConverter profileBadgeConverter) {
|
||||
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
|
||||
@@ -177,11 +146,13 @@ public class ProfileGrpcHelper {
|
||||
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> {
|
||||
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(
|
||||
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
targetAccount.getBadges(),
|
||||
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
|
||||
final List<Locale> acceptedLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
|
||||
final List<Badge> badges =
|
||||
profileBadgeConverter.convert(acceptedLocales, targetAccount.getBadges(), false);
|
||||
|
||||
resultBuilder
|
||||
.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList());
|
||||
|
||||
targetAccount.getUnidentifiedAccessKey()
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
|
||||
@@ -260,7 +260,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
|
||||
|
||||
+15
@@ -16,6 +16,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
@@ -44,6 +45,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestBytes");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME = name(MetricsRequestEventListener.class, "activeRequests");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
|
||||
@@ -65,6 +68,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
private final TrafficSource trafficSource;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
|
||||
|
||||
@@ -81,10 +86,20 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
this.trafficSource = trafficSource;
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(final RequestEvent event) {
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) {
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_FINISHED) {
|
||||
activeRequests.decrement();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.FINISHED) {
|
||||
if (!event.getUriInfo().getMatchedTemplates().isEmpty()) {
|
||||
@Nullable final UserAgent userAgent;
|
||||
|
||||
+41
-6
@@ -61,12 +61,18 @@ public class MessagesManager {
|
||||
private static final String PRESENCE_MATCH_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "presenceMatch");
|
||||
|
||||
private static final Counter INSERT_TIMEOUT_COUNTER =
|
||||
Metrics.counter(name(MessagesManager.class, "insertTimeout"));
|
||||
|
||||
@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";
|
||||
|
||||
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
@@ -129,10 +135,14 @@ public class MessagesManager {
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
|
||||
.exceptionally(e -> {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
if (e instanceof TimeoutException) {
|
||||
INSERT_TIMEOUT_COUNTER.increment();
|
||||
} else {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
|
||||
return Collections.emptyMap();
|
||||
});
|
||||
@@ -283,9 +293,9 @@ public class MessagesManager {
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice);
|
||||
|
||||
return new DeletionMirroringMessageStream(
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
@@ -387,4 +397,29 @@ public class MessagesManager {
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
public void recordFoundationDbVersionstamps() {
|
||||
foundationDbMessageStore.recordVersionstamps();
|
||||
}
|
||||
|
||||
/// Clean up expired entries in the FoundationDB versionstamp clock.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldFoundationDbVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
foundationDbMessageStore.expireOldVersionstamps(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
|
||||
/// Delete messages in FoundationDB for the given devices that were inserted before the given
|
||||
/// time. (Expiration of messages from Redis and Dynamo is handled automatically and do not
|
||||
/// require any interaction with this class.)
|
||||
///
|
||||
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
|
||||
/// trimmed.
|
||||
///
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be.
|
||||
public void deleteFoundationDbMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime);
|
||||
}
|
||||
}
|
||||
+26
-8
@@ -12,28 +12,30 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class DeletionMirroringMessageStream implements MessageStream {
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DeletionMirroringMessageStream.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
public DeletionMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStore foundationDbMessageStore,
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
@@ -42,6 +44,22 @@ public class DeletionMirroringMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
final Disposable foundationDbDisposable =
|
||||
foundationDbMessageStream.getFiniteMessageStream()
|
||||
.limitRate(100)
|
||||
.subscribe();
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
foundationDbDisposable.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@@ -52,7 +70,7 @@ public class DeletionMirroringMessageStream implements MessageStream {
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
foundationDbMessageStore.delete(accountIdentifier, deviceId, messageGuid)
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/// An acknowledged message buffer keeps track of messages that have been sent, whether they have been acknowledged by
|
||||
/// the recipient, and whether those acknowledgements have been flushed to the underlying data store. It also batches
|
||||
/// acknowledgements into contiguous ranges in the interest of efficiency.
|
||||
class AcknowledgedMessageBuffer {
|
||||
|
||||
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
|
||||
private final int maxUnacknowledgedMessages;
|
||||
|
||||
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
|
||||
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
|
||||
private int unacknowledgedMessages = 0;
|
||||
|
||||
AcknowledgedMessageBuffer(final int maxUnacknowledgedMessages) {
|
||||
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
|
||||
}
|
||||
|
||||
public synchronized void addUnacknowledgedMessage(final Versionstamp versionstamp) throws TooManyUnacknowledgedMessagesException {
|
||||
if (++unacknowledgedMessages > maxUnacknowledgedMessages) {
|
||||
throw new TooManyUnacknowledgedMessagesException();
|
||||
}
|
||||
|
||||
sentVersionstamps.put(versionstamp, false);
|
||||
}
|
||||
|
||||
public synchronized void acknowledgeMessage(final Versionstamp versionstamp) {
|
||||
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
|
||||
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unacknowledgedMessages--;
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int getUnacknowledgedMessageCount() {
|
||||
return unacknowledgedMessages;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database and removes
|
||||
/// them from ths unacknowledged mesage buffer.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
public synchronized List<Pair<Versionstamp, Versionstamp>> takeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
|
||||
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
@VisibleForTesting
|
||||
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
|
||||
Versionstamp startInclusive = null;
|
||||
Versionstamp endInclusive = null;
|
||||
|
||||
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
|
||||
if (entry.getValue()) {
|
||||
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
|
||||
// current range
|
||||
if (startInclusive == null) {
|
||||
startInclusive = entry.getKey();
|
||||
}
|
||||
endInclusive = entry.getKey();
|
||||
} else {
|
||||
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
|
||||
// acknowledged range. Mark the currently tracked range flushable, if it exists.
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
startInclusive = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
}
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
|
||||
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
|
||||
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
|
||||
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
|
||||
///
|
||||
/// @param versionstamp The versionstamp to acknowledge
|
||||
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
}
|
||||
+52
-90
@@ -10,9 +10,9 @@ import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
@@ -20,15 +20,13 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
@@ -60,10 +58,6 @@ class FoundationDbMessagePublisher {
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
@@ -131,8 +125,7 @@ class FoundationDbMessagePublisher {
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
@@ -143,37 +136,37 @@ class FoundationDbMessagePublisher {
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
Objects.requireNonNull(presenceKey);
|
||||
Objects.requireNonNull(presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(n -> {
|
||||
final long totalRequestedCount = totalRequested.addAndGet(n);
|
||||
if (totalRequestedCount > totalEmitted.get()) {
|
||||
transitionStateOnEvent(Event.DEMAND_REQUESTED);
|
||||
}
|
||||
});
|
||||
emitter.onDispose(this::onDispose);
|
||||
}).doOnSubscribe(_ -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence immediately and block until we do. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
database.run(transaction -> {
|
||||
setPresence(transaction);
|
||||
return null;
|
||||
});
|
||||
|
||||
// Refresh presence at regular intervals
|
||||
startPresenceRenewal(presenceRenewalExecutorService);
|
||||
}
|
||||
});
|
||||
this.messagePublisher = Mono.fromFuture(() -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence before attempting to fetch messages. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
return database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.thenRun(() -> startPresenceRenewal(presenceRenewalExecutorService));
|
||||
} else {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
})
|
||||
.thenMany(Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(n -> {
|
||||
final long totalRequestedCount = totalRequested.addAndGet(n);
|
||||
if (totalRequestedCount > totalEmitted.get()) {
|
||||
transitionStateOnEvent(Event.DEMAND_REQUESTED);
|
||||
}
|
||||
});
|
||||
emitter.onDispose(this::onDispose);
|
||||
}));
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
|
||||
@@ -185,8 +178,7 @@ class FoundationDbMessagePublisher {
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final int maxMessagesPerScan) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
@@ -196,8 +188,7 @@ class FoundationDbMessagePublisher {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
@@ -211,8 +202,7 @@ class FoundationDbMessagePublisher {
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
@@ -222,8 +212,7 @@ class FoundationDbMessagePublisher {
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
@@ -312,70 +301,43 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
|
||||
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
|
||||
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
|
||||
/// Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans.
|
||||
///
|
||||
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
|
||||
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
|
||||
return database.runAsync(transaction ->
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
doBeforePageFetch.accept(transaction);
|
||||
|
||||
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
return lastKeyReadAndItems;
|
||||
});
|
||||
})
|
||||
// Defer any state mutations until after the transaction has been committed. The transaction block can
|
||||
// fail/retry, and we don't want to trigger spurious state transitions when that happens.
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first()
|
||||
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan) {
|
||||
return keyValues;
|
||||
}))
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
}
|
||||
|
||||
return lastKeyReadAndItems.second();
|
||||
});
|
||||
}
|
||||
if (keyValues.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
|
||||
///
|
||||
/// @param transaction the FoundationDB transaction in which to perform the read query
|
||||
/// @param beginInclusive the range start key (inclusive)
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
|
||||
beginKeyCursor = KeySelector.firstGreaterThan(keyValues.getLast().getKey());
|
||||
|
||||
return keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
|
||||
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp,
|
||||
MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+15
-12
@@ -349,13 +349,11 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
// Note that this method is intended only for initial migration support; in general, callers should clear messages
|
||||
// by acknowledging messages via a `FoundationDbMessageStream`.
|
||||
public CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
@@ -393,15 +391,13 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
|
||||
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
@@ -411,13 +407,12 @@ public class FoundationDbMessageStore {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
|
||||
getPresenceKey(aci, deviceId),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
return new FoundationDbMessageStream(this,
|
||||
aci,
|
||||
deviceId,
|
||||
databasesForQueueByEpoch,
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
clock);
|
||||
@@ -430,6 +425,15 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove any entries from each database's versionstamp-clock namespace that are strictly older than the given timestamp.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
|
||||
versionstampClock.clearExpiredEntries(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete messages for the given devices that were inserted before the given time.
|
||||
///
|
||||
/// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB
|
||||
@@ -447,7 +451,6 @@ public class FoundationDbMessageStore {
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
|
||||
/// date.
|
||||
@VisibleForTesting
|
||||
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
|
||||
|
||||
+60
-111
@@ -5,33 +5,23 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.ByteArrayUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -42,6 +32,10 @@ import reactor.util.function.Tuples;
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final AciServiceIdentifier aciServiceIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
@@ -54,8 +48,6 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
|
||||
|
||||
private final Counter messageReadCounter =
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
|
||||
|
||||
@@ -66,27 +58,25 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
|
||||
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
|
||||
@VisibleForTesting
|
||||
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
|
||||
|
||||
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
|
||||
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] presenceKey,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final AciServiceIdentifier aciServiceIdentifier,
|
||||
final byte deviceId,
|
||||
final Database[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.aciServiceIdentifier = aciServiceIdentifier;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceQueueSubspace = FoundationDbMessageStore.getDeviceQueueSubspace(aciServiceIdentifier, deviceId);
|
||||
this.presenceKey = FoundationDbMessageStore.getPresenceKey(aciServiceIdentifier, deviceId);
|
||||
this.messagesAvailableWatchKey = FoundationDbMessageStore.getMessagesAvailableWatchKey(aciServiceIdentifier);
|
||||
this.databasesByEpoch = databasesByEpoch;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
@@ -94,19 +84,6 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.clock = clock;
|
||||
|
||||
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
|
||||
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
|
||||
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
|
||||
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toMap(database -> database,
|
||||
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
|
||||
(_, _) -> {
|
||||
throw new AssertionError("Duplicate database in distinct stream");
|
||||
},
|
||||
IdentityHashMap::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -114,6 +91,42 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
return this.messageStreamPublisher;
|
||||
}
|
||||
|
||||
public Flux<MessageStreamEntry> getFiniteMessageStream() {
|
||||
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
|
||||
// `Flux#fromArray` cannot handle `null` elements
|
||||
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
return Flux.fromIterable(databases)
|
||||
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
|
||||
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.flatMapMany(endOfQueueKeysByDatabase -> {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
maxMessagesPerScan)
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty);
|
||||
})
|
||||
.toArray(Flux[]::new);
|
||||
|
||||
return Flux.concat(
|
||||
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers)
|
||||
.doOnNext(_ -> messageReadCounter.increment()),
|
||||
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()))
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec));
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a message publisher
|
||||
///
|
||||
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
|
||||
@@ -121,25 +134,13 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// first to keep track of versionstamps sent to the client.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return createFoundationDbMessagePublisher()
|
||||
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
|
||||
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
|
||||
try {
|
||||
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
|
||||
} catch (final TooManyUnacknowledgedMessagesException e) {
|
||||
sink.error(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
sink.next(messageStreamEntry);
|
||||
})
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
|
||||
messageReadCounter.increment();
|
||||
}
|
||||
})
|
||||
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
|
||||
.doFinally(_ -> doAfterCleanup.run());
|
||||
}
|
||||
|
||||
/// Create a message publisher that fetches messages from FoundationDB
|
||||
@@ -176,14 +177,16 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
maxMessagesPerScan,
|
||||
() -> this.clearAcknowledgedMessages(database))
|
||||
maxMessagesPerScan)
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
final MessageProtos.Envelope partialEnvelope = fdbMessageStreamEntry.partialEnvelope();
|
||||
|
||||
// Ephemeral messages from the finite stream are considered stale and automatically discarded
|
||||
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
|
||||
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
|
||||
if (partialEnvelope.getEphemeral()) {
|
||||
foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, fdbMessageStreamEntry.versionstamp());
|
||||
|
||||
staleEphemeralMessagesCounter.increment();
|
||||
return;
|
||||
}
|
||||
@@ -209,8 +212,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
() -> clearAcknowledgedMessages(database)).getMessages();
|
||||
messagesAvailableWatchKey).getMessages();
|
||||
})
|
||||
.toArray(Flux[]::new);
|
||||
|
||||
@@ -249,61 +251,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
|
||||
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
|
||||
|
||||
messageAcknowledgedCounter.increment();
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
|
||||
///
|
||||
/// @param transaction The FoundationDB transaction in which to perform the range clear
|
||||
/// @param startInclusive The starting versionstamp of the range to be cleared (inclusive)
|
||||
/// @param endInclusive The ending versionstamp of the range to be cleared (inclusive)
|
||||
private void clearRange(final Transaction transaction, final Versionstamp startInclusive, final Versionstamp endInclusive) {
|
||||
final byte[] startKeyInclusive = deviceQueueSubspace.pack(Tuple.from(startInclusive));
|
||||
final byte[] endKeyExclusive = ByteArrayUtil.keyAfter(deviceQueueSubspace.pack(Tuple.from(endInclusive)));
|
||||
transaction.clear(startKeyInclusive, endKeyExclusive);
|
||||
}
|
||||
|
||||
/// Clear all outstanding acknowledged messages. Called when the stream ends
|
||||
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
|
||||
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.map(database -> {
|
||||
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
clearAllAcknowlegedMessagedConsumer.accept(transaction);
|
||||
return CompletableFuture.completedFuture((Void) null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear acknowledged messages", throwable);
|
||||
}
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
|
||||
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
|
||||
final Database database = databasesByEpoch[epoch];
|
||||
|
||||
if (database == null) {
|
||||
throw new IllegalStateException("Read message for unrecognized epoch");
|
||||
}
|
||||
|
||||
return acknowledgedMessageBuffersByDatabase.get(database);
|
||||
}
|
||||
|
||||
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
|
||||
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
|
||||
|
||||
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
|
||||
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.stream.Collectors;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String BATCH_SIZE_ARGUMENT = "batch-size";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MESSAGE_TTL_DAYS_ARGUMENT = "message-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String VERSIONSTAMP_TTL_DAYS_ARGUMENT = "versionstamp-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TIMESTAMP_RETENTION_PERIOD = Duration.ofDays(60);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClearExpiredFoundationDbMessagesCommand.class);
|
||||
|
||||
public ClearExpiredFoundationDbMessagesCommand(final Clock clock) {
|
||||
super("clear-expired-foundationdb-messages", "Removes expired messages from FoundationDB");
|
||||
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually delete any messages (but do still make entries in the versionstamp clock)");
|
||||
|
||||
subparser.addArgument("--batch-size")
|
||||
.type(Integer.class)
|
||||
.dest(BATCH_SIZE_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(10000)
|
||||
.help("Maximum number of queues to trim in a single transaction");
|
||||
|
||||
subparser.addArgument("--message-ttl-days")
|
||||
.type(Integer.class)
|
||||
.dest(MESSAGE_TTL_DAYS_ARGUMENT)
|
||||
.required(true)
|
||||
.help("Desired message TTL in days");
|
||||
|
||||
subparser.addArgument("--versionstamp-ttl-days")
|
||||
.type(Integer.class)
|
||||
.dest(VERSIONSTAMP_TTL_DAYS_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(180)
|
||||
.help("Desired versionstamp-clock TTL in days");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
|
||||
|
||||
// Record the current versionstamp/time pair for the benefit of future runs. Because this job runs regularly, it has
|
||||
// the dual role of clearing messages and keeping the versionstamp/time mappings populated.
|
||||
messagesManager.recordFoundationDbVersionstamps();
|
||||
|
||||
final int batchSize = getNamespace().getInt(BATCH_SIZE_ARGUMENT);
|
||||
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int messageTtlDays = getNamespace().getInt(MESSAGE_TTL_DAYS_ARGUMENT);
|
||||
final int versionstampTtlDays = getNamespace().getInt(VERSIONSTAMP_TTL_DAYS_ARGUMENT);
|
||||
|
||||
final Instant oldestMessageTime = clock.instant().minus(Duration.ofDays(messageTtlDays));
|
||||
final Instant oldestVersionstampTime = clock.instant().minus(Duration.ofDays(versionstampTtlDays));
|
||||
|
||||
accounts
|
||||
.buffer(batchSize)
|
||||
.map(batch -> batch.stream().collect(
|
||||
Collectors.toMap(
|
||||
account -> new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)),
|
||||
account -> account.getDevices().stream().map(Device::getId).toList())))
|
||||
.doOnNext(
|
||||
dryRun ? _ -> {}
|
||||
: deviceIdsByAccountIdentifier -> messagesManager.deleteFoundationDbMessagesBefore(deviceIdsByAccountIdentifier, oldestMessageTime))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
messagesManager.expireOldFoundationDbVersionstamps(oldestVersionstampTime);
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,14 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with Signal accounts.
|
||||
service Accounts {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Returns basic identifiers for the authenticated account.
|
||||
rpc GetAccountIdentity(GetAccountIdentityRequest) returns (GetAccountIdentityResponse) {}
|
||||
|
||||
// Returns entitlements for the authenticated account.
|
||||
rpc GetEntitlements(GetEntitlementsRequest) returns (GetEntitlementsResponse) {}
|
||||
|
||||
// Deletes the authenticated account, purging all associated data in the
|
||||
// process.
|
||||
rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse) {}
|
||||
@@ -65,6 +70,8 @@ service Accounts {
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
// identifying credentials when calling methods in this service.
|
||||
service AccountsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Checks whether an account with the given service identifier exists.
|
||||
rpc CheckAccountExistence(CheckAccountExistenceRequest) returns (CheckAccountExistenceResponse) {}
|
||||
|
||||
@@ -84,6 +91,35 @@ message GetAccountIdentityResponse {
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
}
|
||||
|
||||
message GetEntitlementsRequest {
|
||||
}
|
||||
|
||||
message GetEntitlementsResponse {
|
||||
message BadgeEntitlement {
|
||||
// The id of the badge the account is entitled. Metadata to display for
|
||||
// badges may be obtained by cross-referencing badge ids with
|
||||
// ProductConfiguration.GetConfiguration.
|
||||
string badge_id = 1;
|
||||
// When the badge expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
// Whether the badge is currently configured to be visible
|
||||
bool visible = 3;
|
||||
}
|
||||
|
||||
message BackupEntitlement {
|
||||
// The backup level of the account
|
||||
uint64 level = 1;
|
||||
// When the backup entitlement expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
}
|
||||
|
||||
// Active badges added via Donations.redeemReceipt
|
||||
repeated BadgeEntitlement badges = 1;
|
||||
|
||||
// If present, the backup level set via Backups.redeemReceipt
|
||||
BackupEntitlement backup = 2;
|
||||
}
|
||||
|
||||
message DeleteAccountRequest {
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,11 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling.quality;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for submitting call quality surveys
|
||||
service CallQuality {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Submits a call quality survey response.
|
||||
rpc SubmitCallQualitySurvey(SubmitCallQualitySurveyRequest) returns (SubmitCallQualitySurveyResponse) {}
|
||||
|
||||
@@ -9,9 +9,12 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for getting credentials and relay options for one-on-one
|
||||
// calls.
|
||||
service Calling {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieves TURN credentials and relay options for one-on-one calls.
|
||||
rpc GetCallingRelays(GetCallingRelaysRequest) returns (GetCallingRelaysResponse) {}
|
||||
|
||||
@@ -15,6 +15,7 @@ package org.signal.chat.credentials;
|
||||
// authenticated user to authenticate in another service or context without
|
||||
// revealing their identity.
|
||||
service Credentials {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Generates and returns an external service credentials for the caller.
|
||||
rpc GetExternalServiceCredentials(GetExternalServiceCredentialsRequest)
|
||||
@@ -40,6 +41,7 @@ service Credentials {
|
||||
// revealing an association between the credentials and the caller's identity to
|
||||
// the server.
|
||||
service CredentialsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Given a list of secure value recovery (SVR) service credentials and a phone
|
||||
// number, checks and returns which of the provided credentials were generated
|
||||
|
||||
@@ -18,6 +18,8 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with devices attached to a Signal account.
|
||||
service Devices {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Returns a list of devices associated with the caller's account.
|
||||
rpc GetDevices(GetDevicesRequest) returns (GetDevicesResponse) {}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with pre-keys.
|
||||
service Keys {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieves an approximate count of the number of the various kinds of
|
||||
// pre-keys stored for the authenticated device.
|
||||
@@ -57,6 +58,7 @@ service Keys {
|
||||
// Provides methods for working with pre-keys using "unidentified access"
|
||||
// credentials.
|
||||
service KeysAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Retrieves a set of pre-keys for establishing a session with the targeted
|
||||
// device or devices. Callers must not submit any self-identifying credentials
|
||||
|
||||
@@ -9,9 +9,13 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.payments;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for working with payments.
|
||||
service Payments {
|
||||
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
|
||||
rpc GetCurrencyConversions(GetCurrencyConversionsRequest) returns (GetCurrencyConversionsResponse) {}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with profiles and profile-related data.
|
||||
service Profile {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Sets profile data and, if needed, returns credentials used by clients to upload a v1 avatar.
|
||||
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
|
||||
|
||||
@@ -42,6 +44,8 @@ service Profile {
|
||||
// without an unidentified access key should use the equivalent, authenticated
|
||||
// methods in `Profile` instead.
|
||||
service ProfileAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Retrieves versioned profile data.
|
||||
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {}
|
||||
// Retrieves unversioned profile data.
|
||||
@@ -193,8 +197,14 @@ message GetVersionedProfileRequest {
|
||||
message GetVersionedProfileAnonymousRequest {
|
||||
// Contains the data necessary to request a versioned profile.
|
||||
GetVersionedProfileRequest request = 1 [(require.present) = true];
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
|
||||
|
||||
oneof authentication {
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
|
||||
|
||||
// A group send endorsement token for the targeted account.
|
||||
bytes group_send_token = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
}
|
||||
|
||||
message DataEtag {
|
||||
@@ -286,13 +296,16 @@ message GetUnversionedProfileAnonymousRequest {
|
||||
message GetUnversionedProfileResult {
|
||||
// The identity key of the targeted account/identity type.
|
||||
bytes identity_key = 1;
|
||||
// A checksum of the unidentified access key for the targeted account.
|
||||
// A checksum of the unidentified access key for the targeted account. Absent
|
||||
// if the request was for a PNI.
|
||||
bytes unidentified_access = 2;
|
||||
// Whether the account has enabled sealed sender from anyone.
|
||||
// Whether the account has enabled sealed sender from anyone. Always false
|
||||
// if the request was for a PNI.
|
||||
bool unrestricted_unidentified_access = 3;
|
||||
// A list of capabilities enabled on the account.
|
||||
repeated common.DeviceCapability capabilities = 4;
|
||||
// A list of badges associated with the account.
|
||||
// A list of badges associated with the account. Absent if the request was for
|
||||
// a PNI.
|
||||
repeated common.Badge badges = 5;
|
||||
}
|
||||
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package org.whispersystems.textsecuregcm;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.whispersystems.textsecuregcm.filters.RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.Configuration;
|
||||
import io.dropwizard.core.server.DefaultServerFactory;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.http2.Http2CConnectorFactory;
|
||||
import io.dropwizard.jetty.HttpConnectorFactory;
|
||||
import io.dropwizard.testing.DropwizardTestSupport;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
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.server.Server;
|
||||
import org.eclipse.jetty.util.component.Graceful;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.api.StatusCode;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class GracefulShutdownIntegrationTest {
|
||||
private WebSocketClient webSocketClient;
|
||||
private WebSocketClient h2WebSocketClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
webSocketClient = new WebSocketClient();
|
||||
webSocketClient.start();
|
||||
|
||||
final ClientConnector clientConnector = new ClientConnector();
|
||||
final HTTP2Client http2Client = new HTTP2Client(clientConnector);
|
||||
h2WebSocketClient = new WebSocketClient(new HttpClient(new HttpClientTransportOverHTTP2(http2Client)));
|
||||
h2WebSocketClient.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
webSocketClient.stop();
|
||||
h2WebSocketClient.stop();
|
||||
}
|
||||
|
||||
private DropwizardTestSupport<Configuration> configureApplication() {
|
||||
final Http2CConnectorFactory applicationConnector = new Http2CConnectorFactory();
|
||||
applicationConnector.setPort(0);
|
||||
final HttpConnectorFactory adminConnector = new HttpConnectorFactory();
|
||||
adminConnector.setPort(0);
|
||||
|
||||
final DefaultServerFactory serverFactory = new DefaultServerFactory();
|
||||
serverFactory.setApplicationConnectors(List.of(applicationConnector));
|
||||
serverFactory.setAdminConnectors(List.of(adminConnector));
|
||||
|
||||
final Configuration configuration = new Configuration();
|
||||
configuration.setServerFactory(serverFactory);
|
||||
|
||||
return new DropwizardTestSupport<>(TestApplication.class, configuration);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void jettyClosesOpenWebsocketSessions(final boolean useH2) throws Exception {
|
||||
final DropwizardTestSupport<Configuration> support = configureApplication();
|
||||
support.before();
|
||||
try {
|
||||
final Server server = support.getEnvironment().getApplicationContext().getServer();
|
||||
|
||||
final TestWebsocketListener listener = new TestWebsocketListener();
|
||||
final Session session = (useH2 ? h2WebSocketClient : webSocketClient)
|
||||
.connect(listener, URI.create("ws://localhost:%d/websocket".formatted(support.getLocalPort())))
|
||||
.join();
|
||||
assertTrue(session.isOpen(), "session should be open before shutdown");
|
||||
|
||||
// Open websockets should be closed by org.eclipse.jetty.websocket.common.SessionTracker
|
||||
// during the container Lifecycle stopping phase
|
||||
final CompletableFuture<Integer> closeObserved = listener.closeFuture();
|
||||
|
||||
// Keep the jetty graceful-shutdown window open until the client has observed the close
|
||||
server.addBean(new Graceful() {
|
||||
@Override
|
||||
public CompletableFuture<Void> shutdown() {
|
||||
return closeObserved.thenApply(_ -> null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isShutdown() {
|
||||
return closeObserved.isDone();
|
||||
}
|
||||
});
|
||||
server.setStopTimeout(TimeUnit.SECONDS.toMillis(10));
|
||||
server.stop();
|
||||
|
||||
final int shutdownCode = closeObserved.get(1, TimeUnit.SECONDS);
|
||||
|
||||
// In h2, when jetty shuts down a websocket with abnormal status code (e.g. 1001) it also cancels the underlying
|
||||
// H2 stream. It's possible that the stream cancellation makes it to the wire before the close frame which will
|
||||
// be parsed as a 1006, so we accept both . In practice, a 1001 vs an RST_STREAM shouldn't make a difference to a
|
||||
// client. We just care that jetty is attempting to shut down all websockets during graceful shutdowns.
|
||||
assertTrue(shutdownCode == StatusCode.SHUTDOWN || (shutdownCode == StatusCode.NO_CODE && useH2));
|
||||
} finally {
|
||||
support.after();
|
||||
}
|
||||
}
|
||||
|
||||
public static class TestApplication extends Application<Configuration> {
|
||||
|
||||
@Override
|
||||
public void run(final Configuration configuration, final Environment environment) throws Exception {
|
||||
final WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment =
|
||||
new WebSocketEnvironment<>(environment, new WebSocketConfiguration());
|
||||
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
|
||||
webSocketEnvironment.setAuthenticator(upgradeRequest -> Optional.of(mock(AuthenticatedDevice.class)));
|
||||
webSocketEnvironment.setConnectListener(context -> {});
|
||||
|
||||
final WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet =
|
||||
new WebSocketResourceProviderFactory<>(webSocketEnvironment, AuthenticatedDevice.class,
|
||||
REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(),
|
||||
(servletContext, container) -> {
|
||||
container.addMapping("/websocket", webSocketServlet);
|
||||
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,15 +132,6 @@ class WhisperServerServiceTest {
|
||||
|
||||
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
|
||||
|
||||
EXTENSION.getTestSupport().getEnvironment().getApplicationContext().getServer()
|
||||
.addEventListener(new LifeCycle.Listener() {
|
||||
@Override
|
||||
public void lifeCycleStopped(final LifeCycle event) {
|
||||
// closed by org.eclipse.jetty.websocket.common.SessionTracker during the container Lifecycle stopping phase
|
||||
assertEquals(StatusCode.SHUTDOWN, testWebsocketListener.closeFuture().getNow(-1));
|
||||
}
|
||||
});
|
||||
|
||||
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
|
||||
final Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ public class ConfiguredProfileBadgeConverterTest {
|
||||
return objects;
|
||||
}
|
||||
};
|
||||
return new BadgesConfiguration(badges, List.of(), Map.of());
|
||||
return new BadgesConfiguration(badges, Map.of());
|
||||
}
|
||||
|
||||
private BadgeConfiguration getBadge(BadgesConfiguration badgesConfiguration, int i) {
|
||||
|
||||
-1
@@ -75,7 +75,6 @@ class DonationControllerTest {
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG",
|
||||
List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))),
|
||||
List.of("TEST"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3"));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -168,7 +168,7 @@ class ProfileControllerTest {
|
||||
new BadgeConfiguration("TEST1", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST2", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))),
|
||||
new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))
|
||||
), List.of("TEST1"), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")),
|
||||
), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")),
|
||||
postPolicyGenerator,
|
||||
serverSecretParams,
|
||||
zkProfileOperations,
|
||||
|
||||
+47
-1
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -21,6 +22,7 @@ import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -46,6 +48,8 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -73,12 +77,14 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
@@ -97,6 +103,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
@Mock
|
||||
private RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
|
||||
private final TestClock testClock = TestClock.pinned(Instant.now());
|
||||
|
||||
@Override
|
||||
protected AccountsGrpcService createServiceBeforeEachTest() {
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
@@ -111,7 +119,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
return new AccountsGrpcService(accountsManager,
|
||||
rateLimiters,
|
||||
usernameHashZkProofVerifier,
|
||||
registrationRecoveryPasswordsManager);
|
||||
registrationRecoveryPasswordsManager,
|
||||
testClock);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -765,4 +774,41 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
verify(accountsManager, never()).update(any(UUID.class), any());
|
||||
verify(account, never()).setZkCredentialKey(any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void getEntitlements(final boolean expired) {
|
||||
final Account account = mock(Account.class);
|
||||
final Instant expiration = expired
|
||||
? testClock.instant().minus(Duration.ofDays(1))
|
||||
: testClock.instant().plus(Duration.ofMillis(1));
|
||||
final AccountBadge badge1 = new AccountBadge("badge1", expiration, true);
|
||||
final AccountBadge badge2 = new AccountBadge("badge2", expiration, true);
|
||||
|
||||
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(100, expiration));
|
||||
when(account.getBadges()).thenReturn(List.of(badge1, badge2));
|
||||
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
|
||||
|
||||
final GetEntitlementsResponse entitlements = authenticatedServiceStub()
|
||||
.getEntitlements(GetEntitlementsRequest.newBuilder().build());
|
||||
|
||||
if (expired) {
|
||||
assertThat(entitlements.getBadgesCount()).isEqualTo(0);
|
||||
assertThat(entitlements.hasBackup()).isFalse();
|
||||
} else {
|
||||
assertThat(entitlements.getBadges(0)).isEqualTo(toBadgeEntitlement(badge1));
|
||||
assertThat(entitlements.getBadges(1)).isEqualTo(toBadgeEntitlement(badge2));
|
||||
assertThat(entitlements.getBackup().getLevel()).isEqualTo(100);
|
||||
assertThat(entitlements.getBackup().getExpirationEpochSeconds()).isEqualTo(expiration.getEpochSecond());
|
||||
}
|
||||
}
|
||||
|
||||
private static GetEntitlementsResponse.BadgeEntitlement toBadgeEntitlement(AccountBadge badge) {
|
||||
return GetEntitlementsResponse.BadgeEntitlement.newBuilder()
|
||||
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
|
||||
.setBadgeId(badge.id())
|
||||
.setVisible(badge.visible())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -11,6 +11,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
|
||||
@@ -334,7 +335,9 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
|
||||
final SetPushTokenResponse ignored = authenticatedServiceStub().setPushToken(request);
|
||||
|
||||
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
|
||||
// Update push token even if it matches the stored value for apns (to update the timestamp)
|
||||
verify(accountsManager, apnsToken == null ? never() : times(1))
|
||||
.updateDevice(any(), anyByte(), any());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setPushTokenUnchanged() {
|
||||
|
||||
+139
-51
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
@@ -49,8 +50,10 @@ import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
@@ -216,7 +219,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
|
||||
.build()
|
||||
)
|
||||
.build();
|
||||
@@ -270,7 +273,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
|
||||
.build();
|
||||
|
||||
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
|
||||
@@ -399,7 +402,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
@MethodSource
|
||||
void getVersionedProfile(final byte[] requestVersion,
|
||||
@Nullable final byte[] accountVersion,
|
||||
final boolean expectResponseHasPaymentAddress) {
|
||||
final boolean expectResponseHasPaymentAddress,
|
||||
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
@@ -418,18 +423,23 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(profile);
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(requestVersion))
|
||||
.build())
|
||||
.build();
|
||||
.build());
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
|
||||
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
|
||||
}
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
|
||||
requestBuilder.build());
|
||||
|
||||
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
|
||||
.setV1Response(GetVersionedProfileV1Response.newBuilder()
|
||||
@@ -454,14 +464,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] version1 = TestRandomUtil.nextBytes(32);
|
||||
final byte[] version2 = TestRandomUtil.nextBytes(32);
|
||||
return List.of(
|
||||
Arguments.argumentSet("current profile version matches", version1, version1, true),
|
||||
Arguments.argumentSet("current profile version absent",version1, null, true),
|
||||
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
|
||||
Arguments.argumentSet("current profile version matches, unidentified access key auth", version1, version1, true,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
|
||||
Arguments.argumentSet("current profile version absent, unidentified access key auth",version1, null, true,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
|
||||
Arguments.argumentSet("current profile version mismatch, unidentified access key auth",version1, version2, false,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
|
||||
Arguments.argumentSet("current profile version matches, group send endorsement auth", version1, version1, true,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.GROUP_SEND_TOKEN)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileV2() {
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
|
||||
void getVersionedProfileV2(
|
||||
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
@@ -477,18 +495,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.build())
|
||||
.build();
|
||||
.build());
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
|
||||
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
|
||||
}
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build());
|
||||
assertTrue(response.hasResult());
|
||||
|
||||
final GetVersionedProfileResult result = response.getResult();
|
||||
@@ -576,44 +598,38 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
|
||||
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
|
||||
void getVersionedProfileAccountNotFound(
|
||||
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase
|
||||
) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
|
||||
accountNotFound ? Optional.empty() : Optional.of(account));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build());
|
||||
|
||||
|
||||
if (missingUnidentifiedAccessKey) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
|
||||
} else {
|
||||
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
|
||||
requestBuilder.build());
|
||||
|
||||
assertEquals(accountNotFound, response.hasNotFound());
|
||||
assertNotEquals(accountNotFound, response.hasFailedUnidentifiedAuthorization());
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
|
||||
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
|
||||
}
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build());
|
||||
|
||||
}
|
||||
private static Stream<Arguments> getVersionedProfileUnauthenticated() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true)
|
||||
);
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> assertTrue(response.hasNotFound());
|
||||
case UNIDENTIFIED_ACCESS_KEY, AUTHENTICATION_NOT_SET -> assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -631,9 +647,81 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.build();
|
||||
|
||||
//noinspection ThrowableNotThrown
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileNoAuth() {
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()))))
|
||||
.build();
|
||||
|
||||
//noinspection ThrowableNotThrown
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileIncorrectUnidentifiedAccessKey() {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]))
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfileFailingGroupSendEndorsement(final boolean expired, final boolean wrongIdentifier) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final AciServiceIdentifier wrongServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
|
||||
.thenReturn(Optional.of(mock(Account.class)));
|
||||
|
||||
final Instant expiration = expired ? Instant.now().truncatedTo(ChronoUnit.DAYS) : Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS,
|
||||
List.of(wrongIdentifier ? wrongServiceIdentifier : serviceIdentifier), expiration);
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setGroupSendToken(ByteString.copyFrom(token))
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
private static List<Arguments> getVersionedProfileFailingGroupSendEndorsement() {
|
||||
return List.of(
|
||||
Arguments.of(true, true),
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getExpiringProfileKeyCredential() throws Exception {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
+1
-2
@@ -174,7 +174,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
new BadgeSvg("ll", "ld")
|
||||
)
|
||||
)),
|
||||
List.of("TEST1"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")
|
||||
);
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
@@ -655,7 +654,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(true)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
|
||||
.build();
|
||||
|
||||
final GetUnversionedProfileResult expectedResponse;
|
||||
|
||||
+3
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -77,6 +78,8 @@ class MetricsRequestEventListenerTest {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
meterRegistry = mock(MeterRegistry.class);
|
||||
when(meterRegistry.gauge(anyString(), any(Number.class))).thenAnswer(invocation -> invocation.getArgument(1));
|
||||
|
||||
counter = mock(Counter.class);
|
||||
responseBytesCounter = mock(Counter.class);
|
||||
requestBytesCounter = mock(Counter.class);
|
||||
|
||||
+17
-11
@@ -6,9 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -20,26 +21,26 @@ import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
|
||||
class DeletionMirroringMessageStreamTest {
|
||||
class MirroringMessageStreamTest {
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
private FoundationDbMessageStream foundationDbMessageStream;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private DeletionMirroringMessageStream deletionMirroringMessageStream;
|
||||
private MirroringMessageStream mirroringMessageStream;
|
||||
|
||||
private static final AciServiceIdentifier ACCOUNT_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
foundationDbMessageStore = mock(FoundationDbMessageStore.class);
|
||||
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
deletionMirroringMessageStream = new DeletionMirroringMessageStream(
|
||||
mirroringMessageStream = new MirroringMessageStream(
|
||||
mock(RedisDynamoDbMessageStream.class),
|
||||
foundationDbMessageStore,
|
||||
foundationDbMessageStream,
|
||||
experimentEnrollmentManager,
|
||||
ACCOUNT_IDENTIFIER.uuid(),
|
||||
DEVICE_ID);
|
||||
@@ -51,10 +52,15 @@ class DeletionMirroringMessageStreamTest {
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)))
|
||||
.thenReturn(enrolled);
|
||||
|
||||
deletionMirroringMessageStream.acknowledgeMessage(messageGuid, System.currentTimeMillis());
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
verify(foundationDbMessageStore, times(expectFoundationDbDeletion ? 1 : 0))
|
||||
.delete(ACCOUNT_IDENTIFIER, DEVICE_ID, messageGuid);
|
||||
mirroringMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
|
||||
if (expectFoundationDbDeletion) {
|
||||
verify(foundationDbMessageStream).acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
} else {
|
||||
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Arguments> acknowledgeMessage() {
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
class AcknowledgedMessageBufferTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void computeFlushableRanges(final List<Integer> versionstampsSent,
|
||||
final List<Integer> versionstampsAcknowledged,
|
||||
final List<Pair<Integer, Integer>> expectedRanges) {
|
||||
|
||||
final AcknowledgedMessageBuffer acknowledgedMessageBuffer =
|
||||
new AcknowledgedMessageBuffer(FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES);
|
||||
|
||||
versionstampsSent.forEach(versionstamp -> assertDoesNotThrow(() ->
|
||||
acknowledgedMessageBuffer.addUnacknowledgedMessage(versionstampFromInt(versionstamp))));
|
||||
|
||||
versionstampsAcknowledged.forEach(versionstamp ->
|
||||
acknowledgedMessageBuffer.acknowledgeMessage(versionstampFromInt(versionstamp)));
|
||||
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = acknowledgedMessageBuffer.computeFlushableRanges();
|
||||
|
||||
assertEquals(expectedRanges
|
||||
.stream()
|
||||
.map(range -> new Pair<>(versionstampFromInt(range.first()), versionstampFromInt(range.second())))
|
||||
.toList(),
|
||||
flushableRanges);
|
||||
}
|
||||
|
||||
@Test
|
||||
void takeFlushableRanges() {
|
||||
final AcknowledgedMessageBuffer acknowledgedMessageBuffer =
|
||||
new AcknowledgedMessageBuffer(FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES);
|
||||
|
||||
IntStream.range(0, 10)
|
||||
.mapToObj(AcknowledgedMessageBufferTest::versionstampFromInt)
|
||||
.forEach(versionstamp -> assertDoesNotThrow(
|
||||
() -> acknowledgedMessageBuffer.addUnacknowledgedMessage(versionstamp)));
|
||||
|
||||
assertEquals(10, acknowledgedMessageBuffer.getUnacknowledgedMessageCount());
|
||||
|
||||
IntStream.range(2, 8)
|
||||
.mapToObj(AcknowledgedMessageBufferTest::versionstampFromInt)
|
||||
.forEach(acknowledgedMessageBuffer::acknowledgeMessage);
|
||||
|
||||
assertEquals(List.of(new Pair<>(versionstampFromInt(2), versionstampFromInt(7))),
|
||||
acknowledgedMessageBuffer.takeFlushableRanges());
|
||||
|
||||
assertEquals(4, acknowledgedMessageBuffer.getUnacknowledgedMessageCount());
|
||||
}
|
||||
|
||||
static Stream<Arguments> computeFlushableRanges() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Single acknowledged message range", List.of(1, 2, 3), List.of(1),
|
||||
List.of(new Pair<>(1, 1))),
|
||||
Arguments.argumentSet("No acknowledged messages", List.of(1, 2, 3), Collections.emptyList(),
|
||||
Collections.emptyList()),
|
||||
Arguments.argumentSet("Fully acknowledged message range", List.of(1, 2, 3, 4),
|
||||
List.of(1, 2, 3, 4), List.of(new Pair<>(1, 4))),
|
||||
Arguments.argumentSet("Not all messages acknowledged", List.of(1, 2, 3, 4),
|
||||
List.of(1, 2, 3), List.of(new Pair<>(1, 3))),
|
||||
Arguments.argumentSet("Out-of-order acknowledged ranges", List.of(1, 2, 3, 4, 5, 6, 7, 8),
|
||||
List.of(1, 3, 4, 5, 7, 8), List.of(new Pair<>(1, 1), new Pair<>(3, 5), new Pair<>(7, 8))),
|
||||
Arguments.argumentSet("Out-of-order acknowledged single messages", List.of(1, 2, 3, 4, 5, 6, 7, 8),
|
||||
List.of(1, 3, 5), List.of(new Pair<>(1, 1), new Pair<>(3, 3), new Pair<>(5, 5)))
|
||||
);
|
||||
}
|
||||
|
||||
private static Versionstamp versionstampFromInt(final int version) {
|
||||
final ByteBuffer buf = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN);
|
||||
buf.putLong(version); // 8 bytes: transaction version
|
||||
buf.putShort((short) 2); // 2 bytes: batch order within transaction
|
||||
return Versionstamp.complete(buf.array());
|
||||
}
|
||||
}
|
||||
+6
-16
@@ -35,9 +35,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -66,8 +64,6 @@ class FoundationDbMessagePublisherTest {
|
||||
private static final byte[] MESSAGES_AVAILABLE_WATCH_KEY =
|
||||
FoundationDbMessageStore.getMessagesAvailableWatchKey(SERVICE_IDENTIFIER);
|
||||
|
||||
private static final Supplier<Consumer<Transaction>> NOOP_ON_PAGE_FETCH = () -> _ -> {};
|
||||
|
||||
private static final Clock CLOCK = Clock.systemUTC();
|
||||
|
||||
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
|
||||
@@ -131,8 +127,7 @@ class FoundationDbMessagePublisherTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
(_, newState) -> stateTransitions.add(newState)
|
||||
);
|
||||
|
||||
StepVerifier.create(finitePublisher.getMessages())
|
||||
@@ -219,8 +214,7 @@ class FoundationDbMessagePublisherTest {
|
||||
watchFuture2.complete(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
}
|
||||
);
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
@@ -302,8 +296,7 @@ class FoundationDbMessagePublisherTest {
|
||||
.count() == 1) {
|
||||
watchFuture1.complete(null);
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
}
|
||||
);
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
@@ -338,8 +331,7 @@ class FoundationDbMessagePublisherTest {
|
||||
100,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
() -> _ -> {});
|
||||
MESSAGES_AVAILABLE_WATCH_KEY);
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
final KeyValue keyValue = mockKeyValue((byte) 5, message);
|
||||
@@ -399,8 +391,7 @@ class FoundationDbMessagePublisherTest {
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
(_, newState) -> stateTransitions.add(newState)
|
||||
);
|
||||
|
||||
final RuntimeException streamTerminationException = new RuntimeException("Stream terminated");
|
||||
@@ -464,8 +455,7 @@ class FoundationDbMessagePublisherTest {
|
||||
&& newState == FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE) {
|
||||
latch.countDown();
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
}
|
||||
);
|
||||
|
||||
// Request two messages one at a time and verify that we only fetch a single batch (batch size = 2) and not two batches
|
||||
|
||||
+1
-26
@@ -594,7 +594,7 @@ class FoundationDbMessageStoreTest {
|
||||
.toList();
|
||||
|
||||
final MessageStream messageStream =
|
||||
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, numMessages, Util.NOOP);
|
||||
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, Util.NOOP);
|
||||
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
@@ -908,7 +908,6 @@ class FoundationDbMessageStoreTest {
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
latch::countDown);
|
||||
final List<CompletableFuture<Void>> acknowledgeFutures = new ArrayList<>();
|
||||
final AtomicInteger messageCounter = new AtomicInteger(0);
|
||||
@@ -979,7 +978,6 @@ class FoundationDbMessageStoreTest {
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci,
|
||||
deviceId,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanupLatch::countDown);
|
||||
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
@@ -1020,28 +1018,6 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void outstandingUnacknowledgedMessages() {
|
||||
final int numMessages = 5;
|
||||
final int maxUnacknowledgedMessages = 3;
|
||||
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
for (int i = 0; i < numMessages; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
maxUnacknowledgedMessages,
|
||||
Util.NOOP);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), numMessages)
|
||||
.expectNextCount(maxUnacknowledgedMessages)
|
||||
.expectError(TooManyUnacknowledgedMessagesException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardStaleEphemeralMessages() throws InterruptedException {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
@@ -1078,7 +1054,6 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanUpLatch::countDown);
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
// We should have discarded the already-inserted ephemeral message
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
class ClearExpiredFoundationDbMessagesCommandTest {
|
||||
|
||||
private MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
|
||||
private static class TestClearExpiredFoundationDbMessagesCommand extends ClearExpiredFoundationDbMessagesCommand {
|
||||
|
||||
private final CommandDependencies commandDependencies;
|
||||
|
||||
private final boolean dryRun;
|
||||
|
||||
public TestClearExpiredFoundationDbMessagesCommand(final MessagesManager messagesManager,
|
||||
final boolean dryRun,
|
||||
final Clock clock) {
|
||||
|
||||
super(clock);
|
||||
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CommandDependencies getCommandDependencies() {
|
||||
return commandDependencies;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Namespace getNamespace() {
|
||||
return new Namespace(Map.of(
|
||||
ClearExpiredFoundationDbMessagesCommand.BATCH_SIZE_ARGUMENT, 4,
|
||||
ClearExpiredFoundationDbMessagesCommand.DRY_RUN_ARGUMENT, dryRun,
|
||||
ClearExpiredFoundationDbMessagesCommand.MESSAGE_TTL_DAYS_ARGUMENT, 1,
|
||||
ClearExpiredFoundationDbMessagesCommand.VERSIONSTAMP_TTL_DAYS_ARGUMENT, 10
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans={true, false})
|
||||
void crawlAccounts(final boolean dryRun) {
|
||||
|
||||
final Clock clock = TestClock.pinned(Instant.now());
|
||||
final Instant messageCutoffTime = clock.instant().minus(Duration.ofDays(1));
|
||||
final Instant versionstampCutoffTime = clock.instant().minus(Duration.ofDays(10));
|
||||
|
||||
final TestClearExpiredFoundationDbMessagesCommand clearExpiredFoundationDbMessagesCommand =
|
||||
new TestClearExpiredFoundationDbMessagesCommand(messagesManager,
|
||||
dryRun,
|
||||
clock);
|
||||
|
||||
final List<Account> accounts = new ArrayList<>();
|
||||
final AciServiceIdentifier[] acis = new AciServiceIdentifier[10];
|
||||
for (int i = 0; i < 10; i++) {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte primaryDeviceId = Device.PRIMARY_ID;
|
||||
final byte linkedDeviceId = 2;
|
||||
|
||||
final Device primaryDevice = mock(Device.class);
|
||||
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
|
||||
|
||||
final Device linkedDevice = mock(Device.class);
|
||||
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.getDevices()).thenReturn(i % 2 == 0 ? List.of(primaryDevice) : List.of(primaryDevice, linkedDevice));
|
||||
|
||||
accounts.add(account);
|
||||
acis[i] = new AciServiceIdentifier(accountIdentifier);
|
||||
}
|
||||
|
||||
clearExpiredFoundationDbMessagesCommand.crawlAccounts(Flux.fromIterable(accounts));
|
||||
|
||||
final List<Byte> oneDeviceId = List.of(Device.PRIMARY_ID);
|
||||
final List<Byte> twoDeviceIds = List.of(Device.PRIMARY_ID, (byte) 2);
|
||||
if (!dryRun) {
|
||||
verify(messagesManager).deleteFoundationDbMessagesBefore(
|
||||
Map.of(acis[0], oneDeviceId, acis[1], twoDeviceIds, acis[2], oneDeviceId, acis[3], twoDeviceIds),
|
||||
messageCutoffTime);
|
||||
verify(messagesManager).deleteFoundationDbMessagesBefore(
|
||||
Map.of(acis[4], oneDeviceId, acis[5], twoDeviceIds, acis[6], oneDeviceId, acis[7], twoDeviceIds),
|
||||
messageCutoffTime);
|
||||
verify(messagesManager).deleteFoundationDbMessagesBefore(
|
||||
Map.of(acis[8], oneDeviceId, acis[9], twoDeviceIds),
|
||||
messageCutoffTime);
|
||||
} else {
|
||||
verify(messagesManager, never()).deleteFoundationDbMessagesBefore(any(), any());
|
||||
}
|
||||
|
||||
verify(messagesManager).recordFoundationDbVersionstamps();
|
||||
verify(messagesManager)
|
||||
.expireOldFoundationDbVersionstamps(versionstampCutoffTime);
|
||||
}
|
||||
}
|
||||
@@ -372,8 +372,6 @@ badges:
|
||||
svgs:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
badgeIdsEnabledForAll:
|
||||
- TEST
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
|
||||
|
||||
Reference in new issue
Block a user