fix(image-dimension): fix image dimension detection loading whole CBX files into memory (#663)
This commit is contained in:
@@ -5,6 +5,7 @@ import com.github.gotson.nightcompress.ArchiveEntry;
|
||||
import com.github.gotson.nightcompress.LibArchiveException;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -13,6 +14,7 @@ import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.stream.IntStream;
|
||||
@@ -135,6 +137,69 @@ public class ArchiveService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads at most {@code maxBytes} from the given archive entry.
|
||||
* This is used to read image headers for dimension detection without
|
||||
* loading the full (potentially multi-MB) image into memory.
|
||||
*
|
||||
* @return a byte array of at most {@code maxBytes} containing the
|
||||
* leading bytes of the entry
|
||||
*/
|
||||
public byte[] getEntryBytesPrefix(Path path, String entryName, int maxBytes) throws IOException {
|
||||
if (maxBytes < 0) {
|
||||
throw ApiError.INVALID_INPUT.createException("maxBytes must be non-negative");
|
||||
}
|
||||
var bounded = new BoundedOutputStream(maxBytes);
|
||||
try {
|
||||
transferEntryTo(path, entryName, bounded);
|
||||
} catch (BoundedOutputStream.LimitReachedException _) {
|
||||
// expected, we only needed the prefix
|
||||
} catch (IOException e) {
|
||||
if (!(e.getCause() instanceof BoundedOutputStream.LimitReachedException)) {
|
||||
throw e;
|
||||
}
|
||||
// expected, we only needed the prefix
|
||||
}
|
||||
return bounded.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* OutputStream that captures at most {@code limit} bytes, then throws
|
||||
* {@link LimitReachedException} to short-circuit the transfer.
|
||||
*/
|
||||
static final class BoundedOutputStream extends OutputStream {
|
||||
private final byte[] buf;
|
||||
private int count;
|
||||
|
||||
BoundedOutputStream(int limit) {
|
||||
this.buf = new byte[limit];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
if (count >= buf.length) throw new LimitReachedException();
|
||||
buf[count++] = (byte) b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) throws IOException {
|
||||
int remaining = buf.length - count;
|
||||
if (remaining <= 0) throw new LimitReachedException();
|
||||
int toCopy = Math.min(len, remaining);
|
||||
System.arraycopy(b, off, buf, count, toCopy);
|
||||
count += toCopy;
|
||||
if (toCopy < len) throw new LimitReachedException();
|
||||
}
|
||||
|
||||
byte[] toByteArray() {
|
||||
return Arrays.copyOf(buf, count);
|
||||
}
|
||||
|
||||
static final class LimitReachedException extends IOException {
|
||||
LimitReachedException() { super("Bounded output limit reached"); }
|
||||
}
|
||||
}
|
||||
|
||||
public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException {
|
||||
requireAvailable();
|
||||
ReentrantLock lock = getFileLock(path);
|
||||
|
||||
@@ -14,6 +14,7 @@ import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.ArchiveService;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -29,9 +30,13 @@ 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.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
@Slf4j
|
||||
@@ -44,6 +49,8 @@ public class CbxReaderService {
|
||||
private static final Pattern NUMERIC_PATTERN = Pattern.compile("(\\d+)|(\\D+)");
|
||||
private static final Set<String> SYSTEM_FILES = Set.of(".ds_store", "thumbs.db", "desktop.ini");
|
||||
private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+");
|
||||
/** Bytes to read from a non-ZIP archive entry for image-header dimension detection. */
|
||||
private static final int DIMENSION_PREFIX_BYTES = 64 * 1024;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final Cache<String, CachedArchiveMetadata> archiveCache = Caffeine.newBuilder()
|
||||
@@ -54,6 +61,15 @@ public class CbxReaderService {
|
||||
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();
|
||||
|
||||
// L1 Cache: Open ZipFile handles for active reading sessions (TTL 30m)
|
||||
@Setter
|
||||
private Cache<String, ZipFile> zipHandleCache = Caffeine.newBuilder()
|
||||
@@ -87,6 +103,26 @@ public class CbxReaderService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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++) {
|
||||
@@ -120,7 +156,10 @@ public class CbxReaderService {
|
||||
public List<Integer> getAvailablePages(Long bookId, String bookType) {
|
||||
Path cbxPath = getBookPath(bookId, bookType);
|
||||
try {
|
||||
List<String> imageEntries = getImageEntriesFromArchiveCached(cbxPath);
|
||||
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();
|
||||
@@ -161,18 +200,22 @@ public class CbxReaderService {
|
||||
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);
|
||||
|
||||
// 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());
|
||||
archiveCache.put(cbxPath.toString(), updatedMetadata);
|
||||
|
||||
|
||||
return dimensions;
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to read page dimensions for book {}", bookId, e);
|
||||
@@ -180,31 +223,104 @@ public class CbxReaderService {
|
||||
}
|
||||
}
|
||||
|
||||
private CbxPageDimension readEntryDimension(Path cbxPath, String entryName, int pageNumber) {
|
||||
try {
|
||||
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, true, true);
|
||||
int width = reader.getWidth(0);
|
||||
int height = reader.getHeight(0);
|
||||
return CbxPageDimension.builder()
|
||||
.pageNumber(pageNumber)
|
||||
.width(width)
|
||||
.height(height)
|
||||
.wide(width > height)
|
||||
.build();
|
||||
} finally {
|
||||
reader.dispose();
|
||||
/**
|
||||
* Reads image dimensions for all pages using only image headers (a few KB
|
||||
* per page) instead of loading the full image.
|
||||
* <p>
|
||||
* For ZIP/CBZ archives the fast path uses {@link java.util.zip.ZipFile}
|
||||
* which supports random access, so each entry stream feeds directly into
|
||||
* {@link ImageIO}. For non-ZIP archives (RAR, 7z) the first
|
||||
* {@value #DIMENSION_PREFIX_BYTES} bytes of each entry are extracted via
|
||||
* {@link ArchiveService#getEntryBytesPrefix} which is sufficient for all
|
||||
* common image header formats (JPEG SOF, PNG IHDR, WebP VP8, etc.).
|
||||
*/
|
||||
private List<CbxPageDimension> readDimensionsStreaming(Path cbxPath, List<String> imageEntries) {
|
||||
// Try the ZipFile fast-path first (random access, no full extraction)
|
||||
if (isZipPath(cbxPath)) {
|
||||
try {
|
||||
return readDimensionsViaZipFile(cbxPath, imageEntries);
|
||||
} catch (IOException e) {
|
||||
log.debug("ZipFile dimension read failed for {}, falling back to bounded extraction: {}", cbxPath.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for non-ZIP or on ZipFile failure: bounded prefix extraction
|
||||
return readDimensionsViaBoundedPrefix(cbxPath, imageEntries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses a ZipFile handle to stream each entry's image header bytes directly
|
||||
* into ImageIO for dimension detection. Memory cost: only the bytes
|
||||
* ImageIO needs to decode the header (typically < 4 KB per page).
|
||||
*/
|
||||
private List<CbxPageDimension> readDimensionsViaZipFile(Path cbxPath, List<String> imageEntries) throws IOException {
|
||||
List<CbxPageDimension> dimensions = new ArrayList<>(imageEntries.size());
|
||||
try (ZipFile zip = new ZipFile(cbxPath.toFile())) {
|
||||
for (int i = 0; i < imageEntries.size(); i++) {
|
||||
int pageNumber = i + 1;
|
||||
String entryName = imageEntries.get(i);
|
||||
ZipEntry entry = zip.getEntry(entryName);
|
||||
if (entry != null) {
|
||||
try (InputStream is = zip.getInputStream(entry);
|
||||
ImageInputStream iis = ImageIO.createImageInputStream(is)) {
|
||||
dimensions.add(readDimensionFromImageStream(iis, pageNumber));
|
||||
continue;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read dimensions for page {} via ZipFile (entry: {}): {}", pageNumber, entryName, e.getMessage());
|
||||
}
|
||||
}
|
||||
dimensions.add(fallbackDimension(pageNumber));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read dimensions for page {} (entry: {}): {}", pageNumber, entryName, e.getMessage());
|
||||
}
|
||||
return dimensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* For non-ZIP archives (RAR, 7z): extracts only the first
|
||||
* {@value #DIMENSION_PREFIX_BYTES} bytes of each entry, enough for image
|
||||
* header parsing, and reads dimensions from that bounded buffer.
|
||||
*/
|
||||
private List<CbxPageDimension> readDimensionsViaBoundedPrefix(Path cbxPath, List<String> imageEntries) {
|
||||
List<CbxPageDimension> dimensions = new ArrayList<>(imageEntries.size());
|
||||
for (int i = 0; i < imageEntries.size(); i++) {
|
||||
int pageNumber = i + 1;
|
||||
String entryName = imageEntries.get(i);
|
||||
try {
|
||||
byte[] prefix = archiveService.getEntryBytesPrefix(cbxPath, entryName, DIMENSION_PREFIX_BYTES);
|
||||
try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(prefix))) {
|
||||
dimensions.add(readDimensionFromImageStream(iis, pageNumber));
|
||||
continue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read dimensions for page {} via bounded prefix (entry: {}): {}", pageNumber, entryName, e.getMessage());
|
||||
}
|
||||
dimensions.add(fallbackDimension(pageNumber));
|
||||
}
|
||||
return dimensions;
|
||||
}
|
||||
|
||||
private CbxPageDimension readDimensionFromImageStream(ImageInputStream iis, int pageNumber) throws IOException {
|
||||
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);
|
||||
return CbxPageDimension.builder()
|
||||
.pageNumber(pageNumber)
|
||||
.width(width)
|
||||
.height(height)
|
||||
.wide(width > height)
|
||||
.build();
|
||||
} finally {
|
||||
reader.dispose();
|
||||
}
|
||||
}
|
||||
return fallbackDimension(pageNumber);
|
||||
}
|
||||
|
||||
private static CbxPageDimension fallbackDimension(int pageNumber) {
|
||||
return CbxPageDimension.builder()
|
||||
.pageNumber(pageNumber)
|
||||
.width(0)
|
||||
@@ -213,6 +329,10 @@ 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('.');
|
||||
@@ -266,7 +386,7 @@ public class CbxReaderService {
|
||||
String cacheKey = cbxPath.toString() + ":" + lastModified;
|
||||
return zipHandleCache.get(cacheKey, _ -> {
|
||||
try {
|
||||
if (cbxPath.toString().toLowerCase().endsWith(".cbz") || cbxPath.toString().toLowerCase().endsWith(".zip")) {
|
||||
if (isZipPath(cbxPath)) {
|
||||
return new java.util.zip.ZipFile(cbxPath.toFile());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
|
||||
Reference in New Issue
Block a user