Author SHA1 Message Date
neuhauss 856f530f99 extend notification docs
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-09 10:32:32 +01:00
neuhauss 80abd0f34f test fix: correct notification building for ios
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-09 10:27:07 +01:00
15 changed files with 80 additions and 248 deletions
@@ -21,7 +21,6 @@ import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Service
@@ -50,9 +49,7 @@ public class CarrouselService {
}
}
public List<CarrouselCandidate> getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
List<CarrouselCandidate> candidates = new ArrayList<>();
public void addRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
for (var alternative : suggestedAlternatives) {
CarrouselCandidate candidate = CarrouselCandidate.builder()
.userId(userId)
@@ -61,10 +58,9 @@ public class CarrouselService {
.suggestedAt(Instant.now())
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
.build();
candidates.add(candidate);
}
return candidates;
carrouselCandidateRepository.save(candidate);
}
}
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
@@ -1,39 +0,0 @@
package SuMoC.backend.config;
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@RequiredArgsConstructor
public class AsyncConfiguration {
private final RegularTripSuggestionProperties regularTripSuggestionProperties;
/**
* Custom thread pool executor for parallel processing of regular trip suggestions.
* Configured with parallelism setting from application properties.
*/
@Bean(name = "regularTripSuggestionExecutor")
public Executor regularTripSuggestionExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
int parallelism = regularTripSuggestionProperties.getParallelism();
executor.setCorePoolSize(parallelism);
executor.setMaxPoolSize(parallelism);
executor.setQueueCapacity(500); // Queue capacity for pending tasks
executor.setThreadNamePrefix("regular-trip-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}
@@ -116,7 +116,10 @@ public class DevController {
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(
@PathVariable("fcm_token") @NotNull String fcmToken,
@RequestParam(required = false, defaultValue = "false") boolean isIos
) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
@@ -127,7 +130,12 @@ public class DevController {
List<RouteDTO> mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
notification.setData(objectMapper.writeValueAsString(mockRoutes));
Message mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
Message mockAdhocMessage;
if (isIos) {
mockAdhocMessage = firebaseMessageBuilder.generateMessageIos(notification, fcmToken);
} else {
mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
}
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
@@ -292,3 +300,4 @@ public class DevController {
}
}
@@ -14,4 +14,17 @@ public class FirebaseMessageBuilder {
return builder.build();
}
public Message generateMessageIos(Notification notification, String token) {
var builder = Message.builder().setToken(token);
builder.putData("type", notification.getType().toString());
builder.putData("data", notification.getData());
var apnConfig = com.google.firebase.messaging.ApnsConfig.builder()
.setAps(com.google.firebase.messaging.Aps.builder()
.setContentAvailable(true)
.build())
.build();
builder.setApnsConfig(apnConfig);
return builder.build();
}
}
@@ -37,6 +37,19 @@ Each notification type includes a data payload. The main DTOs in the notificatio
To receive push notifications, clients must register their device token. Token registration is handled in the
`NotificationController`. The backend stores or updates the token for the authenticated user.
### Notification Providers
When registering a device token, clients must specify the notification provider. The supported providers are defined in
`NotificationProvider.java`:
- **FIREBASE**: Use this provider for Android devices. Tokens registered with this type will be used to send
notifications via Firebase Cloud Messaging (FCM) for Android.
- **FIREBASE_IOS**: Use this provider for iOS devices. Tokens registered with this type will be used to send
notifications via Firebase Cloud Messaging (FCM) for iOS.
Specify the appropriate provider when registering the device token to ensure notifications are delivered correctly to
the device platform.
---
## For Backend Developers
@@ -2,4 +2,5 @@ package SuMoC.backend.notification.enums;
public enum NotificationProvider {
FIREBASE,
FIREBASE_IOS
}
@@ -1,9 +0,0 @@
package SuMoC.backend.notification.interfaces;
import java.time.LocalTime;
public interface NotifieableWithTime {
Long getUserId();
LocalTime getEarliestTimeOfDayToSend();
}
@@ -3,7 +3,6 @@ package SuMoC.backend.notification.services;
import SuMoC.backend.notification.enums.NotificationStatus;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.interfaces.Notifieable;
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
import SuMoC.backend.notification.models.Notification;
import SuMoC.backend.notification.repositories.NotificationRepository;
import SuMoC.backend.user.models.User;
@@ -66,33 +65,6 @@ public class NotificationSchedulerService {
notificationRepository.saveAll(notifications);
}
public void scheduleAll(List<NotifieableWithTime> dataBodies,
NotificationType notificationType
) {
List<Notification> notifications = dataBodies.stream().map(dataBody -> {
String dataBodyJson;
try {
dataBodyJson = objectMapper.writeValueAsString(dataBody);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize notification data body", e);
}
User userProxy = entityManager.getReference(User.class, dataBody.getUserId());
return Notification.builder()
.user(userProxy)
.type(notificationType)
.data(dataBodyJson)
.earliestTimeOfDayToSend(dataBody.getEarliestTimeOfDayToSend())
.status(NotificationStatus.PENDING)
.createdAt(Instant.now())
.failedSendAttempts(0)
.build();
}).toList();
notificationRepository.saveAll(notifications);
}
/**
* Schedules a notification to be sent to the specified user.
* Data body needs to be serializable to JSON.
@@ -52,9 +52,20 @@ public class NotificationSender {
switch (token.getProvider()) {
case FIREBASE -> sendViaFirebase(token, notification);
case FIREBASE_IOS -> sendViaFirebaseIos(token, notification);
}
}
private void sendViaFirebaseIos(NotificationToken token, Notification notification) {
if (firebaseMessaging == null) {
logger.warning("FirebaseMessaging not configured");
return;
}
Message message = firebaseMessageBuilder.generateMessageIos(notification, token.getToken());
sendAndHandleResultFirebase(message, notification);
}
private void sendViaFirebase(NotificationToken token, Notification notification) {
if (firebaseMessaging == null) {
logger.warning("FirebaseMessaging not configured");
@@ -62,7 +73,10 @@ public class NotificationSender {
}
Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken());
sendAndHandleResultFirebase(message, notification);
}
private void sendAndHandleResultFirebase(Message message, Notification notification) {
ApiFuture<String> future = firebaseMessaging.sendAsync(message);
ApiFutures.addCallback(future, new ApiFutureCallback<String>() {
@Override
@@ -84,6 +98,5 @@ public class NotificationSender {
logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage());
}
}, MoreExecutors.directExecutor());
}
}
@@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties {
public AdHocRoutingProperties() {
super();
setAcceptableAdditionalMultiplierRegular(2.0);
setAcceptableAdditionalMultiplierPrefersPhysical(2.0);
setAcceptableAdditionalMultiplierRegular(1.30);
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
}
@@ -36,36 +36,6 @@ public class DevUserSeeder implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
seedPgMembers();
seedDefaultTestUsers();
//seedNtestUsers(10);
}
/**
* Useful for stress testing with a larger number of users. Seeds the specified number of users dummy users.
*
* @param numberOfUsers
*/
private void seedNtestUsers(int numberOfUsers) {
for (int i = 1; i <= numberOfUsers; i++) {
UserRegistrationDTO userDto = UserRegistrationDTO.builder()
.email("testuser" + i + "@email.com")
.publicName("Test User " + i)
.privateName("Test User " + i)
.password("password" + i)
.build();
authenticationService.registerUser(userDto);
User user = userRepository.findByEmail("testuser" + i + "@email.com").orElseThrow();
notificationTokenService.registerDeviceToken(
user,
NotificationProvider.FIREBASE,
devProperties.getFcmKey()
);
}
}
private void seedDefaultTestUsers() {
UserRegistrationDTO user1dto = UserRegistrationDTO.builder()
.email("user1@email.com")
.publicName("Nutzer 1 Public")
@@ -92,9 +62,6 @@ public class DevUserSeeder implements CommandLineRunner {
NotificationProvider.FIREBASE,
devProperties.getFcmKey()
);
}
private void seedPgMembers() {
UserRegistrationDTO user3dto = UserRegistrationDTO.builder()
.email("david@test.com")
.publicName("David N. Public")
@@ -14,11 +14,4 @@ public class RegularTripSuggestionProperties {
* We keep it relatively short since regular trips have a time window.
*/
private Integer notifyBeforeMinutes = 15;
/**
* Number of parallel threads to use for processing users concurrently when checking
* for regular trip alternatives. Higher values increase throughput but consume more
* resources (database connections, API rate limits, memory).
*/
private Integer parallelism = 10;
}
@@ -1,44 +0,0 @@
package SuMoC.backend.suggestion.dtos;
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
import SuMoC.backend.routing.dtos.RouteDTO;
import lombok.Getter;
import java.time.LocalTime;
/**
* This DTO extends RouteDTO and implements Notifieable to be used as the data body for notifications about route suggestions.
* This allows us to use the saveAll method in NotificationSchedulerService for better performance when scheduling multiple notifications at once.
*/
public class RouteDTOtoBeNotified extends RouteDTO implements NotifieableWithTime {
private Long userId;
@Getter
private LocalTime earliestTimeOfDayToSend;
public RouteDTOtoBeNotified(RouteDTO routeDTO, Long userId, LocalTime earliestTimeOfDayToSend) {
super(
routeDTO.getStartAddress(),
routeDTO.getFirstStopName(),
routeDTO.getStartLat(),
routeDTO.getStartLon(),
routeDTO.getEndAddress(),
routeDTO.getLastStopName(),
routeDTO.getEndLat(),
routeDTO.getEndLon(),
routeDTO.getStartDateTime(),
routeDTO.getEndDateTime(),
routeDTO.getSteps(),
routeDTO.getCo2Savings(),
routeDTO.getTimeDifferenceSeconds(),
routeDTO.getCo2Emissions()
);
this.userId = userId;
this.earliestTimeOfDayToSend = earliestTimeOfDayToSend;
}
@Override
public Long getUserId() {
return this.userId;
}
}
@@ -1,11 +1,8 @@
package SuMoC.backend.suggestion.services;
import SuMoC.backend.carrousel.models.CarrouselCandidate;
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
import SuMoC.backend.carrousel.service.CarrouselService;
import SuMoC.backend.h3.H3Service;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
@@ -14,28 +11,21 @@ import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
import SuMoC.backend.routing.services.AlternativeRoutingService;
import SuMoC.backend.routing.services.RoutingPreferencesService;
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
import SuMoC.backend.suggestion.dtos.RouteDTOtoBeNotified;
import com.uber.h3core.util.LatLng;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.time.*;
import java.util.ArrayList;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
@Service
@RequiredArgsConstructor
public class RegularTripSuggestionService {
private static final Logger logger = LoggerFactory.getLogger(RegularTripSuggestionService.class);
private final AlternativeRoutingService alternativeRoutingService;
private final RoutingPreferencesService routingPreferencesService;
@@ -50,11 +40,6 @@ public class RegularTripSuggestionService {
private final CarrouselService carrouselService;
private final CarrouselCandidateRepository carrouselCandidateRepository;
@Qualifier("regularTripSuggestionExecutor")
private final Executor executor;
public void detectAndNotifyRegularTripsForTodaysDayOfWeek() {
// detect
DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
@@ -65,68 +50,32 @@ public class RegularTripSuggestionService {
}
public void checkAlternativesAndNotify(HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser) {
logger.info("Processing {} users for regular trip alternatives in parallel", detectedRegularTripsByUser.size());
// Use thread-safe collections for parallel processing
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist = new ConcurrentLinkedQueue<>();
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify = new ConcurrentLinkedQueue<>();
// Create a CompletableFuture for each user to process in parallel
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Long userId : detectedRegularTripsByUser.keySet()) {
var detectedRegularTrips = detectedRegularTripsByUser.get(userId);
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
processUserTrips(userId, detectedRegularTrips, candidatesToPersist, alternativesToNotify);
} catch (Exception e) {
logger.error("Error processing regular trips for user {}: {}", userId, e.getMessage(), e);
// For each detected regular trip, determine alternatives and notify the user if applicable
for (var detectedRegularTrip : detectedRegularTrips) {
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
// if present, schedule notification
if (bestAlternative != null) {
// save the alternative in the carrousel candidates so that it can be shown in the carrousel as well
carrouselService.addRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative));
notificationSchedulerService.schedule(
userId,
bestAlternative,
NotificationType.REGULAR_TRIP_ALTERNATIVE,
detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes())
);
}
}, executor);
futures.add(future);
}
// Wait for all user processing tasks to complete
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allFutures.join();
logger.info("Parallel processing completed. Persisting {} carrousel candidates and scheduling {} notifications",
candidatesToPersist.size(), alternativesToNotify.size());
// Batch save all results
carrouselCandidateRepository.saveAll(candidatesToPersist);
notificationSchedulerService.scheduleAll(new ArrayList<>(alternativesToNotify), NotificationType.REGULAR_TRIP_ALTERNATIVE);
}
/**
* Process all detected regular trips for a single user.
* This method is designed to be called in parallel for multiple users.
*/
private void processUserTrips(Long userId, List<DetectedRegularTripDTO> detectedRegularTrips,
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist,
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify) {
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
// For each detected regular trip, determine alternatives and notify the user if applicable
for (var detectedRegularTrip : detectedRegularTrips) {
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
// if present, schedule notification
if (bestAlternative != null) {
// save the alternative in the carrousel candidates so that it can be shown in the carrousel as well
candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative)));
LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes());
alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend));
}
}
}
private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) {
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
+1 -3
View File
@@ -16,9 +16,6 @@ sumoc.scheduling.run-notification-worker=*/15 * * * * *
sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1
sumoc.scheduling.clean-up-old-notifications=0 0 3 * * *
sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * *
# Regular trip suggestion settings
sumoc.regulartripsuggestion.parallelism=5
sumoc.regulartripsuggestion.notify-before-minutes=15
# Trend detection settings
sumoc.trenddetection.positive-threshold=-25.0
sumoc.trenddetection.negative-threshold=-25.0
@@ -39,6 +36,7 @@ geocoding.carta.base-url=https://mobydex.locoslab.com/carta
meteo.base-url=https://api.open-meteo.com/v1
# Dev debug settings
sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk
# 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}