diff --git a/service/config/sample.yml b/service/config/sample.yml index e3607e703..a1082fb2d 100644 --- a/service/config/sample.yml +++ b/service/config/sample.yml @@ -134,8 +134,6 @@ dynamoDbTables: tableName: Example_ProfilesV2 pushChallenge: tableName: Example_PushChallenge - pushNotificationExperimentSamples: - tableName: Example_PushNotificationExperimentSamples redeemedReceipts: tableName: Example_RedeemedReceipts registrationRecovery: diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DynamoDbTables.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DynamoDbTables.java index 5ce13f041..1e0275b0f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DynamoDbTables.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DynamoDbTables.java @@ -68,7 +68,6 @@ public class DynamoDbTables { private final Table profiles; private final Table profilesV2; private final Table pushChallenge; - private final Table pushNotificationExperimentSamples; private final Table redeemedReceipts; private final TableWithExpiration registrationRecovery; private final Table remoteConfig; @@ -100,7 +99,6 @@ public class DynamoDbTables { @JsonProperty("profiles") final Table profiles, @JsonProperty("profilesV2") final Table profilesV2, @JsonProperty("pushChallenge") final Table pushChallenge, - @JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples, @JsonProperty("redeemedReceipts") final Table redeemedReceipts, @JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery, @JsonProperty("remoteConfig") final Table remoteConfig, @@ -131,7 +129,6 @@ public class DynamoDbTables { this.profiles = profiles; this.profilesV2 = profilesV2; this.pushChallenge = pushChallenge; - this.pushNotificationExperimentSamples = pushNotificationExperimentSamples; this.redeemedReceipts = redeemedReceipts; this.registrationRecovery = registrationRecovery; this.remoteConfig = remoteConfig; @@ -268,12 +265,6 @@ public class DynamoDbTables { return pushChallenge; } - @NotNull - @Valid - public Table getPushNotificationExperimentSamples() { - return pushNotificationExperimentSamples; - } - @NotNull @Valid public Table getRedeemedReceipts() { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java b/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java deleted file mode 100644 index 2d8c9ca22..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperiment.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.whispersystems.textsecuregcm.experiment; - -import com.google.common.annotations.VisibleForTesting; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.identity.IdentityType; -import org.whispersystems.textsecuregcm.storage.Account; -import org.whispersystems.textsecuregcm.storage.Device; -import org.whispersystems.textsecuregcm.workers.IdleWakeupEligibilityChecker; -import reactor.core.publisher.Flux; -import javax.annotation.Nullable; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -abstract class IdleDevicePushNotificationExperiment implements PushNotificationExperiment { - - private final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @VisibleForTesting - enum Population { - APNS_CONTROL, - APNS_EXPERIMENT, - FCM_CONTROL, - FCM_EXPERIMENT - } - - @VisibleForTesting - enum Outcome { - DELETED, - UNINSTALLED, - REACTIVATED, - UNCHANGED - } - - protected IdleDevicePushNotificationExperiment(final IdleWakeupEligibilityChecker idleWakeupEligibilityChecker) { - this.idleWakeupEligibilityChecker = idleWakeupEligibilityChecker; - } - - @VisibleForTesting - boolean hasPushToken(final Device device) { - return !StringUtils.isAllBlank(device.getApnId(), device.getGcmId()); - } - - abstract boolean isIdleDeviceEligible(final Account account, final Device idleDevice, final DeviceLastSeenState state); - - @Override - public CompletableFuture isDeviceEligible(final Account account, final Device device) { - return idleWakeupEligibilityChecker.isDeviceEligible(account, device).thenApply(idle -> - idle && isIdleDeviceEligible(account, device, getState(account, device))); - } - - @Override - public DeviceLastSeenState getState(@Nullable final Account account, @Nullable final Device device) { - if (account != null && device != null) { - final DeviceLastSeenState.PushTokenType pushTokenType; - if (StringUtils.isNotBlank(device.getApnId())) { - pushTokenType = DeviceLastSeenState.PushTokenType.APNS; - } else if (StringUtils.isNotBlank(device.getGcmId())) { - pushTokenType = DeviceLastSeenState.PushTokenType.FCM; - } else { - pushTokenType = null; - } - return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType); - } else { - return DeviceLastSeenState.MISSING_DEVICE_STATE; - } - } - - @Override - public void analyzeResults(final Flux> samples) { - final Map> contingencyTable = new EnumMap<>(Population.class); - - samples.doOnNext(sample -> - contingencyTable.computeIfAbsent(getPopulation(sample), ignored -> new EnumMap<>(Outcome.class)) - .merge(getOutcome(sample), 1, Integer::sum)) - .then() - .block(); - - final StringBuilder reportBuilder = new StringBuilder("population,deleted,uninstalled,reactivated,unchanged\n"); - - for (final Population population : Population.values()) { - final Map countsByOutcome = contingencyTable.getOrDefault(population, Collections.emptyMap()); - - reportBuilder.append(population.name()); - reportBuilder.append(","); - reportBuilder.append(countsByOutcome.getOrDefault(Outcome.DELETED, 0)); - reportBuilder.append(","); - reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNINSTALLED, 0)); - reportBuilder.append(","); - reportBuilder.append(countsByOutcome.getOrDefault(Outcome.REACTIVATED, 0)); - reportBuilder.append(","); - reportBuilder.append(countsByOutcome.getOrDefault(Outcome.UNCHANGED, 0)); - reportBuilder.append("\n"); - } - - log.info(reportBuilder.toString()); - } - - @VisibleForTesting - static Population getPopulation(final PushNotificationExperimentSample sample) { - assert sample.initialState() != null && sample.initialState().pushTokenType() != null; - - return switch (sample.initialState().pushTokenType()) { - case APNS -> sample.inExperimentGroup() ? Population.APNS_EXPERIMENT : Population.APNS_CONTROL; - case FCM -> sample.inExperimentGroup() ? Population.FCM_EXPERIMENT : Population.FCM_CONTROL; - }; - } - - @VisibleForTesting - static Outcome getOutcome(final PushNotificationExperimentSample sample) { - final Outcome outcome; - - assert sample.finalState() != null; - - if (!sample.finalState().deviceExists() || sample.initialState().registrationId() != sample.finalState().registrationId()) { - outcome = Outcome.DELETED; - } else if (!sample.finalState().hasPushToken()) { - outcome = Outcome.UNINSTALLED; - } else if (sample.initialState().lastSeenMillis() != sample.finalState().lastSeenMillis()) { - outcome = Outcome.REACTIVATED; - } else { - outcome = Outcome.UNCHANGED; - } - - return outcome; - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperiment.java b/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperiment.java deleted file mode 100644 index 05a8fa43c..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperiment.java +++ /dev/null @@ -1,85 +0,0 @@ - -package org.whispersystems.textsecuregcm.experiment; - -import org.whispersystems.textsecuregcm.storage.Account; -import org.whispersystems.textsecuregcm.storage.Device; -import reactor.core.publisher.Flux; -import javax.annotation.Nullable; -import java.util.concurrent.CompletableFuture; - -/** - * A push notification selects for eligible devices, applies a control or experimental treatment, and provides a - * mechanism for comparing device states before and after receiving the treatment. - * - * @param the type of state object stored for this experiment - */ -public interface PushNotificationExperiment { - - /** - * Returns the unique name of this experiment. - * - * @return the unique name of this experiment - */ - String getExperimentName(); - - /** - * Tests whether a device is eligible for this experiment. An eligible device may be assigned to either the control - * or experiment group within an experiment. Ineligible devices will not participate in the experiment in any way. - * - * @param account the account to which the device belongs - * @param device the device to test for eligibility in this experiment - * - * @return a future that yields a boolean value indicating whether the target device is eligible for this experiment - */ - CompletableFuture isDeviceEligible(Account account, Device device); - - /** - * Returns the class of the state object stored for this experiment. - * - * @return the class of the state object stored for this experiment - */ - Class getStateClass(); - - /** - * Generates an experiment specific state "snapshot" of the given device. Experiment results are generally evaluated - * by comparing a device's state before a treatment is applied and its state after the treatment is applied. - * - * @param account the account to which the device belongs - * @param device the device for which to generate a state "snapshot" - * - * @return an experiment-specific state "snapshot" of the given device - */ - T getState(@Nullable Account account, @Nullable Device device); - - /** - * Applies a control treatment to the given device. In many cases (and by default) no action is taken for devices in - * the control group. - * - * @param account the account to which the device belongs - * @param device the device to which to apply the control treatment for this experiment - * - * @return a future that completes when the control treatment has been applied for the given device - */ - default CompletableFuture applyControlTreatment(Account account, Device device) { - return CompletableFuture.completedFuture(null); - }; - - /** - * Applies an experimental treatment to the given device. This generally involves sending or scheduling a specific - * type of push notification for the given device. - * - * @param account the account to which the device belongs - * @param device the device to which to apply the experimental treatment for this experiment - * - * @return a future that completes when the experimental treatment has been applied for the given device - */ - CompletableFuture applyExperimentTreatment(Account account, Device device); - - /** - * Consumes a stream of finished samples and emits an analysis of the results via an implementation-specific channel - * (e.g. a log message). Implementations must block until all samples have been consumed and analyzed. - * - * @param samples a stream of finished samples from this experiment - */ - void analyzeResults(Flux> samples); -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSample.java b/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSample.java deleted file mode 100644 index 90d39a8f1..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSample.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.whispersystems.textsecuregcm.experiment; - -import javax.annotation.Nullable; -import java.util.UUID; - -public record PushNotificationExperimentSample(UUID accountIdentifier, - byte deviceId, - boolean inExperimentGroup, - T initialState, - @Nullable T finalState) { -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSamples.java b/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSamples.java deleted file mode 100644 index 88f05d947..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSamples.java +++ /dev/null @@ -1,279 +0,0 @@ -package org.whispersystems.textsecuregcm.experiment; - -import com.fasterxml.jackson.core.JsonProcessingException; -import java.nio.ByteBuffer; -import java.time.Clock; -import java.time.Duration; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import com.google.common.annotations.VisibleForTesting; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.util.ExceptionUtils; -import org.whispersystems.textsecuregcm.util.SystemMapper; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; -import reactor.util.retry.Retry; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; -import software.amazon.awssdk.services.dynamodb.model.AttributeValue; -import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; -import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; -import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; -import software.amazon.awssdk.services.dynamodb.model.QueryRequest; -import software.amazon.awssdk.services.dynamodb.model.ReturnValue; -import software.amazon.awssdk.services.dynamodb.model.ScanRequest; -import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; - -public class PushNotificationExperimentSamples { - - private final DynamoDbAsyncClient dynamoDbAsyncClient; - private final String tableName; - private final Clock clock; - - // Experiment name; DynamoDB string; partition key - public static final String KEY_EXPERIMENT_NAME = "N"; - - // Combined ACI and device ID; DynamoDB byte array; sort key - public static final String ATTR_ACI_AND_DEVICE_ID = "AD"; - - // Whether the device is enrolled in the experiment group (as opposed to control group); DynamoDB boolean - static final String ATTR_IN_EXPERIMENT_GROUP = "X"; - - // The experiment-specific state of the device at the start of the experiment, represented as a JSON blob; DynamoDB - // string - static final String ATTR_INITIAL_STATE = "I"; - - // The experiment-specific state of the device at the end of the experiment, represented as a JSON blob; DynamoDB - // string - static final String ATTR_FINAL_STATE = "F"; - - // The time, in seconds since the epoch, at which this sample should be deleted automatically - static final String ATTR_TTL = "E"; - - private static final Duration FINAL_SAMPLE_TTL = Duration.ofDays(7); - - private static final Logger log = LoggerFactory.getLogger(PushNotificationExperimentSamples.class); - - public PushNotificationExperimentSamples(final DynamoDbAsyncClient dynamoDbAsyncClient, - final String tableName, - final Clock clock) { - - this.dynamoDbAsyncClient = dynamoDbAsyncClient; - this.tableName = tableName; - this.clock = clock; - } - - /** - * Writes the initial state of a device participating in a push notification experiment. - * - * @param accountIdentifier the account identifier for the account to which the target device is linked - * @param deviceId the identifier for the device within the given account - * @param experimentName the name of the experiment - * @param inExperimentGroup whether the given device is in the experiment group (as opposed to control group) - * @param initialState the initial state of the object; must be serializable as a JSON text - * - * @return a future that completes when the record has been stored; the future yields {@code true} if a new record - * was stored or {@code false} if a conflicting record already exists - * - * @param the type of state object for this sample - * - * @throws JsonProcessingException if the given {@code initialState} could not be serialized as a JSON text - */ - public CompletableFuture recordInitialState(final UUID accountIdentifier, - final byte deviceId, - final String experimentName, - final boolean inExperimentGroup, - final T initialState) throws JsonProcessingException { - - final AttributeValue initialStateAttributeValue = - AttributeValue.fromS(SystemMapper.jsonMapper().writeValueAsString(initialState)); - - final AttributeValue inExperimentGroupAttributeValue = AttributeValue.fromBool(inExperimentGroup); - - return dynamoDbAsyncClient.putItem(PutItemRequest.builder() - .tableName(tableName) - .item(Map.of( - KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName), - ATTR_ACI_AND_DEVICE_ID, buildSortKey(accountIdentifier, deviceId), - ATTR_IN_EXPERIMENT_GROUP, inExperimentGroupAttributeValue, - ATTR_INITIAL_STATE, initialStateAttributeValue, - ATTR_TTL, AttributeValue.fromN(String.valueOf(clock.instant().plus(FINAL_SAMPLE_TTL).getEpochSecond())))) - .conditionExpression("(attribute_not_exists(#inExperimentGroup) OR #inExperimentGroup = :inExperimentGroup) AND (attribute_not_exists(#initialState) OR #initialState = :initialState) AND attribute_not_exists(#finalState)") - .expressionAttributeNames(Map.of( - "#inExperimentGroup", ATTR_IN_EXPERIMENT_GROUP, - "#initialState", ATTR_INITIAL_STATE, - "#finalState", ATTR_FINAL_STATE)) - .expressionAttributeValues(Map.of( - ":inExperimentGroup", inExperimentGroupAttributeValue, - ":initialState", initialStateAttributeValue)) - .build()) - .thenApply(ignored -> true) - .exceptionally(throwable -> { - if (ExceptionUtils.unwrap(throwable) instanceof ConditionalCheckFailedException) { - return false; - } - - throw ExceptionUtils.wrap(throwable); - }); - } - - /** - * Writes the final state of a device participating in a push notification experiment. - * - * @param accountIdentifier the account identifier for the account to which the target device is linked - * @param deviceId the identifier for the device within the given account - * @param experimentName the name of the experiment - * @param finalState the final state of the object; must be serializable as a JSON text and of the same type as the - * previously-stored initial state - - * @return A future that completes when the final state has been stored; yields a finished sample if an initial sample - * was found or empty if no initial sample was found for the given account, device, and experiment. The future may - * with a {@link JsonProcessingException} if the initial state could not be read or the final state could not be - * written as a JSON text. - * - * @param the type of state object for this sample - */ - public CompletableFuture> recordFinalState(final UUID accountIdentifier, - final byte deviceId, - final String experimentName, - final T finalState) { - - CompletableFuture finalStateJsonFuture; - - // Process the final state JSON on the calling thread, but inside a CompletionStage so there's just one "channel" - // for reporting JSON exceptions. The alternative is to `throw JsonProcessingException`, but then callers would have - // to both catch the exception when calling this method and also watch the returned future for the same exception. - try { - finalStateJsonFuture = - CompletableFuture.completedFuture(SystemMapper.jsonMapper().writeValueAsString(finalState)); - } catch (final JsonProcessingException e) { - finalStateJsonFuture = CompletableFuture.failedFuture(e); - } - - final AttributeValue aciAndDeviceIdAttributeValue = buildSortKey(accountIdentifier, deviceId); - - return finalStateJsonFuture.thenCompose(finalStateJson -> { - return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder() - .tableName(tableName) - .key(Map.of( - KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName), - ATTR_ACI_AND_DEVICE_ID, aciAndDeviceIdAttributeValue)) - // `UpdateItem` will, by default, create a new item if one does not already exist for the given primary key. We - // want update-only-if-exists behavior, though, and so check that there's already an existing item for this ACI - // and device ID. - .conditionExpression("#aciAndDeviceId = :aciAndDeviceId") - .updateExpression("SET #finalState = if_not_exists(#finalState, :finalState)") - .expressionAttributeNames(Map.of( - "#aciAndDeviceId", ATTR_ACI_AND_DEVICE_ID, - "#finalState", ATTR_FINAL_STATE)) - .expressionAttributeValues(Map.of( - ":aciAndDeviceId", aciAndDeviceIdAttributeValue, - ":finalState", AttributeValue.fromS(finalStateJson))) - .returnValues(ReturnValue.ALL_NEW) - .build()) - .thenApply(updateItemResponse -> { - try { - final boolean inExperimentGroup = updateItemResponse.attributes().get(ATTR_IN_EXPERIMENT_GROUP).bool(); - - @SuppressWarnings("unchecked") final T parsedInitialState = - (T) parseState(updateItemResponse.attributes().get(ATTR_INITIAL_STATE).s(), finalState.getClass()); - - @SuppressWarnings("unchecked") final T parsedFinalState = - (T) parseState(updateItemResponse.attributes().get(ATTR_FINAL_STATE).s(), finalState.getClass()); - - return new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, parsedInitialState, parsedFinalState); - } catch (final JsonProcessingException e) { - throw ExceptionUtils.wrap(e); - } - }); - }); - } - - /** - * Returns a publisher across all samples for a given experiment. - * - * @param experimentName the name of the experiment for which to fetch samples - * @param stateClass the type of state object for sample in the given experiment - * - * @return a publisher of tuples of ACI, device ID, and sample for all samples associated with the given experiment - * - * @param the type of the sample's state objects - * - * @see Working with scans - Parallel scan - */ - public Flux> getSamples(final String experimentName, final Class stateClass) { - - return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder() - .tableName(tableName) - .keyConditionExpression("#experiment = :experiment") - .expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME)) - .expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(experimentName))) - .build()) - .items()) - .handle((item, sink) -> { - try { - final Tuple2 aciAndDeviceId = parseSortKey(item.get(ATTR_ACI_AND_DEVICE_ID)); - - final boolean inExperimentGroup = item.get(ATTR_IN_EXPERIMENT_GROUP).bool(); - final T initialState = parseState(item.get(ATTR_INITIAL_STATE).s(), stateClass); - final T finalState = item.get(ATTR_FINAL_STATE) != null - ? parseState(item.get(ATTR_FINAL_STATE).s(), stateClass) - : null; - - sink.next(new PushNotificationExperimentSample<>(aciAndDeviceId.getT1(), aciAndDeviceId.getT2(), inExperimentGroup, initialState, finalState)); - } catch (final JsonProcessingException e) { - sink.error(e); - } - }); - } - - public CompletableFuture discardSamples(final String experimentName, final int maxConcurrency) { - final AttributeValue experimentNameAttributeValue = AttributeValue.fromS(experimentName); - - return Flux.from(dynamoDbAsyncClient.scanPaginator(ScanRequest.builder() - .tableName(tableName) - .filterExpression("#experiment = :experiment") - .expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME)) - .expressionAttributeValues(Map.of(":experiment", experimentNameAttributeValue)) - .projectionExpression(ATTR_ACI_AND_DEVICE_ID) - .build()) - .items()) - .map(item -> item.get(ATTR_ACI_AND_DEVICE_ID)) - .flatMap(aciAndDeviceId -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(DeleteItemRequest.builder() - .tableName(tableName) - .key(Map.of( - KEY_EXPERIMENT_NAME, experimentNameAttributeValue, - ATTR_ACI_AND_DEVICE_ID, aciAndDeviceId)) - .build())) - .retryWhen(Retry.backoff(5, Duration.ofSeconds(5))) - .onErrorResume(throwable -> { - log.warn("Failed to delete sample for experiment {}", experimentName, throwable); - return Mono.empty(); - }), maxConcurrency) - .then() - .toFuture(); - } - - @VisibleForTesting - static AttributeValue buildSortKey(final UUID accountIdentifier, final byte deviceId) { - return AttributeValue.fromB(SdkBytes.fromByteBuffer(ByteBuffer.allocate(17) - .putLong(accountIdentifier.getMostSignificantBits()) - .putLong(accountIdentifier.getLeastSignificantBits()) - .put(deviceId) - .flip())); - } - - private static Tuple2 parseSortKey(final AttributeValue sortKey) { - final ByteBuffer byteBuffer = sortKey.b().asByteBuffer(); - - return Tuples.of(new UUID(byteBuffer.getLong(), byteBuffer.getLong()), byteBuffer.get()); - } - - private static T parseState(final String state, final Class clazz) throws JsonProcessingException { - return SystemMapper.jsonMapper().readValue(state, clazz); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 04b623e0f..20b9849ca 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -43,10 +43,12 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.controllers.SecureStorageController; import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.MicrometerAwsSdkMetricPublisher; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient; +import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; import org.whispersystems.textsecuregcm.push.APNSender; import org.whispersystems.textsecuregcm.push.FcmSender; import org.whispersystems.textsecuregcm.push.PushNotificationManager; @@ -90,9 +92,6 @@ import org.whispersystems.textsecuregcm.storage.TotpManager; import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase; import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore; import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher; -import org.whispersystems.textsecuregcm.purchases.AppleAppStoreClient; -import org.whispersystems.textsecuregcm.purchases.AppleAppStoreManager; -import org.whispersystems.textsecuregcm.purchases.GooglePlayBillingManager; import org.whispersystems.textsecuregcm.util.ManagedAwsCrt; import org.whispersystems.textsecuregcm.util.ManagedExecutors; import org.whispersystems.textsecuregcm.util.ResilienceUtil; @@ -118,7 +117,6 @@ public record CommandDependencies( APNSender apnSender, FcmSender fcmSender, PushNotificationManager pushNotificationManager, - PushNotificationExperimentSamples pushNotificationExperimentSamples, FaultTolerantRedisClusterClient cacheCluster, FaultTolerantRedisClusterClient pushSchedulerCluster, ClientResources.Builder redisClusterClientResourcesBuilder, @@ -461,10 +459,6 @@ public record CommandDependencies( apnSender, fcmSender, accountsManager, 0, 0, retryExecutor); PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler); - PushNotificationExperimentSamples pushNotificationExperimentSamples = - new PushNotificationExperimentSamples(dynamoDbAsyncClient, - configuration.getDynamoDbTables().getPushNotificationExperimentSamples().getTableName(), - Clock.systemUTC()); final DynamoDbRecoveryManager dynamoDbRecoveryManager = new DynamoDbRecoveryManager(accounts, phoneNumberIdentifiers); @@ -485,7 +479,6 @@ public record CommandDependencies( apnSender, fcmSender, pushNotificationManager, - pushNotificationExperimentSamples, cacheCluster, pushSchedulerCluster, redisClientResourcesBuilder, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/DiscardPushNotificationExperimentSamplesCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/DiscardPushNotificationExperimentSamplesCommand.java deleted file mode 100644 index 497208605..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/DiscardPushNotificationExperimentSamplesCommand.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.whispersystems.textsecuregcm.workers; - -import com.google.common.annotations.VisibleForTesting; -import io.dropwizard.core.Application; -import io.dropwizard.core.setup.Environment; -import net.sourceforge.argparse4j.inf.Namespace; -import net.sourceforge.argparse4j.inf.Subparser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.WhisperServerConfiguration; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; - -public class DiscardPushNotificationExperimentSamplesCommand extends AbstractCommandWithDependencies { - - private final PushNotificationExperimentFactory experimentFactory; - - private static final int DEFAULT_MAX_CONCURRENCY = 16; - - @VisibleForTesting - static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency"; - - private static final Logger log = LoggerFactory.getLogger(DiscardPushNotificationExperimentSamplesCommand.class); - - public DiscardPushNotificationExperimentSamplesCommand(final String name, - final String description, - final PushNotificationExperimentFactory experimentFactory) { - - super(new Application<>() { - @Override - public void run(final WhisperServerConfiguration configuration, final Environment environment) { - } - }, name, description); - - this.experimentFactory = experimentFactory; - } - - @Override - public void configure(final Subparser subparser) { - super.configure(subparser); - - subparser.addArgument("--max-concurrency") - .type(Integer.class) - .dest(MAX_CONCURRENCY_ARGUMENT) - .setDefault(DEFAULT_MAX_CONCURRENCY) - .help("Max concurrency for DynamoDB operations"); - } - - @Override - protected void run(final Environment environment, - final Namespace namespace, - final WhisperServerConfiguration configuration, - final CommandDependencies commandDependencies) throws Exception { - - final PushNotificationExperiment experiment = - experimentFactory.buildExperiment(commandDependencies, configuration); - - final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT); - - commandDependencies.pushNotificationExperimentSamples() - .discardSamples(experiment.getExperimentName(), maxConcurrency).join(); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommand.java deleted file mode 100644 index 28cf4d5bd..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommand.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.whispersystems.textsecuregcm.workers; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.google.common.annotations.VisibleForTesting; -import io.dropwizard.core.Application; -import io.dropwizard.core.setup.Environment; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Metrics; -import net.sourceforge.argparse4j.inf.Namespace; -import net.sourceforge.argparse4j.inf.Subparser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.WhisperServerConfiguration; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSample; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; -import org.whispersystems.textsecuregcm.metrics.MetricsUtil; -import org.whispersystems.textsecuregcm.storage.AccountsManager; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.util.retry.Retry; -import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; -import java.time.Duration; - -public class FinishPushNotificationExperimentCommand extends AbstractCommandWithDependencies { - - private final PushNotificationExperimentFactory experimentFactory; - - private static final int DEFAULT_MAX_CONCURRENCY = 16; - - @VisibleForTesting - static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency"; - - private static final String SAMPLES_READ_COUNTER_NAME = - MetricsUtil.name(FinishPushNotificationExperimentCommand.class, "samplesRead"); - - private static final Counter ACCOUNT_READ_COUNTER = - Metrics.counter(MetricsUtil.name(FinishPushNotificationExperimentCommand.class, "accountRead")); - - private static final Counter FINAL_SAMPLE_STORED_COUNTER = - Metrics.counter(MetricsUtil.name(FinishPushNotificationExperimentCommand.class, "finalSampleStored")); - - private static final Logger log = LoggerFactory.getLogger(FinishPushNotificationExperimentCommand.class); - - public FinishPushNotificationExperimentCommand(final String name, - final String description, - final PushNotificationExperimentFactory experimentFactory) { - - super(new Application<>() { - @Override - public void run(final WhisperServerConfiguration configuration, final Environment environment) { - } - }, name, description); - - this.experimentFactory = experimentFactory; - } - - @Override - public void configure(final Subparser subparser) { - super.configure(subparser); - - subparser.addArgument("--max-concurrency") - .type(Integer.class) - .dest(MAX_CONCURRENCY_ARGUMENT) - .setDefault(DEFAULT_MAX_CONCURRENCY) - .help("Max concurrency for DynamoDB operations"); - } - - @Override - protected void run(final Environment environment, - final Namespace namespace, - final WhisperServerConfiguration configuration, - final CommandDependencies commandDependencies) throws Exception { - - final PushNotificationExperiment experiment = - experimentFactory.buildExperiment(commandDependencies, configuration); - - final int maxConcurrency = namespace.getInt(MAX_CONCURRENCY_ARGUMENT); - - log.info("Finishing \"{}\" with max concurrency: {}", experiment.getExperimentName(), maxConcurrency); - - final AccountsManager accountsManager = commandDependencies.accountsManager(); - final PushNotificationExperimentSamples pushNotificationExperimentSamples = commandDependencies.pushNotificationExperimentSamples(); - - final Flux> finishedSamples = - pushNotificationExperimentSamples.getSamples(experiment.getExperimentName(), experiment.getStateClass()) - .doOnNext(sample -> Metrics.counter(SAMPLES_READ_COUNTER_NAME, "final", String.valueOf(sample.finalState() != null)).increment()) - .flatMap(sample -> { - if (sample.finalState() == null) { - // We still need to record a final state for this sample - return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(sample.accountIdentifier())) - .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) - .doOnNext(ignored -> ACCOUNT_READ_COUNTER.increment()) - .flatMap(maybeAccount -> { - final T finalState = experiment.getState(maybeAccount.orElse(null), - maybeAccount.flatMap(account -> account.getDevice(sample.deviceId())).orElse(null)); - - return Mono.fromFuture( - () -> pushNotificationExperimentSamples.recordFinalState(sample.accountIdentifier(), - sample.deviceId(), - experiment.getExperimentName(), - finalState)) - .onErrorResume(ConditionalCheckFailedException.class, throwable -> Mono.empty()) - .onErrorResume(JsonProcessingException.class, throwable -> { - log.error("Failed to parse sample state JSON", throwable); - return Mono.empty(); - }) - .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) - .onErrorResume(throwable -> { - log.warn("Failed to record final state for {}:{} in experiment {}", - sample.accountIdentifier(), sample.deviceId(), experiment.getExperimentName(), throwable); - - return Mono.empty(); - }) - .doOnSuccess(ignored -> FINAL_SAMPLE_STORED_COUNTER.increment()); - }); - } else { - return Mono.just(sample); - } - }, maxConcurrency); - - experiment.analyzeResults(finishedSamples); - } -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/PushNotificationExperimentFactory.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/PushNotificationExperimentFactory.java deleted file mode 100644 index 0aa2f6aa2..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/PushNotificationExperimentFactory.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.whispersystems.textsecuregcm.workers; - -import org.whispersystems.textsecuregcm.WhisperServerConfiguration; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; - -public interface PushNotificationExperimentFactory { - - PushNotificationExperiment buildExperiment(CommandDependencies commandDependencies, - WhisperServerConfiguration configuration); -} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java deleted file mode 100644 index 1650641f3..000000000 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommand.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.whispersystems.textsecuregcm.workers; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.google.common.annotations.VisibleForTesting; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Metrics; -import net.sourceforge.argparse4j.inf.Subparser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; -import org.whispersystems.textsecuregcm.identity.IdentityType; -import org.whispersystems.textsecuregcm.metrics.MetricsUtil; -import org.whispersystems.textsecuregcm.storage.Account; -import org.whispersystems.textsecuregcm.storage.Device; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.util.function.Tuples; -import reactor.util.retry.Retry; -import java.io.UncheckedIOException; -import java.time.Duration; -import java.util.UUID; - -public class StartPushNotificationExperimentCommand extends AbstractSinglePassCrawlAccountsCommand { - - private final PushNotificationExperimentFactory experimentFactory; - - private static final int DEFAULT_MAX_CONCURRENCY = 16; - - @VisibleForTesting - static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency"; - - @VisibleForTesting - static final String DRY_RUN_ARGUMENT = "dry-run"; - - private static final Counter DEVICE_INSPECTED_COUNTER = - Metrics.counter(MetricsUtil.name(StartPushNotificationExperimentCommand.class, "deviceInspected")); - - private static final String RECORD_INITIAL_SAMPLE_COUNTER_NAME = - MetricsUtil.name(StartPushNotificationExperimentCommand.class, "recordInitialSample"); - - private static final String APPLY_TREATMENT_COUNTER_NAME = - MetricsUtil.name(StartPushNotificationExperimentCommand.class, "applyTreatment"); - - private static final String DRY_RUN_TAG_NAME = "dryRun"; - - private static final Logger log = LoggerFactory.getLogger(StartPushNotificationExperimentCommand.class); - - public StartPushNotificationExperimentCommand(final String name, - final String description, - final PushNotificationExperimentFactory experimentFactory) { - - super(name, description); - this.experimentFactory = experimentFactory; - } - - @Override - public void configure(final Subparser subparser) { - super.configure(subparser); - - subparser.addArgument("--max-concurrency") - .type(Integer.class) - .dest(MAX_CONCURRENCY_ARGUMENT) - .setDefault(DEFAULT_MAX_CONCURRENCY) - .help("Max concurrency for DynamoDB operations"); - - subparser.addArgument("--dry-run") - .type(Boolean.class) - .dest(DRY_RUN_ARGUMENT) - .required(false) - .setDefault(true) - .help("If true, don't actually record samples or apply treatments"); - } - - @Override - protected void crawlAccounts(final Flux accounts) { - final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT); - final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT); - - final PushNotificationExperiment experiment = - experimentFactory.buildExperiment(getCommandDependencies(), getConfiguration()); - - final PushNotificationExperimentSamples pushNotificationExperimentSamples = - getCommandDependencies().pushNotificationExperimentSamples(); - - log.info("Starting \"{}\" with max concurrency: {}", experiment.getExperimentName(), maxConcurrency); - - accounts - .flatMap(account -> Flux.fromIterable(account.getDevices()).map(device -> Tuples.of(account, device))) - .doOnNext(ignored -> DEVICE_INSPECTED_COUNTER.increment()) - .flatMap(accountAndDevice -> Mono.fromFuture(() -> - experiment.isDeviceEligible(accountAndDevice.getT1(), accountAndDevice.getT2())) - .mapNotNull(eligible -> eligible ? accountAndDevice : null), maxConcurrency) - .flatMap(accountAndDevice -> { - final UUID accountIdentifier = accountAndDevice.getT1().getAccountIdentifier(); - final byte deviceId = accountAndDevice.getT2().getId(); - - final Mono recordInitialSampleMono = dryRun - ? Mono.just(true) - : Mono.fromFuture(() -> { - try { - return pushNotificationExperimentSamples.recordInitialState( - accountIdentifier, - deviceId, - experiment.getExperimentName(), - isInExperimentGroup(accountIdentifier, deviceId, experiment.getExperimentName()), - experiment.getState(accountAndDevice.getT1(), accountAndDevice.getT2())); - } catch (final JsonProcessingException e) { - throw new UncheckedIOException(e); - } - }) - .retryWhen(Retry.backoff(3, Duration.ofSeconds(1)) - .onRetryExhaustedThrow(((backoffSpec, retrySignal) -> retrySignal.failure()))); - - return recordInitialSampleMono.mapNotNull(stateStored -> { - Metrics.counter(RECORD_INITIAL_SAMPLE_COUNTER_NAME, - DRY_RUN_TAG_NAME, String.valueOf(dryRun), - "initialSampleAlreadyExists", String.valueOf(!stateStored)) - .increment(); - - return stateStored ? accountAndDevice : null; - }) - .onErrorResume(throwable -> { - log.warn("Failed to record initial sample for {}:{} in experiment {}", - accountIdentifier, deviceId, experiment.getExperimentName(), throwable); - - return Mono.empty(); - }); - }, maxConcurrency) - .flatMap(accountAndDevice -> { - final Account account = accountAndDevice.getT1(); - final Device device = accountAndDevice.getT2(); - final boolean inExperimentGroup = - isInExperimentGroup(account.getAccountIdentifier(), device.getId(), experiment.getExperimentName()); - - final Mono applyTreatmentMono = dryRun - ? Mono.empty() - : Mono.fromFuture(() -> inExperimentGroup - ? experiment.applyExperimentTreatment(account, device) - : experiment.applyControlTreatment(account, device)) - .onErrorResume(throwable -> { - log.warn("Failed to apply {} treatment for {}:{} in experiment {}", - inExperimentGroup ? "experimental" : " control", - account.getAccountIdentifier(), - device.getId(), - experiment.getExperimentName(), - throwable); - - return Mono.empty(); - }); - - return applyTreatmentMono - .doOnSuccess(ignored -> Metrics.counter(APPLY_TREATMENT_COUNTER_NAME, - DRY_RUN_TAG_NAME, String.valueOf(dryRun), - "treatment", inExperimentGroup ? "experiment" : "control").increment()); - }, maxConcurrency) - .then() - .block(); - } - - private boolean isInExperimentGroup(final UUID accountIdentifier, final byte deviceId, final String experimentName) { - return ((accountIdentifier.hashCode() ^ Byte.hashCode(deviceId) ^ experimentName.hashCode()) & 0x01) != 0; - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java deleted file mode 100644 index 388deee9f..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/experiment/IdleDevicePushNotificationExperimentTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package org.whispersystems.textsecuregcm.experiment; - -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.identity.IdentityType; -import org.whispersystems.textsecuregcm.storage.Account; -import org.whispersystems.textsecuregcm.storage.Device; -import reactor.core.publisher.Flux; - -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -abstract class IdleDevicePushNotificationExperimentTest { - - protected static final Instant CURRENT_TIME = Instant.now(); - - protected abstract IdleDevicePushNotificationExperiment getExperiment(); - - @ParameterizedTest - @MethodSource - void hasPushToken(final Device device, final boolean expectHasPushToken) { - assertEquals(expectHasPushToken, getExperiment().hasPushToken(device)); - } - - private static List hasPushToken() { - final List arguments = new ArrayList<>(); - - { - // No token at all - final Device device = mock(Device.class); - - arguments.add(Arguments.of(device, false)); - } - - { - // FCM token - final Device device = mock(Device.class); - when(device.getGcmId()).thenReturn("fcm-token"); - - arguments.add(Arguments.of(device, true)); - } - - { - // APNs token - final Device device = mock(Device.class); - when(device.getApnId()).thenReturn("apns-token"); - - arguments.add(Arguments.of(device, true)); - } - - return arguments; - } - - @Test - void getState() { - final IdleDevicePushNotificationExperiment experiment = getExperiment(); - - assertEquals(DeviceLastSeenState.MISSING_DEVICE_STATE, experiment.getState(null, null)); - assertEquals(DeviceLastSeenState.MISSING_DEVICE_STATE, experiment.getState(mock(Account.class), null)); - - final int registrationId = 123; - - { - final Device apnsDevice = mock(Device.class); - when(apnsDevice.getApnId()).thenReturn("apns-token"); - when(apnsDevice.getAccountRegistrationId()).thenReturn(registrationId); - when(apnsDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli()); - - assertEquals( - new DeviceLastSeenState(true, registrationId, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.APNS), - experiment.getState(mock(Account.class), apnsDevice)); - } - - { - final Device fcmDevice = mock(Device.class); - when(fcmDevice.getGcmId()).thenReturn("fcm-token"); - when(fcmDevice.getAccountRegistrationId()).thenReturn(registrationId); - when(fcmDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli()); - - assertEquals( - new DeviceLastSeenState(true, registrationId, true, CURRENT_TIME.toEpochMilli(), DeviceLastSeenState.PushTokenType.FCM), - experiment.getState(mock(Account.class), fcmDevice)); - } - - { - final Device noTokenDevice = mock(Device.class); - when(noTokenDevice.getAccountRegistrationId()).thenReturn(registrationId); - when(noTokenDevice.getLastSeen()).thenReturn(CURRENT_TIME.toEpochMilli()); - - assertEquals( - new DeviceLastSeenState(true, registrationId, false, CURRENT_TIME.toEpochMilli(), null), - experiment.getState(mock(Account.class), noTokenDevice)); - } - } - @ParameterizedTest - @MethodSource - void getPopulation(final boolean inExperimentGroup, - final DeviceLastSeenState.PushTokenType tokenType, - final IdleDevicePushNotificationExperiment.Population expectedPopulation) { - - final DeviceLastSeenState state = new DeviceLastSeenState(true, 0, true, 0, tokenType); - final PushNotificationExperimentSample sample = - new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, inExperimentGroup, state, state); - - assertEquals(expectedPopulation, IdleDevicePushNotificationExperiment.getPopulation(sample)); - } - - private static List getPopulation() { - return List.of( - Arguments.of(true, DeviceLastSeenState.PushTokenType.APNS, - IdleDevicePushNotificationExperiment.Population.APNS_EXPERIMENT), - - Arguments.of(false, DeviceLastSeenState.PushTokenType.APNS, - IdleDevicePushNotificationExperiment.Population.APNS_CONTROL), - - Arguments.of(true, DeviceLastSeenState.PushTokenType.FCM, - IdleDevicePushNotificationExperiment.Population.FCM_EXPERIMENT), - - Arguments.of(false, DeviceLastSeenState.PushTokenType.FCM, - IdleDevicePushNotificationExperiment.Population.FCM_CONTROL) - ); - } - - @ParameterizedTest - @MethodSource - void getOutcome(final DeviceLastSeenState initialState, - final DeviceLastSeenState finalState, - final IdleDevicePushNotificationExperiment.Outcome expectedOutcome) { - - final PushNotificationExperimentSample sample = - new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, true, initialState, finalState); - - assertEquals(expectedOutcome, IdleDevicePushNotificationExperiment.getOutcome(sample)); - } - - private static List getOutcome() { - return List.of( - // Device no longer exists - Arguments.of( - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS), - DeviceLastSeenState.MISSING_DEVICE_STATE, - IdleDevicePushNotificationExperiment.Outcome.DELETED - ), - - // Device re-registered (i.e. registration ID changed) - Arguments.of( - new DeviceLastSeenState(true, 123, true, 0, DeviceLastSeenState.PushTokenType.APNS), - new DeviceLastSeenState(true, 1234, true, 1, DeviceLastSeenState.PushTokenType.APNS), - IdleDevicePushNotificationExperiment.Outcome.DELETED - ), - - // Device has lost push tokens - Arguments.of( - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS), - new DeviceLastSeenState(true, 0, false, 0, DeviceLastSeenState.PushTokenType.APNS), - IdleDevicePushNotificationExperiment.Outcome.UNINSTALLED - ), - - // Device reactivated - Arguments.of( - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS), - new DeviceLastSeenState(true, 0, true, 1, DeviceLastSeenState.PushTokenType.APNS), - IdleDevicePushNotificationExperiment.Outcome.REACTIVATED - ), - - // No change - Arguments.of( - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS), - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS), - IdleDevicePushNotificationExperiment.Outcome.UNCHANGED - ) - ); - } - - @Test - void analyzeResults() { - assertDoesNotThrow(() -> getExperiment().analyzeResults( - Flux.just(new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, true, - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS), - new DeviceLastSeenState(true, 0, true, 0, DeviceLastSeenState.PushTokenType.APNS))))); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSamplesTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSamplesTest.java deleted file mode 100644 index 734b44c16..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/experiment/PushNotificationExperimentSamplesTest.java +++ /dev/null @@ -1,304 +0,0 @@ -package org.whispersystems.textsecuregcm.experiment; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import com.fasterxml.jackson.core.JsonProcessingException; -import java.time.Clock; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.Collectors; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.whispersystems.textsecuregcm.storage.Device; -import org.whispersystems.textsecuregcm.storage.DynamoDbExtension; -import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema; -import org.whispersystems.textsecuregcm.util.SystemMapper; -import software.amazon.awssdk.services.dynamodb.model.AttributeValue; -import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; -import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; -import software.amazon.awssdk.services.dynamodb.model.QueryRequest; -import software.amazon.awssdk.services.dynamodb.model.QueryResponse; -import software.amazon.awssdk.services.dynamodb.model.Select; -import javax.annotation.Nullable; - -class PushNotificationExperimentSamplesTest { - - private PushNotificationExperimentSamples pushNotificationExperimentSamples; - - @RegisterExtension - public static final DynamoDbExtension DYNAMO_DB_EXTENSION = - new DynamoDbExtension(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES); - - private record TestDeviceState(int bounciness) { - } - - @BeforeEach - void setUp() { - pushNotificationExperimentSamples = - new PushNotificationExperimentSamples(DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), - DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName(), - Clock.systemUTC()); - } - - @Test - void recordInitialState() throws JsonProcessingException { - final String experimentName = "test-experiment"; - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); - final boolean inExperimentGroup = ThreadLocalRandom.current().nextBoolean(); - final int bounciness = ThreadLocalRandom.current().nextInt(); - - assertTrue(pushNotificationExperimentSamples.recordInitialState(accountIdentifier, - deviceId, - experimentName, - inExperimentGroup, - new TestDeviceState(bounciness)) - .join(), - "Attempt to record an initial state should succeed for entirely new records"); - - assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null), - getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class)); - - assertTrue(pushNotificationExperimentSamples.recordInitialState(accountIdentifier, - deviceId, - experimentName, - inExperimentGroup, - new TestDeviceState(bounciness)) - .join(), - "Attempt to re-record an initial state should succeed for existing-but-unchanged records"); - - assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null), - getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class), - "Recorded initial state should be unchanged after repeated write"); - - assertFalse(pushNotificationExperimentSamples.recordInitialState(accountIdentifier, - deviceId, - experimentName, - inExperimentGroup, - new TestDeviceState(bounciness + 1)) - .join(), - "Attempt to record a conflicting initial state should fail"); - - assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null), - getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class), - "Recorded initial state should be unchanged after unsuccessful write"); - - assertFalse(pushNotificationExperimentSamples.recordInitialState(accountIdentifier, - deviceId, - experimentName, - !inExperimentGroup, - new TestDeviceState(bounciness)) - .join(), - "Attempt to record a new group assignment should fail"); - - assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), null), - getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class), - "Recorded initial state should be unchanged after unsuccessful write"); - - final int finalBounciness = bounciness + 17; - - pushNotificationExperimentSamples.recordFinalState(accountIdentifier, - deviceId, - experimentName, - new TestDeviceState(finalBounciness)) - .join(); - - assertFalse(pushNotificationExperimentSamples.recordInitialState(accountIdentifier, - deviceId, - experimentName, - inExperimentGroup, - new TestDeviceState(bounciness)) - .join(), - "Attempt to record an initial state should fail for samples with final states"); - - assertEquals(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(bounciness), new TestDeviceState(finalBounciness)), - getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class), - "Recorded initial state should be unchanged after unsuccessful write"); - } - - @Test - void recordFinalState() throws JsonProcessingException { - final String experimentName = "test-experiment"; - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); - final boolean inExperimentGroup = ThreadLocalRandom.current().nextBoolean(); - final int initialBounciness = ThreadLocalRandom.current().nextInt(); - final int finalBounciness = initialBounciness + 17; - - { - pushNotificationExperimentSamples.recordInitialState(accountIdentifier, - deviceId, - experimentName, - inExperimentGroup, - new TestDeviceState(initialBounciness)) - .join(); - - final PushNotificationExperimentSample returnedSample = - pushNotificationExperimentSamples.recordFinalState(accountIdentifier, - deviceId, - experimentName, - new TestDeviceState(finalBounciness)) - .join(); - - final PushNotificationExperimentSample expectedSample = - new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, - new TestDeviceState(initialBounciness), - new TestDeviceState(finalBounciness)); - - assertEquals(expectedSample, returnedSample, - "Attempt to update existing sample without final state should succeed"); - - assertEquals(expectedSample, getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class), - "Attempt to update existing sample without final state should be persisted"); - } - - assertThrows(CompletionException.class, () -> pushNotificationExperimentSamples.recordFinalState(accountIdentifier, - (byte) (deviceId + 1), - experimentName, - new TestDeviceState(finalBounciness)) - .join(), - "Attempts to record a final state without an initial state should fail"); - } - - @SuppressWarnings("SameParameterValue") - private PushNotificationExperimentSample getSample(final UUID accountIdentifier, - final byte deviceId, - final String experimentName, - final Class stateClass) throws JsonProcessingException { - - final GetItemResponse response = DYNAMO_DB_EXTENSION.getDynamoDbClient().getItem(GetItemRequest.builder() - .tableName(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName()) - .key(Map.of( - PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName), - PushNotificationExperimentSamples.ATTR_ACI_AND_DEVICE_ID, PushNotificationExperimentSamples.buildSortKey(accountIdentifier, deviceId))) - .build()); - - final boolean inExperimentGroup = - response.item().get(PushNotificationExperimentSamples.ATTR_IN_EXPERIMENT_GROUP).bool(); - - final T initialState = - SystemMapper.jsonMapper().readValue(response.item().get(PushNotificationExperimentSamples.ATTR_INITIAL_STATE).s(), stateClass); - - @Nullable final T finalState = response.item().containsKey(PushNotificationExperimentSamples.ATTR_FINAL_STATE) - ? SystemMapper.jsonMapper().readValue(response.item().get(PushNotificationExperimentSamples.ATTR_FINAL_STATE).s(), stateClass) - : null; - - return new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, initialState, finalState); - } - - @Test - void getSamples() throws JsonProcessingException { - final String experimentName = "test-experiment"; - final UUID initialSampleAccountIdentifier = UUID.randomUUID(); - final byte initialSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); - final boolean initialSampleInExperimentGroup = ThreadLocalRandom.current().nextBoolean(); - - final UUID finalSampleAccountIdentifier = UUID.randomUUID(); - final byte finalSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); - final boolean finalSampleInExperimentGroup = ThreadLocalRandom.current().nextBoolean(); - - final int initialBounciness = ThreadLocalRandom.current().nextInt(); - final int finalBounciness = initialBounciness + 17; - - pushNotificationExperimentSamples.recordInitialState(initialSampleAccountIdentifier, - initialSampleDeviceId, - experimentName, - initialSampleInExperimentGroup, - new TestDeviceState(initialBounciness)) - .join(); - - pushNotificationExperimentSamples.recordInitialState(finalSampleAccountIdentifier, - finalSampleDeviceId, - experimentName, - finalSampleInExperimentGroup, - new TestDeviceState(initialBounciness)) - .join(); - - pushNotificationExperimentSamples.recordFinalState(finalSampleAccountIdentifier, - finalSampleDeviceId, - experimentName, - new TestDeviceState(finalBounciness)) - .join(); - - pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(), - (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID), - experimentName + "-different", - ThreadLocalRandom.current().nextBoolean(), - new TestDeviceState(ThreadLocalRandom.current().nextInt())) - .join(); - - final Set> expectedSamples = Set.of( - new PushNotificationExperimentSample<>(initialSampleAccountIdentifier, - initialSampleDeviceId, - initialSampleInExperimentGroup, - new TestDeviceState(initialBounciness), - null), - - new PushNotificationExperimentSample<>(finalSampleAccountIdentifier, - finalSampleDeviceId, - finalSampleInExperimentGroup, - new TestDeviceState(initialBounciness), - new TestDeviceState(finalBounciness))); - - assertEquals(expectedSamples, - pushNotificationExperimentSamples.getSamples(experimentName, TestDeviceState.class).collect(Collectors.toSet()).block()); - } - - @Test - void discardSamples() throws JsonProcessingException { - final String discardSamplesExperimentName = "discard-experiment"; - final String retainSamplesExperimentName = "retain-experiment"; - final int sampleCount = 16; - - for (int i = 0; i < sampleCount; i++) { - pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(), - Device.PRIMARY_ID, - discardSamplesExperimentName, - ThreadLocalRandom.current().nextBoolean(), - new TestDeviceState(ThreadLocalRandom.current().nextInt())) - .join(); - - pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(), - Device.PRIMARY_ID, - retainSamplesExperimentName, - ThreadLocalRandom.current().nextBoolean(), - new TestDeviceState(ThreadLocalRandom.current().nextInt())) - .join(); - } - - pushNotificationExperimentSamples.discardSamples(discardSamplesExperimentName, 1).join(); - - { - final QueryResponse queryResponse = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient().query(QueryRequest.builder() - .tableName(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName()) - .keyConditionExpression("#experiment = :experiment") - .expressionAttributeNames(Map.of("#experiment", PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME)) - .expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(discardSamplesExperimentName))) - .select(Select.COUNT) - .build()) - .join(); - - assertEquals(0, queryResponse.count()); - } - - { - final QueryResponse queryResponse = DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient().query(QueryRequest.builder() - .tableName(DynamoDbExtensionSchema.Tables.PUSH_NOTIFICATION_EXPERIMENT_SAMPLES.tableName()) - .keyConditionExpression("#experiment = :experiment") - .expressionAttributeNames(Map.of("#experiment", PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME)) - .expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(retainSamplesExperimentName))) - .select(Select.COUNT) - .build()) - .join(); - - assertEquals(sampleCount, queryResponse.count()); - } - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java index f854c2a03..6d12580c3 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java @@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.storage; import java.util.Collections; import java.util.List; import org.whispersystems.textsecuregcm.backup.BackupsDb; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; import org.whispersystems.textsecuregcm.scheduler.JobScheduler; import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; @@ -160,20 +159,6 @@ public final class DynamoDbExtensionSchema { .build()), List.of(), List.of()), - PUSH_NOTIFICATION_EXPERIMENT_SAMPLES("push_notification_experiment_samples_test", - PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME, - PushNotificationExperimentSamples.ATTR_ACI_AND_DEVICE_ID, - List.of( - AttributeDefinition.builder() - .attributeName(PushNotificationExperimentSamples.KEY_EXPERIMENT_NAME) - .attributeType(ScalarAttributeType.S) - .build(), - AttributeDefinition.builder() - .attributeName(PushNotificationExperimentSamples.ATTR_ACI_AND_DEVICE_ID) - .attributeType(ScalarAttributeType.B) - .build()), - List.of(), List.of()), - REPEATED_USE_EC_SIGNED_PRE_KEYS("repeated_use_signed_ec_pre_keys_test", RepeatedUseSignedPreKeyStore.KEY_ACCOUNT_UUID, RepeatedUseSignedPreKeyStore.KEY_DEVICE_ID, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java index 9870be4a4..fcc44d84f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/ClearExpiredFoundationDbMessagesCommandTest.java @@ -44,7 +44,7 @@ class ClearExpiredFoundationDbMessagesCommandTest { 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, null, null, + 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, null, null, null); this.dryRun = dryRun; } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java deleted file mode 100644 index 31424c1b3..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/FinishPushNotificationExperimentCommandTest.java +++ /dev/null @@ -1,263 +0,0 @@ -package org.whispersystems.textsecuregcm.workers; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyByte; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -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 java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import net.sourceforge.argparse4j.inf.Namespace; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSample; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; -import org.whispersystems.textsecuregcm.storage.Account; -import org.whispersystems.textsecuregcm.storage.AccountsManager; -import org.whispersystems.textsecuregcm.storage.Device; -import reactor.core.publisher.Flux; -import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; - -class FinishPushNotificationExperimentCommandTest { - - private CommandDependencies commandDependencies; - private PushNotificationExperiment experiment; - - private FinishPushNotificationExperimentCommand finishPushNotificationExperimentCommand; - - private static final String EXPERIMENT_NAME = "test"; - - private static final Namespace NAMESPACE = - new Namespace(Map.of(FinishPushNotificationExperimentCommand.MAX_CONCURRENCY_ARGUMENT, 1)); - - private static class TestFinishPushNotificationExperimentCommand extends FinishPushNotificationExperimentCommand { - - public TestFinishPushNotificationExperimentCommand(final PushNotificationExperiment experiment) { - super("test-finish-push-notification-experiment", - "Test start push notification experiment command", - (ignoredDependencies, ignoredConfiguration) -> experiment); - } - } - - @BeforeEach - void setUp() { - final AccountsManager accountsManager = mock(AccountsManager.class); - - final PushNotificationExperimentSamples pushNotificationExperimentSamples = - mock(PushNotificationExperimentSamples.class); - - when(pushNotificationExperimentSamples.recordFinalState(any(), anyByte(), any(), any())) - .thenAnswer(invocation -> { - final UUID accountIdentifier = invocation.getArgument(0); - final byte deviceId = invocation.getArgument(1); - - return CompletableFuture.completedFuture( - new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", "test")); - }); - - commandDependencies = new CommandDependencies(accountsManager, - null, - null, - null, - null, - null, - null, - null, - null, - null, - pushNotificationExperimentSamples, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null); - - //noinspection unchecked - experiment = mock(PushNotificationExperiment.class); - when(experiment.getExperimentName()).thenReturn(EXPERIMENT_NAME); - when(experiment.getState(any(), any())).thenReturn("test"); - when(experiment.getStateClass()).thenReturn(String.class); - - doAnswer(invocation -> { - final Flux> samples = invocation.getArgument(0); - samples.then().block(); - - return null; - }).when(experiment).analyzeResults(any()); - - finishPushNotificationExperimentCommand = new TestFinishPushNotificationExperimentCommand(experiment); - } - - @Test - void run() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(deviceId); - - final Account account = mock(Account.class); - when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); - - when(commandDependencies.accountsManager().getByAccountIdentifierAsync(accountIdentifier)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", null))); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(experiment).getState(account, device); - verify(commandDependencies.pushNotificationExperimentSamples()) - .recordFinalState(eq(accountIdentifier), eq(deviceId), eq(EXPERIMENT_NAME), any()); - } - - @Test - void runMissingAccount() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - when(commandDependencies.accountsManager().getByAccountIdentifierAsync(accountIdentifier)) - .thenReturn(CompletableFuture.completedFuture(Optional.empty())); - - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", null))); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(experiment).getState(null, null); - verify(commandDependencies.pushNotificationExperimentSamples()) - .recordFinalState(eq(accountIdentifier), eq(deviceId), eq(EXPERIMENT_NAME), any()); - } - - @Test - void runMissingDevice() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final Account account = mock(Account.class); - when(account.getDevice(deviceId)).thenReturn(Optional.empty()); - - when(commandDependencies.accountsManager().getByAccountIdentifierAsync(accountIdentifier)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", null))); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(experiment).getState(account, null); - verify(commandDependencies.pushNotificationExperimentSamples()) - .recordFinalState(eq(accountIdentifier), eq(deviceId), eq(EXPERIMENT_NAME), any()); - } - - @Test - void runAccountFetchRetry() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(deviceId); - - final Account account = mock(Account.class); - when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); - - when(commandDependencies.accountsManager().getByAccountIdentifierAsync(accountIdentifier)) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())) - .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", null))); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(experiment).getState(account, device); - verify(commandDependencies.pushNotificationExperimentSamples()) - .recordFinalState(eq(accountIdentifier), eq(deviceId), eq(EXPERIMENT_NAME), any()); - - verify(commandDependencies.accountsManager(), times(3)).getByAccountIdentifierAsync(accountIdentifier); - } - - @Test - void runStoreSampleRetry() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(deviceId); - - final Account account = mock(Account.class); - when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); - - when(commandDependencies.accountsManager().getByAccountIdentifierAsync(accountIdentifier)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", null))); - - when(commandDependencies.pushNotificationExperimentSamples().recordFinalState(any(), anyByte(), any(), any())) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())) - .thenReturn(CompletableFuture.completedFuture(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", "test"))); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(experiment).getState(account, device); - verify(commandDependencies.pushNotificationExperimentSamples(), times(3)) - .recordFinalState(eq(accountIdentifier), eq(deviceId), eq(EXPERIMENT_NAME), any()); - } - - @Test - void runMissingInitialSample() { - final UUID accountIdentifier = UUID.randomUUID(); - final byte deviceId = Device.PRIMARY_ID; - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(deviceId); - - final Account account = mock(Account.class); - when(account.getDevice(deviceId)).thenReturn(Optional.of(device)); - - when(commandDependencies.accountsManager().getByAccountIdentifierAsync(accountIdentifier)) - .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); - - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(accountIdentifier, deviceId, true, "test", null))); - - when(commandDependencies.pushNotificationExperimentSamples().recordFinalState(any(), anyByte(), any(), any())) - .thenReturn(CompletableFuture.failedFuture(ConditionalCheckFailedException.builder().build())); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(experiment).getState(account, device); - verify(commandDependencies.pushNotificationExperimentSamples()) - .recordFinalState(eq(accountIdentifier), eq(deviceId), eq(EXPERIMENT_NAME), any()); - } - - @Test - void runFinalSampleAlreadyRecorded() { - when(commandDependencies.pushNotificationExperimentSamples().getSamples(eq(EXPERIMENT_NAME), eq(String.class))) - .thenReturn(Flux.just(new PushNotificationExperimentSample<>(UUID.randomUUID(), Device.PRIMARY_ID, true, "test", "test"))); - - assertDoesNotThrow(() -> finishPushNotificationExperimentCommand.run(null, NAMESPACE, null, commandDependencies)); - verify(commandDependencies.accountsManager(), never()).getByAccountIdentifier(any()); - verify(experiment, never()).getState(any(), any()); - verify(commandDependencies.pushNotificationExperimentSamples(), never()) - .recordFinalState(any(), anyByte(), any(), any()); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java index c3b78c11b..3501f7cdf 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/NotifyIdleDevicesCommandTest.java @@ -69,7 +69,6 @@ class NotifyIdleDevicesCommandTest { null, null, null, - null, null); this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler; diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java index 00565f511..5535ed386 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/RegenerateSecondaryDynamoDbTableDataCommandTest.java @@ -53,7 +53,6 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest { null, null, null, - null, dynamoDbRecoveryManager, null, null, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java deleted file mode 100644 index 53a6f4f43..000000000 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/StartPushNotificationExperimentCommandTest.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.whispersystems.textsecuregcm.workers; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -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 com.fasterxml.jackson.core.JsonProcessingException; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import net.sourceforge.argparse4j.inf.Namespace; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperiment; -import org.whispersystems.textsecuregcm.experiment.PushNotificationExperimentSamples; -import org.whispersystems.textsecuregcm.storage.Account; -import org.whispersystems.textsecuregcm.storage.Device; -import reactor.core.publisher.Flux; - -class StartPushNotificationExperimentCommandTest { - - private PushNotificationExperimentSamples pushNotificationExperimentSamples; - private PushNotificationExperiment experiment; - - private TestStartPushNotificationExperimentCommand startPushNotificationExperimentCommand; - - // Taken together, these parameters will produce a device that's enrolled in the experimental group (as opposed to the - // control group) for an experiment. - private static final UUID ACCOUNT_IDENTIFIER = UUID.fromString("341fb18f-9dee-4181-bc40-e485958341d3"); - private static final byte DEVICE_ID = Device.PRIMARY_ID; - private static final String EXPERIMENT_NAME = "test"; - - private static class TestStartPushNotificationExperimentCommand extends StartPushNotificationExperimentCommand { - - private final CommandDependencies commandDependencies; - private boolean dryRun = false; - - public TestStartPushNotificationExperimentCommand( - final PushNotificationExperimentSamples pushNotificationExperimentSamples, - final PushNotificationExperiment experiment) { - - super("test-start-push-notification-experiment", - "Test start push notification experiment command", - (ignoredDependencies, ignoredConfiguration) -> experiment); - - this.commandDependencies = new CommandDependencies(null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - pushNotificationExperimentSamples, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null); - } - - void setDryRun(final boolean dryRun) { - this.dryRun = dryRun; - } - - @Override - protected Namespace getNamespace() { - return new Namespace(Map.of( - StartPushNotificationExperimentCommand.MAX_CONCURRENCY_ARGUMENT, 1, - StartPushNotificationExperimentCommand.DRY_RUN_ARGUMENT, dryRun)); - } - - @Override - protected CommandDependencies getCommandDependencies() { - return commandDependencies; - } - } - - @BeforeEach - void setUp() { - //noinspection unchecked - experiment = mock(PushNotificationExperiment.class); - when(experiment.getExperimentName()).thenReturn(EXPERIMENT_NAME); - when(experiment.isDeviceEligible(any(), any())).thenReturn(CompletableFuture.completedFuture(true)); - when(experiment.getState(any(), any())).thenReturn("test"); - when(experiment.applyExperimentTreatment(any(), any())).thenReturn(CompletableFuture.completedFuture(null)); - - pushNotificationExperimentSamples = mock(PushNotificationExperimentSamples.class); - - try { - when(pushNotificationExperimentSamples.recordInitialState(any(), anyByte(), any(), anyBoolean(), any())) - .thenReturn(CompletableFuture.completedFuture(true)); - } catch (final JsonProcessingException e) { - throw new AssertionError(e); - } - - startPushNotificationExperimentCommand = - new TestStartPushNotificationExperimentCommand(pushNotificationExperimentSamples, experiment); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void crawlAccounts(final boolean dryRun) { - startPushNotificationExperimentCommand.setDryRun(dryRun); - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(DEVICE_ID); - - final Account account = mock(Account.class); - when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); - when(account.getDevices()).thenReturn(List.of(device)); - - assertDoesNotThrow(() -> startPushNotificationExperimentCommand.crawlAccounts(Flux.just(account))); - - if (dryRun) { - verify(experiment, never()).applyExperimentTreatment(any(), any()); - } else { - verify(experiment).applyExperimentTreatment(account, device); - } - - verify(experiment, never()).applyControlTreatment(account, device); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void crawlAccountsExistingSample(final boolean dryRun) throws JsonProcessingException { - startPushNotificationExperimentCommand.setDryRun(dryRun); - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(DEVICE_ID); - - final Account account = mock(Account.class); - when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); - when(account.getDevices()).thenReturn(List.of(device)); - - when(pushNotificationExperimentSamples.recordInitialState(any(), anyByte(), any(), anyBoolean(), any())) - .thenReturn(CompletableFuture.completedFuture(false)); - - assertDoesNotThrow(() -> startPushNotificationExperimentCommand.crawlAccounts(Flux.just(account))); - verify(experiment, never()).applyExperimentTreatment(any(), any()); - } - - @ParameterizedTest - @ValueSource(booleans = {true, false}) - void crawlAccountsSampleRetry(final boolean dryRun) throws JsonProcessingException { - startPushNotificationExperimentCommand.setDryRun(dryRun); - - final Device device = mock(Device.class); - when(device.getId()).thenReturn(DEVICE_ID); - - final Account account = mock(Account.class); - when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); - when(account.getDevices()).thenReturn(List.of(device)); - - when(pushNotificationExperimentSamples.recordInitialState(any(), anyByte(), any(), anyBoolean(), any())) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())) - .thenReturn(CompletableFuture.completedFuture(true)); - - assertDoesNotThrow(() -> startPushNotificationExperimentCommand.crawlAccounts(Flux.just(account))); - - if (dryRun) { - verify(experiment, never()).applyExperimentTreatment(any(), any()); - verify(pushNotificationExperimentSamples, never()) - .recordInitialState(any(), anyByte(), any(), anyBoolean(), any()); - } else { - verify(experiment).applyExperimentTreatment(account, device); - verify(pushNotificationExperimentSamples, times(3)) - .recordInitialState(ACCOUNT_IDENTIFIER, DEVICE_ID, EXPERIMENT_NAME, true, "test"); - } - - verify(experiment, never()).applyControlTreatment(account, device); - } - - @Test - void crawlAccountsExperimentException() { - final Device device = mock(Device.class); - when(device.getId()).thenReturn(DEVICE_ID); - - final Account account = mock(Account.class); - when(account.getAccountIdentifier()).thenReturn(ACCOUNT_IDENTIFIER); - when(account.getDevices()).thenReturn(List.of(device)); - - when(experiment.applyExperimentTreatment(account, device)) - .thenReturn(CompletableFuture.failedFuture(new RuntimeException())); - - assertDoesNotThrow(() -> startPushNotificationExperimentCommand.crawlAccounts(Flux.just(account))); - verify(experiment).applyExperimentTreatment(account, device); - } -} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java index a4f85ebf5..821a3a0b2 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/workers/TrimOversizedFoundationDbMessageQueuesCommandTest.java @@ -39,7 +39,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest { final boolean dryRun) { super(); - 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, null, null, null, null); + 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, null, null, null); this.dryRun = dryRun; } diff --git a/service/src/test/resources/config/test.yml b/service/src/test/resources/config/test.yml index c576eaea3..31915b19d 100644 --- a/service/src/test/resources/config/test.yml +++ b/service/src/test/resources/config/test.yml @@ -140,8 +140,6 @@ dynamoDbTables: tableName: profilesV2_test pushChallenge: tableName: push_challenge_test - pushNotificationExperimentSamples: - tableName: Example_PushNotificationExperimentSamples redeemedReceipts: tableName: redeemed_receipts_test registrationRecovery: