diff --git a/src/main/java/SuMoC/backend/config/AsyncConfiguration.java b/src/main/java/SuMoC/backend/config/AsyncConfiguration.java new file mode 100644 index 0000000..068de11 --- /dev/null +++ b/src/main/java/SuMoC/backend/config/AsyncConfiguration.java @@ -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; + } +} + diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index 4017208..bf1a0c8 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -38,7 +38,7 @@ public class DevUserSeeder implements CommandLineRunner { public void run(String... args) throws Exception { seedPgMembers(); seedDefaultTestUsers(); - //seedNtestUsers(1000); + //seedNtestUsers(10); } /** diff --git a/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java b/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java index 5aed4f2..4259b34 100644 --- a/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java +++ b/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java @@ -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; } diff --git a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java index c9f6f78..6625f2b 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -17,17 +17,25 @@ 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.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; @@ -44,6 +52,9 @@ public class RegularTripSuggestionService { private final CarrouselCandidateRepository carrouselCandidateRepository; + @Qualifier("regularTripSuggestionExecutor") + private final Executor executor; + public void detectAndNotifyRegularTripsForTodaysDayOfWeek() { // detect DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek(); @@ -54,35 +65,68 @@ public class RegularTripSuggestionService { } public void checkAlternativesAndNotify(HashMap> detectedRegularTripsByUser) { - // We first gather all candidates to persist and then save them in batch at the end for better performance - List candidatesToPersist = new ArrayList<>(); - List alternativesToNotify = new ArrayList<>(); + logger.info("Processing {} users for regular trip alternatives in parallel", detectedRegularTripsByUser.size()); + + // Use thread-safe collections for parallel processing + ConcurrentLinkedQueue candidatesToPersist = new ConcurrentLinkedQueue<>(); + ConcurrentLinkedQueue alternativesToNotify = new ConcurrentLinkedQueue<>(); + + // Create a CompletableFuture for each user to process in parallel + List> 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 - candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative))); - - LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes()); - alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend)); + CompletableFuture 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 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(alternativesToNotify, NotificationType.REGULAR_TRIP_ALTERNATIVE); + 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 detectedRegularTrips, + ConcurrentLinkedQueue candidatesToPersist, + ConcurrentLinkedQueue 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()); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index aa3002b..0870e95 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -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}