diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index e998636e0..9d8d6441e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -833,7 +833,7 @@ public class WhisperServerService extends Application GetMessagesResponse.newBuilder().setQueueEmpty(Empty.getDefaultInstance()).setServerTimeEpochMillis(clock.millis()).build()), // Emit an invalid credentials error if we receive a disconnection request disconnectionSignal(account, device, userAgent)) - .doFinally(_ -> maybeSendNewMessagePushNotification(account, device)); + .doFinally(_ -> maybeSchedulePush(account, device)); } - /// If the device potentially has more messages available, send a push notification. - private void maybeSendNewMessagePushNotification(final Account account, final Device device) { + /// If the device potentially has more messages available, schedule a push notification. + private void maybeSchedulePush(final Account account, final Device device) { messagesManager.mayHaveMessages(account.getAccountIdentifier(), device) .thenAccept(mayHaveMessages -> { if (mayHaveMessages) { - try { - pushNotificationManager.sendNewMessageNotification(account, device.getId(), true); - } catch (NotPushRegisteredException _) { - } + pushNotificationScheduler.scheduleDelayedNotification(account, device, + CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY); } }); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationScheduler.java b/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationScheduler.java index 3ff435c64..37b2a79c2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationScheduler.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/push/PushNotificationScheduler.java @@ -23,6 +23,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiFunction; @@ -37,6 +38,7 @@ import org.whispersystems.textsecuregcm.storage.Device; import org.whispersystems.textsecuregcm.util.ExceptionUtils; import org.whispersystems.textsecuregcm.util.Pair; import org.whispersystems.textsecuregcm.util.RedisClusterUtil; +import org.whispersystems.textsecuregcm.util.ResilienceUtil; import org.whispersystems.textsecuregcm.util.Util; import reactor.core.publisher.Mono; @@ -47,6 +49,7 @@ public class PushNotificationScheduler implements Managed { private static final String PENDING_BACKGROUND_APN_NOTIFICATIONS_KEY_PREFIX = "PENDING_BACKGROUND_APN"; private static final String PENDING_BACKGROUND_FCM_NOTIFICATIONS_KEY_PREFIX = "PENDING_BACKGROUND_FCM"; private static final String LAST_BACKGROUND_NOTIFICATION_TIMESTAMP_KEY_PREFIX = "LAST_BACKGROUND_NOTIFICATION"; + private static final String PENDING_DELAYED_NOTIFICATIONS_KEY_PREFIX = "DELAYED"; @VisibleForTesting static final String NEXT_SLOT_TO_PROCESS_KEY = "pending_notification_next_slot"; @@ -56,12 +59,16 @@ public class PushNotificationScheduler implements Managed { private static final String BACKGROUND_NOTIFICATION_SCHEDULED_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "scheduled"); private static final String BACKGROUND_NOTIFICATION_SENT_COUNTER_NAME = name(PushNotificationScheduler.class, "backgroundNotification", "sent"); + private static final String DELAYED_NOTIFICATION_SCHEDULED_COUNTER_NAME = name(PushNotificationScheduler.class, "delayedNotificationScheduled"); + private static final String DELAYED_NOTIFICATION_SENT_COUNTER_NAME = name(PushNotificationScheduler.class, "delayedNotificationSent"); + private static final String TOKEN_TYPE_TAG = "tokenType"; private static final String ACCEPTED_TAG = "accepted"; private final APNSender apnSender; private final FcmSender fcmSender; private final AccountsManager accountsManager; private final FaultTolerantRedisClusterClient pushSchedulingCluster; + private final ScheduledExecutorService retryExecutor; private final Clock clock; private final ClusterLuaScript scheduleBackgroundNotificationScript; @@ -73,6 +80,8 @@ public class PushNotificationScheduler implements Managed { private final AtomicBoolean running = new AtomicBoolean(false); + private static final String RETRY_NAME = ResilienceUtil.name(PushNotificationScheduler.class); + class NotificationWorker implements Runnable { private final int maxConcurrency; @@ -109,7 +118,8 @@ public class PushNotificationScheduler implements Managed { connection.sync().incr(NEXT_SLOT_TO_PROCESS_KEY)) % SlotHash.SLOT_COUNT); return processScheduledBackgroundNotifications(PushNotification.TokenType.APN, slot) - + processScheduledBackgroundNotifications(PushNotification.TokenType.FCM, slot); + + processScheduledBackgroundNotifications(PushNotification.TokenType.FCM, slot) + + processScheduledDelayedNotifications(slot); } @VisibleForTesting @@ -119,6 +129,12 @@ public class PushNotificationScheduler implements Managed { } + @VisibleForTesting + long processScheduledDelayedNotifications(final int slot) { + return processScheduledNotifications(getDelayedNotificationQueueKey(slot), + PushNotificationScheduler.this::sendDelayedNotification); + } + private long processScheduledNotifications(final String queueKey, final BiFunction> sendNotificationFunction) { @@ -147,7 +163,8 @@ public class PushNotificationScheduler implements Managed { final FcmSender fcmSender, final AccountsManager accountsManager, final int dedicatedProcessWorkerThreadCount, - final int workerMaxConcurrency) throws IOException { + final int workerMaxConcurrency, + final ScheduledExecutorService retryExecutor) throws IOException { this(pushSchedulingCluster, apnSender, @@ -155,7 +172,8 @@ public class PushNotificationScheduler implements Managed { accountsManager, Clock.systemUTC(), dedicatedProcessWorkerThreadCount, - workerMaxConcurrency); + workerMaxConcurrency, + retryExecutor); } @VisibleForTesting @@ -165,7 +183,8 @@ public class PushNotificationScheduler implements Managed { final AccountsManager accountsManager, final Clock clock, final int dedicatedProcessThreadCount, - final int workerMaxConcurrency) throws IOException { + final int workerMaxConcurrency, + final ScheduledExecutorService retryExecutor) throws IOException { this.apnSender = apnSender; this.fcmSender = fcmSender; @@ -177,6 +196,7 @@ public class PushNotificationScheduler implements Managed { "lua/apn/schedule_background_notification.lua", ScriptOutputType.VALUE); this.workerThreads = new Thread[dedicatedProcessThreadCount]; + this.retryExecutor = retryExecutor; for (int i = 0; i < this.workerThreads.length; i++) { this.workerThreads[i] = new Thread(new NotificationWorker(workerMaxConcurrency), "PushNotificationScheduler-" + i); @@ -206,6 +226,31 @@ public class PushNotificationScheduler implements Managed { .thenRun(Util.NOOP); } + /** + * Schedules a "new message" push notification to be delivered to the given device after at least the given duration. + * If another notification had previously been scheduled, calling this method will replace the previously-scheduled + * delivery time with the given time. + * + * @param account the account to which the target device belongs + * @param device the device to which to deliver a "new message" push notification + * @param minDelay the minimum delay after which to deliver the notification + * + * @return a future that completes once the notification has been scheduled + */ + public CompletableFuture scheduleDelayedNotification(final Account account, final Device device, final Duration minDelay) { + final long deliveryTime = clock.instant().plus(minDelay).toEpochMilli(); + + return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME) + .executeCompletionStage(retryExecutor, () -> pushSchedulingCluster.withCluster(connection -> + connection.async().zadd(getDelayedNotificationQueueKey(account, device), + deliveryTime, + encodeAciAndDeviceId(account, device))) + .thenRun(() -> Metrics.counter(DELAYED_NOTIFICATION_SCHEDULED_COUNTER_NAME, + TOKEN_TYPE_TAG, getTokenType(device)) + .increment())) + .toCompletableFuture(); + } + /** * Cancel scheduled notifications for the given account and device. * @@ -214,7 +259,8 @@ public class PushNotificationScheduler implements Managed { public CompletionStage cancelScheduledNotifications(Account account, Device device) { return CompletableFuture.allOf( cancelBackgroundNotifications(PushNotification.TokenType.FCM, account, device), - cancelBackgroundNotifications(PushNotification.TokenType.APN, account, device)); + cancelBackgroundNotifications(PushNotification.TokenType.APN, account, device), + cancelDelayedNotifications(account, device)); } @VisibleForTesting @@ -225,6 +271,15 @@ public class PushNotificationScheduler implements Managed { .toCompletableFuture(); } + @VisibleForTesting + CompletableFuture cancelDelayedNotifications(final Account account, final Device device) { + return pushSchedulingCluster.withCluster(connection -> + connection.async().zrem(getDelayedNotificationQueueKey(account, device), + encodeAciAndDeviceId(account, device))) + .thenRun(Util.NOOP) + .toCompletableFuture(); + } + @Override public synchronized void start() { running.set(true); @@ -267,6 +322,32 @@ public class PushNotificationScheduler implements Managed { .toCompletableFuture(); } + @VisibleForTesting + CompletableFuture sendDelayedNotification(final Account account, final Device device) { + if (StringUtils.isAllBlank(device.getApnId(), device.getGcmId())) { + return CompletableFuture.completedFuture(null); + } + + final boolean isApnsDevice = StringUtils.isNotBlank(device.getApnId()); + + final PushNotification pushNotification = new PushNotification( + isApnsDevice ? device.getApnId() : device.getGcmId(), + isApnsDevice ? PushNotification.TokenType.APN : PushNotification.TokenType.FCM, + PushNotification.NotificationType.NOTIFICATION, + null, + account, + device, + true, null); + + final PushNotificationSender pushNotificationSender = isApnsDevice ? apnSender : fcmSender; + + return pushNotificationSender.sendNotification(pushNotification) + .thenAccept(response -> Metrics.counter(DELAYED_NOTIFICATION_SENT_COUNTER_NAME, + TOKEN_TYPE_TAG, getTokenType(device), + ACCEPTED_TAG, String.valueOf(response.accepted())) + .increment()); + } + @VisibleForTesting static String encodeAciAndDeviceId(final Account account, final Device device) { // Note: This does not include a device registration id. If a device is unlinked and a new device is linked with @@ -319,6 +400,15 @@ public class PushNotificationScheduler implements Managed { return LAST_BACKGROUND_NOTIFICATION_TIMESTAMP_KEY_PREFIX + "::{" + encodeAciAndDeviceId(account, device) + "}"; } + @VisibleForTesting + static String getDelayedNotificationQueueKey(final Account account, final Device device) { + return getDelayedNotificationQueueKey(SlotHash.getSlot(encodeAciAndDeviceId(account, device))); + } + + private static String getDelayedNotificationQueueKey(final int slot) { + return PENDING_DELAYED_NOTIFICATIONS_KEY_PREFIX + "::{" + RedisClusterUtil.getMinimalHashTag(slot) + "}"; + } + @VisibleForTesting Optional getLastBackgroundApnsNotificationTimestamp(final Account account, final Device device) { return Optional.ofNullable( @@ -336,6 +426,25 @@ public class PushNotificationScheduler implements Managed { .map(timestamp -> Instant.ofEpochMilli(timestamp.longValue())); } + @VisibleForTesting + Optional getNextScheduledDelayedNotificationTimestamp(final Account account, final Device device) { + return Optional.ofNullable( + pushSchedulingCluster.withCluster(connection -> + connection.sync().zscore(getDelayedNotificationQueueKey(account, device), + encodeAciAndDeviceId(account, device)))) + .map(timestamp -> Instant.ofEpochMilli(timestamp.longValue())); + } + + private static String getTokenType(final Device device) { + if (StringUtils.isNotBlank(device.getApnId())) { + return "apns"; + } else if (StringUtils.isNotBlank(device.getGcmId())) { + return "fcm"; + } else { + return "unknown"; + } + } + private static String getPushToken(final PushNotification.TokenType tokenType, final Device device) { return switch (tokenType) { case FCM -> device.getGcmId(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java index 4ad46a32c..779d4abfc 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/AuthenticatedConnectListener.java @@ -70,11 +70,13 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener { messagesManager, messageMetrics, pushNotificationManager, + pushNotificationScheduler, account, device, client, messageDeliveryScheduler, - clientReleaseManager) + clientReleaseManager, + experimentEnrollmentManager) ); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java index cae22c75d..863df9e48 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnection.java @@ -13,6 +13,7 @@ import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.Timer; +import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -26,13 +27,14 @@ import org.eclipse.jetty.util.ConstantThrowable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; +import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; -import org.whispersystems.textsecuregcm.push.NotPushRegisteredException; import org.whispersystems.textsecuregcm.push.PushNotificationManager; +import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; import org.whispersystems.textsecuregcm.push.ReceiptSender; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; @@ -77,6 +79,8 @@ public class WebSocketConnection { @VisibleForTesting static final int MESSAGE_SENDER_MAX_CONCURRENCY = 256; + private static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1); + private static final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class); private static final Logger droppedErrorLogger = LoggerFactory.getLogger("droppedError"); @@ -84,6 +88,8 @@ public class WebSocketConnection { private final MessagesManager messagesManager; private final MessageMetrics messageMetrics; private final PushNotificationManager pushNotificationManager; + private final PushNotificationScheduler pushNotificationScheduler; + private final ExperimentEnrollmentManager experimentEnrollmentManager; private final Account authenticatedAccount; private final Device authenticatedDevice; @@ -103,21 +109,25 @@ public class WebSocketConnection { final MessagesManager messagesManager, final MessageMetrics messageMetrics, final PushNotificationManager pushNotificationManager, + final PushNotificationScheduler pushNotificationScheduler, final Account authenticatedAccount, final Device authenticatedDevice, final WebSocketClient client, final Scheduler messageDeliveryScheduler, - final ClientReleaseManager clientReleaseManager) { + final ClientReleaseManager clientReleaseManager, + final ExperimentEnrollmentManager experimentEnrollmentManager) { this.receiptSender = receiptSender; this.messagesManager = messagesManager; this.messageMetrics = messageMetrics; this.pushNotificationManager = pushNotificationManager; + this.pushNotificationScheduler = pushNotificationScheduler; this.authenticatedAccount = authenticatedAccount; this.authenticatedDevice = authenticatedDevice; this.client = client; this.messageDeliveryScheduler = messageDeliveryScheduler; this.clientReleaseManager = clientReleaseManager; + this.experimentEnrollmentManager = experimentEnrollmentManager; this.messageStream = messagesManager.getMessages(authenticatedAccount.getAccountIdentifier(), authenticatedDevice); @@ -184,10 +194,9 @@ public class WebSocketConnection { messagesManager.mayHaveMessages(authenticatedAccount.getAccountIdentifier(), authenticatedDevice) .thenAccept(mayHaveMessages -> { if (mayHaveMessages) { - try { - pushNotificationManager.sendNewMessageNotification(authenticatedAccount, authenticatedDevice.getId(), true); - } catch (NotPushRegisteredException _) { - } + pushNotificationScheduler.scheduleDelayedNotification(authenticatedAccount, + authenticatedDevice, + CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY); } }); } 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 216de7f3c..0dc263aa4 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -446,7 +446,7 @@ public record CommandDependencies( APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), configuration.getApnConfiguration()); FcmSender fcmSender = new FcmSender(fcmSenderExecutor, configuration.getFcmConfiguration().credentials().value()); PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster, - apnSender, fcmSender, accountsManager, 0, 0); + apnSender, fcmSender, accountsManager, 0, 0, retryExecutor); PushNotificationManager pushNotificationManager = new PushNotificationManager(accountsManager, apnSender, fcmSender, pushNotificationScheduler); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ScheduledApnPushNotificationSenderServiceCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ScheduledApnPushNotificationSenderServiceCommand.java index 759a593e1..356c0b609 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ScheduledApnPushNotificationSenderServiceCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ScheduledApnPushNotificationSenderServiceCommand.java @@ -90,7 +90,8 @@ public class ScheduledApnPushNotificationSenderServiceCommand extends ServerComm deps.fcmSender(), deps.accountsManager(), namespace.getInt(WORKER_COUNT), - namespace.getInt(MAX_CONCURRENCY) + namespace.getInt(MAX_CONCURRENCY), + retryExecutor ); environment.lifecycle().manage(pushNotificationScheduler); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java index 029b268b2..d6643911f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherIntegrationTest.java @@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; import org.whispersystems.textsecuregcm.push.PushNotificationManager; +import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; import org.whispersystems.textsecuregcm.push.ReceiptSender; import org.whispersystems.textsecuregcm.redis.RedisServerExtension; import org.whispersystems.textsecuregcm.storage.Account; @@ -159,6 +160,7 @@ class MessageDispatcherIntegrationTest { sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), disconnectionRequestManager, mock(ClientReleaseManager.class), Clock.systemUTC()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java index 82956c17f..cf0487773 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/MessageDispatcherTest.java @@ -42,7 +42,6 @@ import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope; import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier; import org.whispersystems.textsecuregcm.identity.ServiceIdentifier; import org.whispersystems.textsecuregcm.metrics.MessageMetrics; -import org.whispersystems.textsecuregcm.push.NotPushRegisteredException; import org.whispersystems.textsecuregcm.push.PushNotificationManager; import org.whispersystems.textsecuregcm.push.PushNotificationScheduler; import org.whispersystems.textsecuregcm.push.ReceiptSender; @@ -77,6 +76,7 @@ class MessageDispatcherTest { private PushNotificationManager pushNotificationManager; private MessageDispatcher dispatcher; private DisconnectionRequestManager disconnectionRequestManager; + private PushNotificationScheduler pushNotificationScheduler; @BeforeEach void setUp() { @@ -89,6 +89,7 @@ class MessageDispatcherTest { receiptSender = mock(ReceiptSender.class); pushNotificationManager = mock(PushNotificationManager.class); disconnectionRequestManager = mock(DisconnectionRequestManager.class); + pushNotificationScheduler = mock(PushNotificationScheduler.class); when(device.getId()).thenReturn(DEVICE_ID); when(device.isPrimary()).thenReturn(true); @@ -98,6 +99,7 @@ class MessageDispatcherTest { messagesManager, new MessageMetrics(), pushNotificationManager, + pushNotificationScheduler, disconnectionRequestManager, mock(ClientReleaseManager.class), CLOCK); @@ -105,7 +107,7 @@ class MessageDispatcherTest { @ParameterizedTest @ValueSource(booleans = {false, true}) - void drainSingleMessage(final boolean mayHaveMoreMessages) throws NotPushRegisteredException { + void drainSingleMessage(final boolean mayHaveMoreMessages) { final ServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID()); final long timestamp = 17; @@ -128,9 +130,8 @@ class MessageDispatcherTest { verify(disconnectionRequestManager).removeListener(eq(ACI), eq(DEVICE_ID), any()); verify(pushNotificationManager).handleMessagesRetrieved(account, device, TEST_UA); verify(messagesManager).mayHaveMessages(ACI, device); - verify(pushNotificationManager, times(mayHaveMoreMessages ? 1 : 0)) - .sendNewMessageNotification(account, device.getId(), true); - + verify(pushNotificationScheduler, times(mayHaveMoreMessages ? 1 : 0)) + .scheduleDelayedNotification(account, device, MessageDispatcher.CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY); verifyNoInteractions(receiptSender); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java index c126bc370..162fd640c 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/push/PushNotificationSchedulerTest.java @@ -16,14 +16,17 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.lettuce.core.cluster.SlotHash; +import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ScheduledExecutorService; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -86,7 +89,7 @@ class PushNotificationSchedulerTest { .thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(true, Optional.empty(), false, Optional.empty()))); pushNotificationScheduler = new PushNotificationScheduler(REDIS_CLUSTER_EXTENSION.getRedisCluster(), - apnSender, fcmSender, accountsManager, clock, 1, 1); + apnSender, fcmSender, accountsManager, clock, 1, 1, mock(ScheduledExecutorService.class)); } @ParameterizedTest @@ -204,6 +207,51 @@ class PushNotificationSchedulerTest { verify(apnSender, never()).sendNotification(any()); } + @Test + void testScheduleDelayedNotification() { + clock.pin(Instant.now()); + + assertEquals(Optional.empty(), + pushNotificationScheduler.getNextScheduledDelayedNotificationTimestamp(account, device)); + + pushNotificationScheduler.scheduleDelayedNotification(account, device, Duration.ofMinutes(1)).join(); + + assertEquals(Optional.of(clock.instant().truncatedTo(ChronoUnit.MILLIS).plus(Duration.ofMinutes(1))), + pushNotificationScheduler.getNextScheduledDelayedNotificationTimestamp(account, device)); + + pushNotificationScheduler.scheduleDelayedNotification(account, device, Duration.ofMinutes(2)).join(); + + assertEquals(Optional.of(clock.instant().truncatedTo(ChronoUnit.MILLIS).plus(Duration.ofMinutes(2))), + pushNotificationScheduler.getNextScheduledDelayedNotificationTimestamp(account, device)); + } + + @Test + void testCancelDelayedNotification() { + pushNotificationScheduler.scheduleDelayedNotification(account, device, Duration.ofMinutes(1)).join(); + pushNotificationScheduler.cancelDelayedNotifications(account, device).join(); + + assertEquals(Optional.empty(), + pushNotificationScheduler.getNextScheduledDelayedNotificationTimestamp(account, device)); + } + + @Test + void testProcessScheduledDelayedNotifications() { + final PushNotificationScheduler.NotificationWorker worker = pushNotificationScheduler.new NotificationWorker(1); + final int slot = SlotHash.getSlot(PushNotificationScheduler.getDelayedNotificationQueueKey(account, device)); + + clock.pin(Instant.now()); + + pushNotificationScheduler.scheduleDelayedNotification(account, device, Duration.ofMinutes(1)).join(); + + assertEquals(0, worker.processScheduledDelayedNotifications(slot)); + + clock.pin(clock.instant().plus(Duration.ofMinutes(1))); + + assertEquals(1, worker.processScheduledDelayedNotifications(slot)); + assertEquals(Optional.empty(), + pushNotificationScheduler.getNextScheduledDelayedNotificationTimestamp(account, device)); + } + @ParameterizedTest @CsvSource({ "1, true", @@ -218,7 +266,7 @@ class PushNotificationSchedulerTest { final AccountsManager accountsManager = mock(AccountsManager.class); pushNotificationScheduler = new PushNotificationScheduler(redisCluster, apnSender, fcmSender, - accountsManager, dedicatedThreadCount, 1); + accountsManager, dedicatedThreadCount, 1, mock(ScheduledExecutorService.class)); pushNotificationScheduler.start(); pushNotificationScheduler.stop(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java index 4c91b1e83..e5f928a2e 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionIntegrationTest.java @@ -200,11 +200,13 @@ class WebSocketConnectionIntegrationTest { new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), account, device, webSocketClient, messageDeliveryScheduler, - clientReleaseManager + clientReleaseManager, + mock(ExperimentEnrollmentManager.class) ); final List expectedMessages = new ArrayList<>(dynamoDbMessageCount + foundationDbMessageCount); @@ -283,11 +285,13 @@ class WebSocketConnectionIntegrationTest { new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), account, device, webSocketClient, messageDeliveryScheduler, - clientReleaseManager + clientReleaseManager, + mock(ExperimentEnrollmentManager.class) ); final int dynamoDbMessageCount = 77; @@ -402,11 +406,13 @@ class WebSocketConnectionIntegrationTest { new MessagesManager(messagesDynamoDb, foundationDbMessageStore, reportMessageManager, sharedExecutorService, Clock.systemUTC()), new MessageMetrics(), mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), account, device, webSocketClient, messageDeliveryScheduler, - clientReleaseManager + clientReleaseManager, + mock(ExperimentEnrollmentManager.class) ); final int dynamoDBMessageCount = 207; @@ -487,11 +493,13 @@ class WebSocketConnectionIntegrationTest { messagesManager, new MessageMetrics(), mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), account, device, webSocketClient, messageDeliveryScheduler, - clientReleaseManager); + clientReleaseManager, + mock(ExperimentEnrollmentManager.class)); final WebSocketResponseMessage successResponse = mock(WebSocketResponseMessage.class); when(successResponse.getStatus()).thenReturn(200); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java index c826a2f09..844df9176 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/websocket/WebSocketConnectionTest.java @@ -119,11 +119,13 @@ class WebSocketConnectionTest { messagesManager, new MessageMetrics(), mock(PushNotificationManager.class), + mock(PushNotificationScheduler.class), account, device, client, Schedulers.immediate(), - clientReleaseManager); + clientReleaseManager, + mock(ExperimentEnrollmentManager.class)); } @Test