add NotificationLimiter to avoid sending too many notifications per hour
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
This commit is contained in:
@@ -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();
|
||||
|
||||
|
||||
@@ -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<NotificationType, Integer> maxNotificationsPerHourPerType = new HashMap<>(Map.of(
|
||||
NotificationType.TREND, 1,
|
||||
NotificationType.ADHOC_ALTERNATIVE, 1,
|
||||
NotificationType.REGULAR_TRIP_ALTERNATIVE, 1,
|
||||
NotificationType.FRIENDSHIP_REQUEST_RECEIVED, 3
|
||||
));
|
||||
}
|
||||
|
||||
@@ -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++;
|
||||
|
||||
@@ -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<Notification, Long
|
||||
""")
|
||||
List<Notification> findPendingNotificationsToSend(LocalTime currentTime);
|
||||
|
||||
@Query("""
|
||||
SELECT n
|
||||
FROM Notification n
|
||||
WHERE n.user.id = :userId
|
||||
AND n.status = 'SENT'
|
||||
AND n.createdAt >= :since
|
||||
""")
|
||||
List<Notification> getSentToUserSince(Long userId, Instant since);
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
DELETE
|
||||
FROM Notification n
|
||||
WHERE n.createdAt < :cutOff
|
||||
""")
|
||||
void deleteNotificationsOlder(LocalDateTime cutOff);
|
||||
void deleteNotificationsOlder(Instant cutOff);
|
||||
}
|
||||
|
||||
@@ -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<Notification> enforceHourlyLimits(List<Notification> notifications) {
|
||||
List<Notification> safeToSend = new java.util.ArrayList<>();
|
||||
|
||||
// Avoid multiple queries if user has multiple notifications in the list
|
||||
HashMap<Long, List<Notification>> 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<Notification> sentNotifications, NotificationType type) {
|
||||
return (int) sentNotifications.stream()
|
||||
.filter(n -> n.getType() == type)
|
||||
.count();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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<Notification> 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)));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user