refactor(api): migrate away from nightcompress (#2103)

This commit is contained in:
James Ward
2026-07-30 15:41:29 -04:00
committed by GitHub
parent cb8855829b
commit 134e97f028
12 changed files with 111 additions and 77 deletions
+1 -1
View File
@@ -200,7 +200,7 @@ dependencies {
implementation("com.github.RouHim:jaudiotagger:2.0.27") implementation("com.github.RouHim:jaudiotagger:2.0.27")
// --- Archive Support --- // --- Archive Support ---
implementation("com.github.gotson.nightcompress:nightcompress:1.1.1") implementation("com.github.junrar:junrar:8.0.0")
// --- JSON & Web Scraping --- // --- JSON & Web Scraping ---
implementation("org.jsoup:jsoup:1.22.2") implementation("org.jsoup:jsoup:1.22.2")
+1 -2
View File
@@ -14,8 +14,7 @@ com.fasterxml.jackson:jackson-bom:2.21.4=compileClasspath,productionRuntimeClass
com.fasterxml:classmate:1.7.3=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.fasterxml:classmate:1.7.3=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.RouHim:jaudiotagger:2.0.27=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.RouHim:jaudiotagger:2.0.27=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.gotson.nightcompress:nightcompress:1.1.1=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.junrar:junrar:8.0.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.code.findbugs:jsr305:3.0.2=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.google.errorprone:error_prone_annotations:2.49.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.google.errorprone:error_prone_annotations:2.49.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.h2database:h2:2.4.240=openApiExportRuntimeOnly,testRuntimeClasspath com.h2database:h2:2.4.240=openApiExportRuntimeOnly,testRuntimeClasspath
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
@@ -7,7 +7,6 @@ import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import com.github.gotson.nightcompress.Archive;
import org.grimmory.pdfium4j.PdfiumLibrary; import org.grimmory.pdfium4j.PdfiumLibrary;
/** /**
@@ -21,7 +20,6 @@ public final class NativeLibraries {
public enum Library { public enum Library {
PDFIUM, PDFIUM,
LIBARCHIVE,
EPUB4J_NATIVE EPUB4J_NATIVE
} }
@@ -39,8 +37,6 @@ public final class NativeLibraries {
return true; return true;
})); }));
probes.put(Library.LIBARCHIVE, new Probe("libarchive", Archive::isAvailable));
probes.put(Library.EPUB4J_NATIVE, new Probe("epub4j-native", () -> { probes.put(Library.EPUB4J_NATIVE, new Probe("epub4j-native", () -> {
Boolean clean = tryInvokeStaticBoolean( Boolean clean = tryInvokeStaticBoolean(
"org.grimmory.epub4j.native_parsing.EpubNativeLibrary" "org.grimmory.epub4j.native_parsing.EpubNativeLibrary"
@@ -140,10 +136,6 @@ public final class NativeLibraries {
return isAvailable(Library.PDFIUM); return isAvailable(Library.PDFIUM);
} }
public boolean isLibArchiveAvailable() {
return isAvailable(Library.LIBARCHIVE);
}
public boolean isEpubNativeAvailable() { public boolean isEpubNativeAvailable() {
return isAvailable(Library.EPUB4J_NATIVE); return isAvailable(Library.EPUB4J_NATIVE);
} }
@@ -17,10 +17,6 @@ public class NativeLibraryManager {
return libs.isPdfiumAvailable(); return libs.isPdfiumAvailable();
} }
public boolean isLibArchiveAvailable() {
return libs.isLibArchiveAvailable();
}
public boolean isEpubNativeAvailable() { public boolean isEpubNativeAvailable() {
return libs.isEpubNativeAvailable(); return libs.isEpubNativeAvailable();
} }
@@ -1,11 +1,11 @@
package org.booklore.service; package org.booklore.service;
import com.github.gotson.nightcompress.Archive; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import com.github.gotson.nightcompress.ArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import com.github.gotson.nightcompress.LibArchiveException; import com.github.junrar.exception.RarException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError; import org.booklore.exception.ApiError;
import org.booklore.nativelib.NativeLibraries; import org.booklore.util.ArchiveUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -20,6 +20,8 @@ import java.util.List;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import java.util.stream.Stream; import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import java.util.zip.ZipFile;
@Slf4j @Slf4j
@Service @Service
@@ -29,42 +31,61 @@ public class ArchiveService {
.mapToObj(_ -> new ReentrantLock()) .mapToObj(_ -> new ReentrantLock())
.toArray(ReentrantLock[]::new); .toArray(ReentrantLock[]::new);
// Route through the JVM-wide serialized native loader.
private final boolean available = NativeLibraries.get().isLibArchiveAvailable();
private ReentrantLock getFileLock(Path path) { private ReentrantLock getFileLock(Path path) {
int hash = path.toAbsolutePath().normalize().toString().hashCode(); int hash = path.toAbsolutePath().normalize().toString().hashCode();
return lockStripes[Math.floorMod(hash, LOCK_STRIPE_COUNT)]; return lockStripes[Math.floorMod(hash, LOCK_STRIPE_COUNT)];
} }
private void requireAvailable() throws IOException {
if (!available) {
throw new IOException("LibArchive is not available – cannot process archive");
}
}
public static boolean isAvailable() {
return NativeLibraries.get().isLibArchiveAvailable();
}
public record Entry(String name, long size) {} public record Entry(String name, long size) {}
private Entry getEntryFromArchiveEntry(ArchiveEntry archiveEntry) {
return new Entry(archiveEntry.getName(), archiveEntry.getSize());
}
public List<Entry> getEntries(Path path) throws IOException { public List<Entry> getEntries(Path path) throws IOException {
return streamEntries(path).toList(); return streamEntries(path).toList();
} }
private Stream<Entry> streamEntriesFromZip(Path path) throws IOException {
try (ZipFile file = new ZipFile(path.toFile())) {
// Stream to list so we enumerate all of them before the zipfile closes.
return file.stream()
.toList()
.stream()
.map(e -> new Entry(e.getName(), e.getSize()));
}
}
private Stream<Entry> streamEntriesFromRar(Path path) throws IOException {
try (var archive = new com.github.junrar.Archive(path.toFile())) {
return archive.getFileHeaders()
.stream()
.filter(h -> !h.isDirectory())
.map(h -> new Entry(h.getFileName(), h.getFullUnpackSize()))
.toList()
.stream();
} catch (RarException rarException) {
throw new IOException(rarException);
}
}
private Stream<Entry> streamEntriesFrom7z(Path path) throws IOException {
try (var sevenZFile = new SevenZFile.Builder().setPath(path).get()) {
return StreamSupport.stream(sevenZFile.getEntries().spliterator(), false)
.map(entry -> new Entry(entry.getName(), entry.getSize()))
.toList()
.stream();
}
}
public Stream<Entry> streamEntries(Path path) throws IOException { public Stream<Entry> streamEntries(Path path) throws IOException {
requireAvailable();
ReentrantLock lock = getFileLock(path); ReentrantLock lock = getFileLock(path);
lock.lock();
try { try {
List<ArchiveEntry> entries = Archive.getEntries(path); lock.lock();
return entries.stream().map(this::getEntryFromArchiveEntry);
} catch (LibArchiveException e) { return switch(ArchiveUtils.detectArchiveType(path)) {
case ZIP -> streamEntriesFromZip(path);
case RAR -> streamEntriesFromRar(path);
case SEVEN_ZIP -> streamEntriesFrom7z(path);
case UNKNOWN -> throw new IOException("Unknown Archive Type");
};
} catch (IOException e) {
throw new IOException("Failed to read archive", e); throw new IOException("Failed to read archive", e);
} finally { } finally {
lock.unlock(); lock.unlock();
@@ -76,43 +97,78 @@ public class ArchiveService {
} }
public Stream<String> streamEntryNames(Path path) throws IOException { public Stream<String> streamEntryNames(Path path) throws IOException {
requireAvailable(); return streamEntries(path).map(Entry::name);
ReentrantLock lock = getFileLock(path); }
lock.lock();
try { private long transferZipEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException {
List<ArchiveEntry> entries = Archive.getEntries(path); try (ZipFile zipFile = new ZipFile(path.toFile())) {
return entries.stream().map(ArchiveEntry::getName); var entry = zipFile.getEntry(entryName);
} catch (LibArchiveException e) {
throw new IOException("Failed to read archive", e); if (entry == null || entry.isDirectory()) {
} finally { throw new IOException("Entry not found in archive");
lock.unlock(); }
try (InputStream is = zipFile.getInputStream(entry)) {
return is.transferTo(outputStream);
}
}
}
private long transferRarEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException {
try (var archive = new com.github.junrar.Archive(path.toFile())) {
var fileHeader = archive.getFileHeaders()
.stream()
.filter(h -> !h.isDirectory())
.filter(h -> entryName.equals(h.getFileName()))
.findFirst()
.orElse(null);
if (fileHeader == null) {
throw new IOException("Entry not found in archive");
}
try (InputStream is = archive.getInputStream(fileHeader)) {
return is.transferTo(outputStream);
}
} catch (RarException rarException) {
throw new IOException(rarException);
}
}
private long transfer7zEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException {
try (var sevenZFile = new SevenZFile.Builder().setPath(path).get()) {
var entry = StreamSupport.stream(sevenZFile.getEntries().spliterator(), false)
.filter(e -> entryName.equals(e.getName()))
.filter(SevenZArchiveEntry::hasStream)
.findFirst()
.orElse(null);
if (entry == null) {
throw new IOException("Entry not found in archive");
}
try (InputStream is = sevenZFile.getInputStream(entry)) {
return is.transferTo(outputStream);
}
} }
} }
public long transferEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException { 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); ReentrantLock lock = getFileLock(path);
lock.lock(); try {
try (InputStream inputStream = Archive.getInputStream(path, entryName)) { lock.lock();
if (inputStream != null) {
try { return switch(ArchiveUtils.detectArchiveType(path)) {
return inputStream.transferTo(outputStream); case ZIP -> transferZipEntryTo(path, entryName, outputStream);
} finally { case RAR -> transferRarEntryTo(path, entryName, outputStream);
// NightCompress fails with a SIGSEGV if you do not read the case SEVEN_ZIP -> transfer7zEntryTo(path, entryName, outputStream);
// entirety of the input stream from the zip. case UNKNOWN -> throw new IOException("Unknown Archive Type");
inputStream.transferTo(OutputStream.nullOutputStream()); };
}
}
} catch (Exception e) { } catch (Exception e) {
throw new IOException("Failed to extract from archive: " + e.getMessage(), e); throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
} finally { } finally {
lock.unlock(); lock.unlock();
} }
throw new IOException("Entry not found in archive");
} }
public byte[] getEntryBytes(Path path, String entryName) throws IOException { public byte[] getEntryBytes(Path path, String entryName) throws IOException {
@@ -189,7 +245,6 @@ public class ArchiveService {
} }
public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException { public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException {
requireAvailable();
ReentrantLock lock = getFileLock(path); ReentrantLock lock = getFileLock(path);
lock.lock(); lock.lock();
@@ -33,8 +33,6 @@ public class ChapterCacheService {
/** /**
* Ensures all pages of a CBX archive are extracted to the disk cache. * 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 { public void prepareCbxCache(String cacheKey, Path cbxPath, List<String> entries) throws IOException {
ReentrantLock lock = cacheLocks.computeIfAbsent(cacheKey, _ -> new ReentrantLock()); ReentrantLock lock = cacheLocks.computeIfAbsent(cacheKey, _ -> new ReentrantLock());
@@ -31,7 +31,6 @@ logging:
root: WARN root: WARN
org.booklore: WARN org.booklore: WARN
org.hibernate.orm.deprecation: ERROR org.hibernate.orm.deprecation: ERROR
com.github.gotson.nightcompress.Archive: ERROR
io.micrometer.core.instrument.binder.cache.CaffeineCacheMetrics: ERROR io.micrometer.core.instrument.binder.cache.CaffeineCacheMetrics: ERROR
org.booklore.config.WebSocketConfig: ERROR org.booklore.config.WebSocketConfig: ERROR
org.booklore.config.security.SecurityConfig: ERROR org.booklore.config.security.SecurityConfig: ERROR
@@ -34,7 +34,6 @@ import org.mockito.Mockito;
/** /**
* Integration tests that feed a real RAR5 archive into the service layer * Integration tests that feed a real RAR5 archive into the service layer
*/ */
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class Rar5IntegrationTest { class Rar5IntegrationTest {
@@ -25,7 +25,6 @@ import java.util.List;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
@DisplayName("CBX Conversion Integration Test") @DisplayName("CBX Conversion Integration Test")
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
class CbxConversionIntegrationTest { class CbxConversionIntegrationTest {
@TempDir @TempDir
@@ -26,7 +26,6 @@ import java.util.List;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
@DisplayName("CBX Conversion Service Tests") @DisplayName("CBX Conversion Service Tests")
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
class CbxConversionServiceTest { class CbxConversionServiceTest {
@TempDir @TempDir
@@ -31,7 +31,6 @@ import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
class CbxComicInfoComplianceTest { class CbxComicInfoComplianceTest {
private static final Pattern EMPTY_LINES_PATTERN = Pattern.compile("(?s).*\\n\\s*\\n\\s*<.*"); private static final Pattern EMPTY_LINES_PATTERN = Pattern.compile("(?s).*\\n\\s*\\n\\s*<.*");
@@ -36,7 +36,6 @@ import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@EnabledIf("org.booklore.service.ArchiveService#isAvailable")
class CbxMetadataWriterTest { class CbxMetadataWriterTest {
private CbxMetadataWriter writer; private CbxMetadataWriter writer;