WIP: Watcher

This commit is contained in:
aditya.chandel
2025-02-07 02:19:35 -07:00
parent 8918c2b344
commit 931718bdae
4 changed files with 104 additions and 49 deletions
@@ -17,15 +17,13 @@ import jakarta.persistence.EntityManager;
import lombok.AllArgsConstructor; 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.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -54,29 +52,37 @@ public class LibraryProcessingService {
} }
@Transactional @Transactional
public void processFile(long libraryId, String libraryPath, String 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)); LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath)); .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();
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); LibraryFile libraryFile = LibraryFile.builder()
BookFileType bookFileType = getBookFileType(fileName); .libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path))
.fileName(fileName)
.bookFileType(getBookFileType(fileName))
.build();
LibraryFile libraryFile = LibraryFile.builder() processLibraryFiles(List.of(libraryFile));
.libraryEntity(libraryEntity) notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
.libraryPathEntity(libraryPathEntity)
.fileSubPath(fileSubPath)
.fileName(fileName)
.bookFileType(bookFileType)
.build();
processLibraryFiles(List.of(libraryFile)); } else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
.ifPresent(bookEntity -> {
deleteRemovedBooks(List.of(bookEntity));
notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId()));
});
}
} }
@Transactional @Transactional
@@ -16,6 +16,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryPathRepository; 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 jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -23,6 +24,8 @@ 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.Path;
import java.nio.file.Paths;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -108,8 +111,15 @@ public class LibraryService {
) )
.icon(request.getIcon()) .icon(request.getIcon())
.build(); .build();
libraryEntity = libraryRepository.save(libraryEntity); libraryEntity = libraryRepository.save(libraryEntity);
Long libraryId = libraryEntity.getId(); Long libraryId = libraryEntity.getId();
/*for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
Path path = Paths.get(pathEntity.getPath());
monitoringService.registerPathWithLibraryId(path, libraryId);
}*/
Thread.startVirtualThread(() -> { Thread.startVirtualThread(() -> {
try { try {
libraryProcessingService.processLibrary(libraryId); libraryProcessingService.processLibrary(libraryId);
@@ -120,6 +130,7 @@ public class LibraryService {
} }
log.info("Parsing task completed!"); log.info("Parsing task completed!");
}); });
return libraryMapper.toLibrary(libraryEntity); return libraryMapper.toLibrary(libraryEntity);
} }
@@ -149,9 +160,14 @@ public class LibraryService {
public void deleteLibrary(long id) { public void deleteLibrary(long id) {
LibraryEntity library = libraryRepository.findById(id).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(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<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet()); Set<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet());
fileProcessingUtils.deleteBookCovers(bookIds); fileProcessingUtils.deleteBookCovers(bookIds);
libraryRepository.deleteById(id); libraryRepository.deleteById(id);
log.info("Library deleted successfully: {}", id);
} }
public Book getBook(long libraryId, long bookId) { public Book getBook(long libraryId, long bookId) {
@@ -5,9 +5,9 @@ import com.adityachandel.booklore.service.LibraryProcessingService;
import com.adityachandel.booklore.service.LibraryService; import com.adityachandel.booklore.service.LibraryService;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import jakarta.transaction.Transactional;
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;
@@ -16,7 +16,7 @@ import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.*;
@Slf4j @Slf4j
@Service @Service
@@ -27,14 +27,19 @@ public class MonitoringService {
private final WatchService watchService; private final WatchService watchService;
private final LibraryService libraryService; 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();
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>(); private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
private final BlockingQueue<FileChangeEvent> eventQueue = new LinkedBlockingQueue<>();
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
@PostConstruct @PostConstruct
public void initializeMonitoring() { public void initializeMonitoring() {
log.info("Initializing monitoring service..."); log.info("Initializing monitoring service...");
loadInitialPaths(); loadInitialPaths();
monitoringTask.monitor(); monitoringTask.monitor();
startProcessingThread();
} }
private void loadInitialPaths() { private void loadInitialPaths() {
@@ -45,23 +50,22 @@ public class MonitoringService {
library.getPaths().forEach(libraryPath -> { library.getPaths().forEach(libraryPath -> {
Path path = Paths.get(libraryPath.getPath()); Path path = Paths.get(libraryPath.getPath());
if (Files.isDirectory(path)) { if (Files.isDirectory(path)) {
pathToLibraryIdMap.put(path, library.getId()); // Map path to libraryId registerPathWithLibraryId(path, library.getId());
registerPathWithLibraryId(path);
} }
}); });
}); });
log.info("Loaded initial monitored folders: {}", pathToLibraryIdMap); log.info("Loaded initial monitored folders: {}", pathToLibraryIdMap);
} }
public synchronized void registerPathWithLibraryId(Path path) { public synchronized void registerPathWithLibraryId(Path path, Long libraryId) {
try { try {
if (monitoredPaths.add(path)) { if (monitoredPaths.add(path)) {
path.register(watchService, path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE); 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 { } else {
log.warn("Path is already registered: {}", path); log.warn("Path is already registered: {}", path);
} }
@@ -73,7 +77,7 @@ public class MonitoringService {
public synchronized void unregisterPath(String folderPath) { public synchronized void unregisterPath(String folderPath) {
Path path = Paths.get(folderPath); Path path = Paths.get(folderPath);
if (monitoredPaths.remove(path)) { if (monitoredPaths.remove(path)) {
pathToLibraryIdMap.remove(path); // Remove the path-to-libraryId mapping pathToLibraryIdMap.remove(path);
log.info("Unregistered folder from monitoring: {}", folderPath); log.info("Unregistered folder from monitoring: {}", folderPath);
} else { } else {
log.warn("Folder not found in monitored paths: {}", folderPath); log.warn("Folder not found in monitored paths: {}", folderPath);
@@ -82,19 +86,40 @@ public class MonitoringService {
@EventListener @EventListener
public void handleFileChangeEvent(FileChangeEvent event) { 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 filePath = event.getFilePath();
Path watchedFolder = event.getWatchedFolder(); Path watchedFolder = event.getWatchedFolder();
Long libraryId = pathToLibraryIdMap.get(watchedFolder); Long libraryId = pathToLibraryIdMap.get(watchedFolder);
if (libraryId != null) { if (libraryId != null) {
Thread.startVirtualThread(() -> { try {
try { libraryProcessingService.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString());
libraryProcessingService.processFile(libraryId, watchedFolder.toString(), filePath.toString()); } catch (InvalidDataAccessApiUsageException e) {
} catch (InvalidDataAccessApiUsageException e) { log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId); }
} log.info("Processed file change event for library {}: {} (from folder: {}) with kind: {}",
log.info("Parsing task completed!"); libraryId, filePath, watchedFolder, event.getEventKind());
});
log.info("Handling file change event for library {}: {} (from folder: {}) with kind: {}", 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);
} }
@@ -103,6 +128,7 @@ public class MonitoringService {
@PreDestroy @PreDestroy
public void stopMonitoring() { public void stopMonitoring() {
log.info("Shutting down monitoring service..."); log.info("Shutting down monitoring service...");
singleThreadExecutor.shutdownNow();
if (watchService != null) { if (watchService != null) {
try { try {
watchService.close(); watchService.close();
@@ -6,10 +6,7 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.nio.file.Path; import java.nio.file.*;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
@Slf4j @Slf4j
@Service @Service
@@ -26,23 +23,33 @@ public class MonitoringTask {
public void monitor() { public void monitor() {
log.info("START_MONITORING"); log.info("START_MONITORING");
try { try {
WatchKey key; while (!Thread.currentThread().isInterrupted()) {
while ((key = watchService.take()) != null) { 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()) { for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind(); WatchEvent.Kind<?> kind = event.kind();
Path fileName = (Path) event.context(); Path fileName = (Path) event.context();
Path directory = (Path) key.watchable(); Path directory = (Path) key.watchable();
Path fullPath = directory.resolve(fileName); Path fullPath = directory.resolve(fileName);
if (isPdfOrEpub(fileName)) { if (isPdfOrEpub(fileName)) {
log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory);
kind,
fileName,
fullPath,
directory);
eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, 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) { } catch (InterruptedException e) {
log.warn("Monitoring task interrupted", e); log.warn("Monitoring task interrupted", e);