chore: drop chapter cache service (#2773)

This commit is contained in:
James Ward
2026-10-01 19:20:18 -06:00
committed by GitHub
parent 003345b07c
commit 84a6097f8a
7 changed files with 2 additions and 381 deletions
@@ -55,16 +55,6 @@ public class CbxReaderService {
.build();
private final ArchiveService archiveService;
private final ChapterCacheService chapterCacheService;
/** Single-threaded executor for background disk-cache population. */
private final ExecutorService cacheExecutor = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "cbx-cache-init");
t.setDaemon(true);
return t;
});
/** Tracks books whose async cache init has already been submitted. */
private final Set<String> cacheInitSubmitted = ConcurrentHashMap.newKeySet();
private record CachedArchiveMetadata(List<String> imageEntries, List<CbxPageDimension> pageDimensions, long lastModified) {
CachedArchiveMetadata {
@@ -73,65 +63,6 @@ public class CbxReaderService {
}
}
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);
}
}
/**
* Submits a background task to extract all pages to the disk cache.
* This runs once per book/type combination and makes subsequent
* {@link #streamPageImage} calls hit Tier 2 (disk) instead of Tier 3
* (native extraction per request).
*/
private void submitBackgroundCacheInit(Long bookId, String bookType, long lastModified) {
String key = bookId + ":" + bookType + ":" + lastModified;
if (cacheInitSubmitted.add(key)) {
cacheExecutor.submit(() -> {
try {
initCache(bookId, bookType);
} catch (Exception e) {
log.warn("Background cache init failed for book {}: {}", bookId, e.getMessage());
cacheInitSubmitted.remove(key);
}
});
}
}
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);
}
@@ -141,8 +72,6 @@ public class CbxReaderService {
try {
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
List<String> imageEntries = metadata.imageEntries();
// Trigger background disk-cache population for faster subsequent page serving
submitBackgroundCacheInit(bookId, bookType, metadata.lastModified());
return IntStream.rangeClosed(1, imageEntries.size())
.boxed()
.toList();
@@ -184,16 +113,6 @@ public class CbxReaderService {
return metadata.pageDimensions();
}
// Try disk cache first (fast, memory-safe)
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified());
if (chapterCacheService.hasPage(cacheKey, 1) && chapterCacheService.hasPage(cacheKey, metadata.imageEntries().size())) {
List<CbxPageDimension> dimensions = computeDimensionsFromDiskCache(cacheKey, metadata.imageEntries().size());
CachedArchiveMetadata updated = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
archiveCache.put(cbxPath.toString(), updated);
return dimensions;
}
// Streaming: read only image headers, not full images
List<CbxPageDimension> dimensions = readDimensionsStreaming(cbxPath, metadata.imageEntries());
CachedArchiveMetadata updatedMetadata = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
@@ -259,10 +178,6 @@ public class CbxReaderService {
.build();
}
private static boolean isZipPath(Path path) {
return ArchiveUtils.detectArchiveType(path) == ArchiveUtils.ArchiveType.ZIP;
}
private String extractDisplayName(String entryPath) {
String fileName = baseName(entryPath);
int lastDotIndex = fileName.lastIndexOf('.');
@@ -281,29 +196,10 @@ public class CbxReaderService {
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
validatePageRequest(bookId, page, metadata.imageEntries());
// 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;
}
// Fallback to full extraction/stream (slowest)
String entryName = metadata.imageEntries().get(page - 1);
archiveService.transferEntryTo(cbxPath, entryName, outputStream);
}
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.findByIdForStreaming(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookType != null) {
@@ -1,121 +0,0 @@
package org.booklore.service.reader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.AppProperties;
import org.booklore.exception.ApiError;
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.
*/
public void prepareCbxCache(String cacheKey, Path cbxPath, List<String> entries) throws IOException {
ReentrantLock lock = cacheLocks.computeIfAbsent(cacheKey, _ -> 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 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;
}
}
@@ -19,7 +19,6 @@ 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.Comparator;
@@ -39,7 +38,6 @@ public class PdfReaderService {
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))
@@ -47,41 +45,6 @@ public class PdfReaderService {
private record CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> 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) {
getAvailablePages(bookId, null);
}
@@ -120,20 +83,10 @@ 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);
// 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);
}
@@ -251,18 +204,4 @@ public class PdfReaderService {
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);
}
}
}