From d40a650df761014db8c8c383784a8caa36fede19 Mon Sep 17 00:00:00 2001 From: Sergio Visinoni Date: Tue, 2 Dec 2025 18:06:59 +0100 Subject: [PATCH] Fix race conditions between Bookdrop and Monitoring Service when importing multiple files (#1709) * fix(bookdrop): gate library re-registration during single-file moves - query MonitoringService to see if the library is actively watched before unregistering/re-registering it - lower log noise for these operations and monitoring registration - expose MonitoringService#isLibraryMonitored via MonitoringRegistrationService - add FileMoveServiceTest covering monitored vs unmonitored scenarios This fixes issues when importing multiple files via bookdrop. Refs: #1608 * fix(bookdrop): avoid unnecessary stacktrace * Use `deleteIfExists` to avoid trying to delete a missing file This happens regularly as the file has already been removed by other methods --- .../service/bookdrop/BookDropService.java | 2 +- .../booklore/service/file/FileMoveHelper.java | 1 + .../service/file/FileMoveService.java | 12 +- .../MonitoringRegistrationService.java | 5 + .../service/monitoring/MonitoringService.java | 4 + .../service/file/FileMoveServiceTest.java | 109 ++++++++++++++++++ 6 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java index 3b70a9044..5c837db19 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java @@ -507,7 +507,7 @@ public class BookDropService { private void cleanupTempFile(Path tempPath) { if (tempPath != null) { try { - Files.delete(tempPath); + Files.deleteIfExists(tempPath); } catch (Exception e) { log.warn("Failed to cleanup temp file: {}", tempPath, e); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java index 56b0dcaa4..86846bf03 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveHelper.java @@ -74,6 +74,7 @@ public class FileMoveHelper { } public void registerLibraryPaths(Long libraryId, Path libraryRoot) { + log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot); monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java index 5160cd941..04f711d1f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java @@ -122,8 +122,10 @@ public class FileMoveService { Long libraryId = bookEntity.getLibraryPath().getLibrary().getId(); Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize(); + boolean isLibraryMonitoredWhenCalled = false; try { + isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId); String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary()); Path currentFilePath = bookEntity.getFullFilePath(); Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern); @@ -134,7 +136,10 @@ public class FileMoveService { log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath); - fileMoveHelper.unregisterLibrary(libraryId); + if (isLibraryMonitoredWhenCalled) { + log.debug("Unregistering library {} before moving a single file", libraryId); + fileMoveHelper.unregisterLibrary(libraryId); + } fileMoveHelper.moveFile(currentFilePath, expectedFilePath); @@ -151,7 +156,10 @@ public class FileMoveService { } catch (Exception e) { log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e); } finally { - fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot); + if (isLibraryMonitoredWhenCalled) { + log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot); + fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot); + } } return FileMoveResult.builder().moved(false).build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java index 57c83e807..f4455ef0a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java @@ -21,6 +21,10 @@ public class MonitoringRegistrationService { return monitoringService.isPathMonitored(path); } + public boolean isLibraryMonitored(Long libraryId) { + return monitoringService.isLibraryMonitored(libraryId); + } + public void unregisterSpecificPath(Path path) { monitoringService.unregisterPath(path); } @@ -42,6 +46,7 @@ public class MonitoringRegistrationService { return; } try { + log.debug("Registering library paths for libraryId {} at {}", libraryId, libraryRoot); monitoringService.registerPath(libraryRoot, libraryId); try (var stream = Files.walk(libraryRoot)) { stream.filter(Files::isDirectory) 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 606e99bf3..acde6d8f9 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 @@ -241,4 +241,8 @@ public class MonitoringService { public boolean isPathMonitored(Path path) { return monitoredPaths.contains(path.toAbsolutePath().normalize()); } + + public boolean isLibraryMonitored(Long libraryId) { + return libraryWatchStatusMap.getOrDefault(libraryId, false); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java new file mode 100644 index 000000000..59a59300f --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceTest.java @@ -0,0 +1,109 @@ +package com.adityachandel.booklore.service.file; + +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.mapper.LibraryMapper; +import com.adityachandel.booklore.model.dto.FileMoveResult; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.LibraryRepository; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FileMoveServiceTest { + + @Mock + private BookRepository bookRepository; + @Mock + private LibraryRepository libraryRepository; + @Mock + private FileMoveHelper fileMoveHelper; + @Mock + private MonitoringRegistrationService monitoringRegistrationService; + @Mock + private LibraryMapper libraryMapper; + @Mock + private BookMapper bookMapper; + @Mock + private NotificationService notificationService; + @Mock + private EntityManager entityManager; + + @InjectMocks + private FileMoveService fileMoveService; + + private BookEntity bookEntity; + private Path expectedFilePath; + + @BeforeEach + void setUp() throws Exception { + LibraryEntity library = new LibraryEntity(); + library.setId(42L); + + LibraryPathEntity libraryPath = new LibraryPathEntity(); + libraryPath.setId(77L); + libraryPath.setPath("/library/root"); + libraryPath.setLibrary(library); + + bookEntity = new BookEntity(); + bookEntity.setId(999L); + bookEntity.setLibrary(library); + bookEntity.setLibraryPath(libraryPath); + bookEntity.setFileSubPath("SciFi"); + bookEntity.setFileName("Original.epub"); + + expectedFilePath = Paths.get(libraryPath.getPath(), bookEntity.getFileSubPath(), "Renamed.epub"); + + when(fileMoveHelper.getFileNamingPattern(library)).thenReturn("{title}"); + when(fileMoveHelper.generateNewFilePath(bookEntity, libraryPath, "{title}")).thenReturn(expectedFilePath); + when(fileMoveHelper.extractSubPath(expectedFilePath, libraryPath)).thenReturn(bookEntity.getFileSubPath()); + doNothing().when(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); + doNothing().when(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet()); + } + + @Test + void moveSingleFile_whenLibraryMonitored_reRegistersLibraryPaths() throws Exception { + when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); + + FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + + assertTrue(result.isMoved()); + + verify(fileMoveHelper).unregisterLibrary(42L); + Path expectedRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize(); + verify(fileMoveHelper).registerLibraryPaths(42L, expectedRoot); + } + + @Test + void moveSingleFile_whenLibraryNotMonitored_skipsMonitoringCalls() throws Exception { + when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); + + FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + + assertTrue(result.isMoved()); + + verify(fileMoveHelper, never()).unregisterLibrary(anyLong()); + verify(fileMoveHelper, never()).registerLibraryPaths(anyLong(), any(Path.class)); + } +}