From 25ee5103797f077a5badf5385ee1ead8644f5e48 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" <> Date: Fri, 23 May 2025 22:32:02 -0600 Subject: [PATCH] Refine handling of file create/delete events in library watcher --- .../booklore/model/entity/BookEntity.java | 9 ++ .../service/LibraryProcessingService.java | 145 ++++++++++++------ .../service/monitoring/MonitoringService.java | 5 +- .../service/monitoring/MonitoringTask.java | 2 +- .../booklore/util/FileUtils.java | 5 +- 5 files changed, 117 insertions(+), 49 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java index 6d3b13fb8..8870dcd9c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java @@ -6,6 +6,8 @@ import com.adityachandel.booklore.model.enums.BookFileType; import jakarta.persistence.*; import lombok.*; +import java.nio.file.Path; +import java.nio.file.Paths; import java.time.Instant; import java.util.List; @@ -60,4 +62,11 @@ public class BookEntity { @Column(name = "similar_books_json", columnDefinition = "TEXT") private List similarBooksJson; + public Path getFullFilePath() { + if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) { + throw new IllegalStateException("Cannot construct file path: missing library path, file subpath, or file name"); + } + + return Paths.get(libraryPath.getPath(), fileSubPath, fileName); + } } 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 660e668e0..3fea7d668 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 @@ -18,12 +18,15 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; import java.io.IOException; import java.nio.file.*; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.concurrent.*; import java.util.stream.Collectors; import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification; @@ -39,6 +42,11 @@ public class LibraryProcessingService { private final EpubProcessor epubProcessor; private final BookRepository bookRepository; private final EntityManager entityManager; + private final TransactionTemplate transactionTemplate; + + private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + private final Map> deletionTasks = new ConcurrentHashMap<>(); + private static final int DELETE_DEBOUNCE_SECONDS = 3; @Transactional public void processLibrary(long libraryId) throws IOException { @@ -51,18 +59,34 @@ public class LibraryProcessingService { @Transactional public void processFile(WatchEvent.Kind eventKind, long libraryId, String libraryPath, String filePath) { - LibraryEntity libraryEntity = libraryRepository.findById(libraryId) - .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); - + LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); Path path = Paths.get(filePath); String fileName = path.getFileName().toString(); - if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) { + ScheduledFuture scheduledDeletion = deletionTasks.remove(filePath); + if (scheduledDeletion != null) { + scheduledDeletion.cancel(false); + log.debug("Cancelled scheduled deletion for file: {}", filePath); + } + notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath)); LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath); libraryPathEntity = entityManager.merge(libraryPathEntity); + LibraryPathEntity finalLibraryPathEntity = libraryPathEntity; + bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId) + .ifPresent(existingBook -> { + Path newFullPath = path; + Path oldFullPath = existingBook.getFullFilePath(); + if (!newFullPath.equals(oldFullPath)) { + existingBook.setLibraryPath(finalLibraryPathEntity); + existingBook.setFileSubPath(FileUtils.getRelativeSubPath(finalLibraryPathEntity.getPath(), newFullPath)); + bookRepository.save(existingBook); + log.debug("Updated path for moved book: {}", fileName); + } + }); + LibraryFile libraryFile = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(libraryPathEntity) @@ -75,11 +99,33 @@ public class LibraryProcessingService { 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())); - }); + ScheduledFuture scheduledDeletion = deletionTasks.putIfAbsent(filePath, scheduler.schedule(() -> { + try { + boolean fileStillExists = libraryEntity.getLibraryPaths().stream() + .anyMatch(lp -> { + Path fullPath = Path.of(lp.getPath()).resolve(fileName); + return Files.exists(fullPath); + }); + if (!fileStillExists) { + transactionTemplate.executeWithoutResult(status -> { + bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId) + .ifPresent(bookEntity -> { + deleteRemovedBooks(List.of(bookEntity.getId())); + notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId())); + log.debug("Deleted book after debounce: {}", fileName); + }); + }); + } else { + log.debug("File '{}' detected to still exist after debounce, skipping delete.", fileName); + } + } catch (Exception e) { + log.error("Error during delayed deletion of file: {}", filePath, e); + } finally { + deletionTasks.remove(filePath); + } + }, DELETE_DEBOUNCE_SECONDS, TimeUnit.SECONDS)); + + // If scheduledDeletion != null, it means a task was already scheduled, so we skip scheduling again } } @@ -103,23 +149,58 @@ public class LibraryProcessingService { public void rescanLibrary(long libraryId) throws IOException { LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName())); - processLibraryFiles(getUnProcessedFiles(libraryEntity)); - deleteRemovedBooks(getRemovedBooks(libraryEntity)); + detectMovedBooksAndUpdatePaths(libraryEntity); + deleteRemovedBooks(detectDeletedBookIds(libraryEntity)); + processLibraryFiles(detectNewBookPaths(libraryEntity)); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName())); } - @Transactional - protected void deleteRemovedBooks(List removedBookEntities) { - if (!removedBookEntities.isEmpty()) { - entityManager.flush(); - entityManager.clear(); - Set bookIds = removedBookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()); - bookRepository.deleteByIdIn(bookIds); - notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds); - log.info("Books removed: {}", bookIds); + void detectMovedBooksAndUpdatePaths(LibraryEntity libraryEntity) throws IOException { + List currentLibraryFiles = getLibraryFiles(libraryEntity); + Map currentFileMap = currentLibraryFiles.stream() + .collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing)); + for (BookEntity book : libraryEntity.getBookEntities()) { + Path existingPath = book.getFullFilePath(); + Path updatedPath = currentFileMap.get(book.getFileName()); + if (updatedPath != null && !updatedPath.equals(existingPath)) { + log.info("Detected moved book: '{}' from '{}' to '{}'", book.getFileName(), existingPath, updatedPath); + libraryEntity.getLibraryPaths().stream() + .filter(lp -> updatedPath.startsWith(Path.of(lp.getPath()))) + .findFirst() + .ifPresent(matchingPath -> { + book.setLibraryPath(matchingPath); + book.setFileSubPath(FileUtils.getRelativeSubPath(matchingPath.getPath(), updatedPath)); + }); + } } } + public List detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException { + Set currentFileNames = getLibraryFiles(libraryEntity).stream() + .map(LibraryFile::getFileName) + .collect(Collectors.toSet()); + return libraryEntity.getBookEntities().stream() + .filter(book -> !currentFileNames.contains(book.getFileName())) + .map(BookEntity::getId) + .collect(Collectors.toList()); + } + + public List detectNewBookPaths(LibraryEntity libraryEntity) throws IOException { + Set existingFileNames = libraryEntity.getBookEntities().stream() + .map(BookEntity::getFileName) + .collect(Collectors.toSet()); + return getLibraryFiles(libraryEntity).stream() + .filter(file -> !existingFileNames.contains(file.getFileName())) + .collect(Collectors.toList()); + } + + @Transactional + protected void deleteRemovedBooks(List bookIds) { + bookRepository.deleteByIdIn(bookIds); + notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds); + log.info("Books removed: {}", bookIds); + } + @Transactional protected void processLibraryFiles(List libraryFiles) { for (LibraryFile libraryFile : libraryFiles) { @@ -143,30 +224,6 @@ public class LibraryProcessingService { return null; } - @Transactional - protected List getRemovedBooks(LibraryEntity libraryEntity) throws IOException { - List libraryFiles = getLibraryFiles(libraryEntity); - List bookEntities = libraryEntity.getBookEntities(); - Set libraryFilePaths = libraryFiles.stream() - .map(LibraryFile::getFileName) - .collect(Collectors.toSet()); - return bookEntities.stream() - .filter(book -> !libraryFilePaths.contains(book.getFileName())) - .collect(Collectors.toList()); - } - - @Transactional - protected List getUnProcessedFiles(LibraryEntity libraryEntity) throws IOException { - List libraryFiles = getLibraryFiles(libraryEntity); - List bookEntities = libraryEntity.getBookEntities(); - Set processedPaths = bookEntities.stream() - .map(BookEntity::getFileName) - .collect(Collectors.toSet()); - return libraryFiles.stream() - .filter(libraryFile -> !processedPaths.contains(libraryFile.getFileName())) - .collect(Collectors.toList()); - } - private List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { List libraryFiles = new ArrayList<>(); for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) { 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 cac814f50..9bc664c35 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 @@ -84,7 +84,7 @@ public class MonitoringService { 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()); + log.debug("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size()); } } @@ -113,8 +113,7 @@ public class MonitoringService { } 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()); + log.debug("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); } 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 4e62627be..7c4cf65f5 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 @@ -40,7 +40,7 @@ public class MonitoringTask { Path fullPath = directory.resolve(fileName); if (isPdfOrEpub(fileName) && (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_DELETE)) { - log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory); + log.debug("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory); eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory)); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java index 9b94dc21a..b79261ab0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java @@ -14,7 +14,10 @@ public class FileUtils { private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: "; public static String getBookFullPath(BookEntity bookEntity) { - return String.format("%s/%s/%s", bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName()); + return Path.of(bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName()) + .normalize() + .toString() + .replace("\\", "/"); } public static String getRelativeSubPath(String basePath, Path fullFilePath) {