Remove cyclic dependency between LibraryService and MonitoringService

This commit is contained in:
aditya.chandel
2025-02-08 06:02:07 -07:00
parent 540ef21525
commit 25e2147aa0
5 changed files with 83 additions and 63 deletions
@@ -13,6 +13,4 @@ import java.util.List;
public interface LibraryPathMapper { public interface LibraryPathMapper {
LibraryPath toLibraryPath(LibraryPathEntity libraryPathEntity); LibraryPath toLibraryPath(LibraryPathEntity libraryPathEntity);
List<LibraryPath> toLibraryPathList(List<LibraryPathEntity> libraryPathEntities);
} }
@@ -28,7 +28,7 @@ public class LibraryEntity {
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true)
private List<BookEntity> bookEntities; private List<BookEntity> bookEntities;
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<LibraryPathEntity> libraryPaths; private List<LibraryPathEntity> libraryPaths;
private boolean watch; private boolean watch;
@@ -17,6 +17,7 @@ import com.adityachandel.booklore.repository.LibraryPathRepository;
import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils; import com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils;
import com.adityachandel.booklore.service.monitoring.MonitoringService; import com.adityachandel.booklore.service.monitoring.MonitoringService;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -45,59 +46,90 @@ public class LibraryService {
private final LibraryMapper libraryMapper; private final LibraryMapper libraryMapper;
private final NotificationService notificationService; private final NotificationService notificationService;
private final FileProcessingUtils fileProcessingUtils; private final FileProcessingUtils fileProcessingUtils;
private final MonitoringService monitoringService;
@Transactional
@PostConstruct
public void initializeMonitoring() {
List<Library> libraries = libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList());
monitoringService.registerLibrariesForMonitoring(libraries);
log.info("Monitoring initialized with {} libraries", libraries.size());
}
public Library updateLibrary(CreateLibraryRequest request, Long libraryId) { public Library updateLibrary(CreateLibraryRequest request, Long libraryId) {
LibraryEntity library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); LibraryEntity library = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
library.setName(request.getName()); library.setName(request.getName());
library.setIcon(request.getIcon()); library.setIcon(request.getIcon());
library.setWatch(request.isWatch()); library.setWatch(request.isWatch());
Set<String> currentPaths = library.getLibraryPaths().stream().map(LibraryPathEntity::getPath).collect(Collectors.toSet()); Set<String> currentPaths = library.getLibraryPaths().stream()
Set<String> updatedPaths = request.getPaths().stream().map(LibraryPath::getPath).collect(Collectors.toSet()); .map(LibraryPathEntity::getPath)
.collect(Collectors.toSet());
Set<String> updatedPaths = request.getPaths().stream()
.map(LibraryPath::getPath)
.collect(Collectors.toSet());
Set<String> deletedPaths = currentPaths.stream().filter(path -> !updatedPaths.contains(path)).collect(Collectors.toSet()); Set<String> deletedPaths = currentPaths.stream()
Set<String> newPaths = updatedPaths.stream().filter(path -> !currentPaths.contains(path)).collect(Collectors.toSet()); .filter(path -> !updatedPaths.contains(path))
.collect(Collectors.toSet());
Set<String> newPaths = updatedPaths.stream()
.filter(path -> !currentPaths.contains(path))
.collect(Collectors.toSet());
if (newPaths.isEmpty() && deletedPaths.isEmpty()) { if (!deletedPaths.isEmpty()) {
return libraryMapper.toLibrary(libraryRepository.save(library)); Set<LibraryPathEntity> pathsToRemove = library.getLibraryPaths().stream()
} else { .filter(pathEntity -> deletedPaths.contains(pathEntity.getPath()))
if (!deletedPaths.isEmpty()) { .collect(Collectors.toSet());
Set<LibraryPathEntity> pathsToRemove = library.getLibraryPaths().stream()
.filter(pathEntity -> deletedPaths.contains(pathEntity.getPath()))
.collect(Collectors.toSet());
library.getLibraryPaths().removeAll(pathsToRemove);
List<Long> books = bookRepository.findAllBookIdsByLibraryPathIdIn(pathsToRemove.stream().map(LibraryPathEntity::getId).collect(Collectors.toSet())); library.getLibraryPaths().removeAll(pathsToRemove);
if (!books.isEmpty()) { List<Long> books = bookRepository.findAllBookIdsByLibraryPathIdIn(
notificationService.sendMessage(Topic.BOOKS_REMOVE, books); pathsToRemove.stream().map(LibraryPathEntity::getId).collect(Collectors.toSet()));
}
libraryPathRepository.deleteAll(pathsToRemove); if (!books.isEmpty()) {
libraryPathRepository.saveAll(library.getLibraryPaths()); notificationService.sendMessage(Topic.BOOKS_REMOVE, books);
libraryRepository.save(library);
} }
if (!newPaths.isEmpty()) { libraryPathRepository.deleteAll(pathsToRemove);
Set<LibraryPathEntity> newPathEntities = newPaths.stream()
.map(path -> LibraryPathEntity.builder().path(path).library(library).build())
.collect(Collectors.toSet());
library.getLibraryPaths().addAll(newPathEntities);
libraryPathRepository.saveAll(library.getLibraryPaths());
libraryRepository.save(library);
Thread.startVirtualThread(() -> {
try {
libraryProcessingService.processLibrary(libraryId);
} catch (InvalidDataAccessApiUsageException e) {
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
} catch (IOException e) {
log.error("Error while parsing library books", e);
}
log.info("Parsing task completed!");
});
}
return libraryMapper.toLibrary(libraryRepository.save(library));
} }
if (!newPaths.isEmpty()) {
Set<LibraryPathEntity> newPathEntities = newPaths.stream()
.map(path -> LibraryPathEntity.builder().path(path).library(library).build())
.collect(Collectors.toSet());
library.getLibraryPaths().addAll(newPathEntities);
libraryPathRepository.saveAll(library.getLibraryPaths());
}
LibraryEntity savedLibrary = libraryRepository.save(library);
if (request.isWatch()) {
for (LibraryPathEntity pathEntity : savedLibrary.getLibraryPaths()) {
Path path = Paths.get(pathEntity.getPath());
monitoringService.registerPathWithLibraryId(path, libraryId);
}
} else {
for (LibraryPathEntity pathEntity : savedLibrary.getLibraryPaths()) {
monitoringService.unregisterPath(pathEntity.getPath());
}
}
if (!newPaths.isEmpty()) {
Thread.startVirtualThread(() -> {
try {
libraryProcessingService.processLibrary(libraryId);
} catch (InvalidDataAccessApiUsageException e) {
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
} catch (IOException e) {
log.error("Error while parsing library books", e);
}
log.info("Parsing task completed!");
});
}
return libraryMapper.toLibrary(savedLibrary);
} }
public Library createLibrary(CreateLibraryRequest request) { public Library createLibrary(CreateLibraryRequest request) {
@@ -117,10 +149,12 @@ public class LibraryService {
libraryEntity = libraryRepository.save(libraryEntity); libraryEntity = libraryRepository.save(libraryEntity);
Long libraryId = libraryEntity.getId(); Long libraryId = libraryEntity.getId();
/*for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { if (request.isWatch()) {
Path path = Paths.get(pathEntity.getPath()); for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
monitoringService.registerPathWithLibraryId(path, libraryId); Path path = Paths.get(pathEntity.getPath());
}*/ monitoringService.registerPathWithLibraryId(path, libraryId);
}
}
Thread.startVirtualThread(() -> { Thread.startVirtualThread(() -> {
try { try {
@@ -183,10 +217,4 @@ public class LibraryService {
List<BookEntity> bookEntities = bookRepository.findBooksByLibraryId(libraryId); List<BookEntity> bookEntities = bookRepository.findBooksByLibraryId(libraryId);
return bookEntities.stream().map(bookMapper::toBook).toList(); return bookEntities.stream().map(bookMapper::toBook).toList();
} }
@Transactional
public List<Library> getAllLibraries() {
return libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList());
}
} }
@@ -2,18 +2,17 @@ package com.adityachandel.booklore.service.monitoring;
import com.adityachandel.booklore.model.dto.Library; import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.service.LibraryProcessingService; import com.adityachandel.booklore.service.LibraryProcessingService;
import com.adityachandel.booklore.service.LibraryService;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.*; import java.util.concurrent.*;
@@ -25,7 +24,6 @@ public class MonitoringService {
private final LibraryProcessingService libraryProcessingService; private final LibraryProcessingService libraryProcessingService;
private final WatchService watchService; private final WatchService watchService;
private final LibraryService libraryService;
private final MonitoringTask monitoringTask; private final MonitoringTask monitoringTask;
private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet(); private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
@@ -36,15 +34,12 @@ public class MonitoringService {
@PostConstruct @PostConstruct
public void initializeMonitoring() { public void initializeMonitoring() {
log.info("Initializing monitoring service...");
loadInitialPaths();
monitoringTask.monitor(); monitoringTask.monitor();
startProcessingThread(); startProcessingThread();
} }
private void loadInitialPaths() { public void registerLibrariesForMonitoring(List<Library> libraries) {
libraryService.getAllLibraries() libraries.stream()
.stream()
.filter(Library::isWatch) .filter(Library::isWatch)
.forEach(library -> { .forEach(library -> {
library.getPaths().forEach(libraryPath -> { library.getPaths().forEach(libraryPath -> {
@@ -54,7 +49,7 @@ public class MonitoringService {
} }
}); });
}); });
log.info("Loaded initial monitored folders: {}", pathToLibraryIdMap); log.info("Registered libraries for monitoring: {}", libraries.size());
} }
public synchronized void registerPathWithLibraryId(Path path, Long libraryId) { public synchronized void registerPathWithLibraryId(Path path, Long libraryId) {
@@ -21,7 +21,6 @@ public class MonitoringTask {
@Async @Async
public void monitor() { public void monitor() {
log.info("START_MONITORING");
try { try {
while (!Thread.currentThread().isInterrupted()) { while (!Thread.currentThread().isInterrupted()) {
WatchKey key; WatchKey key;