Fix 'Lock wait timeout exceeded exception' during library re-scan

This commit is contained in:
aditya.chandel
2025-07-04 17:19:45 -06:00
committed by Aditya Chandel
parent 841e359b92
commit 8edf589f3d
7 changed files with 35 additions and 67 deletions
@@ -7,6 +7,7 @@ public enum Topic {
BOOK_ADD("/topic/book-add"),
BOOKS_REMOVE("/topic/books-remove"),
BOOK_METADATA_UPDATE("/topic/book-metadata-update"),
BOOK_METADATA_BATCH_UPDATE("/topic/book-metadata-batch-update"),
LOG("/topic/log");
@@ -17,13 +17,8 @@ import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.nio.file.*;
import java.util.*;
@Slf4j
@Service
@@ -45,6 +40,7 @@ public class FileMoveService {
log.info("Starting file move for {} books using pattern: '{}'", books.size(), pattern);
Set<Long> libraryIds = new HashSet<>();
List<Book> updatedBooks = new ArrayList<>();
boolean didPause = false;
if (!monitoringService.isPaused()) {
@@ -99,10 +95,9 @@ public class FileMoveService {
book.setFileName(newFileName);
bookRepository.save(book);
Book updatedBookDto = bookMapper.toBook(book);
notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, updatedBookDto);
updatedBooks.add(bookMapper.toBook(book));
log.info("Updated book id {} with new path", book.getId());
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
if (book.getLibraryPath().getLibrary().getId() != null) {
@@ -115,6 +110,10 @@ public class FileMoveService {
log.info("Completed file move for {} books.", books.size());
if (!updatedBooks.isEmpty()) {
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
}
for (Long libraryId : libraryIds) {
try {
libraryService.rescanLibrary(libraryId);
@@ -26,12 +26,7 @@ public abstract class AbstractFileProcessor implements FileProcessor {
protected final BookMetadataRepository bookMetadataRepository;
protected final MetadataMatchService metadataMatchService;
protected AbstractFileProcessor(BookRepository bookRepository,
BookCreatorService bookCreatorService,
BookMapper bookMapper,
FileProcessingUtils fileProcessingUtils,
BookMetadataRepository bookMetadataRepository,
MetadataMatchService metadataMatchService) {
protected AbstractFileProcessor(BookRepository bookRepository, BookCreatorService bookCreatorService, BookMapper bookMapper, FileProcessingUtils fileProcessingUtils, BookMetadataRepository bookMetadataRepository, MetadataMatchService metadataMatchService) {
this.bookRepository = bookRepository;
this.bookCreatorService = bookCreatorService;
this.bookMapper = bookMapper;
@@ -48,7 +43,9 @@ public abstract class AbstractFileProcessor implements FileProcessor {
String hash = FileUtils.computeFileHash(filePath);
Optional<Book> existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, forceProcess, bookRepository, bookMapper);
if (existing.isPresent()) return existing.get();
if (existing.isPresent()) {
return existing.get();
}
if (!forceProcess) {
Optional<BookEntity> byName = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
if (byName.isPresent()) {
@@ -69,9 +66,6 @@ public abstract class AbstractFileProcessor implements FileProcessor {
bookCreatorService.saveConnections(bookEntity);
bookEntity = bookRepository.save(bookEntity);
bookRepository.flush();
return bookMapper.toBook(bookEntity);
}
}
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.mapper.BookMapper;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@@ -93,43 +94,25 @@ public class FileProcessingUtils {
log.info("Deleted {} book covers", bookIds.size());
}
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(
LibraryFile libraryFile,
String hash,
boolean forceProcess,
BookRepository bookRepository,
BookMapper bookMapper
) {
@Transactional
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, boolean forceProcess, BookRepository bookRepository, BookMapper bookMapper) {
if (StringUtils.isBlank(hash)) {
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
return Optional.empty();
}
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
if (existingByHash.isPresent() && !forceProcess) {
BookEntity book = existingByHash.get();
boolean changed = false;
String fileName = libraryFile.getFullPath().getFileName().toString();
if (!book.getFileName().equals(fileName)) {
book.setFileName(fileName);
changed = true;
}
if (!Objects.equals(book.getLibraryPath().getId(), libraryFile.getLibraryPathEntity().getId())) {
book.setLibraryPath(libraryFile.getLibraryPathEntity());
book.setFileSubPath(libraryFile.getFileSubPath());
changed = true;
}
if (changed) {
bookRepository.save(book);
}
return Optional.of(bookMapper.toBook(book));
}
return Optional.empty();
}
@@ -16,7 +16,6 @@ import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.persistence.EntityManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@@ -43,7 +42,6 @@ public class LibraryProcessingService {
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final BookRepository bookRepository;
private final EntityManager entityManager;
private final FileService fileService;
@Transactional
@@ -59,36 +57,11 @@ public class LibraryProcessingService {
public void rescanLibrary(long libraryId) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
detectMovedBooksAndUpdatePaths(libraryEntity);
entityManager.flush();
entityManager.clear();
deleteRemovedBooks(detectDeletedBookIds(libraryEntity));
entityManager.flush();
entityManager.clear();
processLibraryFiles(detectNewBookPaths(libraryEntity));
entityManager.flush();
entityManager.clear();
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
}
void detectMovedBooksAndUpdatePaths(LibraryEntity libraryEntity) throws IOException {
Map<String, Path> currentFileMap = getLibraryFiles(libraryEntity).stream().collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing));
for (BookEntity book : libraryEntity.getBookEntities()) {
Path existingPath = book.getFullFilePath();
Path updatedPath = currentFileMap.get(book.getFileName());
if (updatedPath != null && !updatedPath.equals(existingPath)) {
log.info("Detected moved book: '{}' from '{}' to '{}'", book.getFileName(), existingPath, updatedPath);
libraryEntity.getLibraryPaths().stream()
.filter(lp -> updatedPath.startsWith(Path.of(lp.getPath())))
.findFirst()
.ifPresent(matchingPath -> {
book.setLibraryPath(matchingPath);
book.setFileSubPath(FileUtils.getRelativeSubPath(matchingPath.getPath(), updatedPath));
});
}
}
}
public List<Long> detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException {
Set<String> currentFileNames = getLibraryFiles(libraryEntity).stream()
.map(LibraryFile::getFileName)
+5
View File
@@ -42,6 +42,11 @@ export class AppComponent implements OnInit {
this.bookService.handleBookUpdate(JSON.parse(message.body));
});
this.rxStompService.watch('/topic/book-metadata-batch-update').subscribe((message: Message) => {
const updatedBooks = JSON.parse(message.body);
this.bookService.handleMultipleBookUpdates(updatedBooks);
});
this.rxStompService.watch('/topic/log').subscribe((message: Message) => {
const logNotification = parseLogNotification(message.body);
this.eventService.handleIncomingLog(logNotification);
@@ -426,6 +426,19 @@ export class BookService {
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
handleMultipleBookUpdates(updatedBooks: Book[]): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
const mergedBooks = currentBooks.map(book =>
updatedMap.has(book.id) ? updatedMap.get(book.id)! : book
);
this.bookStateSubject.next({ ...currentState, books: mergedBooks });
}
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata) {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {