fix(bookdrop): Ensure source file is only deleted after successful import and cleanup target on failure (#1638)

* fix(bookdrop): improve error handling and cleanup for file move failures

- Ensure target file is deleted if processing or metadata refresh fails after move
- Only delete source file on successful processing
- Add tests to verify file cleanup and source preservation on failure scenarios
- Use lenient mocking for Files in tests to support error simulation

* fix(bookdrop): enhance file and cover cleanup logic, improve test coverage for import finalization

* test(bookdrop): improve finalize import test with LibraryPathRepository mock and enhanced stubbing
This commit is contained in:
Balázs Szücs
2025-11-27 06:48:17 -07:00
committed by GitHub
parent ff052c2fed
commit d2c6e535e2
2 changed files with 270 additions and 28 deletions
@@ -405,11 +405,29 @@ public class BookDropService {
Files.createDirectories(target.getParent());
Files.move(tempPath, target, StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(source);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
return processMovedFile(bookdropFile, target.toFile(), library, path, metadata);
BookdropFileResult result;
try {
result = processMovedFile(bookdropFile, target.toFile(), library, path, metadata);
} catch (Exception e) {
cleanupTargetFile(target, bookdropFile.getId(), "processing exception");
return failureResult(bookdropFile.getFileName(), "Processing failed: " + e.getMessage());
}
if (result.isSuccess()) {
try {
Files.delete(source);
log.info("Successfully deleted source file '{}' after successful import for file id={}", source, bookdropFile.getId());
} catch (IOException e) {
log.warn("Failed to delete source file '{}' after successful import for file id={}: {}", source, bookdropFile.getId(), e.getMessage());
}
} else {
cleanupTargetFile(target, bookdropFile.getId(), "logical failure");
}
return result;
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
@@ -463,34 +481,52 @@ public class BookDropService {
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
Path cachedCoverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg");
if (Files.exists(cachedCoverPath)) {
try {
Files.delete(cachedCoverPath);
log.debug("Deleted cached cover image for bookdropId={}", bookdropFile.getId());
} catch (IOException e) {
log.warn("Failed to delete cached cover image for bookdropId={}: {}", bookdropFile.getId(), e.getMessage());
}
}
}
private void cleanupFailedMove(Path target) {
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
if (Files.deleteIfExists(target)) {
log.info("Cleaned up partially created target file: {}", target);
} else {
log.debug("No partially created target file to cleanup: {}", target);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
} catch (IOException e) {
log.warn("Failed to cleanup partially created target file: {}: {}", target, e.getMessage());
}
}
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
Files.delete(tempPath);
} catch (Exception e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
}
}
private void cleanupTargetFile(Path target, Long fileId, String reason) {
try {
if (Files.deleteIfExists(target)) {
log.info("Cleaned up target file '{}' after {} for file id={}", target, reason, fileId);
} else {
log.debug("Target file '{}' not present, nothing to cleanup for file id={}", target, fileId);
}
} catch (IOException e) {
log.warn("Failed to cleanup target file '{}' after {} for file id={}: {}",
target, reason, fileId, e.getMessage());
}
}
private FileProcessResult processFileInLibrary(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(library)
@@ -520,19 +556,25 @@ public class BookDropService {
private void deleteFilesAndCovers(List<BookdropFileEntity> filesToDelete, AtomicInteger deletedFiles, AtomicInteger deletedCovers) {
for (BookdropFileEntity entity : filesToDelete) {
try {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath)) {
try {
Files.delete(filePath);
deletedFiles.incrementAndGet();
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
} catch (IOException e) {
log.warn("Failed to delete file from disk for bookdropId={}: {}", entity.getId(), e.getMessage());
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath)) {
try {
Files.delete(coverPath);
deletedCovers.incrementAndGet();
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
} catch (IOException e) {
log.warn("Failed to delete cover image for bookdropId={}: {}", entity.getId(), e.getMessage());
}
} catch (IOException e) {
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
}
}
}
@@ -544,9 +586,13 @@ public class BookDropService {
.forEach(p -> {
try (Stream<Path> subPaths = Files.list(p)) {
if (subPaths.findAny().isEmpty()) {
Files.deleteIfExists(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
try {
Files.delete(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
} catch (IOException e) {
log.warn("Failed to delete empty directory: {}: {}", p, e.getMessage());
}
}
} catch (IOException e) {
log.warn("Failed to delete folder: {}", p, e);
@@ -15,6 +15,7 @@ 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.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryPathRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.file.FileMovingHelper;
@@ -23,6 +24,7 @@ import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistr
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -32,6 +34,8 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
@@ -41,6 +45,7 @@ import org.springframework.data.domain.Pageable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
@@ -49,6 +54,7 @@ import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class BookDropServiceTest {
@Mock
@@ -58,6 +64,8 @@ class BookDropServiceTest {
@Mock
private LibraryRepository libraryRepository;
@Mock
private LibraryPathRepository libraryPathRepository;
@Mock
private BookRepository bookRepository;
@Mock
private BookdropMonitoringService bookdropMonitoringService;
@@ -114,6 +122,24 @@ class BookDropServiceTest {
Files.createFile(tempDir.resolve("test-book.pdf"));
}
@AfterEach
void tearDown() throws IOException {
if (Files.exists(tempDir)) {
try (var stream = Files.walk(tempDir)) {
stream.sorted(Comparator.reverseOrder()) // reverse order for directories
.forEach(path -> {
try {
if (!path.equals(tempDir)) { // Don't delete the tempDir itself
Files.deleteIfExists(path);
}
} catch (IOException e) {
// Ignore cleanup failures in tearDown
}
});
}
}
}
@Test
void getFileNotificationSummary_ShouldReturnCorrectCounts() {
when(bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW)).thenReturn(5L);
@@ -236,7 +262,7 @@ class BookDropServiceTest {
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempDir.resolve("temp-file"));
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(1024L);
@@ -267,7 +293,7 @@ class BookDropServiceTest {
BookMetadata metadata = new BookMetadata();
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(metadata);
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
@@ -292,7 +318,7 @@ class BookDropServiceTest {
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.walk(any(Path.class))).thenReturn(java.util.stream.Stream.of(tempDir));
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
@@ -317,7 +343,7 @@ class BookDropServiceTest {
when(appProperties.getBookdropFolder()).thenReturn(tempDir.toString());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.walk(any(Path.class))).thenReturn(java.util.stream.Stream.of(tempDir));
filesMock.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
@@ -337,7 +363,7 @@ class BookDropServiceTest {
void discardSelectedFiles_WhenBookdropFolderDoesNotExist_ShouldHandleGracefully() {
when(appProperties.getBookdropFolder()).thenReturn("/non-existent-path");
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(false);
bookDropService.discardSelectedFiles(true, null, null);
@@ -372,7 +398,7 @@ class BookDropServiceTest {
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(Path.of("/non-existent/missing-file.pdf"))).thenReturn(false);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
@@ -403,7 +429,7 @@ class BookDropServiceTest {
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("target-file.pdf"));
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
try (MockedStatic<Files> filesMock = mockStatic(Files.class, withSettings().lenient())) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString()))
.thenThrow(new IOException("Disk full"));
@@ -416,4 +442,174 @@ class BookDropServiceTest {
assertEquals(1, result.getFailed());
}
}
@Test
void finalizeImport_WhenProcessingSucceeds_ShouldDeleteSourceFileFromBookdrop() throws Exception {
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(true);
request.setDefaultLibraryId(1L);
request.setDefaultPathId(1L);
request.setExcludedIds(List.of());
when(bookdropFileRepository.findAllExcludingIdsFlat(any())).thenReturn(List.of(1L));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/books");
when(libraryPathRepository.findById(1L)).thenReturn(Optional.of(pathEntity));
lenient().when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(new BookMetadata());
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("moved-book.pdf"));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
Book book = Book.builder().id(1L).title("Test Book").build();
FileProcessResult processResult = FileProcessResult.builder().book(book).build();
when(processor.processFile(any())).thenReturn(processResult);
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.save(any())).thenAnswer(i -> i.getArguments()[0]);
doNothing().when(bookdropFileRepository).deleteById(any());
doNothing().when(bookdropNotificationService).sendBookdropFileSummaryNotification();
doNothing().when(notificationService).sendMessage(any(), any());
lenient().doNothing().when(metadataRefreshService).updateBookMetadata(any());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
Path sourcePath = Path.of(bookdropFileEntity.getFilePath());
Path tempPath = tempDir.resolve("temp-file");
Path targetPath = tempDir.resolve("moved-book.pdf");
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempPath);
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(tempPath);
filesMock.when(() -> Files.createDirectories(any(Path.class))).thenReturn(tempDir);
filesMock.when(() -> Files.move(any(Path.class), any(Path.class), any())).thenReturn(targetPath);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(1, result.getSuccessfullyImported());
assertEquals(0, result.getFailed());
filesMock.verify(() -> Files.delete(sourcePath), times(1));
}
}
@Test
void finalizeImport_WhenProcessingFails_ShouldPreserveSourceFileInBookdrop() throws Exception {
BookdropFinalizeRequest.BookdropFinalizeFile finalizeFile = new BookdropFinalizeRequest.BookdropFinalizeFile();
finalizeFile.setFileId(1L);
finalizeFile.setLibraryId(1L);
finalizeFile.setPathId(1L);
finalizeFile.setMetadata(new BookMetadata());
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(false);
request.setFiles(List.of(finalizeFile));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata());
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(tempDir.resolve("moved-book.pdf"));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
when(processor.processFile(any())).thenThrow(new RuntimeException("Processing failed"));
Path sourcePath = Path.of(bookdropFileEntity.getFilePath());
Path tempPath = tempDir.resolve("temp-file");
Path targetPath = tempDir.resolve("moved-book.pdf");
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
filesMock.when(() -> Files.exists(any(Path.class))).thenReturn(true);
filesMock.when(() -> Files.createTempFile(anyString(), anyString())).thenReturn(tempPath);
filesMock.when(() -> Files.copy(any(Path.class), any(Path.class), any())).thenReturn(tempPath);
filesMock.when(() -> Files.createDirectories(any(Path.class))).thenReturn(tempDir);
filesMock.when(() -> Files.move(any(Path.class), any(Path.class), any())).thenReturn(targetPath);
filesMock.when(() -> Files.deleteIfExists(targetPath)).thenReturn(true);
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
filesMock.verify(() -> Files.delete(sourcePath), never());
filesMock.verify(() -> Files.deleteIfExists(targetPath), times(1));
}
}
@Test
void finalizeImport_WhenMetadataRefreshFails_ShouldPreserveSourceFileInBookdrop() throws Exception {
Path sourceFile = tempDir.resolve("metadata-failure-test-book.pdf");
Files.createFile(sourceFile);
assertTrue(Files.exists(sourceFile), "Source file should exist");
bookdropFileEntity.setFilePath(sourceFile.toString());
Path targetDir = tempDir.resolve("library");
Files.createDirectories(targetDir);
BookdropFinalizeRequest.BookdropFinalizeFile finalizeFile = new BookdropFinalizeRequest.BookdropFinalizeFile();
finalizeFile.setFileId(1L);
finalizeFile.setLibraryId(1L);
finalizeFile.setPathId(1L);
finalizeFile.setMetadata(new BookMetadata());
BookdropFinalizeRequest request = new BookdropFinalizeRequest();
request.setSelectAll(false);
request.setFiles(List.of(finalizeFile));
when(bookdropFileRepository.findAllById(any())).thenReturn(List.of(bookdropFileEntity));
when(libraryRepository.findById(1L)).thenReturn(Optional.of(libraryEntity));
when(objectMapper.readValue(anyString(), eq(BookMetadata.class))).thenReturn(new BookMetadata());
when(fileMovingHelper.getFileNamingPattern(libraryEntity)).thenReturn("{title}");
when(fileMovingHelper.generateNewFilePath(anyString(), any(), anyString(), anyString()))
.thenReturn(targetDir.resolve("moved-book.pdf"));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
Book book = Book.builder().id(1L).title("Test Book").build();
FileProcessResult processResult = FileProcessResult.builder().book(book).build();
when(processor.processFile(any())).thenReturn(processResult);
BookEntity bookEntity = new BookEntity();
bookEntity.setId(1L);
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
doNothing().when(bookdropFileRepository).deleteById(any());
doNothing().when(bookdropNotificationService).sendBookdropFileSummaryNotification();
doNothing().when(notificationService).sendMessage(any(), any());
doThrow(new RuntimeException("Metadata refresh failed")).when(metadataRefreshService).updateBookMetadata(any());
when(appProperties.getPathConfig()).thenReturn(tempDir.toString());
BookdropFinalizeResult result = bookDropService.finalizeImport(request);
assertNotNull(result);
assertEquals(1, result.getTotalFiles());
assertEquals(0, result.getSuccessfullyImported());
assertEquals(1, result.getFailed());
assertTrue(Files.exists(sourceFile), "Source file should be preserved on failure");
assertFalse(Files.exists(targetDir.resolve("moved-book.pdf")), "Target file should be cleaned up on failure");
}
}