From fb41f800619b3d064549b2ce812abb7bd72065d2 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 5 Feb 2026 11:56:24 +0100 Subject: [PATCH] add NotificationLimiter to avoid sending too many notifications per hour --- .../java/SuMoC/backend/dev/DevController.java | 6 +- .../config/NotificationProperties.java | 14 ++++ .../notification/models/Notification.java | 8 ++- .../repositories/NotificationRepository.java | 13 +++- .../services/NotificationLimiter.java | 65 +++++++++++++++++++ .../NotificationSchedulerService.java | 6 +- .../services/NotificationSender.java | 2 + .../services/NotificationWorker.java | 14 ++-- src/main/resources/application.properties | 6 +- 9 files changed, 117 insertions(+), 17 deletions(-) create mode 100644 src/main/java/SuMoC/backend/notification/services/NotificationLimiter.java diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index 16a3cdf..e087bfb 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -31,9 +31,9 @@ import org.springframework.context.annotation.Profile; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; +import java.time.Duration; import java.time.Instant; import java.time.LocalDate; -import java.time.LocalDateTime; import java.time.LocalTime; import java.util.HashMap; import java.util.List; @@ -239,7 +239,7 @@ public class DevController { .data(objectMapper.writeValueAsString(mockDTO)) .user(user) .earliestTimeOfDayToSend(LocalTime.now()) - .createdAt(LocalDateTime.now()) + .createdAt(Instant.now()) .status(NotificationStatus.PENDING) .build(); @@ -261,7 +261,7 @@ public class DevController { .data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO())) .user(user) .earliestTimeOfDayToSend(LocalTime.now()) - .createdAt(LocalDateTime.now().minusDays(60)) + .createdAt(Instant.now().minus(Duration.ofDays(60))) .status(NotificationStatus.SENT) .build(); diff --git a/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java b/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java index c30fa86..6b2b2ff 100644 --- a/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java +++ b/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java @@ -1,9 +1,13 @@ package SuMoC.backend.notification.config; +import SuMoC.backend.notification.enums.NotificationType; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; +import java.util.HashMap; +import java.util.Map; + @Data @Component @ConfigurationProperties(prefix = "sumoc.notification") @@ -12,4 +16,14 @@ public class NotificationProperties { * Maximum number of failed send attempts before giving up on a notification. */ private int maxFailedSendAttempts = 3; + + /** + * Maximum number of notifications to send to a user per hour per notification type. + */ + private Map maxNotificationsPerHourPerType = new HashMap<>(Map.of( + NotificationType.TREND, 1, + NotificationType.ADHOC_ALTERNATIVE, 1, + NotificationType.REGULAR_TRIP_ALTERNATIVE, 1, + NotificationType.FRIENDSHIP_REQUEST_RECEIVED, 3 + )); } diff --git a/src/main/java/SuMoC/backend/notification/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java index 52c1719..3989c98 100644 --- a/src/main/java/SuMoC/backend/notification/models/Notification.java +++ b/src/main/java/SuMoC/backend/notification/models/Notification.java @@ -6,7 +6,7 @@ import SuMoC.backend.user.models.User; import jakarta.persistence.*; import lombok.*; -import java.time.LocalDateTime; +import java.time.Instant; import java.time.LocalTime; @Entity @@ -54,8 +54,10 @@ public class Notification { private String lastFailureReason; @Column(nullable = false) - - private LocalDateTime createdAt; + private Instant createdAt; + + @Column(nullable = true) + private Instant sentAt = null; public void incrementFailedSendAttempts() { this.failedSendAttempts++; diff --git a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java index 1376d14..d26819d 100644 --- a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java +++ b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java @@ -5,7 +5,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; -import java.time.LocalDateTime; +import java.time.Instant; import java.time.LocalTime; import java.util.List; @@ -20,11 +20,20 @@ public interface NotificationRepository extends JpaRepository findPendingNotificationsToSend(LocalTime currentTime); + @Query(""" + SELECT n + FROM Notification n + WHERE n.user.id = :userId + AND n.status = 'SENT' + AND n.createdAt >= :since + """) + List getSentToUserSince(Long userId, Instant since); + @Modifying @Query(""" DELETE FROM Notification n WHERE n.createdAt < :cutOff """) - void deleteNotificationsOlder(LocalDateTime cutOff); + void deleteNotificationsOlder(Instant cutOff); } diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationLimiter.java b/src/main/java/SuMoC/backend/notification/services/NotificationLimiter.java new file mode 100644 index 0000000..0777c7f --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationLimiter.java @@ -0,0 +1,65 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.notification.config.NotificationProperties; +import SuMoC.backend.notification.enums.NotificationStatus; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.repositories.NotificationRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; + +@Service +@RequiredArgsConstructor +class NotificationLimiter { + + private final NotificationRepository notificationRepository; + + private final NotificationProperties notificationProperties; + + /** + * Filters the given list of notifications to ensure that no user exceeds the hourly limit. + * Notifications exceeding the limit are excluded and set to FAILED status. + * + * @param notifications + * @return + */ + public List enforceHourlyLimits(List notifications) { + List safeToSend = new java.util.ArrayList<>(); + + // Avoid multiple queries if user has multiple notifications in the list + HashMap> notificationsByUser = new HashMap<>(); + + for (var notification : notifications) { + var userId = notification.getUser().getId(); + + notificationsByUser + .computeIfAbsent(userId, + k -> notificationRepository.getSentToUserSince(k, Instant.now().minus(Duration.ofHours(1L)))); + + var numberSent = getNumberSentPerType(notificationsByUser.get(userId), notification.getType()); + + if (numberSent < notificationProperties.getMaxNotificationsPerHourPerType().getOrDefault(notification.getType(), Integer.MAX_VALUE)) { + safeToSend.add(notification); + notificationsByUser.get(userId).add(notification); // Consider this one as sent for further checks + } else { + // Exceeded limit, mark as FAILED + notification.setStatus(NotificationStatus.FAILED); + notification.setLastFailureReason("Hourly limit exceeded for notification type"); + notificationRepository.save(notification); + } + } + + return safeToSend; + } + + private Integer getNumberSentPerType(List sentNotifications, NotificationType type) { + return (int) sentNotifications.stream() + .filter(n -> n.getType() == type) + .count(); + } +} diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java index e6593aa..7642a94 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java @@ -11,7 +11,7 @@ import jakarta.persistence.EntityManager; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; +import java.time.Instant; import java.time.LocalTime; import java.util.List; @@ -57,7 +57,7 @@ public class NotificationSchedulerService { .data(dataBodyJson) .earliestTimeOfDayToSend(earliestTimeOfDayToSend) .status(NotificationStatus.PENDING) - .createdAt(LocalDateTime.now()) + .createdAt(Instant.now()) .failedSendAttempts(0) .build(); }).toList(); @@ -99,7 +99,7 @@ public class NotificationSchedulerService { .data(dataBodyJson) .earliestTimeOfDayToSend(earliestTimeOfDayToSend) .status(NotificationStatus.PENDING) - .createdAt(LocalDateTime.now()) + .createdAt(Instant.now()) .failedSendAttempts(0) .build(); diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java index ae0ced7..e4d2b58 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -16,6 +16,7 @@ import com.google.firebase.messaging.Message; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.time.Instant; import java.util.logging.Logger; @Service @@ -67,6 +68,7 @@ public class NotificationSender { @Override public void onSuccess(String messageId) { notification.setStatus(NotificationStatus.SENT); + notification.setSentAt(Instant.now()); notificationRepository.save(notification); logger.info("Notification sent successfully to user: " + notification.getUser().getId()); } diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java index 0a0a81d..9af9ce7 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java @@ -6,7 +6,8 @@ import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; +import java.time.Duration; +import java.time.Instant; import java.time.LocalTime; import java.util.List; @@ -19,15 +20,18 @@ public class NotificationWorker { private final NotificationSender notificationSender; + private final NotificationLimiter notificationLimiter; + /** * Process all pending notifications. */ public void run() { - // Get all pending notifications where earliest send time has passed and status is pending List pendingNotifications = notificationRepository.findPendingNotificationsToSend(LocalTime.now()); - // Send them - for (Notification notification : pendingNotifications) { + + var notificationSafeToSend = notificationLimiter.enforceHourlyLimits(pendingNotifications); + + for (Notification notification : notificationSafeToSend) { notificationSender.sendNotification(notification); } } @@ -37,6 +41,6 @@ public class NotificationWorker { */ public void cleanUpOldNotifications() { // Delete notifications older than 30 days - notificationRepository.deleteNotificationsOlder(LocalDateTime.now().minusDays(30)); + notificationRepository.deleteNotificationsOlder(Instant.now().minus(Duration.ofDays(30))); } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index f6d222d..aa3002b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -22,6 +22,11 @@ sumoc.trenddetection.negative-threshold=-25.0 # FireBase firebase.config.enabled=true firebase.config.service-account=file:./secrets/fcm-key.json +# Notification limits per hour TODO for development we set them extremly high +sumoc.notification.max-notifications-per-hour-per-type.adhoc-alternative=10000 +sumoc.notification.max-notifications-per-hour-per-type.friendship-request-received=10000 +sumoc.notification.max-notifications-per-hour-per-type.trend=10000 +sumoc.notification.max-notifications-per-hour-per-type.regular-trip-alternative=10000 # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 # Geocoding configuration @@ -35,5 +40,4 @@ sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG # RSA key paths (file paths, not directories) security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem} security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem} - logging.file.name=logs/app.log