fix(pdf): handle out-of-memory errors gracefully during cover generation and limit image size to prevent OOM (#1680)

* fix(pdf): handle out-of-memory errors gracefully during cover generation and limit image size to prevent OOM

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(file): release native resources after saving image to prevent memory leaks

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2025-11-29 17:00:43 -07:00
committed by GitHub
parent 7baa2ee8bd
commit 348e8e9022
2 changed files with 45 additions and 2 deletions
@@ -66,6 +66,19 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
bookMetadataRepository.save(bookEntity.getMetadata());
return saved;
} catch (OutOfMemoryError e) {
// Note: Catching OOM is generally discouraged, but for batch processing
// of potentially large/corrupted PDFs, we prefer graceful degradation
// over crashing the entire service.
log.error("Out of memory (heap space exhausted) while generating cover for '{}'. Skipping cover generation.", bookEntity.getFileName());
System.gc(); // Hint to JVM to reclaim memory
return false;
} catch (NegativeArraySizeException e) {
// This can appear on corrupted PDF, or PDF with such large images that the
// initial memory buffer is already bigger than the entire JVM heap, therefore
// it leads to NegativeArrayException (basically run out of memory, and overflows)
log.warn("Corrupted PDF structure for '{}'. Skipping cover generation.", bookEntity.getFileName());
return false;
} catch (Exception e) {
log.warn("Failed to generate cover for '{}': {}", bookEntity.getFileName(), e.getMessage());
return false;
@@ -139,7 +152,18 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
}
private boolean generateCoverImageAndSave(Long bookId, PDDocument document) throws IOException {
BufferedImage coverImage = new PDFRenderer(document).renderImageWithDPI(0, 300, ImageType.RGB);
return fileService.saveCoverImages(coverImage, bookId);
BufferedImage coverImage = null;
try {
coverImage = new PDFRenderer(document).renderImageWithDPI(0, 150, ImageType.RGB);
return fileService.saveCoverImages(coverImage, bookId);
} catch (OutOfMemoryError e) {
log.error("Out of memory (heap space exhausted) while generating cover for bookId {}. Skipping cover generation.", bookId);
System.gc(); // Hint to JVM to reclaim memory
return false;
} finally {
if (coverImage != null) {
coverImage.flush(); // Release native resources
}
}
}
}
@@ -49,6 +49,8 @@ public class FileService {
private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024;
private static final int THUMBNAIL_WIDTH = 250;
private static final int THUMBNAIL_HEIGHT = 350;
private static final int MAX_ORIGINAL_WIDTH = 1000;
private static final int MAX_ORIGINAL_HEIGHT = 1500;
private static final String IMAGE_FORMAT = "JPEG";
// @formatter:on
@@ -148,6 +150,7 @@ public class FileService {
throw new IOException("Failed to create directory: " + parentDir);
}
ImageIO.write(originalImage, IMAGE_FORMAT, outputFile);
originalImage.flush(); // Release native resources
log.info("Image saved successfully to: {}", filePath);
}
@@ -237,6 +240,18 @@ public class FileService {
Graphics2D g = rgbImage.createGraphics();
g.drawImage(coverImage, 0, 0, Color.WHITE, null);
g.dispose();
coverImage.flush(); // Original input no longer needed after conversion
// Resize original image if too large to prevent OOM
double scale = Math.min(
(double) MAX_ORIGINAL_WIDTH / rgbImage.getWidth(),
(double) MAX_ORIGINAL_HEIGHT / rgbImage.getHeight()
);
if (scale < 1.0) {
BufferedImage resized = resizeImage(rgbImage, (int) (rgbImage.getWidth() * scale), (int) (rgbImage.getHeight() * scale));
rgbImage.flush(); // Release resources of the original large image
rgbImage = resized;
}
File originalFile = new File(folder, COVER_FILENAME);
boolean originalSaved = ImageIO.write(rgbImage, IMAGE_FORMAT, originalFile);
@@ -245,6 +260,10 @@ public class FileService {
File thumbnailFile = new File(folder, THUMBNAIL_FILENAME);
boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile);
// Cleanup resources
rgbImage.flush();
thumb.flush();
return originalSaved && thumbnailSaved;
}