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 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<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 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<String, ScheduledFuture<?>> 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<BookEntity> removedBookEntities) {
if (!removedBookEntities.isEmpty()) {
entityManager.flush();
entityManager.clear();
Set<Long> 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<LibraryFile> currentLibraryFiles = getLibraryFiles(libraryEntity);
Map<String, Path> 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<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
protected void processLibraryFiles(List<LibraryFile> libraryFiles) {
for (LibraryFile libraryFile : libraryFiles) {
@@ -143,30 +224,6 @@ public class LibraryProcessingService {
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 {
List<LibraryFile> libraryFiles = new ArrayList<>();
for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) {
@@ -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);
}
@@ -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));
}
}
@@ -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) {