fix(regenerate-covers): wrap book query stream in transaction to prevent lazy init exception (#916)
This commit is contained in:
@@ -143,6 +143,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllFullBooks();
|
List<BookEntity> findAllFullBooks();
|
||||||
|
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "library", "bookFiles"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
List<BookEntity> findAllFullBooksWithFiles();
|
||||||
|
|
||||||
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) AND b.id > :afterId ORDER BY b.id")
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) AND b.id > :afterId ORDER BY b.id")
|
||||||
List<BookEntity> findBooksForMigrationBatch(@Param("afterId") long afterId, Pageable pageable);
|
List<BookEntity> findBooksForMigrationBatch(@Param("afterId") long afterId, Pageable pageable);
|
||||||
|
|
||||||
|
|||||||
@@ -81,6 +81,10 @@ public class BookQueryService {
|
|||||||
return bookRepository.findAllFullBooks();
|
return bookRepository.findAllFullBooks();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<BookEntity> getAllFullBookEntitiesWithFiles() {
|
||||||
|
return bookRepository.findAllFullBooksWithFiles();
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void saveAll(List<BookEntity> books) {
|
public void saveAll(List<BookEntity> books) {
|
||||||
bookRepository.saveAll(books);
|
bookRepository.saveAll(books);
|
||||||
|
|||||||
@@ -78,9 +78,6 @@ public class BookCoverService {
|
|||||||
private record BookCoverInfo(Long id, String title) {
|
private record BookCoverInfo(Long id, String title) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private record BookRegenerationInfo(Long id, String title, BookFileType bookType, boolean coverLocked) {
|
|
||||||
}
|
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// SECTION: COVER UPDATES
|
// SECTION: COVER UPDATES
|
||||||
// =========================
|
// =========================
|
||||||
@@ -304,7 +301,7 @@ public class BookCoverService {
|
|||||||
* Regenerate covers for a set of books.
|
* Regenerate covers for a set of books.
|
||||||
*/
|
*/
|
||||||
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
||||||
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
List<BookCoverInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
||||||
String username = getCurrentUsername();
|
String username = getCurrentUsername();
|
||||||
taskExecutor.execute(() -> processBulkCoverRegeneration(unlockedBooks, username));
|
taskExecutor.execute(() -> processBulkCoverRegeneration(unlockedBooks, username));
|
||||||
}
|
}
|
||||||
@@ -325,11 +322,12 @@ public class BookCoverService {
|
|||||||
String username = getCurrentUsername();
|
String username = getCurrentUsername();
|
||||||
taskExecutor.execute(() -> {
|
taskExecutor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
|
List<BookCoverInfo> books = bookQueryService.getAllFullBookEntitiesWithFiles().stream()
|
||||||
|
.filter(book -> book.getMetadata() != null)
|
||||||
.filter(book -> !isCoverLocked(book))
|
.filter(book -> !isCoverLocked(book))
|
||||||
.filter(book -> book.getPrimaryBookFile() != null)
|
.filter(book -> book.getPrimaryBookFile() != null)
|
||||||
.filter(book -> !missingOnly || book.getBookCoverHash() == null)
|
.filter(book -> !missingOnly || book.getBookCoverHash() == null)
|
||||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getPrimaryBookFile().getBookType(), false))
|
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||||
.toList();
|
.toList();
|
||||||
int total = books.size();
|
int total = books.size();
|
||||||
String label = missingOnly ? "missing" : "all";
|
String label = missingOnly ? "missing" : "all";
|
||||||
@@ -337,7 +335,7 @@ public class BookCoverService {
|
|||||||
|
|
||||||
int current = 1;
|
int current = 1;
|
||||||
|
|
||||||
for (BookRegenerationInfo bookInfo : books) {
|
for (BookCoverInfo bookInfo : books) {
|
||||||
try {
|
try {
|
||||||
String progress = "(" + current + "/" + total + ") ";
|
String progress = "(" + current + "/" + total + ") ";
|
||||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||||
@@ -418,21 +416,26 @@ public class BookCoverService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void processBulkCoverRegeneration(List<BookRegenerationInfo> books, String username) {
|
private void processBulkCoverRegeneration(List<BookCoverInfo> books, String username) {
|
||||||
try {
|
try {
|
||||||
int total = books.size();
|
int total = books.size();
|
||||||
sendNotification(username, Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
|
sendNotification(username, Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
|
||||||
|
|
||||||
int current = 1;
|
int current = 1;
|
||||||
|
|
||||||
for (BookRegenerationInfo bookInfo : books) {
|
for (BookCoverInfo bookInfo : books) {
|
||||||
try {
|
try {
|
||||||
String progress = "(" + current + "/" + total + ") ";
|
String progress = "(" + current + "/" + total + ") ";
|
||||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||||
|
|
||||||
transactionTemplate.execute(status -> {
|
transactionTemplate.execute(status -> {
|
||||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType());
|
var primaryFile = book.getPrimaryBookFile();
|
||||||
|
if (primaryFile == null) {
|
||||||
|
log.warn("{}Skipping book ID {} ({}) - no primary file", progress, book.getId(), bookInfo.title());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType());
|
||||||
boolean success = processor.generateCover(book);
|
boolean success = processor.generateCover(book);
|
||||||
|
|
||||||
if (success) {
|
if (success) {
|
||||||
@@ -547,25 +550,27 @@ public class BookCoverService {
|
|||||||
|
|
||||||
private List<BookCoverInfo> getUnlockedBookCoverInfos(Set<Long> bookIds) {
|
private List<BookCoverInfo> getUnlockedBookCoverInfos(Set<Long> bookIds) {
|
||||||
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||||
|
.filter(book -> book.getMetadata() != null)
|
||||||
.filter(book -> !isCoverLocked(book))
|
.filter(book -> !isCoverLocked(book))
|
||||||
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
|
private List<BookCoverInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
|
||||||
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||||
|
.filter(book -> book.getMetadata() != null)
|
||||||
.filter(book -> !isCoverLocked(book))
|
.filter(book -> !isCoverLocked(book))
|
||||||
.filter(book -> book.getPrimaryBookFile() != null)
|
.filter(book -> book.getPrimaryBookFile() != null)
|
||||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getPrimaryBookFile().getBookType(), false))
|
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isCoverLocked(BookEntity book) {
|
private boolean isCoverLocked(BookEntity book) {
|
||||||
return book.getMetadata().getCoverLocked() != null && book.getMetadata().getCoverLocked();
|
return book.getMetadata() != null && Boolean.TRUE.equals(book.getMetadata().getCoverLocked());
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isAudiobookCoverLocked(BookEntity book) {
|
private boolean isAudiobookCoverLocked(BookEntity book) {
|
||||||
return book.getMetadata().getAudiobookCoverLocked() != null && book.getMetadata().getAudiobookCoverLocked();
|
return book.getMetadata() != null && Boolean.TRUE.equals(book.getMetadata().getAudiobookCoverLocked());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getAuthorNames(BookEntity bookEntity) {
|
private String getAuthorNames(BookEntity bookEntity) {
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import org.mockito.InjectMocks;
|
|||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.MockedStatic;
|
import org.mockito.MockedStatic;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.transaction.support.TransactionCallback;
|
||||||
import org.springframework.transaction.support.TransactionTemplate;
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
@@ -768,11 +769,11 @@ class BookCoverServiceTest {
|
|||||||
book.setBookFiles(List.of(ebookFile));
|
book.setBookFiles(List.of(ebookFile));
|
||||||
book.setLibrary(LibraryEntity.builder().build());
|
book.setLibrary(LibraryEntity.builder().build());
|
||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book));
|
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(book));
|
||||||
|
|
||||||
BookFileProcessor processor = mock(BookFileProcessor.class);
|
BookFileProcessor processor = mock(BookFileProcessor.class);
|
||||||
when(transactionTemplate.execute(any())).thenAnswer(inv -> {
|
when(transactionTemplate.execute(any())).thenAnswer(inv -> {
|
||||||
var callback = inv.getArgument(0, org.springframework.transaction.support.TransactionCallback.class);
|
var callback = inv.getArgument(0, TransactionCallback.class);
|
||||||
return callback.doInTransaction(null);
|
return callback.doInTransaction(null);
|
||||||
});
|
});
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
|
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
|
||||||
@@ -799,7 +800,7 @@ class BookCoverServiceTest {
|
|||||||
locked.setBookFiles(List.of(ebookFile));
|
locked.setBookFiles(List.of(ebookFile));
|
||||||
locked.setLibrary(LibraryEntity.builder().build());
|
locked.setLibrary(LibraryEntity.builder().build());
|
||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(locked));
|
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(locked));
|
||||||
|
|
||||||
doAnswer(inv -> {
|
doAnswer(inv -> {
|
||||||
inv.<Runnable>getArgument(0).run();
|
inv.<Runnable>getArgument(0).run();
|
||||||
@@ -827,11 +828,11 @@ class BookCoverServiceTest {
|
|||||||
withoutCover.setBookFiles(List.of(ebookFile2));
|
withoutCover.setBookFiles(List.of(ebookFile2));
|
||||||
withoutCover.setLibrary(LibraryEntity.builder().build());
|
withoutCover.setLibrary(LibraryEntity.builder().build());
|
||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(withCover, withoutCover));
|
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(withCover, withoutCover));
|
||||||
|
|
||||||
BookFileProcessor processor = mock(BookFileProcessor.class);
|
BookFileProcessor processor = mock(BookFileProcessor.class);
|
||||||
when(transactionTemplate.execute(any())).thenAnswer(inv -> {
|
when(transactionTemplate.execute(any())).thenAnswer(inv -> {
|
||||||
var callback = inv.getArgument(0, org.springframework.transaction.support.TransactionCallback.class);
|
var callback = inv.getArgument(0, TransactionCallback.class);
|
||||||
return callback.doInTransaction(null);
|
return callback.doInTransaction(null);
|
||||||
});
|
});
|
||||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(withoutCover));
|
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(withoutCover));
|
||||||
@@ -846,6 +847,7 @@ class BookCoverServiceTest {
|
|||||||
|
|
||||||
service.regenerateCovers(true);
|
service.regenerateCovers(true);
|
||||||
|
|
||||||
|
// Now it is 1 call because the initial query is moved to bookQueryService (which is mocked)
|
||||||
verify(transactionTemplate, times(1)).execute(any());
|
verify(transactionTemplate, times(1)).execute(any());
|
||||||
verify(bookRepository).save(withoutCover);
|
verify(bookRepository).save(withoutCover);
|
||||||
verify(bookRepository, never()).findById(1L);
|
verify(bookRepository, never()).findById(1L);
|
||||||
@@ -856,7 +858,7 @@ class BookCoverServiceTest {
|
|||||||
BookEntity book = buildBook(1L, false);
|
BookEntity book = buildBook(1L, false);
|
||||||
book.setBookFiles(new ArrayList<>());
|
book.setBookFiles(new ArrayList<>());
|
||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book));
|
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(book));
|
||||||
|
|
||||||
doAnswer(inv -> {
|
doAnswer(inv -> {
|
||||||
inv.<Runnable>getArgument(0).run();
|
inv.<Runnable>getArgument(0).run();
|
||||||
@@ -865,6 +867,57 @@ class BookCoverServiceTest {
|
|||||||
|
|
||||||
service.regenerateCovers(false);
|
service.regenerateCovers(false);
|
||||||
|
|
||||||
|
// Fetching list is moved to bookQueryService
|
||||||
|
verify(transactionTemplate, never()).execute(any());
|
||||||
|
verify(bookRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void skipsBooksWithNoMetadata() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.id(1L)
|
||||||
|
.metadata(null)
|
||||||
|
.bookFiles(new ArrayList<>())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(book));
|
||||||
|
|
||||||
|
doAnswer(inv -> {
|
||||||
|
inv.<Runnable>getArgument(0).run();
|
||||||
|
return null;
|
||||||
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
|
|
||||||
|
service.regenerateCovers(false);
|
||||||
|
|
||||||
|
verify(transactionTemplate, never()).execute(any());
|
||||||
|
verify(bookRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class LockStatusEdgeCases {
|
||||||
|
@Test
|
||||||
|
void unlockedMethodsHandleNullMetadata() throws Exception {
|
||||||
|
BookEntity book = BookEntity.builder().id(1L).metadata(null).build();
|
||||||
|
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||||
|
|
||||||
|
// Test getUnlockedBookCoverInfos via updateCoverFromFileForBooks (async)
|
||||||
|
doAnswer(inv -> {
|
||||||
|
inv.<Runnable>getArgument(0).run();
|
||||||
|
return null;
|
||||||
|
}).when(taskExecutor).execute(any(Runnable.class));
|
||||||
|
|
||||||
|
MultipartFile file = mock(MultipartFile.class);
|
||||||
|
when(file.isEmpty()).thenReturn(false);
|
||||||
|
when(file.getSize()).thenReturn(1024L);
|
||||||
|
when(file.getInputStream()).thenReturn(new java.io.ByteArrayInputStream(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}));
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||||
|
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(10);
|
||||||
|
|
||||||
|
service.updateCoverFromFileForBooks(Set.of(1L), file);
|
||||||
|
|
||||||
|
verify(bookQueryService).findAllWithMetadataByIds(any());
|
||||||
|
// Should not proceed to transaction if filtered out
|
||||||
verify(transactionTemplate, never()).execute(any());
|
verify(transactionTemplate, never()).execute(any());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user