From 998b07d24304e7e7b00e4550ce6cbb9fc2c5d5f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Fri, 2 Jan 2026 18:49:34 +0100 Subject: [PATCH] fix(filemove): improve handling of library monitoring during file moves and add tests for operation order (#2104) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../service/file/FileMoveService.java | 23 +- .../file/FileMoveServiceOrderingTest.java | 198 ++++++++++++++++++ .../service/file/FileMoveServiceTest.java | 47 ++++- 3 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java 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 5c05a6604..a2fca19c7 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 @@ -55,6 +55,8 @@ public class FileMoveService { for (FileMoveRequest.Move move : moves) { processSingleMove(move); } + // Ensure any file system events from the moves are drained/ignored while we are still unregistered + sleep(EVENT_DRAIN_TIMEOUT_MS); } finally { for (Long libraryId : allAffectedLibraryIds) { libraryRepository.findById(libraryId) @@ -148,7 +150,9 @@ public class FileMoveService { boolean isLibraryMonitoredWhenCalled = false; try { - isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId); + Set existingPaths = monitoringRegistrationService.getPathsForLibraries(Set.of(libraryId)); + isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId) || !existingPaths.isEmpty(); + String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary()); Path currentFilePath = bookEntity.getFullFilePath(); Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern); @@ -161,15 +165,19 @@ public class FileMoveService { if (isLibraryMonitoredWhenCalled) { log.debug("Unregistering library {} before moving a single file", libraryId); - Set libraryPaths = monitoringRegistrationService.getPathsForLibraries(Set.of(libraryId)); fileMoveHelper.unregisterLibrary(libraryId); - monitoringRegistrationService.waitForEventsDrainedByPaths(libraryPaths, EVENT_DRAIN_TIMEOUT_MS); + monitoringRegistrationService.waitForEventsDrainedByPaths(existingPaths, EVENT_DRAIN_TIMEOUT_MS); } fileMoveHelper.moveFile(currentFilePath, expectedFilePath); fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot)); + if (isLibraryMonitoredWhenCalled) { + // Ensure any file system events from the move and cleanup are drained/ignored while we are still unregistered + sleep(EVENT_DRAIN_TIMEOUT_MS); + } + String newFileName = expectedFilePath.getFileName().toString(); String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath()); @@ -192,4 +200,13 @@ public class FileMoveService { return FileMoveResult.builder().moved(false).build(); } + + protected void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Sleep interrupted", e); + } + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java new file mode 100644 index 000000000..37b054f86 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/file/FileMoveServiceOrderingTest.java @@ -0,0 +1,198 @@ +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.dto.Library; +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.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.Set; + +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.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FileMoveServiceOrderingTest { + + @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; + + private TestableFileMoveService fileMoveService; + + private BookEntity bookEntity; + private Path expectedFilePath; + + // Subclass to mock sleep + static class TestableFileMoveService extends FileMoveService { + public TestableFileMoveService(BookRepository bookRepository, LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) { + super(bookRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager); + } + + @Override + protected void sleep(long millis) { + // No-op for test, but can be verified by spy + } + } + + @BeforeEach + void setUp() throws Exception { + fileMoveService = spy(new TestableFileMoveService( + bookRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager)); + + 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_guaranteesCorrectOrderOfOperations_WhenMonitored() throws Exception { + // Arrange + when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); + + Library libraryDto = Library.builder().watch(true).build(); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); + + // Act + FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + + // Assert + assertTrue(result.isMoved()); + + InOrder inOrder = inOrder(monitoringRegistrationService, fileMoveHelper, fileMoveService); + + // 1. Unregister library + inOrder.verify(fileMoveHelper).unregisterLibrary(42L); + + // 2. Wait for initial events to drain (before move) + inOrder.verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong()); + + // 3. Perform the move + inOrder.verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); + + // 4. Perform cleanup + inOrder.verify(fileMoveHelper).deleteEmptyParentDirsUpToLibraryFolders(any(Path.class), anySet()); + + // 5. CRITICAL: Sleep/Wait for events generated by move/cleanup to drain *before* re-registering + inOrder.verify(fileMoveService).sleep(anyLong()); + + // 6. Register library *last* + inOrder.verify(monitoringRegistrationService).registerLibrary(libraryDto); + } + + @Test + void moveSingleFile_guaranteesCorrectOrderOfOperations_WhenStatusNotMonitoredButHasPaths() throws Exception { + // Arrange: status says FALSE, but getPaths returns paths. Should still unregister. + when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); + + Library libraryDto = Library.builder().watch(true).build(); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); + + // Act + FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + + // Assert + assertTrue(result.isMoved()); + + InOrder inOrder = inOrder(monitoringRegistrationService, fileMoveHelper, fileMoveService); + + // 1. Unregister library + inOrder.verify(fileMoveHelper).unregisterLibrary(42L); + + // 2. Wait for initial events to drain + inOrder.verify(monitoringRegistrationService).waitForEventsDrainedByPaths(anySet(), anyLong()); + + // 3. Move + inOrder.verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); + + // 4. Sleep + inOrder.verify(fileMoveService).sleep(anyLong()); + + // 5. Register + inOrder.verify(monitoringRegistrationService).registerLibrary(libraryDto); + } + + @Test + void moveSingleFile_skipsMonitoringOps_WhenNotMonitoredAndNoPaths() throws Exception { + // Arrange + when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Collections.emptySet()); + + // Act + FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + + // Assert + assertTrue(result.isMoved()); + + // Verify NO unregister/register happens + verify(fileMoveHelper, never()).unregisterLibrary(anyLong()); + verify(monitoringRegistrationService, never()).waitForEventsDrainedByPaths(anySet(), anyLong()); + + // Move happens + verify(fileMoveHelper).moveFile(any(Path.class), any(Path.class)); + + // NO sleep + verify(fileMoveService, never()).sleep(anyLong()); + + // NO register + verify(monitoringRegistrationService, never()).registerLibrary(any()); + } +} \ No newline at end of file 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 index 59e1e09b6..b96b65e12 100644 --- 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 @@ -15,12 +15,13 @@ 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 java.util.Collections; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -28,6 +29,7 @@ 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.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -51,14 +53,29 @@ class FileMoveServiceTest { @Mock private EntityManager entityManager; - @InjectMocks private FileMoveService fileMoveService; private BookEntity bookEntity; private Path expectedFilePath; + // Subclass to mock sleep for tests + static class TestableFileMoveService extends FileMoveService { + public TestableFileMoveService(BookRepository bookRepository, LibraryRepository libraryRepository, FileMoveHelper fileMoveHelper, MonitoringRegistrationService monitoringRegistrationService, LibraryMapper libraryMapper, BookMapper bookMapper, NotificationService notificationService, EntityManager entityManager) { + super(bookRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager); + } + + @Override + protected void sleep(long millis) { + // No-op for test + } + } + @BeforeEach void setUp() throws Exception { + // Use spy/subclass to avoid actual sleep + fileMoveService = spy(new TestableFileMoveService( + bookRepository, libraryRepository, fileMoveHelper, monitoringRegistrationService, libraryMapper, bookMapper, notificationService, entityManager)); + LibraryEntity library = new LibraryEntity(); library.setId(42L); @@ -84,8 +101,9 @@ class FileMoveServiceTest { } @Test - void moveSingleFile_whenLibraryMonitored_reRegistersLibraryPaths() { + void moveSingleFile_whenLibraryMonitored_reRegistersLibraryPaths() throws Exception { when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); Library libraryDto = Library.builder().watch(true).build(); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); @@ -100,8 +118,9 @@ class FileMoveServiceTest { } @Test - void moveSingleFile_ensuresLibraryWatchStatusIsRestored() { + void moveSingleFile_ensuresLibraryWatchStatusIsRestored() throws Exception { when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(true); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/library/root"))); Library libraryDto = Library.builder().watch(false).build(); when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); @@ -113,8 +132,9 @@ class FileMoveServiceTest { } @Test - void moveSingleFile_whenLibraryNotMonitored_skipsMonitoringCalls() { + void moveSingleFile_whenLibraryNotMonitored_skipsMonitoringCalls() throws Exception { when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Collections.emptySet()); FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); @@ -123,4 +143,19 @@ class FileMoveServiceTest { verify(fileMoveHelper, never()).unregisterLibrary(anyLong()); verify(fileMoveHelper, never()).registerLibraryPaths(anyLong(), any(Path.class)); } -} + + @Test + void moveSingleFile_whenLibraryNotMonitoredStatusButHasPaths_triggersUnregister() throws Exception { + when(monitoringRegistrationService.isLibraryMonitored(42L)).thenReturn(false); + when(monitoringRegistrationService.getPathsForLibraries(Set.of(42L))).thenReturn(Set.of(Paths.get("/some/path"))); + Library libraryDto = Library.builder().watch(true).build(); + when(libraryMapper.toLibrary(any(LibraryEntity.class))).thenReturn(libraryDto); + + FileMoveResult result = fileMoveService.moveSingleFile(bookEntity); + + assertTrue(result.isMoved()); + + verify(fileMoveHelper).unregisterLibrary(42L); + verify(monitoringRegistrationService).registerLibrary(libraryDto); + } +} \ No newline at end of file