Refine handling of file create/delete events in library watcher

This commit is contained in:
aditya.chandel
2025-05-23 22:32:56 -06:00
committed by Aditya Chandel
parent 17ba20fbe9
commit 25ee510379
5 changed files with 117 additions and 49 deletions
@@ -6,6 +6,8 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant; import java.time.Instant;
import java.util.List; import java.util.List;
@@ -60,4 +62,11 @@ public class BookEntity {
@Column(name = "similar_books_json", columnDefinition = "TEXT") @Column(name = "similar_books_json", columnDefinition = "TEXT")
private List<BookRecommendationLite> similarBooksJson; private List<BookRecommendationLite> 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);
}
} }
@@ -18,12 +18,15 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification; import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@@ -39,6 +42,11 @@ public class LibraryProcessingService {
private final EpubProcessor epubProcessor; private final EpubProcessor epubProcessor;
private final BookRepository bookRepository; private final BookRepository bookRepository;
private final EntityManager entityManager; private final EntityManager entityManager;
private final TransactionTemplate transactionTemplate;
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final Map<String, ScheduledFuture<?>> deletionTasks = new ConcurrentHashMap<>();
private static final int DELETE_DEBOUNCE_SECONDS = 3;
@Transactional @Transactional
public void processLibrary(long libraryId) throws IOException { public void processLibrary(long libraryId) throws IOException {
@@ -51,18 +59,34 @@ public class LibraryProcessingService {
@Transactional @Transactional
public void processFile(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath) { public void processFile(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId) LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
Path path = Paths.get(filePath); Path path = Paths.get(filePath);
String fileName = path.getFileName().toString(); String fileName = path.getFileName().toString();
if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) { 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)); notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath));
LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath); LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath);
libraryPathEntity = entityManager.merge(libraryPathEntity); 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() LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity) .libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity) .libraryPathEntity(libraryPathEntity)
@@ -75,11 +99,33 @@ public class LibraryProcessingService {
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
} else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) { } else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId) ScheduledFuture<?> scheduledDeletion = deletionTasks.putIfAbsent(filePath, scheduler.schedule(() -> {
.ifPresent(bookEntity -> { try {
deleteRemovedBooks(List.of(bookEntity)); boolean fileStillExists = libraryEntity.getLibraryPaths().stream()
notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId())); .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 { public void rescanLibrary(long libraryId) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName())); notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
processLibraryFiles(getUnProcessedFiles(libraryEntity)); detectMovedBooksAndUpdatePaths(libraryEntity);
deleteRemovedBooks(getRemovedBooks(libraryEntity)); deleteRemovedBooks(detectDeletedBookIds(libraryEntity));
processLibraryFiles(detectNewBookPaths(libraryEntity));
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName())); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
} }
@Transactional void detectMovedBooksAndUpdatePaths(LibraryEntity libraryEntity) throws IOException {
protected void deleteRemovedBooks(List<BookEntity> removedBookEntities) { List<LibraryFile> currentLibraryFiles = getLibraryFiles(libraryEntity);
if (!removedBookEntities.isEmpty()) { Map<String, Path> currentFileMap = currentLibraryFiles.stream()
entityManager.flush(); .collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing));
entityManager.clear(); for (BookEntity book : libraryEntity.getBookEntities()) {
Set<Long> bookIds = removedBookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()); Path existingPath = book.getFullFilePath();
bookRepository.deleteByIdIn(bookIds); Path updatedPath = currentFileMap.get(book.getFileName());
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds); if (updatedPath != null && !updatedPath.equals(existingPath)) {
log.info("Books removed: {}", bookIds); 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<Long> detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException {
Set<String> 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<LibraryFile> detectNewBookPaths(LibraryEntity libraryEntity) throws IOException {
Set<String> 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<Long> bookIds) {
bookRepository.deleteByIdIn(bookIds);
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
log.info("Books removed: {}", bookIds);
}
@Transactional @Transactional
protected void processLibraryFiles(List<LibraryFile> libraryFiles) { protected void processLibraryFiles(List<LibraryFile> libraryFiles) {
for (LibraryFile libraryFile : libraryFiles) { for (LibraryFile libraryFile : libraryFiles) {
@@ -143,30 +224,6 @@ public class LibraryProcessingService {
return null; return null;
} }
@Transactional
protected List<BookEntity> getRemovedBooks(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
List<BookEntity> bookEntities = libraryEntity.getBookEntities();
Set<String> libraryFilePaths = libraryFiles.stream()
.map(LibraryFile::getFileName)
.collect(Collectors.toSet());
return bookEntities.stream()
.filter(book -> !libraryFilePaths.contains(book.getFileName()))
.collect(Collectors.toList());
}
@Transactional
protected List<LibraryFile> getUnProcessedFiles(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
List<BookEntity> bookEntities = libraryEntity.getBookEntities();
Set<String> processedPaths = bookEntities.stream()
.map(BookEntity::getFileName)
.collect(Collectors.toSet());
return libraryFiles.stream()
.filter(libraryFile -> !processedPaths.contains(libraryFile.getFileName()))
.collect(Collectors.toList());
}
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException { private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>(); List<LibraryFile> libraryFiles = new ArrayList<>();
for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) { for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) {
@@ -84,7 +84,7 @@ public class MonitoringService {
if (!eventQueue.offer(event)) { if (!eventQueue.offer(event)) {
log.warn("Event queue is full, dropping event: {}", event.getFilePath()); log.warn("Event queue is full, dropping event: {}", event.getFilePath());
} else { } 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) { } catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId); log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
} }
log.info("Processed file change event for library {}: {} (from folder: {}) with kind: {}", log.debug("Processed file change event for library {}: {} (from folder: {}) with kind: {}", libraryId, filePath, watchedFolder, event.getEventKind());
libraryId, filePath, watchedFolder, event.getEventKind());
} else { } else {
log.warn("No libraryId found for watched folder: {}", watchedFolder); log.warn("No libraryId found for watched folder: {}", watchedFolder);
} }
@@ -40,7 +40,7 @@ public class MonitoringTask {
Path fullPath = directory.resolve(fileName); Path fullPath = directory.resolve(fileName);
if (isPdfOrEpub(fileName) && (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_DELETE)) { 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)); eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory));
} }
} }
@@ -14,7 +14,10 @@ public class FileUtils {
private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: "; private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
public static String getBookFullPath(BookEntity bookEntity) { 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) { public static String getRelativeSubPath(String basePath, Path fullFilePath) {