fix(readers): add chapter caching and improve page rendering (#514)

* fix(readers): add chapter caching and improve page rendering

* fix(readers): simplify caching logic and remove unused methods in CbxReaderService and PdfReaderService
# Conflicts:
#	booklore-api/src/main/java/org/booklore/controller/EpubReaderController.java
This commit is contained in:
brios
2026-04-22 17:27:34 -04:00
committed by Zach Yale
parent 502f5738bf
commit 649c485c2d
16 changed files with 671 additions and 220 deletions
@@ -42,22 +42,21 @@ public class EpubReaderController {
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
@ApiResponse(responseCode = "200", description = "File content returned successfully")
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/file/**")
@GetMapping("/{bookId}/file/{*filePath}")
public void getFile(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@PathVariable String filePath,
@Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String prefix = "/api/v1/epub/" + bookId + "/file/";
String filePath = fullPath.substring(prefix.length());
filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
String cleanPath = filePath.startsWith("/") ? filePath.substring(1) : filePath;
cleanPath = URLDecoder.decode(cleanPath, StandardCharsets.UTF_8);
String contentType = epubReaderService.getContentType(bookId, bookType, filePath);
String contentType = epubReaderService.getContentType(bookId, bookType, cleanPath);
response.setContentType(contentType);
long fileSize = epubReaderService.getFileSize(bookId, bookType, filePath);
long fileSize = epubReaderService.getFileSize(bookId, bookType, cleanPath);
if (fileSize > 0) {
response.setContentLengthLong(fileSize);
}
@@ -71,10 +70,10 @@ public class EpubReaderController {
// Defense in depth for untrusted EPUB resources. See Foliate's security guidance:
// https://github.com/johnfactotum/foliate-js#security
response.setHeader("Content-Security-Policy", "script-src 'none'");
response.setHeader("Cache-Control", "public, max-age=3600");
response.setHeader("Cache-Control", "private, max-age=3600");
try {
epubReaderService.streamFile(bookId, bookType, filePath, response.getOutputStream());
epubReaderService.streamFile(bookId, bookType, cleanPath, response.getOutputStream());
} catch (FileNotFoundException e) {
response.reset();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
@@ -27,6 +27,13 @@ public enum BookFileType {
return extensions.contains(extension.toLowerCase());
}
public static Optional<BookFileType> fromName(String name) {
if (name == null) return Optional.empty();
return Arrays.stream(values())
.filter(type -> type.name().equalsIgnoreCase(name))
.findFirst();
}
public static Optional<BookFileType> fromExtension(String extension) {
String ext = extension.toLowerCase();
return Arrays.stream(values())
@@ -26,6 +26,10 @@ 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> findByIdWithBookFiles(@Param("id") Long id);
@EntityGraph(attributePaths = { "metadata", "bookFiles", "libraryPath", "library" })
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdForStreaming(@Param("id") Long id);
@EntityGraph(attributePaths = { "metadata", "metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags", "metadata.comicMetadata", "library" })
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdWithMetadata(@Param("id") Long id);
@@ -4,7 +4,6 @@ import com.github.gotson.nightcompress.Archive;
import com.github.gotson.nightcompress.ArchiveEntry;
import com.github.gotson.nightcompress.LibArchiveException;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -15,22 +14,48 @@ import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@Slf4j
@Service
public class ArchiveService {
@PostConstruct
public void checkArchiveAvailable() {
private static final int LOCK_STRIPE_COUNT = 256;
private final ReentrantLock[] lockStripes = IntStream.range(0, LOCK_STRIPE_COUNT)
.mapToObj(ignored -> new ReentrantLock())
.toArray(ReentrantLock[]::new);
private volatile boolean available = safeCheckAvailable();
private static boolean safeCheckAvailable() {
try {
// We want to check the version early because it allows for
// NightCompress to preload the libarchive library in a safe
// thread. Loading native libraries is not a thread safe operation.
if (!Archive.isAvailable()) {
log.warn("LibArchive is not available");
}
return Archive.isAvailable();
} catch (Throwable e) {
log.error("LibArchive could not be loaded", e);
return false;
}
}
private ReentrantLock getFileLock(Path path) {
int hash = path.toAbsolutePath().normalize().toString().hashCode();
return lockStripes[Math.floorMod(hash, LOCK_STRIPE_COUNT)];
}
@PostConstruct
public void initLibArchive() {
// Log the availability result that was already determined at construction
// time. The @PostConstruct runs on the Spring startup thread which also
// ensures the native library is fully loaded before any concurrent HTTP
// request thread can call into it.
if (available) {
log.info("LibArchive loaded successfully");
} else {
log.error("LibArchive is not available – CBX/archive features will not work");
}
}
private void requireAvailable() throws IOException {
if (!available) {
throw new IOException("LibArchive is not available – cannot process archive");
}
}
@@ -38,23 +63,10 @@ public class ArchiveService {
return Archive.isAvailable();
}
public static class Entry {
private Entry() {}
@Getter
private String name;
@Getter
private long size;
}
public record Entry(String name, long size) {}
private Entry getEntryFromArchiveEntry(ArchiveEntry archiveEntry) {
Entry entry = new Entry();
entry.name = archiveEntry.getName();
entry.size = archiveEntry.getSize();
return entry;
return new Entry(archiveEntry.getName(), archiveEntry.getSize());
}
public List<Entry> getEntries(Path path) throws IOException {
@@ -62,12 +74,16 @@ public class ArchiveService {
}
public Stream<Entry> streamEntries(Path path) throws IOException {
requireAvailable();
ReentrantLock lock = getFileLock(path);
lock.lock();
try {
return Archive.getEntries(path)
.stream()
.map(this::getEntryFromArchiveEntry);
List<ArchiveEntry> entries = Archive.getEntries(path);
return entries.stream().map(this::getEntryFromArchiveEntry);
} catch (LibArchiveException e) {
throw new IOException("Failed to read archive", e);
} finally {
lock.unlock();
}
}
@@ -76,25 +92,34 @@ public class ArchiveService {
}
public Stream<String> streamEntryNames(Path path) throws IOException {
requireAvailable();
ReentrantLock lock = getFileLock(path);
lock.lock();
try {
return Archive.getEntries(path)
.stream()
.map(ArchiveEntry::getName);
List<ArchiveEntry> entries = Archive.getEntries(path);
return entries.stream().map(ArchiveEntry::getName);
} catch (LibArchiveException e) {
throw new IOException("Failed to read archive", e);
} finally {
lock.unlock();
}
}
public long transferEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException {
requireAvailable();
// We cannot directly use the NightCompress `InputStream` as it is limited
// in its implementation and will cause fatal errors. Instead, we can use
// the `transferTo` on an output stream to copy data around.
ReentrantLock lock = getFileLock(path);
lock.lock();
try (InputStream inputStream = Archive.getInputStream(path, entryName)) {
if (inputStream != null) {
return inputStream.transferTo(outputStream);
}
} catch (Exception e) {
throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
} finally {
lock.unlock();
}
throw new IOException("Entry not found in archive");
@@ -111,12 +136,17 @@ public class ArchiveService {
}
public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException {
requireAvailable();
ReentrantLock lock = getFileLock(path);
lock.lock();
try (InputStream inputStream = Archive.getInputStream(path, entryName)) {
if (inputStream != null) {
return Files.copy(inputStream, outputPath);
}
} catch (Exception e) {
throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
} finally {
lock.unlock();
}
throw new IOException("Entry not found in archive");
@@ -174,7 +174,7 @@ public class AppSettingService {
if (sessionDurationStr != null && !sessionDurationStr.isBlank()) {
try {
builder.oidcSessionDurationHours(Integer.parseInt(sessionDurationStr));
} catch (NumberFormatException _) {
} catch (NumberFormatException ignored) {
}
}
@@ -187,20 +187,20 @@ public class CbxConversionService {
List<Path> imagePaths = new ArrayList<>();
for (ArchiveService.Entry entry : archiveService.getEntries(cbxFile.toPath())) {
if (!isImageFile(entry.getName())) {
if (!isImageFile(entry.name())) {
continue;
}
validateImageSize(entry.getName(), entry.getSize());
validateImageSize(entry.name(), entry.size());
try {
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.name()));
archiveService.extractEntryToPath(cbxFile.toPath(), entry.getName(), outputPath);
archiveService.extractEntryToPath(cbxFile.toPath(), entry.name(), outputPath);
imagePaths.add(outputPath);
} catch (Exception e) {
log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
log.warn("Error extracting image {}: {}", entry.name(), e.getMessage());
}
}
@@ -1,6 +1,10 @@
package org.booklore.service.reader;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.response.CbxPageDimension;
@@ -17,19 +21,18 @@ import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.zip.ZipFile;
@Slf4j
@Service
@@ -43,22 +46,73 @@ public class CbxReaderService {
private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+");
private final BookRepository bookRepository;
private final Map<String, CachedArchiveMetadata> archiveCache = new ConcurrentHashMap<>();
private final Cache<String, CachedArchiveMetadata> archiveCache = Caffeine.newBuilder()
.maximumSize(MAX_CACHE_ENTRIES)
.expireAfterAccess(Duration.ofMinutes(30))
.build();
private final ArchiveService archiveService;
private final ChapterCacheService chapterCacheService;
private static class CachedArchiveMetadata {
final List<String> imageEntries;
final long lastModified;
volatile long lastAccessed;
// L1 Cache: Open ZipFile handles for active reading sessions (TTL 30m)
@Setter
private Cache<String, ZipFile> zipHandleCache = Caffeine.newBuilder()
.maximumSize(MAX_CACHE_ENTRIES)
.expireAfterAccess(Duration.ofMinutes(30))
.removalListener((String _, ZipFile value, RemovalCause _) -> {
try {
value.close();
} catch (IOException _) {
}
})
.build();
CachedArchiveMetadata(List<String> imageEntries, long lastModified) {
this.imageEntries = List.copyOf(imageEntries);
this.lastModified = lastModified;
this.lastAccessed = System.currentTimeMillis();
private record CachedArchiveMetadata(List<String> imageEntries, List<CbxPageDimension> pageDimensions, long lastModified) {
CachedArchiveMetadata {
imageEntries = List.copyOf(imageEntries);
pageDimensions = pageDimensions != null ? List.copyOf(pageDimensions) : null;
}
}
public void initCache(Long bookId, String bookType) throws IOException {
Path cbxPath = getBookPath(bookId, bookType);
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified());
chapterCacheService.prepareCbxCache(cacheKey, cbxPath, metadata.imageEntries());
if (metadata.pageDimensions() == null) {
List<CbxPageDimension> dimensions = computeDimensionsFromDiskCache(cacheKey, metadata.imageEntries().size());
CachedArchiveMetadata updated = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
archiveCache.put(cbxPath.toString(), updated);
}
}
private List<CbxPageDimension> computeDimensionsFromDiskCache(String cacheKey, int pageCount) {
List<CbxPageDimension> dimensions = new ArrayList<>();
for (int i = 1; i <= pageCount; i++) {
Path cachedPage = chapterCacheService.getCachedPage(cacheKey, i);
try (ImageInputStream iis = ImageIO.createImageInputStream(cachedPage.toFile())) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(iis, true, true);
int width = reader.getWidth(0);
int height = reader.getHeight(0);
dimensions.add(CbxPageDimension.builder().pageNumber(i).width(width).height(height).wide(width > height).build());
continue;
} finally {
reader.dispose();
}
}
} catch (Exception e) {
log.warn("Failed to read dimensions for cached page {}: {}", i, e.getMessage());
}
dimensions.add(CbxPageDimension.builder().pageNumber(i).width(0).height(0).wide(false).build());
}
return dimensions;
}
public List<Integer> getAvailablePages(Long bookId) {
return getAvailablePages(bookId, null);
}
@@ -69,7 +123,7 @@ public class CbxReaderService {
List<String> imageEntries = getImageEntriesFromArchiveCached(cbxPath);
return IntStream.rangeClosed(1, imageEntries.size())
.boxed()
.collect(Collectors.toList());
.toList();
} catch (IOException e) {
log.error("Failed to read archive for book {}", bookId, e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage());
@@ -100,21 +154,25 @@ public class CbxReaderService {
}
}
public List<CbxPageDimension> getPageDimensions(Long bookId) {
return getPageDimensions(bookId, null);
}
public List<CbxPageDimension> getPageDimensions(Long bookId, String bookType) {
Path cbxPath = getBookPath(bookId, bookType);
try {
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
List<String> imageEntries = metadata.imageEntries;
if (metadata.pageDimensions() != null) {
return metadata.pageDimensions();
}
List<String> imageEntries = metadata.imageEntries();
List<CbxPageDimension> dimensions = new ArrayList<>();
for (int i = 0; i < imageEntries.size(); i++) {
String entryName = imageEntries.get(i);
CbxPageDimension dim = readEntryDimension(cbxPath, entryName, i + 1);
dimensions.add(dim);
}
CachedArchiveMetadata updatedMetadata = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
archiveCache.put(cbxPath.toString(), updatedMetadata);
return dimensions;
} catch (IOException e) {
log.error("Failed to read page dimensions for book {}", bookId, e);
@@ -124,15 +182,13 @@ public class CbxReaderService {
private CbxPageDimension readEntryDimension(Path cbxPath, String entryName, int pageNumber) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
archiveService.transferEntryTo(cbxPath, entryName, baos);
byte[] imageBytes = baos.toByteArray();
byte[] imageBytes = archiveService.getEntryBytes(cbxPath, entryName);
try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageBytes))) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(iis);
reader.setInput(iis, true, true);
int width = reader.getWidth(0);
int height = reader.getHeight(0);
return CbxPageDimension.builder()
@@ -146,7 +202,7 @@ public class CbxReaderService {
}
}
}
} catch (IOException e) {
} catch (Exception e) {
log.warn("Failed to read dimensions for page {} (entry: {}): {}", pageNumber, entryName, e.getMessage());
}
return CbxPageDimension.builder()
@@ -173,15 +229,68 @@ public class CbxReaderService {
public void streamPageImage(Long bookId, String bookType, int page, OutputStream outputStream) throws IOException {
Path cbxPath = getBookPath(bookId, bookType);
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
validatePageRequest(bookId, page, metadata.imageEntries);
String entryName = metadata.imageEntries.get(page - 1);
validatePageRequest(bookId, page, metadata.imageEntries());
// Tier 1: Check L1 Memory Map (OS File Cache) via open ZipFile
// This is the fastest path for ZIP/CBZ
try {
java.util.zip.ZipFile zip = getZipFile(cbxPath, metadata.lastModified());
if (zip != null) {
String entryName = metadata.imageEntries().get(page - 1);
java.util.zip.ZipEntry entry = zip.getEntry(entryName);
if (entry != null) {
try (InputStream is = zip.getInputStream(entry)) {
is.transferTo(outputStream);
return;
}
}
}
} catch (IOException e) {
log.trace("L1 Zip cache miss or unsupported format for book {}: {}", bookId, e.getMessage());
}
// Tier 2: Check L3 Disk Cache (extracted files)
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified());
if (chapterCacheService.hasPage(cacheKey, page)) {
Path cached = chapterCacheService.getCachedPage(cacheKey, page);
Files.copy(cached, outputStream);
return;
}
// Tier 3: Fallback to full extraction/stream (slowest)
String entryName = metadata.imageEntries().get(page - 1);
archiveService.transferEntryTo(cbxPath, entryName, outputStream);
}
private Path getBookPath(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
private ZipFile getZipFile(Path cbxPath, long lastModified) {
String cacheKey = cbxPath.toString() + ":" + lastModified;
return zipHandleCache.get(cacheKey, _ -> {
try {
if (cbxPath.toString().toLowerCase().endsWith(".cbz") || cbxPath.toString().toLowerCase().endsWith(".zip")) {
return new java.util.zip.ZipFile(cbxPath.toFile());
}
} catch (IOException e) {
log.warn("Failed to open ZipFile for {}: {}", cbxPath, e.getMessage());
}
return null;
});
}
private String getCacheKey(Long bookId, String bookType, long lastModified) {
if (bookType != null) {
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
// Ensure we use the safe enum name to prevent path traversal
BookFileType type = BookFileType.fromName(bookType)
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
return bookId + "_" + type.name() + "_" + lastModified;
}
return bookId + "_" + lastModified;
}
private Path getBookPath(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdForStreaming(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookType != null) {
BookFileType requestedType = BookFileType.fromName(bookType)
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
.filter(bf -> bf.getBookType() == requestedType)
.findFirst()
@@ -203,43 +312,26 @@ public class CbxReaderService {
private CachedArchiveMetadata getCachedMetadata(Path cbxPath) throws IOException {
String cacheKey = cbxPath.toString();
long currentModified = Files.getLastModifiedTime(cbxPath).toMillis();
CachedArchiveMetadata cached = archiveCache.get(cacheKey);
if (cached != null && cached.lastModified == currentModified) {
cached.lastAccessed = System.currentTimeMillis();
CachedArchiveMetadata cached = archiveCache.getIfPresent(cacheKey);
if (cached != null && cached.lastModified() == currentModified) {
log.debug("Cache hit for archive: {}", cbxPath.getFileName());
return cached;
}
log.debug("Cache miss for archive: {}, scanning...", cbxPath.getFileName());
CachedArchiveMetadata newMetadata = scanArchiveMetadata(cbxPath);
archiveCache.put(cacheKey, newMetadata);
evictOldestCacheEntries();
return newMetadata;
}
private List<String> getImageEntriesFromArchiveCached(Path cbxPath) throws IOException {
return getCachedMetadata(cbxPath).imageEntries;
}
private void evictOldestCacheEntries() {
if (archiveCache.size() <= MAX_CACHE_ENTRIES) {
return;
}
List<String> keysToRemove = archiveCache.entrySet().stream()
.sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed))
.limit(archiveCache.size() - MAX_CACHE_ENTRIES)
.map(Map.Entry::getKey)
.toList();
keysToRemove.forEach(key -> {
archiveCache.remove(key);
log.debug("Evicted cache entry: {}", key);
});
return getCachedMetadata(cbxPath).imageEntries();
}
private CachedArchiveMetadata scanArchiveMetadata(Path cbxPath) throws IOException {
long lastModified = Files.getLastModifiedTime(cbxPath).toMillis();
List<String> entries = getImageEntries(cbxPath);
return new CachedArchiveMetadata(entries, lastModified);
return new CachedArchiveMetadata(entries, null, lastModified);
}
private List<String> getImageEntries(Path cbxPath) throws IOException {
@@ -283,13 +375,10 @@ public class CbxReaderService {
}
}
String baseName = baseName(normalized).toLowerCase();
if (baseName.startsWith("._") || baseName.startsWith(".")) {
if (baseName.startsWith("._") || !baseName.isEmpty() && baseName.charAt(0) == '.') {
return false;
}
if (SYSTEM_FILES.contains(baseName)) {
return false;
}
return true;
return !SYSTEM_FILES.contains(baseName);
}
private String baseName(String path) {
@@ -0,0 +1,122 @@
package org.booklore.service.reader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.AppProperties;
import org.booklore.service.ArchiveService;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* Service for managing the on-disk extraction cache for reader chapters.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ChapterCacheService {
private static final long MTIME_TOLERANCE_MS = 2000;
private final AppProperties appProperties;
private final ArchiveService archiveService;
private final ConcurrentHashMap<String, ReentrantLock> cacheLocks = new ConcurrentHashMap<>();
/**
* Ensures all pages of a CBX archive are extracted to the disk cache.
* Extracts pages sequentially to avoid concurrent native libarchive access
* which can cause SIGSEGV / out-of-memory crashes in the native heap.
*/
public void prepareCbxCache(String cacheKey, Path cbxPath, List<String> entries) throws IOException {
ReentrantLock lock = cacheLocks.computeIfAbsent(cacheKey, ignored -> new ReentrantLock());
lock.lock();
try {
Path cacheDir = getCacheDir(cacheKey);
if (!Files.exists(cacheDir)) {
Files.createDirectories(cacheDir);
}
// Only extract if the cache is empty or stale
if (isCacheStale(cacheDir, cbxPath, entries.size())) {
log.info("Populating disk cache for {}: {} pages", cacheKey, entries.size());
for (int i = 0; i < entries.size(); i++) {
Path target = cacheDir.resolve("page_" + (i + 1) + ".jpg");
if (!Files.exists(target) || Files.size(target) == 0) {
String entryName = entries.get(i);
writeAtomically(target, out ->
archiveService.transferEntryTo(cbxPath, entryName, out));
}
}
// Mark cache as fresh by setting its mtime to match the archive
Files.setLastModifiedTime(cacheDir, Files.getLastModifiedTime(cbxPath));
}
} finally {
lock.unlock();
}
}
public Path getCachedPage(String cacheKey, int pageNumber) {
return getCacheDir(cacheKey).resolve("page_" + pageNumber + ".jpg");
}
public boolean hasPage(String cacheKey, int pageNumber) {
Path pagePath = getCachedPage(cacheKey, pageNumber);
try {
return Files.exists(pagePath) && Files.size(pagePath) > 0;
} catch (IOException e) {
return false;
}
}
/**
* Writes data to a temp file in the same directory, then atomically moves
* it to the target path. If the write fails, the partial temp file is
* cleaned up and the target is never touched.
*/
void writeAtomically(Path target, IOConsumer<OutputStream> writer) throws IOException {
Path tmp = Files.createTempFile(target.getParent(), target.getFileName().toString() + ".", ".tmp");
try {
try (OutputStream out = Files.newOutputStream(tmp)) {
writer.accept(out);
}
Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(tmp);
}
}
@FunctionalInterface
interface IOConsumer<T> {
void accept(T t) throws IOException;
}
private Path getCacheDir(String cacheKey) {
if (cacheKey == null || cacheKey.contains("..") || cacheKey.contains("/") || cacheKey.contains("\\")) {
throw org.booklore.exception.ApiError.INVALID_INPUT.createException("Invalid cache key: " + cacheKey);
}
return Paths.get(appProperties.getPathConfig(), "cache", "chapters", cacheKey);
}
private boolean isCacheStale(Path cacheDir, Path sourcePath, int expectedPages) throws IOException {
if (!Files.exists(cacheDir)) return true;
for (int i = 1; i <= expectedPages; i++) {
Path page = cacheDir.resolve("page_" + i + ".jpg");
if (!Files.exists(page) || Files.size(page) == 0) return true;
}
long cacheMtime = Files.getLastModifiedTime(cacheDir).toMillis();
long sourceMtime = Files.getLastModifiedTime(sourcePath).toMillis();
return Math.abs(cacheMtime - sourceMtime) > MTIME_TOLERANCE_MS;
}
}
@@ -21,8 +21,8 @@ import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Service
@@ -33,76 +33,70 @@ public class EpubReaderService {
private static final int MAX_CACHE_ENTRIES = 50;
private static final Map<String, String> CONTENT_TYPE_MAP = createContentTypeMap();
private static Map<String, String> createContentTypeMap() {
Map<String, String> map = new HashMap<>(32);
map.put(".xhtml", "application/xhtml+xml");
map.put(".html", "application/xhtml+xml");
map.put(".htm", "application/xhtml+xml");
map.put(".css", "text/css");
map.put(".js", "application/javascript");
map.put(".jpg", "image/jpeg");
map.put(".jpeg", "image/jpeg");
map.put(".png", "image/png");
map.put(".gif", "image/gif");
map.put(".svg", "image/svg+xml");
map.put(".webp", "image/webp");
map.put(".woff", "font/woff");
map.put(".woff2", "font/woff2");
map.put(".ttf", "font/ttf");
map.put(".otf", "font/otf");
map.put(".eot", "application/vnd.ms-fontobject");
map.put(".xml", "application/xml");
map.put(".ncx", "application/x-dtbncx+xml");
map.put(".smil", "application/smil+xml");
map.put(".mp3", "audio/mpeg");
map.put(".mp4", "video/mp4");
map.put(".m4a", "audio/mp4");
map.put(".m4b", "audio/mp4");
map.put(".aac", "audio/aac");
map.put(".wav", "audio/wav");
map.put(".flac", "audio/flac");
map.put(".ogg", "audio/ogg");
map.put(".webm", "video/webm");
map.put(".avif", "image/avif");
map.put(".opf", "application/oebps-package+xml");
return Collections.unmodifiableMap(map);
}
private static final Map<String, String> CONTENT_TYPE_MAP = Map.ofEntries(
Map.entry(".xhtml", "application/xhtml+xml"),
Map.entry(".html", "application/xhtml+xml"),
Map.entry(".htm", "application/xhtml+xml"),
Map.entry(".css", "text/css"),
Map.entry(".js", "application/javascript"),
Map.entry(".jpg", "image/jpeg"),
Map.entry(".jpeg", "image/jpeg"),
Map.entry(".png", "image/png"),
Map.entry(".gif", "image/gif"),
Map.entry(".svg", "image/svg+xml"),
Map.entry(".webp", "image/webp"),
Map.entry(".woff", "font/woff"),
Map.entry(".woff2", "font/woff2"),
Map.entry(".ttf", "font/ttf"),
Map.entry(".otf", "font/otf"),
Map.entry(".eot", "application/vnd.ms-fontobject"),
Map.entry(".xml", "application/xml"),
Map.entry(".ncx", "application/x-dtbncx+xml"),
Map.entry(".smil", "application/smil+xml"),
Map.entry(".mp3", "audio/mpeg"),
Map.entry(".mp4", "video/mp4"),
Map.entry(".m4a", "audio/mp4"),
Map.entry(".m4b", "audio/mp4"),
Map.entry(".aac", "audio/aac"),
Map.entry(".wav", "audio/wav"),
Map.entry(".flac", "audio/flac"),
Map.entry(".ogg", "audio/ogg"),
Map.entry(".webm", "video/webm"),
Map.entry(".avif", "image/avif"),
Map.entry(".opf", "application/oebps-package+xml")
);
private final BookRepository bookRepository;
private final Map<String, CachedEpubMetadata> metadataCache = new ConcurrentHashMap<>();
private static class CachedEpubMetadata {
final EpubBookInfo bookInfo;
final long lastModified;
final Set<String> validPaths;
final Map<String, EpubManifestItem> manifestByHref;
volatile long lastAccessed;
private final com.github.benmanes.caffeine.cache.Cache<String, CachedEpubMetadata> metadataCache = com.github.benmanes.caffeine.cache.Caffeine.newBuilder()
.maximumSize(MAX_CACHE_ENTRIES)
.expireAfterAccess(Duration.ofMinutes(30))
.build();
private record CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified,
Set<String> validPaths,
Map<String, EpubManifestItem> manifestByHref) {
CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified) {
this.bookInfo = bookInfo;
this.lastModified = lastModified;
this.lastAccessed = System.currentTimeMillis();
this(bookInfo, lastModified, buildValidPaths(bookInfo), buildManifestByHref(bookInfo));
}
private static Set<String> buildValidPaths(EpubBookInfo bookInfo) {
Set<String> paths = new HashSet<>(bookInfo.getManifest().size() + 2);
paths.add(CONTAINER_PATH);
if (bookInfo.getContainerPath() != null) {
paths.add(bookInfo.getContainerPath());
}
Map<String, EpubManifestItem> byHref = new HashMap<>(bookInfo.getManifest().size());
for (EpubManifestItem item : bookInfo.getManifest()) {
paths.add(item.getHref());
byHref.put(item.getHref(), item);
}
this.validPaths = Collections.unmodifiableSet(paths);
this.manifestByHref = Collections.unmodifiableMap(byHref);
return Collections.unmodifiableSet(paths);
}
void touch() {
this.lastAccessed = System.currentTimeMillis();
private static Map<String, EpubManifestItem> buildManifestByHref(EpubBookInfo bookInfo) {
Map<String, EpubManifestItem> byHref = new HashMap<>(bookInfo.getManifest().size());
for (EpubManifestItem item : bookInfo.getManifest()) {
byHref.put(item.getHref(), item);
}
return Collections.unmodifiableMap(byHref);
}
}
@@ -152,7 +146,6 @@ public class EpubReaderService {
Path epubPath = getBookPath(bookId, bookType);
try {
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
metadata.touch();
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
EpubManifestItem item = metadata.manifestByHref.get(normalizedPath);
return item != null ? item.getMediaType() : guessContentType(filePath);
@@ -169,7 +162,6 @@ public class EpubReaderService {
Path epubPath = getBookPath(bookId, bookType);
try {
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
metadata.touch();
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
// O(1) lookup instead of O(n) stream filter
@@ -181,7 +173,7 @@ public class EpubReaderService {
}
private Path getBookPath(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
BookEntity bookEntity = bookRepository.findByIdForStreaming(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookType != null) {
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
@@ -197,10 +189,9 @@ public class EpubReaderService {
private CachedEpubMetadata getCachedMetadata(Path epubPath) throws IOException {
String cacheKey = epubPath.toString();
long currentModified = Files.getLastModifiedTime(epubPath).toMillis();
CachedEpubMetadata cached = metadataCache.get(cacheKey);
CachedEpubMetadata cached = metadataCache.getIfPresent(cacheKey);
if (cached != null && cached.lastModified == currentModified) {
cached.lastAccessed = System.currentTimeMillis();
if (cached != null && cached.lastModified() == currentModified) {
log.debug("Cache hit for EPUB: {}", epubPath.getFileName());
return cached;
}
@@ -208,25 +199,9 @@ public class EpubReaderService {
log.debug("Cache miss for EPUB: {}, parsing...", epubPath.getFileName());
CachedEpubMetadata newMetadata = parseEpubMetadata(epubPath, currentModified);
metadataCache.put(cacheKey, newMetadata);
evictOldestCacheEntries();
return newMetadata;
}
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 EPUB cache entry: {}", key);
});
}
private CachedEpubMetadata parseEpubMetadata(Path epubPath, long lastModified) throws IOException {
try {
Book book = new EpubReader().readEpubLazy(epubPath, "UTF-8");
@@ -19,10 +19,10 @@ import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.github.benmanes.caffeine.cache.Cache;
@@ -35,23 +35,50 @@ public class PdfReaderService {
private static final int MAX_CACHE_ENTRIES = 15;
private static final float DEFAULT_DPI = 200f;
private static final long MTIME_TOLERANCE_MS = 2000;
private final BookRepository bookRepository;
private final ChapterCacheService chapterCacheService;
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;
private record CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {}
CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {
this.pageCount = pageCount;
this.lastModified = lastModified;
this.outline = outline;
public void initCache(Long bookId, String bookType) throws IOException {
Path pdfPath = getBookPath(bookId, bookType);
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified);
Path cacheDir = chapterCacheService.getCachedPage(cacheKey, 1).getParent();
if (!Files.exists(cacheDir)) {
Files.createDirectories(cacheDir);
}
long cacheMtime = Files.getLastModifiedTime(cacheDir).toMillis();
boolean cacheEmpty;
try (var stream = Files.list(cacheDir)) {
cacheEmpty = stream.findAny().isEmpty();
}
if (!cacheEmpty && Math.abs(cacheMtime - metadata.lastModified) <= MTIME_TOLERANCE_MS) {
return;
}
log.info("Populating PDF disk cache for {}: {} pages", cacheKey, metadata.pageCount);
// PdfDocument is not thread-safe — render pages serially then cache
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
for (int i = 1; i <= metadata.pageCount; i++) {
Path target = chapterCacheService.getCachedPage(cacheKey, i);
if (!Files.exists(target) || Files.size(target) == 0) {
byte[] jpeg = doc.renderPageToBytes(i - 1, (int) DEFAULT_DPI, "jpeg");
writeAtomically(target, jpeg);
}
}
}
Files.setLastModifiedTime(cacheDir, Files.getLastModifiedTime(pdfPath));
}
public void getAvailablePages(Long bookId) {
@@ -64,7 +91,7 @@ public class PdfReaderService {
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
return IntStream.rangeClosed(1, metadata.pageCount)
.boxed()
.collect(Collectors.toList());
.toList();
} catch (IOException e) {
log.error("Failed to read PDF for book {}", bookId, e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read PDF: " + e.getMessage());
@@ -92,15 +119,39 @@ public class PdfReaderService {
public void streamPageImage(Long bookId, String bookType, int page, OutputStream outputStream) throws IOException {
Path pdfPath = getBookPath(bookId, bookType);
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified);
if (chapterCacheService.hasPage(cacheKey, page)) {
Files.copy(chapterCacheService.getCachedPage(cacheKey, page), outputStream);
return;
}
validatePageRequest(bookId, page, metadata.pageCount);
renderPageToStream(pdfPath, page, outputStream);
// Render, cache atomically, then stream
Path cached = chapterCacheService.getCachedPage(cacheKey, page);
Files.createDirectories(cached.getParent());
byte[] jpeg = renderPageToBytes(pdfPath, page);
writeAtomically(cached, jpeg);
outputStream.write(jpeg);
}
private String getCacheKey(Long bookId, String bookType, long lastModified) {
if (bookType != null) {
// Ensure we use the safe enum name to prevent path traversal
BookFileType type = BookFileType.fromName(bookType)
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
return bookId + "_" + type.name() + "_" + lastModified;
}
return bookId + "_" + lastModified;
}
private Path getBookPath(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookType != null) {
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
BookFileType requestedType = BookFileType.fromName(bookType)
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
.filter(bf -> bf.getBookType() == requestedType)
.findFirst()
@@ -190,14 +241,27 @@ public class PdfReaderService {
}
}
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
private byte[] renderPageToBytes(Path pdfPath, int page) throws IOException {
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
// page is 1-based from the API, renderPageToBytes expects 0-based
byte[] jpeg = doc.renderPageToBytes(page - 1, (int) DEFAULT_DPI, "jpeg");
outputStream.write(jpeg);
} catch (IOException e) {
return doc.renderPageToBytes(page - 1, (int) DEFAULT_DPI, "jpeg");
} catch (Exception e) {
log.error("Failed to render PDF page {} from {}", page, pdfPath, e);
throw e;
throw new IOException(e);
}
}
/**
* Writes bytes to a temp file then atomically moves to the target path.
* If the write fails the partial temp file is cleaned up.
*/
private void writeAtomically(Path target, byte[] data) throws IOException {
Path tmp = Files.createTempFile(target.getParent(), target.getFileName().toString() + ".", ".tmp");
try {
Files.write(tmp, data);
Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(tmp);
}
}
}