Revert "Retire delayed push notifications"

This reverts commit 8e37334d2a.
This commit is contained in:
Jon Chambers authored and Jon Chambers committed 2026-10-29 16:38:31 -04:00
1 parent ca7a105f15
commit ecd881a280
12 files changed
+219 -36

No files matched your search

@@ -833,7 +833,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.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);
RateLimiters rateLimiters = RateLimiters.create(dynamicConfigurationManager, rateLimitersCluster, retryExecutor);
@@ -1112,7 +1112,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
final MessageMetrics messageMetrics = new MessageMetrics();
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
pushNotificationManager, disconnectionRequestManager, clientReleaseManager, Clock.systemUTC());
pushNotificationManager, pushNotificationScheduler, disconnectionRequestManager, clientReleaseManager, Clock.systemUTC());
final CertificateGenerator certificateGenerator =
new CertificateGenerator(config.getDeliveryCertificate().certificate(),
@@ -22,8 +22,8 @@ import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
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;
@@ -64,6 +64,7 @@ public class MessageDispatcher {
private final MessagesManager messagesManager;
private final MessageMetrics messageMetrics;
private final PushNotificationManager pushNotificationManager;
private final PushNotificationScheduler pushNotificationScheduler;
private final ClientReleaseManager clientReleaseManager;
private final DisconnectionRequestManager disconnectionRequestManager;
private final Clock clock;
@@ -72,6 +73,7 @@ public class MessageDispatcher {
final MessagesManager messagesManager,
final MessageMetrics messageMetrics,
final PushNotificationManager pushNotificationManager,
final PushNotificationScheduler pushNotificationScheduler,
final DisconnectionRequestManager disconnectionRequestManager,
final ClientReleaseManager clientReleaseManager,
final Clock clock) {
@@ -79,6 +81,7 @@ public class MessageDispatcher {
this.messagesManager = messagesManager;
this.messageMetrics = messageMetrics;
this.pushNotificationManager = pushNotificationManager;
this.pushNotificationScheduler = pushNotificationScheduler;
this.disconnectionRequestManager = disconnectionRequestManager;
this.clientReleaseManager = clientReleaseManager;
this.clock = clock;
@@ -197,18 +200,16 @@ public class MessageDispatcher {
_ -> 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);
}
});
}
@@ -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<Account, Device, CompletableFuture<Void>> 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<Void> 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<Void> 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<Void> 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<Void> 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<Instant> 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<Instant> 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();
@@ -70,11 +70,13 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
messagesManager,
messageMetrics,
pushNotificationManager,
pushNotificationScheduler,
account,
device,
client,
messageDeliveryScheduler,
clientReleaseManager)
clientReleaseManager,
experimentEnrollmentManager)
);
}
@@ -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);
}
});
}
@@ -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);
@@ -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);
@@ -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());
@@ -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);
}
@@ -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();
@@ -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<MessageProtos.Envelope> 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);
@@ -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