Files
sumoc-backend/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java
T
neuhauss b95355c10f
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
parallelize regular trip detection for massively improved performance
2026-02-09 14:30:32 +01:00

150 lines
6.9 KiB
Java

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;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
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.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;
private final RegularTripSuggestionProperties properties;
private final NotificationSchedulerService notificationSchedulerService;
private final RegularTripDetectionService regularTripDetectionService;
private final H3Service h3Service;
private final CarrouselService carrouselService;
private final CarrouselCandidateRepository carrouselCandidateRepository;
@Qualifier("regularTripSuggestionExecutor")
private final Executor executor;
public void detectAndNotifyRegularTripsForTodaysDayOfWeek() {
// detect
DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
var detectedRegularTripsByUser = regularTripDetectionService.detectRegularCarTripsByUserForDayOfWeek(dayOfWeek);
// notify
checkAlternativesAndNotify(detectedRegularTripsByUser);
}
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);
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());
// we plan the trip to arrive at the average arrival time of the regular trip
Instant arrivalTime = LocalDateTime.now()
.with(trip.getAverageArrivalTime())
.atZone(ZoneId.systemDefault())
.toInstant();
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
return RoutingAlternativeRequestDTO.builder()
.originLat(origin.lat)
.originLon(origin.lng)
.destinationLat(destination.lat)
.destinationLon(destination.lng)
.arrivalTime(arrivalTime)
.departureTime(departureTime)
.build();
}
}