refactor(api): optimize caching mechanisms and improve book filtering (#372)

* refactor(api): optimize caching mechanisms and improve book filtering logic

* refactor(preferences): remove unused ExternalDocLinkComponent and enhance translate function typing

* refactor(initializer): add Duration import for improved cache management

* refactor(docker): increase MaxMetaspaceSize for improved memory management

* refactor(repository): replace findAllForSummaryByIds with findAllById

* refactor(cache): implement invalidateAppBooksQueries for improved cache management

* refactor(AppBookService): increase default page size and optimize magic shelf book resolution

* refactor(AppBookSpecification, MagicShelfBookService, TaskCancellationManager, magic-shelf-component): streamline join handling and improve memory management

* refactor(AppBookService, MagicShelfBookService): enhance book retrieval logic and improve error handling

* chore: fix formatting

* chore: fix formatting
This commit is contained in:
brios
2026-04-22 17:27:10 -04:00
committed by Zach Yale
parent 402c6f07c8
commit 3e5a6a9de8
40 changed files with 1296 additions and 429 deletions
+7 -3
View File
@@ -69,13 +69,17 @@ ENV JAVA_TOOL_OPTIONS="-XX:+UseShenandoahGC \
-XX:MaxRAMPercentage=60.0 \
-XX:InitialRAMPercentage=8.0 \
-XX:+ExitOnOutOfMemoryError \
-XX:MaxMetaspaceSize=192m \
-XX:ReservedCodeCacheSize=64m \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/tmp/heapdump.hprof \
-XX:MaxMetaspaceSize=256m \
-XX:ReservedCodeCacheSize=48m \
-Xss512k \
-XX:CICompilerCount=2 \
-XX:+UnlockExperimentalVMOptions \
-XX:+UseStringDeduplication \
-XX:ShenandoahUncommitDelay=5000 \
-XX:ShenandoahGuaranteedGCInterval=30000"
-XX:ShenandoahGuaranteedGCInterval=30000 \
-XX:MaxDirectMemorySize=256m"
RUN apk add --no-cache su-exec libstdc++ libgcc libarchive && \
mkdir -p /bookdrop
@@ -4,8 +4,6 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.booklore.app.dto.*;
import org.booklore.app.service.AppBookService;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -28,23 +26,9 @@ public class AppBookController {
)
@GetMapping
public ResponseEntity<AppPageResponse<AppBookSummary>> getBooks(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "50") Integer size,
@RequestParam(required = false, defaultValue = "addedOn") String sort,
@RequestParam(required = false, defaultValue = "desc") String dir,
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) Long shelfId,
@RequestParam(required = false) ReadStatus status,
@RequestParam(required = false) String search,
@RequestParam(required = false) BookFileType fileType,
@RequestParam(required = false) Integer minRating,
@RequestParam(required = false) Integer maxRating,
@RequestParam(required = false) String authors,
@RequestParam(required = false) String language) {
@ModelAttribute BookListRequest request) {
return ResponseEntity.ok(mobileBookService.getBooks(
page, size, sort, dir, libraryId, shelfId, status, search,
fileType, minRating, maxRating, authors, language));
return ResponseEntity.ok(mobileBookService.getBooks(request));
}
@Operation(
@@ -1,40 +1,25 @@
package org.booklore.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AppFilterOptions {
private List<AuthorOption> authors;
private List<LanguageOption> languages;
private List<String> readStatuses;
private List<String> fileTypes;
public record AppFilterOptions(
List<CountedOption> authors,
List<LanguageOption> languages,
List<String> readStatuses,
List<String> fileTypes,
List<CountedOption> categories,
List<CountedOption> publishers,
List<CountedOption> series,
List<CountedOption> tags,
List<CountedOption> moods,
List<CountedOption> narrators) {
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class AuthorOption {
private String name;
private long count;
}
public record LanguageOption(String code, String label, long count) {}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class LanguageOption {
private String code;
private String label;
private long count;
}
public record CountedOption(String name, long count) {}
}
@@ -0,0 +1,58 @@
package org.booklore.app.dto;
import jakarta.validation.constraints.Size;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import java.util.List;
public record BookListRequest(
Integer page,
Integer size,
String sort,
String dir,
Long libraryId,
Long shelfId,
ReadStatus status,
String search,
BookFileType fileType,
Integer minRating,
Integer maxRating,
@Size(max = 20) List<String> authors,
@Size(max = 20) List<String> language,
@Size(max = 20) List<String> series,
@Size(max = 20) List<String> category,
@Size(max = 20) List<String> publisher,
@Size(max = 20) List<String> tag,
@Size(max = 20) List<String> mood,
@Size(max = 20) List<String> narrator,
Long magicShelfId,
Boolean unshelved,
String filterMode) {
/**
* Returns the effective filter mode, defaulting to "or" when not specified.
*/
public String effectiveFilterMode() {
if (filterMode == null || filterMode.isBlank()) return "or";
return switch (filterMode.toLowerCase()) {
case "and", "not" -> filterMode.toLowerCase();
default -> "or";
};
}
private static boolean hasValues(List<String> list) {
return list != null && !list.isEmpty() && list.stream().anyMatch(s -> s != null && !s.isBlank());
}
/**
* Returns non-blank trimmed values from the given list, or an empty list.
*/
public static List<String> cleanValues(List<String> list) {
if (list == null) return List.of();
return list.stream()
.filter(s -> s != null && !s.isBlank())
.map(String::trim)
.toList();
}
}
@@ -1,12 +1,15 @@
package org.booklore.app.service;
import lombok.AllArgsConstructor;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.app.dto.AppBookDetail;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.dto.BookListRequest;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.app.specification.AppBookSpecification;
import org.booklore.model.dto.Book;
@@ -36,12 +39,14 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class AppBookService {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final int DEFAULT_PAGE_SIZE = 50;
private static final int MAX_PAGE_SIZE = 50;
private final BookRepository bookRepository;
@@ -53,34 +58,64 @@ public class AppBookService {
private final MagicShelfBookService magicShelfBookService;
private final EntityManager entityManager;
public AppPageResponse<AppBookSummary> getBooks(
Integer page,
Integer size,
String sortBy,
String sortDir,
Long libraryId,
Long shelfId,
ReadStatus status,
String search,
BookFileType fileType,
Integer minRating,
Integer maxRating,
String authors,
String language) {
private final Cache<String, AppFilterOptions> filterOptionsCache = Caffeine.newBuilder()
.expireAfterWrite(java.time.Duration.ofSeconds(30))
.maximumSize(50)
.build();
public AppBookService(BookRepository bookRepository,
UserBookProgressRepository userBookProgressRepository,
UserBookFileProgressRepository userBookFileProgressRepository,
ShelfRepository shelfRepository,
AuthenticationService authenticationService,
AppBookMapper mobileBookMapper,
MagicShelfBookService magicShelfBookService,
EntityManager entityManager) {
this.bookRepository = bookRepository;
this.userBookProgressRepository = userBookProgressRepository;
this.userBookFileProgressRepository = userBookFileProgressRepository;
this.shelfRepository = shelfRepository;
this.authenticationService = authenticationService;
this.mobileBookMapper = mobileBookMapper;
this.magicShelfBookService = magicShelfBookService;
this.entityManager = entityManager;
}
public AppPageResponse<AppBookSummary> getBooks(BookListRequest req) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int pageNum = page != null && page >= 0 ? page : 0;
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
int pageNum = req.page() != null && req.page() >= 0 ? req.page() : 0;
int pageSize = req.size() != null && req.size() > 0 ? Math.min(req.size(), MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
Sort sort = buildSort(sortBy, sortDir);
// Handle magic shelf: compose the DB-side specification directly (no IN-list)
if (req.magicShelfId() != null) {
Sort sort = buildSort(req.sort(), req.dir());
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Specification<BookEntity> spec = buildSpecification(
accessibleLibraryIds, userId, req);
spec = spec.and(magicShelfBookService.toSpecification(userId, req.magicShelfId()));
if (Boolean.TRUE.equals(req.unshelved())) {
spec = spec.and(AppBookSpecification.unshelved());
}
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
return buildPageResponse(bookPage, userId, pageNum, pageSize);
}
Sort sort = buildSort(req.sort(), req.dir());
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Specification<BookEntity> spec = buildSpecification(
accessibleLibraryIds, libraryId, shelfId, status, search, userId,
fileType, minRating, maxRating, authors, language);
accessibleLibraryIds, userId, req);
if (Boolean.TRUE.equals(req.unshelved())) {
spec = spec.and(AppBookSpecification.unshelved());
}
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
return buildPageResponse(bookPage, userId, pageNum, pageSize);
@@ -152,7 +187,7 @@ public class AppBookService {
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
Map<Long, BookEntity> enrichedMap = bookRepository.findAllById(topIds)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
return topIds.stream()
@@ -175,7 +210,7 @@ public class AppBookService {
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
Map<Long, BookEntity> enrichedMap = bookRepository.findAllById(topIds)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
return topIds.stream()
@@ -271,18 +306,21 @@ public class AppBookService {
var booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, pageNum, pageSize);
Set<Long> bookIds = booksPage.getContent().stream()
List<Long> orderedBookIds = booksPage.getContent().stream()
.map(Book::getId)
.collect(Collectors.toSet());
.toList();
if (bookIds.isEmpty()) {
if (orderedBookIds.isEmpty()) {
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
}
List<BookEntity> bookEntities = bookRepository.findAllForSummaryByIds(bookIds);
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, bookEntities);
Map<Long, BookEntity> bookEntitiesById = bookRepository.findAllById(orderedBookIds).stream()
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookEntitiesById.keySet());
List<AppBookSummary> summaries = bookEntities.stream()
List<AppBookSummary> summaries = orderedBookIds.stream()
.map(bookEntitiesById::get)
.filter(Objects::nonNull)
.filter(BookEntity::hasFiles)
.map(bookEntity -> mobileBookMapper.toSummary(bookEntity, progressMap.get(bookEntity.getId())))
.collect(Collectors.toList());
@@ -295,20 +333,6 @@ public class AppBookService {
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
// Resolve magic shelf to a set of book IDs if requested
Set<Long> magicBookIds = null;
if (magicShelfId != null) {
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
if (magicBookIds.isEmpty()) {
return AppFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
.readStatuses(getReadStatusOptions())
.build();
}
}
// Validate library access
if (libraryId != null && accessibleLibraryIds != null && !accessibleLibraryIds.contains(libraryId)) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
@@ -323,6 +347,34 @@ public class AppBookService {
}
}
// Cache lookup avoid re-running 9 aggregate queries within the TTL window
String cacheKey = userId + ":" + libraryId + ":" + shelfId + ":" + magicShelfId;
AppFilterOptions cached = filterOptionsCache.getIfPresent(cacheKey);
if (cached != null) {
return cached;
}
Set<Long> magicBookIds = null;
if (magicShelfId != null) {
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
if (magicBookIds.isEmpty()) {
AppFilterOptions empty = AppFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
.readStatuses(getReadStatusOptions())
.categories(Collections.emptyList())
.publishers(Collections.emptyList())
.series(Collections.emptyList())
.tags(Collections.emptyList())
.moods(Collections.emptyList())
.narrators(Collections.emptyList())
.build();
filterOptionsCache.put(cacheKey, empty);
return empty;
}
}
// Build scoping clauses
String libraryClause = "";
String shelfClause = "";
@@ -343,44 +395,20 @@ public class AppBookService {
// Build the optional WHERE suffix once — each clause already starts with "AND"
String scopeClause = buildScopeClause(libraryClause, shelfClause, magicBookClause);
// Authors with book count (top 200 by count)
String authorQuery = "SELECT a.name, COUNT(DISTINCT b.id) FROM BookEntity b"
+ " JOIN b.metadata m JOIN m.authors a"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ scopeClause
+ " GROUP BY a.name ORDER BY COUNT(DISTINCT b.id) DESC";
var authorQ = entityManager.createQuery(authorQuery, Tuple.class);
setFilterQueryParams(authorQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
authorQ.setMaxResults(200);
List<AppFilterOptions.CountedOption> authors = queryCountedOptions(
"a.name", "JOIN b.metadata m JOIN m.authors a", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.AuthorOption> authors = authorQ.getResultList().stream()
.map(t -> AppFilterOptions.AuthorOption.builder()
.name(t.get(0, String.class))
.count(t.get(1, Long.class))
.build())
List<AppFilterOptions.LanguageOption> languages = queryCountedOptions(
"m.language", "JOIN b.metadata m",
"AND m.language IS NOT NULL AND m.language <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds).stream()
.map(c -> new AppFilterOptions.LanguageOption(
c.name(),
Locale.forLanguageTag(c.name()).getDisplayLanguage(Locale.ENGLISH),
c.count()))
.toList();
// Languages with book count
String langQuery = "SELECT m.language, COUNT(DISTINCT b.id) FROM BookEntity b"
+ " JOIN b.metadata m"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ " AND m.language IS NOT NULL AND m.language <> ''"
+ scopeClause
+ " GROUP BY m.language ORDER BY COUNT(DISTINCT b.id) DESC";
var langQ = entityManager.createQuery(langQuery, Tuple.class);
setFilterQueryParams(langQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.LanguageOption> languages = langQ.getResultList().stream()
.map(t -> AppFilterOptions.LanguageOption.builder()
.code(t.get(0, String.class))
.label(Locale.forLanguageTag(t.get(0, String.class)).getDisplayLanguage(Locale.ENGLISH))
.count(t.get(1, Long.class))
.build())
.toList();
// Distinct file types present in scoped books
String fileTypeQuery = "SELECT DISTINCT bf.bookType FROM BookEntity b"
+ " JOIN b.bookFiles bf"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
@@ -389,21 +417,68 @@ public class AppBookService {
+ scopeClause;
var ftQ = entityManager.createQuery(fileTypeQuery, BookFileType.class);
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<String> fileTypes = ftQ.getResultList().stream().map(Enum::name).sorted().toList();
List<String> fileTypes = ftQ.getResultList().stream()
.map(Enum::name)
.sorted()
.toList();
List<AppFilterOptions.CountedOption> categories = queryCountedOptions(
"c.name", "JOIN b.metadata m JOIN m.categories c", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
// Read statuses — return all meaningful values
List<String> readStatuses = getReadStatusOptions();
List<AppFilterOptions.CountedOption> publishers = queryCountedOptions(
"m.publisher", "JOIN b.metadata m",
"AND m.publisher IS NOT NULL AND m.publisher <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
return AppFilterOptions.builder()
List<AppFilterOptions.CountedOption> seriesOptions = queryCountedOptions(
"m.seriesName", "JOIN b.metadata m",
"AND m.seriesName IS NOT NULL AND m.seriesName <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> tags = queryCountedOptions(
"t.name", "JOIN b.metadata m JOIN m.tags t", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> moods = queryCountedOptions(
"mo.name", "JOIN b.metadata m JOIN m.moods mo", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> narrators = queryCountedOptions(
"m.narrator", "JOIN b.metadata m",
"AND m.narrator IS NOT NULL AND m.narrator <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
AppFilterOptions result = AppFilterOptions.builder()
.authors(authors)
.languages(languages)
.fileTypes(fileTypes)
.readStatuses(readStatuses)
.readStatuses(getReadStatusOptions())
.categories(categories)
.publishers(publishers)
.series(seriesOptions)
.tags(tags)
.moods(moods)
.narrators(narrators)
.build();
filterOptionsCache.put(cacheKey, result);
return result;
}
private List<AppFilterOptions.CountedOption> queryCountedOptions(
String selectExpr, String joins, String extraWhere,
String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
String jpql = "SELECT " + selectExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b"
+ " " + joins
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ (extraWhere.isEmpty() ? "" : " " + extraWhere)
+ scopeClause
+ " GROUP BY " + selectExpr + " ORDER BY COUNT(DISTINCT b.id) DESC";
var q = entityManager.createQuery(jpql, Tuple.class);
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
q.setMaxResults(200);
return q.getResultList().stream()
.map(t -> new AppFilterOptions.CountedOption(t.get(0, String.class), t.get(1, Long.class)))
.toList();
}
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
@@ -429,12 +504,14 @@ public class AppBookService {
}
private Set<Long> resolveMagicShelfBookIds(Long magicShelfId, Long userId) {
// Reuse MagicShelfBookService which already handles access validation,
// rule evaluation, and library filtering.
var booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, 0, 10000);
return booksPage.getContent().stream()
.map(Book::getId)
.collect(Collectors.toSet());
Specification<BookEntity> spec = magicShelfBookService.toSpecification(userId, magicShelfId);
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<BookEntity> root = cq.from(BookEntity.class);
cq.select(root.get("id"));
cq.where(spec.toPredicate(root, cq, cb));
return new HashSet<>(entityManager.createQuery(cq)
.getResultList());
}
private List<String> getReadStatusOptions() {
@@ -519,68 +596,108 @@ public class AppBookService {
private Specification<BookEntity> buildSpecification(
Set<Long> accessibleLibraryIds,
Long libraryId,
Long shelfId,
ReadStatus status,
String search,
Long userId,
BookFileType fileType,
Integer minRating,
Integer maxRating,
String authors,
String language) {
BookListRequest req) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(AppBookSpecification.notDeleted());
specs.add(AppBookSpecification.hasDigitalFile());
if (accessibleLibraryIds != null) {
if (libraryId != null && accessibleLibraryIds.contains(libraryId)) {
specs.add(AppBookSpecification.inLibrary(libraryId));
} else if (libraryId != null) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
if (req.libraryId() != null && accessibleLibraryIds.contains(req.libraryId())) {
specs.add(AppBookSpecification.inLibrary(req.libraryId()));
} else if (req.libraryId() != null) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + req.libraryId());
} else {
specs.add(AppBookSpecification.inLibraries(accessibleLibraryIds));
}
} else if (libraryId != null) {
specs.add(AppBookSpecification.inLibrary(libraryId));
} else if (req.libraryId() != null) {
specs.add(AppBookSpecification.inLibrary(req.libraryId()));
}
if (shelfId != null) {
ShelfEntity shelf = shelfRepository.findById(shelfId)
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
if (req.shelfId() != null) {
ShelfEntity shelf = shelfRepository.findById(req.shelfId())
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(req.shelfId()));
if (!shelf.isPublic() && !shelf.getUser().getId().equals(userId)) {
throw ApiError.FORBIDDEN.createException("Access denied to shelf " + shelfId);
throw ApiError.FORBIDDEN.createException("Access denied to shelf " + req.shelfId());
}
specs.add(AppBookSpecification.inShelf(shelfId));
specs.add(AppBookSpecification.inShelf(req.shelfId()));
}
if (status != null) {
specs.add(AppBookSpecification.withReadStatus(status, userId));
if (req.status() != null) {
specs.add(AppBookSpecification.withReadStatus(req.status(), userId));
}
if (search != null && !search.trim().isEmpty()) {
specs.add(AppBookSpecification.searchText(search));
if (req.search() != null && !req.search().trim().isEmpty()) {
specs.add(AppBookSpecification.searchText(req.search()));
}
if (fileType != null) {
specs.add(AppBookSpecification.withFileType(fileType));
if (req.fileType() != null) {
specs.add(AppBookSpecification.withFileType(req.fileType()));
}
if (minRating != null) {
specs.add(AppBookSpecification.withMinRating(minRating, userId));
if (req.minRating() != null) {
specs.add(AppBookSpecification.withMinRating(req.minRating(), userId));
}
if (maxRating != null) {
specs.add(AppBookSpecification.withMaxRating(maxRating, userId));
if (req.maxRating() != null) {
specs.add(AppBookSpecification.withMaxRating(req.maxRating(), userId));
}
if (authors != null && !authors.trim().isEmpty()) {
specs.add(AppBookSpecification.withAuthor(authors.trim()));
if (req.authors() != null && !req.authors().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.authors());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withAuthors(cleaned, req.effectiveFilterMode()));
}
}
if (language != null && !language.trim().isEmpty()) {
specs.add(AppBookSpecification.withLanguage(language.trim()));
if (req.language() != null && !req.language().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.language());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withLanguages(cleaned, req.effectiveFilterMode()));
}
}
if (req.series() != null && !req.series().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.series());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.inSeriesMulti(cleaned, req.effectiveFilterMode()));
}
}
if (req.category() != null && !req.category().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.category());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withCategories(cleaned, req.effectiveFilterMode()));
}
}
if (req.publisher() != null && !req.publisher().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.publisher());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withPublishers(cleaned, req.effectiveFilterMode()));
}
}
if (req.tag() != null && !req.tag().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.tag());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withTags(cleaned, req.effectiveFilterMode()));
}
}
if (req.mood() != null && !req.mood().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.mood());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withMoods(cleaned, req.effectiveFilterMode()));
}
}
if (req.narrator() != null && !req.narrator().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.narrator());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withNarrators(cleaned, req.effectiveFilterMode()));
}
}
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
@@ -591,10 +708,17 @@ public class AppBookService {
? Sort.Direction.ASC
: Sort.Direction.DESC;
// "author" needs a join to the authors collection, which can't be expressed
// as a simple property path, fall through to the default (addedOn) for now.
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
case "title" -> "metadata.title";
case "seriesname", "series" -> "metadata.seriesName";
case "lastreadtime" -> "addedOn";
case "seriesnumber" -> "metadata.seriesNumber";
case "publisher" -> "metadata.publisher";
case "language" -> "metadata.language";
case "publisheddate" -> "metadata.publishedDate";
case "lastreadtime" -> "lastReadTime";
case "pagecount" -> "metadata.pageCount";
default -> "addedOn";
};
@@ -638,25 +762,16 @@ public class AppBookService {
int pageNum,
int pageSize) {
List<BookEntity> enriched = enrichBooksForSummary(bookPage.getContent());
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, enriched);
List<BookEntity> books = bookPage.getContent();
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, books);
List<AppBookSummary> summaries = enriched.stream()
List<AppBookSummary> summaries = books.stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList());
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
}
private List<BookEntity> enrichBooksForSummary(List<BookEntity> books) {
if (books.isEmpty()) return books;
Set<Long> ids = books.stream().map(BookEntity::getId).collect(Collectors.toSet());
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(ids)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
return books.stream()
.map(b -> enrichedMap.getOrDefault(b.getId(), b))
.collect(Collectors.toList());
}
private Map<Long, UserBookProgressEntity> getProgressMapForBooks(Long userId, List<BookEntity> books) {
if (books.isEmpty()) {
@@ -17,6 +17,16 @@ public class AppBookSpecification {
private AppBookSpecification() {
}
@SuppressWarnings("unchecked")
private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) {
for (Join<X, ?> join : from.getJoins()) {
if (join.getAttribute().getName().equals(attribute) && join.getJoinType() == joinType) {
return (Join<X, Y>) join;
}
}
return from.join(attribute, joinType);
}
public static Specification<BookEntity> inLibraries(Collection<Long> libraryIds) {
return (root, query, cb) -> {
if (libraryIds == null || libraryIds.isEmpty()) {
@@ -92,16 +102,22 @@ public class AppBookSpecification {
String pattern = "%" + searchQuery.toLowerCase().trim() + "%";
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
Join<BookMetadataEntity, AuthorEntity> authorsJoin = metadataJoin.join("authors", JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.like(cb.lower(metadataJoin.get("title")), pattern));
predicates.add(cb.like(cb.lower(metadataJoin.get("seriesName")), pattern));
predicates.add(cb.like(cb.lower(authorsJoin.get("name")), pattern));
// Use EXISTS subquery for author search to avoid DISTINCT and cartesian products
Subquery<Long> authorSubquery = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = authorSubquery.from(BookMetadataEntity.class);
Join<BookMetadataEntity, AuthorEntity> authorJoin = metaRoot.join("authors", JoinType.INNER);
authorSubquery.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.like(cb.lower(authorJoin.get("name")), pattern)
);
query.distinct(true);
return cb.or(predicates.toArray(new Predicate[0]));
return cb.or(
cb.like(cb.lower(metadataJoin.get("title")), pattern),
cb.like(cb.lower(metadataJoin.get("seriesName")), pattern),
cb.exists(authorSubquery)
);
};
}
@@ -206,14 +222,22 @@ public class AppBookSpecification {
* Filter books by author name (case-insensitive exact match).
*/
public static Specification<BookEntity> withAuthor(String authorName) {
return withAuthors(authorName == null ? List.of() : List.of(authorName), "or");
}
/**
* Filter books by multiple author names with mode support.
* OR = books with ANY of the authors
* AND = books with ALL of the authors
* NOT = books with NONE of the authors
*/
public static Specification<BookEntity> withAuthors(List<String> authorNames, String mode) {
return (root, query, cb) -> {
if (authorName == null || authorName.trim().isEmpty()) {
return cb.conjunction();
}
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
Join<BookMetadataEntity, AuthorEntity> authorsJoin = metadataJoin.join("authors", JoinType.LEFT);
query.distinct(true);
return cb.equal(cb.lower(authorsJoin.get("name")), authorName.toLowerCase().trim());
List<String> cleaned = cleanLowerCase(authorNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "authors", "name");
};
}
@@ -221,25 +245,203 @@ public class AppBookSpecification {
* Filter books by language code (case-insensitive).
*/
public static Specification<BookEntity> withLanguage(String language) {
return withLanguages(language == null ? List.of() : List.of(language), "or");
}
/**
* Filter books by multiple language codes with mode support.
*/
public static Specification<BookEntity> withLanguages(List<String> languages, String mode) {
return (root, query, cb) -> {
if (language == null || language.trim().isEmpty()) {
return cb.conjunction();
}
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
return cb.equal(cb.lower(metadataJoin.get("language")), language.toLowerCase().trim());
List<String> cleaned = cleanLowerCase(languages);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "language");
};
}
public static Specification<BookEntity> inSeries(String seriesName) {
return inSeriesMulti(seriesName == null ? List.of() : List.of(seriesName), "or");
}
/**
* Filter books by multiple series names with mode support.
*/
public static Specification<BookEntity> inSeriesMulti(List<String> seriesNames, String mode) {
return (root, query, cb) -> {
if (seriesName == null || seriesName.trim().isEmpty()) {
return cb.conjunction();
}
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
return cb.equal(metadataJoin.get("seriesName"), seriesName);
List<String> cleaned = cleanLowerCase(seriesNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "seriesName");
};
}
public static Specification<BookEntity> withCategory(String categoryName) {
return withCategories(categoryName == null ? List.of() : List.of(categoryName), "or");
}
/**
* Filter books by multiple categories with mode support.
*/
public static Specification<BookEntity> withCategories(List<String> categoryNames, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(categoryNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "categories", "name");
};
}
public static Specification<BookEntity> withPublisher(String publisher) {
return withPublishers(publisher == null ? List.of() : List.of(publisher), "or");
}
/**
* Filter books by multiple publishers with mode support.
*/
public static Specification<BookEntity> withPublishers(List<String> publishers, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(publishers);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "publisher");
};
}
public static Specification<BookEntity> withTag(String tagName) {
return withTags(tagName == null ? List.of() : List.of(tagName), "or");
}
/**
* Filter books by multiple tags with mode support.
*/
public static Specification<BookEntity> withTags(List<String> tagNames, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(tagNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "tags", "name");
};
}
public static Specification<BookEntity> withMood(String moodName) {
return withMoods(moodName == null ? List.of() : List.of(moodName), "or");
}
/**
* Filter books by multiple moods with mode support.
*/
public static Specification<BookEntity> withMoods(List<String> moodNames, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(moodNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "moods", "name");
};
}
public static Specification<BookEntity> withNarrator(String narrator) {
return withNarrators(narrator == null ? List.of() : List.of(narrator), "or");
}
/**
* Filter books by multiple narrators with mode support.
*/
public static Specification<BookEntity> withNarrators(List<String> narrators, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(narrators);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "narrator");
};
}
public static Specification<BookEntity> unshelved() {
return (root, query, cb) -> {
Subquery<Long> subquery = query.subquery(Long.class);
Root<BookEntity> subRoot = subquery.correlate(root);
Join<BookEntity, ShelfEntity> shelvesJoin = subRoot.join("shelves", JoinType.INNER);
subquery.select(cb.literal(1L));
return cb.not(cb.exists(subquery));
};
}
private static List<String> cleanLowerCase(List<String> values) {
if (values == null) return List.of();
return values.stream()
.filter(s -> s != null && !s.isBlank())
.map(s -> s.trim().toLowerCase())
.toList();
}
/**
* Builds a specification for a scalar field on BookMetadataEntity (language, seriesName, publisher, narrator).
* OR = metadata field IN (values)
* AND = impossible for scalar fields with multiple values (treated as OR since a scalar can only be one value)
* NOT = metadata field NOT IN (values)
*/
private static Predicate buildMetadataFieldSpec(
Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
List<String> values, String mode, String fieldName) {
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
Expression<String> fieldExpr = cb.lower(metadataJoin.get(fieldName));
if ("not".equals(mode)) {
return fieldExpr.in(values).not();
}
// Both "or" and "and" use IN for scalar fields (a single field can only match one value)
return fieldExpr.in(values);
}
/**
* Builds a specification for a many-to-many collection (authors, categories, tags, moods).
* Uses EXISTS subqueries to avoid DISTINCT and cartesian product issues.
*
* OR = book has at least one related entity whose name is IN (values)
* AND = book has ALL of the named entities (one EXISTS per value)
* NOT = book has NONE of the named entities
*/
private static Predicate buildManyToManySpec(
Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
List<String> values, String mode,
String metadataAttr, String collectionAttr, String nameAttr) {
if ("and".equals(mode)) {
// AND: book must have ALL values one EXISTS subquery per value
List<Predicate> predicates = new ArrayList<>();
for (String value : values) {
Subquery<Long> sub = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
Join<?, ?> collJoin = metaRoot.join(collectionAttr, JoinType.INNER);
sub.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.equal(cb.lower(collJoin.get(nameAttr)), value)
);
predicates.add(cb.exists(sub));
}
return cb.and(predicates.toArray(new Predicate[0]));
}
// OR or NOT: single EXISTS subquery with IN clause
Subquery<Long> sub = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
Join<?, ?> collJoin = metaRoot.join(collectionAttr, JoinType.INNER);
sub.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.lower(collJoin.get(nameAttr)).in(values)
);
if ("not".equals(mode)) {
return cb.not(cb.exists(sub));
}
return cb.exists(sub);
}
@SafeVarargs
public static Specification<BookEntity> combine(Specification<BookEntity>... specs) {
Specification<BookEntity> result = (root, query, cb) -> cb.conjunction();
@@ -23,6 +23,7 @@ import java.util.Set;
@AllArgsConstructor
@DynamicUpdate
@Table(name = "book_metadata")
@BatchSize(size = 20)
public class BookMetadataEntity {
@Id
@@ -9,7 +9,7 @@ import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.model.enums.MetadataSource;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import java.util.*;
@Entity
@@ -19,6 +19,7 @@ import java.util.*;
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "library")
@BatchSize(size = 20)
public class LibraryEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -33,12 +33,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdFull(@Param("id") Long id);
// Minimal graph for summary mapping: metadata (OneToOne), library (ManyToOne), bookFiles (OneToMany).
// metadata.authors is intentionally excluded — @BatchSize on BookMetadataEntity.authors
// triggers a batched query when first accessed, so no N+1 occurs.
@EntityGraph(attributePaths = { "metadata", "library", "bookFiles" })
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllForSummaryByIds(@Param("bookIds") Collection<Long> bookIds);
@EntityGraph(attributePaths = {"bookFiles", "metadata", "library", "libraryPath"})
@Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
@@ -21,10 +21,12 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Slf4j
@RequiredArgsConstructor
@Service
@@ -33,12 +35,14 @@ public class IconService {
private static final Pattern INVALID_FILENAME_CHARS_PATTERN = Pattern.compile("[^a-zA-Z0-9._-]");
private final AppProperties appProperties;
private final ConcurrentHashMap<String, String> svgCache = new ConcurrentHashMap<>();
private final Cache<String, String> svgCache = Caffeine.newBuilder()
.maximumSize(200)
.expireAfterAccess(java.time.Duration.ofHours(1))
.build();
private static final String ICONS_DIR = "icons";
private static final String SVG_DIR = "svg";
private static final String SVG_EXTENSION = ".svg";
private static final int MAX_CACHE_SIZE = 200;
private static final String SVG_START_TAG = "<svg";
private static final String XML_DECLARATION = "<?xml";
private static final String SVG_END_TAG = "</svg>";
@@ -109,7 +113,7 @@ public class IconService {
public String getSvgIcon(String name) {
String filename = normalizeFilename(name);
String cachedSvg = svgCache.get(filename);
String cachedSvg = svgCache.getIfPresent(filename);
if (cachedSvg != null) {
return cachedSvg;
@@ -146,7 +150,7 @@ public class IconService {
}
Files.delete(filePath);
svgCache.remove(filename);
svgCache.invalidate(filename);
log.info("SVG icon deleted successfully: {}", filename);
} catch (IOException e) {
@@ -192,10 +196,6 @@ public class IconService {
}
private void updateCache(String filename, String content) {
if (!svgCache.containsKey(filename) && svgCache.size() >= MAX_CACHE_SIZE) {
String firstKey = svgCache.keys().nextElement();
svgCache.remove(firstKey);
}
svgCache.put(filename, content);
}
@@ -236,7 +236,7 @@ public class IconService {
return sanitized.endsWith(SVG_EXTENSION) ? sanitized : sanitized + SVG_EXTENSION;
}
ConcurrentHashMap<String, String> getSvgCache() {
Cache<String, String> getSvgCache() {
return svgCache;
}
@@ -256,7 +256,14 @@ public class IconService {
try {
String filename = path.getFileName().toString();
String iconName = filename.replace(SVG_EXTENSION, "");
String content = svgCache.getOrDefault(filename, Files.readString(path));
String cached = svgCache.getIfPresent(filename);
String content;
if (cached != null) {
content = cached;
} else {
content = Files.readString(path);
svgCache.put(filename, content);
}
iconMap.put(iconName, content);
} catch (IOException e) {
log.warn("Failed to read icon: {}", path.getFileName(), e);
@@ -30,7 +30,7 @@ public class FilenamePatternExtractor {
private static final Pattern PATTERN = Pattern.compile("[,;&]");
private final BookdropFileRepository bookdropFileRepository;
private final BookdropMetadataHelper metadataHelper;
private final ExecutorService regexExecutor;
private final ExecutorService regexExecutor = Executors.newVirtualThreadPerTaskExecutor();
private static final int PREVIEW_FILE_LIMIT = 5;
private static final long REGEX_TIMEOUT_SECONDS = 5;
@@ -26,6 +26,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.databind.ObjectMapper;
import org.booklore.exception.APIException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -44,13 +46,12 @@ public class MagicShelfBookService {
private final ContentRestrictionService contentRestrictionService;
private final ObjectMapper objectMapper;
private record ShelfAccess(MagicShelfEntity shelf, BookLoreUserEntity user) {}
@Transactional(readOnly = true)
public Page<Book> getBooksByMagicShelfId(Long userId, Long magicShelfId, int page, int size) {
MagicShelfEntity shelf = validateMagicShelfAccess(userId, magicShelfId);
Specification<BookEntity> specification = toSpecification(userId, magicShelfId);
try {
GroupRule groupRule = objectMapper.readValue(shelf.getFilterJson(), GroupRule.class);
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
specification = specification.and(createLibraryFilterSpecification(userId));
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
@@ -61,27 +62,45 @@ public class MagicShelfBookService {
.map(book -> filterBook(book, userId))
.toList();
return new PageImpl<>(books, pageable, booksPage.getTotalElements());
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Failed to parse or execute magic shelf rules", e);
throw new RuntimeException("Failed to parse or execute magic shelf rules: " + e.getMessage(), e);
}
}
public Specification<BookEntity> toSpecification(Long userId, Long magicShelfId) {
ShelfAccess access = validateMagicShelfAccess(userId, magicShelfId);
try {
GroupRule groupRule = objectMapper.readValue(access.shelf().getFilterJson(), GroupRule.class);
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
return specification.and(createLibraryFilterSpecification(access.user()));
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Failed to parse magic shelf rules", e);
throw new RuntimeException("Failed to parse magic shelf rules: " + e.getMessage(), e);
}
}
public List<Long> getBookIdsByMagicShelfId(Long userId, Long magicShelfId) {
return getBookIdsByMagicShelfId(userId, magicShelfId, Integer.MAX_VALUE);
}
public List<Long> getBookIdsByMagicShelfId(Long userId, Long magicShelfId, int limit) {
MagicShelfEntity shelf = validateMagicShelfAccess(userId, magicShelfId);
ShelfAccess access = validateMagicShelfAccess(userId, magicShelfId);
try {
GroupRule groupRule = objectMapper.readValue(shelf.getFilterJson(), GroupRule.class);
GroupRule groupRule = objectMapper.readValue(access.shelf().getFilterJson(), GroupRule.class);
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
specification = specification.and(createLibraryFilterSpecification(userId));
specification = specification.and(createLibraryFilterSpecification(access.user()));
Pageable pageable = PageRequest.of(0, limit);
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
List<BookEntity> filtered = contentRestrictionService.applyRestrictions(booksPage.getContent(), userId);
return filtered.stream().map(BookEntity::getId).toList();
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Failed to parse or execute magic shelf rules", e);
throw new RuntimeException("Failed to parse or execute magic shelf rules: " + e.getMessage(), e);
@@ -94,7 +113,7 @@ public class MagicShelfBookService {
.orElse("Magic Shelf Books");
}
private MagicShelfEntity validateMagicShelfAccess(Long userId, Long magicShelfId) {
private ShelfAccess validateMagicShelfAccess(Long userId, Long magicShelfId) {
MagicShelfEntity shelf = magicShelfRepository.findById(magicShelfId)
.orElseThrow(() -> ApiError.MAGIC_SHELF_NOT_FOUND.createException(magicShelfId));
@@ -102,7 +121,7 @@ public class MagicShelfBookService {
if (!shelf.isPublic()) {
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
}
return shelf;
return new ShelfAccess(shelf, null);
}
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
@@ -121,26 +140,25 @@ public class MagicShelfBookService {
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
}
return shelf;
return new ShelfAccess(shelf, entity);
}
private Specification<BookEntity> createLibraryFilterSpecification(Long userId) {
return (root, query, cb) -> {
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
private Specification<BookEntity> createLibraryFilterSpecification(BookLoreUserEntity entity) {
if (entity == null) {
return (root, query, cb) -> cb.conjunction();
}
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
if (user.getPermissions() != null && user.getPermissions().isAdmin()) {
return cb.conjunction();
}
if (user.getPermissions() != null && user.getPermissions().isAdmin()) {
return (root, query, cb) -> cb.conjunction();
}
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
return root.get("library").get("id").in(userLibraryIds);
};
return (root, query, cb) -> root.get("library").get("id").in(userLibraryIds);
}
private Book filterBook(Book dto, Long userId) {
@@ -19,36 +19,38 @@ import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Slf4j
@Service
@RequiredArgsConstructor
public class PdfReaderService {
private static final int MAX_CACHE_ENTRIES = 50;
private static final int MAX_CACHE_ENTRIES = 15;
private static final float DEFAULT_DPI = 200f;
private final BookRepository bookRepository;
private final Map<String, CachedPdfMetadata> metadataCache = new ConcurrentHashMap<>();
private final Cache<String, CachedPdfMetadata> metadataCache = Caffeine.newBuilder()
.maximumSize(MAX_CACHE_ENTRIES)
.expireAfterAccess(Duration.ofMinutes(30))
.build();
private static class CachedPdfMetadata {
final int pageCount;
final long lastModified;
final List<PdfOutlineItem> outline;
volatile long lastAccessed;
CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {
this.pageCount = pageCount;
this.lastModified = lastModified;
this.outline = outline;
this.lastAccessed = System.currentTimeMillis();
}
}
@@ -120,16 +122,14 @@ public class PdfReaderService {
private CachedPdfMetadata getCachedMetadata(Path pdfPath) throws IOException {
String cacheKey = pdfPath.toString();
long currentModified = Files.getLastModifiedTime(pdfPath).toMillis();
CachedPdfMetadata cached = metadataCache.get(cacheKey);
CachedPdfMetadata cached = metadataCache.getIfPresent(cacheKey);
if (cached != null && cached.lastModified == currentModified) {
cached.lastAccessed = System.currentTimeMillis();
log.debug("Cache hit for PDF: {}", pdfPath.getFileName());
return cached;
}
log.debug("Cache miss for PDF: {}, scanning...", pdfPath.getFileName());
CachedPdfMetadata newMetadata = scanPdfMetadata(pdfPath);
metadataCache.put(cacheKey, newMetadata);
evictOldestCacheEntries();
return newMetadata;
}
@@ -190,21 +190,6 @@ public class PdfReaderService {
}
}
private void evictOldestCacheEntries() {
if (metadataCache.size() <= MAX_CACHE_ENTRIES) {
return;
}
List<String> keysToRemove = metadataCache.entrySet().stream()
.sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed))
.limit(metadataCache.size() - MAX_CACHE_ENTRIES)
.map(Map.Entry::getKey)
.toList();
keysToRemove.forEach(key -> {
metadataCache.remove(key);
log.debug("Evicted cache entry: {}", key);
});
}
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
// page is 1-based from the API, renderPageToBytes expects 0-based
@@ -12,11 +12,13 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tools.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.time.Duration;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@RequiredArgsConstructor
@Service
@@ -26,25 +28,28 @@ public class DefaultSettingInitializer {
private final UserRepository userRepository;
private final ObjectMapper objectMapper;
private final DefaultUserSettingsProvider settingsProvider;
private static final Set<Long> initializedUsers = Collections.newSetFromMap(new ConcurrentHashMap<>());
private static final Cache<Long, Boolean> initializedUsers = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(Duration.ofHours(24))
.build();
private static final ConcurrentHashMap<Long, Lock> userLocks = new ConcurrentHashMap<>();
@Transactional
public void ensureDefaultSettings(BookLoreUser bookLoreUser) {
if (initializedUsers.contains(bookLoreUser.getId())) {
if (initializedUsers.getIfPresent(bookLoreUser.getId()) != null) {
return;
}
Lock lock = userLocks.computeIfAbsent(bookLoreUser.getId(), _ -> new ReentrantLock());
lock.lock();
try {
if (initializedUsers.contains(bookLoreUser.getId())) return;
if (initializedUsers.getIfPresent(bookLoreUser.getId()) != null) return;
BookLoreUserEntity user = userRepository.findByIdWithSettings(bookLoreUser.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (UserSettingKey key : settingsProvider.getAllKeys()) {
addSettingIfMissing(user, key, settingsProvider.getDefaultValue(key));
}
patchPerBookSetting(user);
userRepository.save(user);
initializedUsers.add(bookLoreUser.getId());
initializedUsers.put(bookLoreUser.getId(), Boolean.TRUE);
} finally {
lock.unlock();
userLocks.remove(bookLoreUser.getId());
@@ -90,4 +95,3 @@ public class DefaultSettingInitializer {
});
}
}
@@ -1,25 +1,29 @@
package org.booklore.task;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.time.Duration;
@Component
public class TaskCancellationManager {
private final Set<String> cancelledTasks = ConcurrentHashMap.newKeySet();
private final Cache<String, Boolean> cancelledTasks = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofHours(24))
.build();
public void cancelTask(String taskId) {
cancelledTasks.add(taskId);
cancelledTasks.put(taskId, Boolean.TRUE);
}
public boolean isTaskCancelled(String taskId) {
return cancelledTasks.contains(taskId);
return cancelledTasks.getIfPresent(taskId) != null;
}
public void clearCancellation(String taskId) {
cancelledTasks.remove(taskId);
cancelledTasks.invalidate(taskId);
}
}
@@ -23,7 +23,6 @@ public class EpubCfiService {
this.documentCache = Caffeine.newBuilder()
.maximumSize(10)
.expireAfterAccess(Duration.ofMinutes(5))
.softValues()
.build();
}
@@ -66,8 +66,8 @@ spring:
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
connection-test-query: SELECT 1
connection-timeout: 30000 # 30s to acquire a connection before timeout
maximum-pool-size: 10 # Virtual threads don't need large pools
minimum-idle: 2 # Minimal warm connections; virtual threads handle bursts
maximum-pool-size: 5 # Virtual threads don't need large pools; 5 is enough for a self-hosted app
minimum-idle: 1 # Minimal warm connections; virtual threads handle bursts
idle-timeout: 300000 # 5 minutes before idle connections are closed
jpa:
open-in-view: false
@@ -0,0 +1,16 @@
-- Indexes for filterable columns used by AppBookSpecification.
-- All additive; safe to run on existing data without downtime.
CREATE INDEX IF NOT EXISTS idx_author_name ON author (name);
CREATE INDEX IF NOT EXISTS idx_book_metadata_language ON book_metadata (language);
CREATE INDEX IF NOT EXISTS idx_book_metadata_publisher ON book_metadata (publisher);
CREATE INDEX IF NOT EXISTS idx_book_metadata_series_name ON book_metadata (series_name);
CREATE INDEX IF NOT EXISTS idx_book_metadata_narrator ON book_metadata (narrator);
CREATE INDEX IF NOT EXISTS idx_category_name ON category (name);
CREATE INDEX IF NOT EXISTS idx_tag_name ON tag (name);
CREATE INDEX IF NOT EXISTS idx_mood_name ON mood (name);
-- Composite index for personal-rating filter subqueries
CREATE INDEX IF NOT EXISTS idx_user_book_progress_rating ON user_book_progress (user_id, personal_rating, book_id);
@@ -43,8 +43,8 @@ class AppFilterControllerTest {
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(5L, null, null);
assertEquals(200, response.getStatusCode().value());
assertEquals(1, response.getBody().getAuthors().size());
assertEquals("Author B", response.getBody().getAuthors().getFirst().getName());
assertEquals(1, response.getBody().authors().size());
assertEquals("Author B", response.getBody().authors().getFirst().name());
verify(mobileBookService).getFilterOptions(5L, null, null);
}
@@ -56,7 +56,7 @@ class AppFilterControllerTest {
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, 10L, null);
assertEquals(200, response.getStatusCode().value());
assertTrue(response.getBody().getAuthors().isEmpty());
assertTrue(response.getBody().authors().isEmpty());
verify(mobileBookService).getFilterOptions(null, 10L, null);
}
@@ -68,16 +68,16 @@ class AppFilterControllerTest {
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, null, 7L);
assertEquals(200, response.getStatusCode().value());
assertEquals("Author C", response.getBody().getAuthors().getFirst().getName());
assertEquals("Author C", response.getBody().authors().getFirst().name());
verify(mobileBookService).getFilterOptions(null, null, 7L);
}
private AppFilterOptions buildOptions(List<String> authorNames, List<String> fileTypes, List<String> langCodes) {
List<AppFilterOptions.AuthorOption> authors = authorNames.stream()
.map(name -> AppFilterOptions.AuthorOption.builder().name(name).count(1L).build())
List<AppFilterOptions.CountedOption> authors = authorNames.stream()
.map(name -> new AppFilterOptions.CountedOption(name, 1L))
.toList();
List<AppFilterOptions.LanguageOption> languages = langCodes.stream()
.map(code -> AppFilterOptions.LanguageOption.builder().code(code).label(code).count(1L).build())
.map(code -> new AppFilterOptions.LanguageOption(code, code, 1L))
.toList();
return AppFilterOptions.builder()
.authors(authors)
@@ -7,10 +7,10 @@ import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.ShelfEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
@@ -25,9 +25,12 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -75,10 +78,10 @@ class AppBookServiceFilterOptionsTest {
AppFilterOptions result = service.getFilterOptions(null, null, null);
assertNotNull(result);
assertNotNull(result.getAuthors());
assertNotNull(result.getLanguages());
assertNotNull(result.getFileTypes());
assertFalse(result.getReadStatuses().isEmpty());
assertNotNull(result.authors());
assertNotNull(result.languages());
assertNotNull(result.fileTypes());
assertFalse(result.readStatuses().isEmpty());
}
// -------------------------------------------------------------------------
@@ -93,7 +96,7 @@ class AppBookServiceFilterOptionsTest {
AppFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
verify(entityManager, times(3)).createQuery(anyString(), any(Class.class));
verify(entityManager, times(9)).createQuery(anyString(), any(Class.class));
}
@Test
@@ -168,35 +171,33 @@ class AppBookServiceFilterOptionsTest {
@Test
void getFilterOptions_withMagicShelfId_emptyResult_returnsEmptyOptions() {
mockAdminUser();
mockMagicShelfBooks(7L, Collections.emptyList());
mockMagicShelfSpec(7L, Collections.emptyList());
AppFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
assertTrue(result.getAuthors().isEmpty());
assertTrue(result.getLanguages().isEmpty());
assertTrue(result.getFileTypes().isEmpty());
assertFalse(result.getReadStatuses().isEmpty());
assertTrue(result.authors().isEmpty());
assertTrue(result.languages().isEmpty());
assertTrue(result.fileTypes().isEmpty());
assertFalse(result.readStatuses().isEmpty());
}
@Test
void getFilterOptions_withMagicShelfId_withBooks_returnsFilteredOptions() {
mockAdminUser();
Book book1 = Book.builder().id(100L).build();
Book book2 = Book.builder().id(200L).build();
mockMagicShelfBooks(7L, List.of(book1, book2));
mockMagicShelfSpec(7L, List.of(100L, 200L));
mockJpqlQueries();
AppFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
verify(magicShelfBookService).getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt());
verify(magicShelfBookService).toSpecification(eq(userId), eq(7L));
}
@Test
void getFilterOptions_withMagicShelfId_serviceThrows_propagatesException() {
mockAdminUser();
when(magicShelfBookService.getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt()))
when(magicShelfBookService.toSpecification(eq(userId), eq(7L)))
.thenThrow(new RuntimeException("Magic shelf not found"));
assertThrows(RuntimeException.class, () -> service.getFilterOptions(null, null, 7L));
@@ -230,30 +231,44 @@ class AppBookServiceFilterOptionsTest {
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
private void mockMagicShelfBooks(Long magicShelfId, List<Book> books) {
var page = new PageImpl<>(books, PageRequest.of(0, Math.max(books.size(), 1)), books.size());
when(magicShelfBookService.getBooksByMagicShelfId(eq(userId), eq(magicShelfId), eq(0), anyInt()))
.thenReturn(page);
@SuppressWarnings("unchecked")
private void mockMagicShelfSpec(Long magicShelfId, List<Long> bookIds) {
Specification<BookEntity> mockSpec = mock(Specification.class);
when(magicShelfBookService.toSpecification(eq(userId), eq(magicShelfId)))
.thenReturn(mockSpec);
jakarta.persistence.criteria.Predicate mockPredicate = mock(jakarta.persistence.criteria.Predicate.class);
CriteriaBuilder cb = mock(CriteriaBuilder.class);
CriteriaQuery<Long> cq = mock(CriteriaQuery.class);
Root<BookEntity> root = mock(Root.class);
Path<Long> idPath = mock(Path.class);
jakarta.persistence.TypedQuery<Long> typedQuery = mock(jakarta.persistence.TypedQuery.class);
when(entityManager.getCriteriaBuilder()).thenReturn(cb);
when(cb.createQuery(Long.class)).thenReturn(cq);
when(cq.from(BookEntity.class)).thenReturn(root);
when(root.get("id")).thenReturn((Path) idPath);
when(cq.select(idPath)).thenReturn(cq);
when(mockSpec.toPredicate(root, cq, cb)).thenReturn(mockPredicate);
when(cq.where(mockPredicate)).thenReturn(cq);
when(entityManager.createQuery(cq)).thenReturn(typedQuery);
when(typedQuery.setMaxResults(anyInt())).thenReturn(typedQuery);
when(typedQuery.getResultList()).thenReturn(bookIds);
}
@SuppressWarnings("unchecked")
private void mockJpqlQueries() {
TypedQuery<Tuple> authorQuery = mock(TypedQuery.class);
when(authorQuery.setMaxResults(anyInt())).thenReturn(authorQuery);
when(authorQuery.setParameter(anyString(), any())).thenReturn(authorQuery);
when(authorQuery.getResultList()).thenReturn(Collections.emptyList());
TypedQuery<Tuple> langQuery = mock(TypedQuery.class);
when(langQuery.setParameter(anyString(), any())).thenReturn(langQuery);
when(langQuery.getResultList()).thenReturn(Collections.emptyList());
TypedQuery<Tuple> tupleQuery = mock(TypedQuery.class);
when(tupleQuery.setParameter(anyString(), any())).thenReturn(tupleQuery);
when(tupleQuery.setMaxResults(anyInt())).thenReturn(tupleQuery);
when(tupleQuery.getResultList()).thenReturn(Collections.emptyList());
TypedQuery<BookFileType> ftQuery = mock(TypedQuery.class);
when(ftQuery.setParameter(anyString(), any())).thenReturn(ftQuery);
when(ftQuery.getResultList()).thenReturn(Collections.emptyList());
when(entityManager.createQuery(anyString(), eq(Tuple.class)))
.thenReturn(authorQuery)
.thenReturn(langQuery);
.thenReturn(tupleQuery);
when(entityManager.createQuery(anyString(), eq(BookFileType.class)))
.thenReturn(ftQuery);
}
@@ -46,7 +46,7 @@ class IconServiceTest {
Files.deleteIfExists(entry);
}
}
iconService.getSvgCache().clear();
iconService.getSvgCache().invalidateAll();
}
@AfterAll
@@ -164,7 +164,7 @@ class IconServiceTest {
@Test
void cacheEviction_worksWhenMaxSizeExceeded() {
iconService.getSvgCache().clear();
iconService.getSvgCache().invalidateAll();
for (int i = 0; i < 1002; i++) {
SvgIconCreateRequest req = new SvgIconCreateRequest();
@@ -173,7 +173,8 @@ class IconServiceTest {
iconService.saveSvgIcon(req);
}
assertEquals(1002, iconService.getIconNames(0, 2000).getContent().size());
assertTrue(iconService.getSvgCache().size() <= 1000);
iconService.getSvgCache().cleanUp();
assertTrue(iconService.getSvgCache().estimatedSize() <= 200);
}
@Test
@@ -183,11 +184,11 @@ class IconServiceTest {
req.setSvgData(SVG_DATA);
iconService.saveSvgIcon(req);
int initialSize = iconService.getSvgCache().size();
long initialSize = iconService.getSvgCache().estimatedSize();
req.setSvgData("<svg><circle r=\"50\"/></svg>");
assertThrows(APIException.class, () -> iconService.saveSvgIcon(req));
assertEquals(initialSize, iconService.getSvgCache().size());
assertEquals(initialSize, iconService.getSvgCache().estimatedSize());
}
}
+3 -1
View File
@@ -21,7 +21,9 @@ services:
- SWAGGER_ENABLED=false
- FORCE_DISABLE_OIDC=false
# ALLOWED_ORIGINS=
# JAVA_TOOL_OPTIONS=-XX:+UseSerialGC -Xmx256m -XX:+UseCompactObjectHeaders -XX:+ExitOnOutOfMemoryError
# Override JVM memory defaults (the image ships sensible defaults for ~512 MB heap).
# Uncomment and adjust if you want a tighter or looser cap:
# JAVA_TOOL_OPTIONS=-Xmx256m
depends_on:
mariadb:
condition: service_healthy
+1 -1
View File
@@ -17,7 +17,7 @@ services:
- REMOTE_DEBUG_ENABLED=true
- ALLOWED_ORIGINS=http://localhost:4200
- API_DOCS_ENABLED=true
- JAVA_TOOL_OPTIONS=-XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=60.0 -XX:InitialRAMPercentage=8.0 -XX:+ExitOnOutOfMemoryError -XX:MaxMetaspaceSize=192m -XX:ReservedCodeCacheSize=64m -Xss512k -XX:CICompilerCount=2 -XX:+UnlockExperimentalVMOptions -XX:ShenandoahUncommitDelay=5000 -XX:ShenandoahGuaranteedGCInterval=30000
- JAVA_TOOL_OPTIONS=-XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=60.0 -XX:InitialRAMPercentage=8.0 -XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heapdump.hprof -XX:MaxMetaspaceSize=256m -XX:ReservedCodeCacheSize=48m -Xss512k -XX:CICompilerCount=2 -XX:+UnlockExperimentalVMOptions -XX:+UseStringDeduplication -XX:ShenandoahUncommitDelay=5000 -XX:ShenandoahGuaranteedGCInterval=30000 -XX:MaxDirectMemorySize=256m
stdin_open: true
tty: true
restart: unless-stopped
@@ -85,6 +85,7 @@ describe('SecureSrcDirective', () => {
expect(errorSpy).not.toHaveBeenCalled();
fixture.componentInstance.src = '/covers/3';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const secondRequest = httpTestingController.expectOne('/covers/3');
@@ -104,6 +105,7 @@ describe('SecureSrcDirective', () => {
httpTestingController.expectOne('/covers/4').flush(new Blob(['first']));
fixture.componentInstance.src = '/covers/5';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(revokeSpy).toHaveBeenCalledWith('blob:first');
@@ -318,7 +318,7 @@
></app-book-table>
}
@if (currentViewMode === 'grid') {
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16">
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16" (vsEnd)="onScrollEnd()">
<div
class="grid"
#container
@@ -1,4 +1,4 @@
import {signal, WritableSignal} from '@angular/core';
import {computed, signal, WritableSignal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
import {BehaviorSubject, Subject} from 'rxjs';
@@ -31,6 +31,8 @@ import {AppSettingsService} from '../../../../shared/service/app-settings.servic
import {BookBrowserComponent, EntityType} from './book-browser.component';
import {SortService} from '../../service/sort.service';
import {TranslocoService} from '@jsverse/transloco';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters, AppBookSort} from '../../model/app-book.model';
function makeBook(id: number, libraryId: number, title: string, addedOn: string): Book {
return {
@@ -239,6 +241,45 @@ function createHarness(options?: {
booksError: booksError.asReadonly(),
},
},
{
provide: AppBooksApiService,
useFactory: () => {
const _filters = signal<AppBookFilters>({});
const _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
const _search = signal('');
const filteredSortedBooks = computed(() => {
let result = books();
const f = _filters();
if (f.libraryId) result = result.filter(b => b.libraryId === f.libraryId);
const s = _sort();
const dir = s.dir === 'asc' ? 1 : -1;
result = [...result].sort((a, b) => {
if (s.field === 'title') return dir * ((a.metadata?.title ?? '') as string).localeCompare((b.metadata?.title ?? '') as string);
if (s.field === 'addedOn') return dir * (a.addedOn ?? '').localeCompare(b.addedOn ?? '');
return 0;
});
return result;
});
return {
books: filteredSortedBooks,
totalElements: computed(() => filteredSortedBooks().length),
hasNextPage: computed(() => false),
isLoading: isBooksLoading.asReadonly(),
isFetchingNextPage: computed(() => false),
isError: computed(() => !!booksError()),
error: computed(() => booksError()),
filterOptions: computed(() => null),
setFilters: (f: AppBookFilters) => _filters.set(f),
setSort: (s: AppBookSort) => _sort.set(s),
setSearch: (s: string) => _search.set(s),
fetchNextPage: vi.fn(),
invalidate: vi.fn(),
};
},
},
{provide: BookMetadataManageService, useValue: {}},
{provide: BookDialogHelperService, useValue: {}},
{
@@ -56,8 +56,8 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {DeferredRenderState} from './deferred-render-state';
import {SortService} from '../../service/sort.service';
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
import {filterBooksByFilters} from './filters/sidebar-filter';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters} from '../../model/app-book.model';
export enum EntityType {
LIBRARY = 'Library',
@@ -118,6 +118,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private queryParamsService = inject(BookBrowserQueryParamsService);
private entityService = inject(BookBrowserEntityService);
private sortService = inject(SortService);
private appBooksApi = inject(AppBooksApiService);
private localStorageService = inject(LocalStorageService);
private scrollService = inject(BookBrowserScrollService);
private readonly t = inject(TranslocoService);
@@ -184,28 +185,64 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
return actions;
});
// --- Layered pipeline: each computed only recomputes when its direct inputs change ---
private readonly entityBooks = computed(() => {
const {entityId, entityType} = this.entityInfo();
return this.entityService.getBooksByEntity(this.bookService.books(), entityId, entityType);
});
private readonly searchedBooks = computed(() =>
filterBooksBySearchTerm(this.entityBooks(), this.debouncedSearchTerm())
);
private readonly filteredBooks = computed(() =>
filterBooksByFilters(this.searchedBooks(), this.selectedFilter(), this.selectedFilterMode())
);
// --- Server-side data pipeline: delegates filtering, sorting, searching to the API ---
private readonly forceExpandSeries = computed(() =>
this.queryParamsService.shouldForceExpandSeries(this.queryParamMap())
);
private readonly collapsedBooks = computed(() =>
this.seriesCollapseFilter.collapseBooks(
this.filteredBooks(), this.forceExpandSeries(), this.seriesCollapsed()
)
);
private readonly sortedBooks = computed(() =>
this.sortService.applyMultiSort(this.collapsedBooks(), this.sortCriteria())
);
/** Sync entity scope, filters, search, and sort to the API service. */
private readonly syncApiStateEffect = effect(() => {
const {entityId, entityType} = this.entityInfo();
const search = this.debouncedSearchTerm();
const sidebarFilters = this.selectedFilter();
const sortCriteria = this.sortCriteria();
const scopeFilters: AppBookFilters = {};
switch (entityType) {
case EntityType.LIBRARY:
if (!Number.isNaN(entityId)) scopeFilters.libraryId = entityId;
break;
case EntityType.SHELF:
if (!Number.isNaN(entityId)) scopeFilters.shelfId = entityId;
break;
case EntityType.MAGIC_SHELF:
if (!Number.isNaN(entityId)) scopeFilters.magicShelfId = entityId;
break;
case EntityType.UNSHELVED:
scopeFilters.unshelved = true;
break;
}
if (sidebarFilters) {
for (const [type, values] of Object.entries(sidebarFilters)) {
if (!values || values.length === 0) continue;
const strValues = values.map(String);
switch (type) {
case 'author': scopeFilters.authors = strValues; break;
case 'category': scopeFilters.category = strValues; break;
case 'series': scopeFilters.series = strValues; break;
case 'publisher': scopeFilters.publisher = strValues; break;
case 'tag': scopeFilters.tag = strValues; break;
case 'mood': scopeFilters.mood = strValues; break;
case 'narrator': scopeFilters.narrator = strValues; break;
case 'language': scopeFilters.language = strValues; break;
case 'readStatus': scopeFilters.status = strValues[0]; break;
case 'bookType': scopeFilters.fileType = strValues[0]; break;
}
}
const mode = this.selectedFilterMode();
scopeFilters.filterMode = mode === 'single' ? 'or' : mode;
}
this.appBooksApi.setFilters(scopeFilters);
this.appBooksApi.setSearch(search);
if (sortCriteria.length > 0) {
const primary = sortCriteria[0];
const dir = primary.direction === SortDirection.ASCENDING ? 'asc' as const : 'desc' as const;
this.appBooksApi.setSort({field: primary.field, dir});
}
});
// --- Deferred render: lets skeleton/refresh indicator paint before committing ---
private readonly booksRenderState = new DeferredRenderState<Book[]>();
@@ -220,7 +257,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
});
private readonly pipelineInputs = computed(() => ({
books: this.bookService.books(),
books: this.appBooksApi.books(),
entity: this.entityInfo(),
search: this.debouncedSearchTerm(),
filter: this.selectedFilter(),
@@ -238,20 +275,15 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.lastBooksContextKey = contextKey;
if (shouldRefreshInPlace) {
// Same context (sort/filter/search change within the same entity).
// Commit synchronously — the memoized computed chain is fast and
// skipping the setTimeout avoids a one-frame skeleton flash.
const requestId = this.booksRenderState.begin('refresh');
this.booksRenderState.commit(requestId, this.sortedBooks());
this.booksRenderState.commit(requestId, this.appBooksApi.books());
return;
}
// Context changed (navigation between entities or first load).
// Defer so the skeleton can paint before the pipeline evaluates.
const requestId = this.booksRenderState.begin('reset');
const timeout = globalThis.setTimeout(() => {
this.booksRenderState.commit(requestId, this.sortedBooks());
this.booksRenderState.commit(requestId, this.appBooksApi.books());
});
onCleanup(() => {
@@ -259,8 +291,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.booksRenderState.cancel(requestId);
});
});
readonly isBooksLoading = this.bookService.isBooksLoading;
readonly booksError = this.bookService.booksError;
readonly isBooksLoading = computed(() => this.appBooksApi.isLoading());
readonly booksError = this.appBooksApi.error;
readonly bookIndexById = computed(() => {
const books = this.books();
if (!books) return new Map<number, number>();
@@ -1046,7 +1078,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
attachFilesToBook(): void {
const selectedBookIds = Array.from(this.selectedBooks());
const sourceBooks = this.bookService.books().filter(book =>
const sourceBooks = (this.books() ?? []).filter(book =>
selectedBookIds.includes(book.id)
);
@@ -1084,7 +1116,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
const selectedBookIds = Array.from(this.selectedBooks());
if (selectedBookIds.length === 0) return false;
const selectedBooks = this.bookService.books().filter(book =>
const selectedBooks = (this.books() ?? []).filter(book =>
selectedBookIds.includes(book.id)
);
@@ -1106,4 +1138,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
onScrollEnd(): void {
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
this.appBooksApi.fetchNextPage();
}
}
}
@@ -4,6 +4,7 @@ import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {BookService} from '../../../service/book.service';
import {AppBooksApiService} from '../../../service/app-books-api.service';
import {LibraryService} from '../../../service/library.service';
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
@@ -11,64 +12,85 @@ import {EntityType} from '../book-browser.component';
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, SortMode} from './book-filter.config';
import {filterBooksByFilters} from '../filters/sidebar-filter';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
import {AppFilterOptions, CountedOption, LanguageOption} from '../../../model/app-book.model';
const MAX_FILTER_ITEMS = 100;
@Injectable({providedIn: 'root'})
export class BookFilterService {
private readonly bookService = inject(BookService);
private readonly appBooksApi = inject(AppBooksApiService);
private readonly libraryService = inject(LibraryService);
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
/** Server-supported filter types -- these use /api/v1/app/filter-options data. */
private static readonly SERVER_FILTER_TYPES = new Set<FilterType>([
'author', 'category', 'series', 'publisher', 'tag', 'mood',
'narrator', 'language', 'readStatus', 'bookType',
]);
createFilterSignals(
entity: Signal<Library | Shelf | MagicShelf | null>,
entityType: Signal<EntityType>,
activeFilters: Signal<Record<string, unknown[]> | null>,
filterMode: Signal<BookFilterMode>
): Record<FilterType, Signal<Filter[]>> {
const filteredBooks = computed(() =>
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
);
const signals = {} as Record<FilterType, Signal<Filter[]>>;
// Server-backed filter types use the filter-options API
for (const type of BookFilterService.SERVER_FILTER_TYPES) {
signals[type] = computed(() => {
const options = this.appBooksApi.filterOptions();
if (!options) return [];
return this.serverOptionsToFilters(type, options);
});
}
// Client-side filter types that don't have server support use loaded books
const filteredBooks = computed(() =>
this.appBooksApi.books()
);
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
const filterType = type as Exclude<FilterType, 'library'>;
if (BookFilterService.SERVER_FILTER_TYPES.has(filterType)) continue;
signals[filterType] = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
});
}
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
if (!signals.library) {
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const filterMap = new Map<number, Filter>();
const filterMap = new Map<number, Filter>();
for (const book of books) {
if (book.libraryId == null) continue;
for (const book of books) {
if (book.libraryId == null) continue;
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
}
return signals;
}
@@ -108,6 +130,49 @@ export class BookFilterService {
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
}
private serverOptionsToFilters(type: FilterType, options: AppFilterOptions): Filter[] {
switch (type) {
case 'author':
return this.countedToFilters(options.authors);
case 'category':
return this.countedToFilters(options.categories);
case 'series':
return this.countedToFilters(options.series);
case 'publisher':
return this.countedToFilters(options.publishers);
case 'tag':
return this.countedToFilters(options.tags);
case 'mood':
return this.countedToFilters(options.moods);
case 'narrator':
return this.countedToFilters(options.narrators);
case 'language':
return (options.languages ?? []).map((lang: LanguageOption) => ({
value: {id: lang.code, name: lang.label || lang.code},
bookCount: lang.count,
}));
case 'readStatus':
return (options.readStatuses ?? []).map((status: string) => ({
value: {id: status, name: status},
bookCount: 0,
}));
case 'bookType':
return (options.fileTypes ?? []).map((ft: string) => ({
value: {id: ft, name: ft},
bookCount: 0,
}));
default:
return [];
}
}
private countedToFilters(items: CountedOption[]): Filter[] {
return (items ?? []).map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count,
}));
}
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
@@ -0,0 +1,78 @@
export interface AppPageResponse<T> {
content: T[];
page: number;
size: number;
totalElements: number;
totalPages: number;
hasNext: boolean;
hasPrevious: boolean;
}
export interface AppBookSummary {
id: number;
title: string;
authors: string[];
thumbnailUrl: string | null;
readStatus: string | null;
personalRating: number | null;
seriesName: string | null;
seriesNumber: number | null;
libraryId: number;
addedOn: string | null;
lastReadTime: string | null;
readProgress: number | null;
primaryFileType: string | null;
coverUpdatedOn: string | null;
audiobookCoverUpdatedOn: string | null;
isPhysical: boolean | null;
}
export interface AppFilterOptions {
authors: CountedOption[];
languages: LanguageOption[];
readStatuses: string[];
fileTypes: string[];
categories: CountedOption[];
publishers: CountedOption[];
series: CountedOption[];
tags: CountedOption[];
moods: CountedOption[];
narrators: CountedOption[];
}
export interface CountedOption {
name: string;
count: number;
}
export interface LanguageOption {
code: string;
label: string;
count: number;
}
export interface AppBookFilters {
libraryId?: number;
shelfId?: number;
magicShelfId?: number;
unshelved?: boolean;
status?: string;
search?: string;
fileType?: string;
minRating?: number;
maxRating?: number;
authors?: string[];
language?: string[];
series?: string[];
category?: string[];
publisher?: string[];
tag?: string[];
mood?: string[];
narrator?: string[];
filterMode?: 'and' | 'or' | 'not';
}
export interface AppBookSort {
field: string;
dir: 'asc' | 'desc';
}
@@ -0,0 +1,190 @@
import {computed, inject, Injectable, signal} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {lastValueFrom} from 'rxjs';
import {injectInfiniteQuery, injectQuery, QueryClient} from '@tanstack/angular-query-experimental';
import {API_CONFIG} from '../../../core/config/api-config';
import {AuthService} from '../../../shared/service/auth.service';
import {
AppBookFilters,
AppBookSort,
AppBookSummary,
AppFilterOptions,
AppPageResponse,
} from '../model/app-book.model';
import {Book, BookType, ReadStatus} from '../model/book.model';
const PAGE_SIZE = 50;
@Injectable({providedIn: 'root'})
export class AppBooksApiService {
private readonly http = inject(HttpClient);
private readonly authService = inject(AuthService);
private readonly queryClient = inject(QueryClient);
private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/app/books`;
private readonly filterOptionsUrl = `${API_CONFIG.BASE_URL}/api/v1/app/filter-options`;
private readonly token = this.authService.token;
private readonly _filters = signal<AppBookFilters>({});
private readonly _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
private readonly _search = signal('');
readonly booksQuery = injectInfiniteQuery(() => ({
queryKey: ['app-books', this._filters(), this._sort(), this._search()] as const,
queryFn: ({pageParam}: {pageParam: number}) => {
const params = this.buildParams(pageParam);
return lastValueFrom(this.http.get<AppPageResponse<AppBookSummary>>(this.booksUrl, {params}));
},
initialPageParam: 0,
getNextPageParam: (lastPage: AppPageResponse<AppBookSummary>) =>
lastPage.hasNext ? lastPage.page + 1 : undefined,
enabled: !!this.token(),
staleTime: 30_000,
}));
readonly filterOptionsQuery = injectQuery(() => ({
queryKey: ['app-filter-options', this._filters().libraryId, this._filters().shelfId, this._filters().magicShelfId] as const,
queryFn: () => {
const filters = this._filters();
let params = new HttpParams();
if (filters.libraryId) params = params.set('libraryId', filters.libraryId.toString());
if (filters.shelfId) params = params.set('shelfId', filters.shelfId.toString());
if (filters.magicShelfId) params = params.set('magicShelfId', filters.magicShelfId.toString());
return lastValueFrom(this.http.get<AppFilterOptions>(this.filterOptionsUrl, {params}));
},
enabled: !!this.token(),
staleTime: 60_000,
}));
/** Accumulated books from all loaded pages, mapped to the Book interface. */
readonly books = computed<Book[]>(() => {
const data = this.booksQuery.data();
if (!data) return [];
return data.pages.flatMap(page => page.content.map(summaryToBook));
});
readonly totalElements = computed(() => {
const data = this.booksQuery.data();
if (!data || data.pages.length === 0) return 0;
return data.pages[0].totalElements;
});
readonly hasNextPage = computed(() => this.booksQuery.hasNextPage());
readonly isLoading = computed(() => this.booksQuery.isPending());
readonly isFetchingNextPage = computed(() => this.booksQuery.isFetchingNextPage());
readonly isError = computed(() => this.booksQuery.isError());
readonly error = computed<string | null>(() => {
if (!this.booksQuery.isError()) return null;
const err = this.booksQuery.error();
return err instanceof Error ? err.message : 'Failed to load books';
});
readonly filterOptions = computed(() => this.filterOptionsQuery.data() ?? null);
setFilters(filters: AppBookFilters): void {
if (JSON.stringify(this._filters()) !== JSON.stringify(filters)) {
this._filters.set(filters);
}
}
setSort(sort: AppBookSort): void {
const current = this._sort();
if (current.field !== sort.field || current.dir !== sort.dir) {
this._sort.set(sort);
}
}
setSearch(search: string): void {
if (this._search() !== search) {
this._search.set(search);
}
}
fetchNextPage(): void {
this.booksQuery.fetchNextPage();
}
/** Invalidate the books query to force a refresh from the server. */
invalidate(): void {
void this.queryClient.invalidateQueries({queryKey: ['app-books']});
void this.queryClient.invalidateQueries({queryKey: ['app-filter-options']});
}
private buildParams(page: number): HttpParams {
const filters = this._filters();
const sort = this._sort();
const search = this._search();
let params = new HttpParams()
.set('page', page.toString())
.set('size', PAGE_SIZE.toString())
.set('sort', sort.field)
.set('dir', sort.dir);
if (search) params = params.set('search', search);
if (filters.libraryId) params = params.set('libraryId', filters.libraryId.toString());
if (filters.shelfId) params = params.set('shelfId', filters.shelfId.toString());
if (filters.magicShelfId) params = params.set('magicShelfId', filters.magicShelfId.toString());
if (filters.unshelved) params = params.set('unshelved', 'true');
if (filters.status) params = params.set('status', filters.status);
if (filters.fileType) params = params.set('fileType', filters.fileType);
if (filters.minRating != null) params = params.set('minRating', filters.minRating.toString());
if (filters.maxRating != null) params = params.set('maxRating', filters.maxRating.toString());
if (filters.filterMode) params = params.set('filterMode', filters.filterMode);
// Array filters: use append() to produce repeated query params (e.g. ?authors=A&authors=B)
const arrayFilters: [string, string[] | undefined][] = [
['authors', filters.authors],
['language', filters.language],
['series', filters.series],
['category', filters.category],
['publisher', filters.publisher],
['tag', filters.tag],
['mood', filters.mood],
['narrator', filters.narrator],
];
for (const [key, values] of arrayFilters) {
if (values?.length) {
for (const v of values) {
params = params.append(key, v);
}
}
}
return params;
}
}
/**
* Maps a server-side AppBookSummary to a Book-shaped object
* compatible with BookCardComponent's @Input() book property.
*/
function summaryToBook(summary: AppBookSummary): Book {
return {
id: summary.id,
libraryId: summary.libraryId,
readStatus: (summary.readStatus as ReadStatus) ?? ReadStatus.UNSET,
personalRating: summary.personalRating ?? 0,
addedOn: summary.addedOn,
lastReadTime: summary.lastReadTime,
isPhysical: summary.isPhysical ?? false,
metadata: {
bookId: summary.id,
title: summary.title,
authors: summary.authors ?? [],
seriesName: summary.seriesName,
seriesNumber: summary.seriesNumber,
coverUpdatedOn: summary.coverUpdatedOn,
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn,
},
primaryFile: summary.primaryFileType
? {bookType: summary.primaryFileType as BookType}
: null,
pdfProgress: summary.readProgress != null
? {page: 0, percentage: summary.readProgress}
: null,
epubProgress: null,
cbxProgress: null,
shelves: [],
} as unknown as Book;
}
@@ -100,7 +100,8 @@ describe('BookPatchService', () => {
]);
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('updates cached date finished after the backend accepts the change', () => {
@@ -133,7 +134,8 @@ describe('BookPatchService', () => {
]);
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('updates the cached last read timestamp without calling the backend', () => {
@@ -9,6 +9,7 @@ import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from '../model/b
import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
invalidateAppBooksQueries,
patchBooksInCache,
patchBookFieldsInCache,
} from './book-query-cache';
@@ -270,5 +271,6 @@ export class BookPatchService {
book.id === bookId ? {...book, lastReadTime: timestamp} : book
)
);
invalidateAppBooksQueries(this.queryClient);
}
}
@@ -51,6 +51,7 @@ describe('book-query-cache', () => {
title: 'Updated Book 2'
}
});
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook]);
@@ -59,6 +60,9 @@ describe('book-query-cache', () => {
addBookToCache(queryClient, updatedSecondBook);
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('invalidates the full books query and book detail queries', () => {
@@ -72,7 +76,8 @@ describe('book-query-cache', () => {
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)});
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(5);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('patches list entries and invalidates matching detail queries', () => {
@@ -89,7 +94,8 @@ describe('book-query-cache', () => {
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('patches metadata, selected fields, and updater callbacks in the list cache', () => {
@@ -156,6 +162,8 @@ describe('book-query-cache', () => {
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('removes detail and recommendation queries for deleted books', () => {
@@ -178,6 +186,7 @@ describe('book-query-cache', () => {
it('removes deleted books from the list cache and associated queries', () => {
const firstBook = makeBook(1);
const secondBook = makeBook(2);
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
@@ -188,6 +197,8 @@ describe('book-query-cache', () => {
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([secondBook]);
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('ignores an empty remove request', () => {
@@ -3,10 +3,19 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {Book, BookMetadata} from '../model/book.model';
import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys';
const APP_BOOKS_QUERY_PREFIX = ['app-books'] as const;
const APP_FILTER_OPTIONS_QUERY_PREFIX = ['app-filter-options'] as const;
export function invalidateAppBooksQueries(queryClient: QueryClient): void {
void queryClient.invalidateQueries({queryKey: APP_BOOKS_QUERY_PREFIX});
void queryClient.invalidateQueries({queryKey: APP_FILTER_OPTIONS_QUERY_PREFIX});
}
// --- Full invalidation (refetches from server) ---
export function invalidateBooksQuery(queryClient: QueryClient): void {
void queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
invalidateAppBooksQueries(queryClient);
}
export function invalidateBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
@@ -37,6 +46,7 @@ export function removeBooksFromCache(queryClient: QueryClient, bookIds: Iterable
(current ?? []).filter(book => !removedIds.has(book.id))
);
removeBookQueries(queryClient, removedIds);
invalidateAppBooksQueries(queryClient);
}
// --- Surgical patches (updates cache directly, no list refetch) ---
@@ -47,6 +57,7 @@ export function addBookToCache(queryClient: QueryClient, book: Book): void {
const exists = books.some(b => b.id === book.id);
return exists ? books.map(b => b.id === book.id ? book : b) : [...books, book];
});
invalidateAppBooksQueries(queryClient);
}
export function patchBooksInCache(queryClient: QueryClient, updatedBooks: Book[]): void {
@@ -55,6 +66,7 @@ export function patchBooksInCache(queryClient: QueryClient, updatedBooks: Book[]
(current ?? []).map(book => updatedMap.get(book.id) ?? book)
);
invalidateBookDetailQueries(queryClient, updatedBooks.map(b => b.id));
invalidateAppBooksQueries(queryClient);
}
export function patchBookMetadataInCache(queryClient: QueryClient, bookId: number, metadata: BookMetadata): void {
@@ -64,6 +76,7 @@ export function patchBookMetadataInCache(queryClient: QueryClient, bookId: numbe
)
);
invalidateBookDetailQueries(queryClient, [bookId]);
invalidateAppBooksQueries(queryClient);
}
export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, updater: (book: Book) => Book): void {
@@ -71,6 +84,7 @@ export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, u
(current ?? []).map(book => book.id === bookId ? updater(book) : book)
);
invalidateBookDetailQueries(queryClient, [bookId]);
invalidateAppBooksQueries(queryClient);
}
export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookId: number; fields: Partial<Book>}[]): void {
@@ -82,4 +96,5 @@ export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookI
})
);
invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
invalidateAppBooksQueries(queryClient);
}
@@ -4,6 +4,7 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
addBookToCache,
invalidateAppBooksQueries,
invalidateBookDetailQueries,
invalidateBooksQuery,
patchBooksInCache,
@@ -50,5 +51,6 @@ export class BookSocketService {
})
);
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
invalidateAppBooksQueries(this.queryClient);
}
}
@@ -18,6 +18,7 @@ import {
bookRecommendationsQueryKey,
} from './book-query-keys';
import {
invalidateAppBooksQueries,
invalidateBooksQuery,
patchBooksInCache,
removeBookQueries,
@@ -151,6 +152,7 @@ export class BookService {
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}))
);
invalidateAppBooksQueries(this.queryClient);
}
/*------------------ Book Retrieval ------------------*/
@@ -259,11 +261,20 @@ export class BookService {
readBook(bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
const book = this.findBookById(bookId);
if (!book) {
console.error('Book not found');
if (book) {
this.navigateToReader(book, bookId, reader, explicitBookType);
return;
}
this.ensureBookDetail(bookId, false).then(detail => {
this.navigateToReader(detail, bookId, reader, explicitBookType);
}).catch(() => {
console.error('Book not found:', bookId);
});
}
private navigateToReader(book: Book, bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
const bookType: BookType | undefined = explicitBookType ?? book.primaryFile?.bookType;
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
@@ -1,4 +1,4 @@
import {Component, computed, effect, inject, OnInit} from '@angular/core';
import {Component, computed, effect, inject, Injector, OnInit, runInInjectionContext} from '@angular/core';
import {AbstractControl, FormArray, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
import {Button} from 'primeng/button';
import {NgTemplateOutlet} from '@angular/common';
@@ -248,6 +248,7 @@ const READ_STATUS_KEYS: Record<string, string> = {
export class MagicShelfComponent implements OnInit {
private readonly t = inject(TranslocoService);
private readonly injector = inject(Injector);
private readonly controlIds = new WeakMap<AbstractControl, string>();
private controlIdCounter = 0;
@@ -514,14 +515,16 @@ export class MagicShelfComponent implements OnInit {
if (id) {
this.shelfId = id;
effect(() => {
const shelf = this.magicShelfService.findShelfById(id);
if (!shelf || this.formInitializedFromShelf) {
return;
}
runInInjectionContext(this.injector, () => {
effect(() => {
const shelf = this.magicShelfService.findShelfById(id);
if (!shelf || this.formInitializedFromShelf) {
return;
}
this.initializeForm(shelf);
this.formInitializedFromShelf = true;
this.initializeForm(shelf);
this.formInitializedFromShelf = true;
});
});
} else {
this.initializeForm();
@@ -1,10 +1,12 @@
import {NO_ERRORS_SCHEMA} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {Observable, Subject, of, throwError} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TranslocoService} from '@jsverse/transloco';
import {TranslocoService, TranslateParams} from '@jsverse/transloco';
import {MessageService} from 'primeng/api';
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
import {
MetadataReplaceMode,
TaskHistory,
@@ -17,6 +19,7 @@ import {
import {TaskManagementComponent} from './task-management.component';
describe('TaskManagementComponent', () => {
let fixture: ComponentFixture<TaskManagementComponent>;
let component: TaskManagementComponent;
let taskService: {
getAvailableTasks: ReturnType<typeof vi.fn>;
@@ -30,7 +33,7 @@ describe('TaskManagementComponent', () => {
let messageService: {
add: ReturnType<typeof vi.fn>;
};
let translate: ReturnType<typeof vi.fn>;
let translate: ReturnType<typeof vi.fn<(key: TranslateParams, params?: Record<string, unknown>, lang?: string) => unknown>>;
const clearPdfTask: TaskInfo = {
taskType: TaskType.CLEAR_PDF_CACHE,
@@ -83,7 +86,10 @@ describe('TaskManagementComponent', () => {
vi.setSystemTime(new Date('2026-03-27T03:06:00Z'));
taskProgressSubject = new Subject<TaskProgressPayload | null>();
translate = vi.fn((key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key));
translate = vi.fn<(key: TranslateParams, params?: Record<string, unknown>, lang?: string) => unknown>((key: TranslateParams, params?: Record<string, unknown>) => {
const keyStr = typeof key === 'string' ? key : key.join(',');
return params ? `${keyStr}:${JSON.stringify(params)}` : keyStr;
});
messageService = {
add: vi.fn(),
};
@@ -114,16 +120,18 @@ describe('TaskManagementComponent', () => {
};
TestBed.configureTestingModule({
imports: [TaskManagementComponent],
imports: [TaskManagementComponent, getTranslocoModule()],
schemas: [NO_ERRORS_SCHEMA],
providers: [
{provide: TaskService, useValue: taskService},
{provide: MessageService, useValue: messageService},
{provide: TranslocoService, useValue: {translate}},
],
});
component = TestBed.createComponent(TaskManagementComponent).componentInstance;
const translocoService = TestBed.inject(TranslocoService);
vi.spyOn(translocoService, 'translate').mockImplementation(translate);
fixture = TestBed.createComponent(TaskManagementComponent);
component = fixture.componentInstance;
});
afterEach(() => {
@@ -162,7 +170,7 @@ describe('TaskManagementComponent', () => {
it('tracks task progress updates and reloads after a completed task', () => {
const loadTasksSpy = vi.spyOn(component, 'loadTasks');
component.ngOnInit();
fixture.detectChanges();
expect(loadTasksSpy).toHaveBeenCalledTimes(1);
taskProgressSubject.next({
@@ -157,9 +157,13 @@ describe('MetadataProgressWidgetComponent', () => {
translocoService.translate('shared.metadataProgress.statusError')
);
component.ngOnDestroy();
vi.advanceTimersByTime(60000);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((component as any).timeoutHandles.size).toBe(1);
component.ngOnDestroy();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((component as any).timeoutHandles.size).toBe(0);
expect(component.activeTasks[task.taskId]).toEqual(task);
});
});
@@ -58,6 +58,7 @@ describe('TagComponent', () => {
host.variant = 'pill';
host.rounded = true;
host.pill = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tag = fixture.nativeElement.querySelector('span') as HTMLSpanElement;