implemented scheduled worker that processes queued notifications
This commit is contained in:
@@ -3,14 +3,19 @@ package SuMoC.backend.dev;
|
||||
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
||||
import SuMoC.backend.meteo.ForecastService;
|
||||
import SuMoC.backend.meteo.MeteoClient;
|
||||
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 SuMoC.backend.scheduling.ScheduledTasks;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
import com.google.firebase.messaging.Message;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
@@ -18,6 +23,8 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/dev")
|
||||
@@ -31,6 +38,8 @@ public class DevController {
|
||||
private final ForecastService forecastService;
|
||||
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final NotificationRepository notificationRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public DevController(
|
||||
ScheduledTasks scheduledTasks,
|
||||
@@ -39,7 +48,8 @@ public class DevController {
|
||||
MeteoClient meteoClient,
|
||||
ForecastService forecastService,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
ObjectMapper objectMapper
|
||||
ObjectMapper objectMapper,
|
||||
NotificationRepository notificationRepository, UserRepository userRepository
|
||||
) {
|
||||
this.scheduledTasks = scheduledTasks;
|
||||
this.statTableUpdateService = statTableUpdateService;
|
||||
@@ -48,6 +58,8 @@ public class DevController {
|
||||
this.forecastService = forecastService;
|
||||
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
||||
this.objectMapper = objectMapper;
|
||||
this.notificationRepository = notificationRepository;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@PostMapping("/trigger-trend-calculation")
|
||||
@@ -61,6 +73,7 @@ public class DevController {
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase/{fcm_token}")
|
||||
@Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.")
|
||||
public ResponseEntity<String> testFirebaseConnection(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
@@ -83,6 +96,33 @@ public class DevController {
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(description = "Immediately queues a notification to the fcm key specified in application-dev.properties to be processed by the notification queue.")
|
||||
@GetMapping("/queue-test-notification")
|
||||
public ResponseEntity<String> queueTestNotification() {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
.type(NotificationType.TREND)
|
||||
.data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()))
|
||||
.user(user)
|
||||
.earliestTimeOfDayToSend(LocalTime.now())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.status(NotificationStatus.PENDING)
|
||||
.build();
|
||||
|
||||
notificationRepository.save(notification);
|
||||
|
||||
return ResponseEntity.ok("✓ Test notification queued.");
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-meteo")
|
||||
public void testMeteoClient() {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.dev;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sumoc.dev")
|
||||
public class DevProperties {
|
||||
/**
|
||||
* Will be used to init the seeded users with in the dev profile.
|
||||
*/
|
||||
private String fcmKey = "";
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.notification.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sumoc.notification")
|
||||
public class NotificationProperties {
|
||||
/**
|
||||
* Maximum number of failed send attempts before giving up on a notification.
|
||||
*/
|
||||
private int maxFailedSendAttempts = 3;
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
package SuMoC.backend.notification.enums;
|
||||
|
||||
public enum NotificationStatus {
|
||||
/**
|
||||
* Has never been sent successfully. Will be retried.
|
||||
*/
|
||||
PENDING,
|
||||
/**
|
||||
* Has been sent successfully.
|
||||
*/
|
||||
SENT,
|
||||
/**
|
||||
* Has failed to send and will not be retried.
|
||||
*/
|
||||
FAILED
|
||||
}
|
||||
|
||||
@@ -42,11 +42,19 @@ public class Notification {
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationStatus status;
|
||||
private NotificationStatus status = NotificationStatus.PENDING;
|
||||
|
||||
/**
|
||||
* Number of retry attempts made to send this notification.
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private int retryCount;
|
||||
private int failedSendAttempts = 0;
|
||||
|
||||
@Column(nullable = false)
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public void incrementFailedSendAttempts() {
|
||||
this.failedSendAttempts++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,15 +11,13 @@ import lombok.Setter;
|
||||
public class NotificationToken {
|
||||
|
||||
@Id
|
||||
@Column(nullable = false, unique = true)
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationProvider provider;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 512)
|
||||
@Column(nullable = false, length = 512)
|
||||
private String token;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,19 @@ package SuMoC.backend.notification.repositories;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
public interface NotificationRepository extends JpaRepository<Notification, Long> {
|
||||
@Query("""
|
||||
SELECT n
|
||||
FROM Notification n
|
||||
LEFT JOIN FETCH n.user u
|
||||
LEFT JOIN FETCH u.notificationToken
|
||||
WHERE n.status = 'PENDING'
|
||||
AND n.earliestTimeOfDayToSend <= :currentTime
|
||||
""")
|
||||
List<Notification> findPendingNotificationsToSend(LocalTime currentTime);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
||||
import SuMoC.backend.notification.config.NotificationProperties;
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
import com.google.firebase.messaging.Message;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Service
|
||||
@@ -20,24 +21,29 @@ public class NotificationSender {
|
||||
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
||||
private final Logger logger = Logger.getLogger(NotificationSender.class.getName());
|
||||
private final FirebaseMessaging firebaseMessaging;
|
||||
private final NotificationRepository notificationRepository;
|
||||
private final NotificationProperties notificationProperties;
|
||||
|
||||
public NotificationSender(
|
||||
NotificationTokenRepository notificationTokenRepository,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
@Autowired(required = false) FirebaseMessaging firebaseMessaging
|
||||
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
|
||||
NotificationRepository notificationRepository, NotificationProperties notificationProperties
|
||||
) {
|
||||
this.notificationTokenRepository = notificationTokenRepository;
|
||||
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
||||
this.firebaseMessaging = firebaseMessaging;
|
||||
this.notificationRepository = notificationRepository;
|
||||
this.notificationProperties = notificationProperties;
|
||||
}
|
||||
|
||||
public void sendNotification(User user, Notification notification) {
|
||||
// get users notification token
|
||||
NotificationToken token;
|
||||
try {
|
||||
token = notificationTokenRepository.findByUserId(user.getId()).orElseThrow();
|
||||
} catch (NoSuchElementException e) {
|
||||
logger.warning("No notification token found for user id, skipping send: " + user.getId());
|
||||
public void sendNotification(Notification notification) {
|
||||
NotificationToken token = notification.getUser().getNotificationToken();
|
||||
|
||||
if (token == null) {
|
||||
logger.warning("No notification token found notification id: " + notification.getId());
|
||||
notification.incrementFailedSendAttempts();
|
||||
notificationRepository.save(notification);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -55,6 +61,19 @@ public class NotificationSender {
|
||||
Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken());
|
||||
|
||||
firebaseMessaging.sendAsync(message)
|
||||
.addListener(() -> logger.info("Notification sent to user"), Runnable::run);
|
||||
.addListener(() -> {
|
||||
try {
|
||||
notification.setStatus(NotificationStatus.SENT);
|
||||
notificationRepository.save(notification);
|
||||
logger.info("Notification sent successfully to user: " + notification.getUser().getId());
|
||||
} catch (Exception e) {
|
||||
notification.incrementFailedSendAttempts();
|
||||
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
||||
notification.setStatus(NotificationStatus.FAILED);
|
||||
}
|
||||
notificationRepository.save(notification);
|
||||
logger.severe("Failed to send notification: " + e.getMessage());
|
||||
}
|
||||
}, Runnable::run);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationWorker {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final NotificationSender notificationSender;
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
notificationSender.sendNotification(notification);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.scheduling;
|
||||
|
||||
import SuMoC.backend.notification.services.NotificationWorker;
|
||||
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.slf4j.Logger;
|
||||
@@ -19,6 +20,8 @@ public class ScheduledTasks {
|
||||
|
||||
private final StatTableUpdateService statTableUpdateService;
|
||||
|
||||
private final NotificationWorker notificationWorker;
|
||||
|
||||
@Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}")
|
||||
public void scheduleCalculateWeeklyMobilityStats() {
|
||||
logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers");
|
||||
@@ -29,4 +32,14 @@ public class ScheduledTasks {
|
||||
logger.error("Error calculating weekly mobility stats.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(cron = "#{@schedulingProperties.runNotificationWorker}")
|
||||
public void scheduleRunNotificationWorker() {
|
||||
logger.info("Scheduled task triggered: runNotificationWorker");
|
||||
try {
|
||||
notificationWorker.run();
|
||||
} catch (Exception e) {
|
||||
logger.error("Error running notification worker.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,5 @@ import org.springframework.stereotype.Component;
|
||||
public class SchedulingProperties {
|
||||
private int poolSize = 5;
|
||||
private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week
|
||||
private String runNotificationWorker = "0 * * * * *"; // Every minute
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package SuMoC.backend.seed.user;
|
||||
|
||||
import SuMoC.backend.dev.DevProperties;
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import SuMoC.backend.notification.services.NotificationTokenService;
|
||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||
import SuMoC.backend.security.services.AuthenticationService;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
@@ -15,26 +20,47 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
private final NotificationTokenService notificationTokenService;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final DevProperties devProperties;
|
||||
|
||||
@Autowired
|
||||
public DevUserSeeder(AuthenticationService authenticationService) {
|
||||
public DevUserSeeder(AuthenticationService authenticationService, NotificationTokenService notificationTokenService, UserRepository userRepository, DevProperties devProperties) {
|
||||
this.authenticationService = authenticationService;
|
||||
this.notificationTokenService = notificationTokenService;
|
||||
this.userRepository = userRepository;
|
||||
this.devProperties = devProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
UserRegistrationDTO user1 = UserRegistrationDTO.builder()
|
||||
UserRegistrationDTO user1dto = UserRegistrationDTO.builder()
|
||||
.email("user1@email.com")
|
||||
.publicName("Nutzer 1 Public")
|
||||
.privateName("Nutzer 1 Privat")
|
||||
.password("password1")
|
||||
.build();
|
||||
authenticationService.registerUser(user1);
|
||||
UserRegistrationDTO user2 = UserRegistrationDTO.builder()
|
||||
authenticationService.registerUser(user1dto);
|
||||
User user1 = userRepository.findByEmail("user1@email.com").orElseThrow();
|
||||
notificationTokenService.registerDeviceToken(
|
||||
user1,
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
UserRegistrationDTO user2dto = UserRegistrationDTO.builder()
|
||||
.email("user2@email.com")
|
||||
.publicName("Nutzer 2 Public")
|
||||
.privateName("Nutzer 2 Privat")
|
||||
.password("password2")
|
||||
.build();
|
||||
authenticationService.registerUser(user2);
|
||||
authenticationService.registerUser(user2dto);
|
||||
User user2 = userRepository.findByEmail("user2@email.com").orElseThrow();
|
||||
notificationTokenService.registerDeviceToken(
|
||||
user2,
|
||||
NotificationProvider.FIREBASE,
|
||||
devProperties.getFcmKey()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
package SuMoC.backend.user.models;
|
||||
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.enums.RoleName;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Getter
|
||||
@Setter
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@@ -52,6 +57,10 @@ public class User {
|
||||
@Column(name = "role")
|
||||
private Set<RoleName> roles;
|
||||
|
||||
@OneToOne
|
||||
@JoinColumn(name = "id", referencedColumnName = "user_id")
|
||||
private NotificationToken notificationToken;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
@@ -78,84 +87,4 @@ public class User {
|
||||
this.roles = new HashSet<>();
|
||||
this.roles.add(RoleName.USER);
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getPublicName() {
|
||||
return publicName;
|
||||
}
|
||||
|
||||
public void setPublicName(String publicName) {
|
||||
this.publicName = publicName;
|
||||
}
|
||||
|
||||
public String getPrivateName() {
|
||||
return privateName;
|
||||
}
|
||||
|
||||
public void setPrivateName(String privateName) {
|
||||
this.privateName = privateName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public VisibilityPrivacy getVisibilityPrivacy() {
|
||||
return visibilityPrivacy;
|
||||
}
|
||||
|
||||
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
this.visibilityPrivacy = visibilityPrivacy;
|
||||
}
|
||||
|
||||
public String getFriendCode() {
|
||||
return friendCode;
|
||||
}
|
||||
|
||||
public void setFriendCode(String friendCode) {
|
||||
this.friendCode = friendCode;
|
||||
}
|
||||
|
||||
public Set<Trip> getTrips() {
|
||||
return trips;
|
||||
}
|
||||
|
||||
public void setTrips(Set<Trip> trips) {
|
||||
this.trips = trips;
|
||||
}
|
||||
|
||||
public Set<Friendship> getFriendships() {
|
||||
return friendships;
|
||||
}
|
||||
|
||||
public void setFriendships(Set<Friendship> friendships) {
|
||||
this.friendships = friendships;
|
||||
}
|
||||
|
||||
public Set<RoleName> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(Set<RoleName> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user