From 931718bdae0590dc9033ac1918e1a50c93d6fec7 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" <> Date: Fri, 7 Feb 2025 02:19:35 -0700 Subject: [PATCH] WIP: Watcher --- .../service/LibraryProcessingService.java | 46 +++++++------- .../booklore/service/LibraryService.java | 16 +++++ .../service/monitoring/MonitoringService.java | 60 +++++++++++++------ .../service/monitoring/MonitoringTask.java | 31 ++++++---- 4 files changed, 104 insertions(+), 49 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java index 4e325526e..36d508760 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java @@ -17,15 +17,13 @@ import jakarta.persistence.EntityManager; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.nio.file.*; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -54,29 +52,37 @@ public class LibraryProcessingService { } @Transactional - public void processFile(long libraryId, String libraryPath, String filePath) { - LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); - notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath)); + public void processFile(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { + LibraryEntity libraryEntity = libraryRepository.findById(libraryId) + .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); + Path path = Paths.get(filePath); String fileName = path.getFileName().toString(); - LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath); + if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) { + notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath)); - libraryPathEntity = entityManager.merge(libraryPathEntity); + LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath); + libraryPathEntity = entityManager.merge(libraryPathEntity); - String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path); - BookFileType bookFileType = getBookFileType(fileName); + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileSubPath(FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path)) + .fileName(fileName) + .bookFileType(getBookFileType(fileName)) + .build(); - LibraryFile libraryFile = LibraryFile.builder() - .libraryEntity(libraryEntity) - .libraryPathEntity(libraryPathEntity) - .fileSubPath(fileSubPath) - .fileName(fileName) - .bookFileType(bookFileType) - .build(); + processLibraryFiles(List.of(libraryFile)); + notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); - processLibraryFiles(List.of(libraryFile)); - notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); + } else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) { + bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId) + .ifPresent(bookEntity -> { + deleteRemovedBooks(List.of(bookEntity)); + notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId())); + }); + } } @Transactional diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryService.java index a42cc89bd..a4a2a8b36 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryService.java @@ -16,6 +16,7 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.LibraryPathRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils; +import com.adityachandel.booklore.service.monitoring.MonitoringService; import jakarta.transaction.Transactional; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -23,6 +24,8 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.stereotype.Service; import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Set; @@ -108,8 +111,15 @@ public class LibraryService { ) .icon(request.getIcon()) .build(); + libraryEntity = libraryRepository.save(libraryEntity); Long libraryId = libraryEntity.getId(); + + /*for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { + Path path = Paths.get(pathEntity.getPath()); + monitoringService.registerPathWithLibraryId(path, libraryId); + }*/ + Thread.startVirtualThread(() -> { try { libraryProcessingService.processLibrary(libraryId); @@ -120,6 +130,7 @@ public class LibraryService { } log.info("Parsing task completed!"); }); + return libraryMapper.toLibrary(libraryEntity); } @@ -149,9 +160,14 @@ public class LibraryService { public void deleteLibrary(long id) { LibraryEntity library = libraryRepository.findById(id).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id)); + /*library.getLibraryPaths().forEach(libraryPath -> { + Path path = Paths.get(libraryPath.getPath()); + monitoringService.unregisterPath(path.toString()); + });*/ Set bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet()); fileProcessingUtils.deleteBookCovers(bookIds); libraryRepository.deleteById(id); + log.info("Library deleted successfully: {}", id); } public Book getBook(long libraryId, long bookId) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java index 3fd25fd1b..c8e684022 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java @@ -5,9 +5,9 @@ import com.adityachandel.booklore.service.LibraryProcessingService; import com.adityachandel.booklore.service.LibraryService; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -import jakarta.transaction.Transactional; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Lazy; import org.springframework.context.event.EventListener; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.stereotype.Service; @@ -16,7 +16,7 @@ import java.io.IOException; import java.nio.file.*; import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.*; @Slf4j @Service @@ -27,14 +27,19 @@ public class MonitoringService { private final WatchService watchService; private final LibraryService libraryService; private final MonitoringTask monitoringTask; + private final Set monitoredPaths = ConcurrentHashMap.newKeySet(); private final Map pathToLibraryIdMap = new ConcurrentHashMap<>(); + private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); + private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); + @PostConstruct public void initializeMonitoring() { log.info("Initializing monitoring service..."); loadInitialPaths(); monitoringTask.monitor(); + startProcessingThread(); } private void loadInitialPaths() { @@ -45,23 +50,22 @@ public class MonitoringService { library.getPaths().forEach(libraryPath -> { Path path = Paths.get(libraryPath.getPath()); if (Files.isDirectory(path)) { - pathToLibraryIdMap.put(path, library.getId()); // Map path to libraryId - registerPathWithLibraryId(path); + registerPathWithLibraryId(path, library.getId()); } }); }); - log.info("Loaded initial monitored folders: {}", pathToLibraryIdMap); } - public synchronized void registerPathWithLibraryId(Path path) { + public synchronized void registerPathWithLibraryId(Path path, Long libraryId) { try { if (monitoredPaths.add(path)) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); - log.info("Registered folder for monitoring: {}", path); + pathToLibraryIdMap.put(path, libraryId); + log.info("Registered folder for monitoring: {} (Library ID: {})", path, libraryId); } else { log.warn("Path is already registered: {}", path); } @@ -73,7 +77,7 @@ public class MonitoringService { public synchronized void unregisterPath(String folderPath) { Path path = Paths.get(folderPath); if (monitoredPaths.remove(path)) { - pathToLibraryIdMap.remove(path); // Remove the path-to-libraryId mapping + pathToLibraryIdMap.remove(path); log.info("Unregistered folder from monitoring: {}", folderPath); } else { log.warn("Folder not found in monitored paths: {}", folderPath); @@ -82,19 +86,40 @@ public class MonitoringService { @EventListener public void handleFileChangeEvent(FileChangeEvent event) { + if (!eventQueue.offer(event)) { + log.warn("Event queue is full, dropping event: {}", event.getFilePath()); + } else { + log.info("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size()); + } + } + + private void startProcessingThread() { + singleThreadExecutor.submit(() -> { + while (!Thread.currentThread().isInterrupted()) { + try { + FileChangeEvent event = eventQueue.take(); + processFileChangeEvent(event); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + }); + } + + private void processFileChangeEvent(FileChangeEvent event) { Path filePath = event.getFilePath(); Path watchedFolder = event.getWatchedFolder(); Long libraryId = pathToLibraryIdMap.get(watchedFolder); + if (libraryId != null) { - Thread.startVirtualThread(() -> { - try { - libraryProcessingService.processFile(libraryId, watchedFolder.toString(), filePath.toString()); - } catch (InvalidDataAccessApiUsageException e) { - log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId); - } - log.info("Parsing task completed!"); - }); - log.info("Handling file change event for library {}: {} (from folder: {}) with kind: {}", libraryId, filePath, watchedFolder, event.getEventKind()); + try { + libraryProcessingService.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString()); + } catch (InvalidDataAccessApiUsageException e) { + log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId); + } + log.info("Processed file change event for library {}: {} (from folder: {}) with kind: {}", + libraryId, filePath, watchedFolder, event.getEventKind()); } else { log.warn("No libraryId found for watched folder: {}", watchedFolder); } @@ -103,6 +128,7 @@ public class MonitoringService { @PreDestroy public void stopMonitoring() { log.info("Shutting down monitoring service..."); + singleThreadExecutor.shutdownNow(); if (watchService != null) { try { watchService.close(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java index e0fdb258c..f954c3047 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java @@ -6,10 +6,7 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; -import java.nio.file.Path; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; +import java.nio.file.*; @Slf4j @Service @@ -26,23 +23,33 @@ public class MonitoringTask { public void monitor() { log.info("START_MONITORING"); try { - WatchKey key; - while ((key = watchService.take()) != null) { + while (!Thread.currentThread().isInterrupted()) { + WatchKey key; + try { + key = watchService.take(); + } catch (ClosedWatchServiceException e) { + log.warn("WatchService has been closed. Stopping monitoring."); + break; + } + if (key == null) { + continue; + } for (WatchEvent event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); Path fileName = (Path) event.context(); Path directory = (Path) key.watchable(); Path fullPath = directory.resolve(fileName); + if (isPdfOrEpub(fileName)) { - log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", - kind, - fileName, - fullPath, - directory); + log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory); eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory)); } } - key.reset(); + boolean valid = key.reset(); + if (!valid) { + log.warn("WatchKey is no longer valid. Stopping monitoring for {}", key.watchable()); + break; + } } } catch (InterruptedException e) { log.warn("Monitoring task interrupted", e);