Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b95355c10f | ||
|
|
f7d7f6bc53 | ||
|
|
a401b9a6c1 |
@@ -21,6 +21,7 @@ import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@@ -49,7 +50,9 @@ public class CarrouselService {
|
||||
}
|
||||
}
|
||||
|
||||
public void addRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
|
||||
public List<CarrouselCandidate> getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
|
||||
List<CarrouselCandidate> candidates = new ArrayList<>();
|
||||
|
||||
for (var alternative : suggestedAlternatives) {
|
||||
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
||||
.userId(userId)
|
||||
@@ -58,9 +61,10 @@ public class CarrouselService {
|
||||
.suggestedAt(Instant.now())
|
||||
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
|
||||
.build();
|
||||
|
||||
carrouselCandidateRepository.save(candidate);
|
||||
candidates.add(candidate);
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
public interface NotifieableWithTime {
|
||||
Long getUserId();
|
||||
|
||||
LocalTime getEarliestTimeOfDayToSend();
|
||||
}
|
||||
@@ -3,6 +3,7 @@ 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;
|
||||
@@ -65,6 +66,33 @@ 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.
|
||||
|
||||
@@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties {
|
||||
|
||||
public AdHocRoutingProperties() {
|
||||
super();
|
||||
setAcceptableAdditionalMultiplierRegular(1.30);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
|
||||
setAcceptableAdditionalMultiplierRegular(2.0);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(2.0);
|
||||
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
|
||||
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,36 @@ 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")
|
||||
@@ -62,6 +92,9 @@ 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,4 +14,11 @@ 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
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,8 +1,11 @@
|
||||
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;
|
||||
@@ -11,21 +14,28 @@ 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.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.*;
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
@@ -40,6 +50,11 @@ 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();
|
||||
@@ -50,32 +65,68 @@ 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);
|
||||
|
||||
// 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())
|
||||
);
|
||||
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);
|
||||
}
|
||||
}, 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());
|
||||
|
||||
@@ -16,6 +16,9 @@ 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
|
||||
@@ -36,7 +39,6 @@ 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}
|
||||
|
||||
Reference in New Issue
Block a user