refactor(nativelib): implement JVM-wide native library availability checks and management (#790)

This commit is contained in:
brios
2026-04-24 10:31:38 +02:00
committed by GitHub
parent 8765a3e63c
commit 48efff74b7
6 changed files with 227 additions and 39 deletions
@@ -0,0 +1,155 @@
package org.booklore.nativelib;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* JVM-wide single source of truth for native-library availability.
*
* <p>Initialization is intentionally serialized via the holder idiom so native
* library loading is forced exactly once under the JVM class-init lock.
*/
@Slf4j
public final class NativeLibraries {
public enum Library {
PDFIUM,
LIBARCHIVE,
EPUB4J_NATIVE
}
private static final Map<Library, Probe> PROBES;
static {
Map<Library, Probe> probes = new LinkedHashMap<>();
probes.put(Library.PDFIUM, new Probe("PDFium", () -> {
Boolean clean = tryInvokeStaticBoolean("org.grimmory.pdfium4j.PdfiumLibrary");
if (clean != null) {
return clean;
}
org.grimmory.pdfium4j.PdfiumLibrary.initialize();
return true;
}));
probes.put(Library.LIBARCHIVE, new Probe("libarchive", com.github.gotson.nightcompress.Archive::isAvailable));
probes.put(Library.EPUB4J_NATIVE, new Probe("epub4j-native", () -> {
Boolean clean = tryInvokeStaticBoolean(
"org.grimmory.epub4j.native_parsing.EpubNativeLibrary"
);
if (clean != null) {
return clean;
}
Class.forName(
"org.grimmory.epub4j.native_parsing.PanamaConstants",
true,
NativeLibraries.class.getClassLoader()
);
return true;
}));
PROBES = Collections.unmodifiableMap(probes);
}
private final Map<Library, Boolean> status;
private NativeLibraries() {
Map<Library, Boolean> result = new LinkedHashMap<>();
for (Map.Entry<Library, Probe> entry : PROBES.entrySet()) {
result.put(entry.getKey(), runProbe(entry.getValue()));
}
this.status = Collections.unmodifiableMap(result);
logSummary();
}
private static boolean runProbe(Probe probe) {
try {
return probe.fn.get();
} catch (Throwable t) {
log.warn("{} native library unavailable: {}", probe.name, t.toString());
return false;
}
}
private static Boolean tryInvokeStaticBoolean(String fqcn) throws Throwable {
Class<?> cls;
try {
cls = Class.forName(fqcn, false, NativeLibraries.class.getClassLoader());
} catch (ClassNotFoundException _) {
return null;
}
Method method;
try {
method = cls.getMethod("isAvailable");
} catch (NoSuchMethodException _) {
return null;
}
if (method.getReturnType() != boolean.class) {
return null;
}
Class.forName(fqcn, true, NativeLibraries.class.getClassLoader());
try {
return (Boolean) method.invoke(null);
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
throw cause != null ? cause : ite;
}
}
private void logSummary() {
StringBuilder sb = new StringBuilder("Native libraries,");
boolean first = true;
for (Map.Entry<Library, Boolean> entry : status.entrySet()) {
sb.append(first ? " " : ", ")
.append(PROBES.get(entry.getKey()).name)
.append(": ")
.append(entry.getValue() ? "loaded" : "NOT available");
first = false;
}
log.info(sb.toString());
}
private static final class Holder {
static final NativeLibraries INSTANCE = new NativeLibraries();
}
public static NativeLibraries get() {
return Holder.INSTANCE;
}
public static void ensureInitialized() {
NativeLibraries ignored = Holder.INSTANCE;
}
public boolean isAvailable(Library library) {
return Boolean.TRUE.equals(status.get(library));
}
public boolean isPdfiumAvailable() {
return isAvailable(Library.PDFIUM);
}
public boolean isLibArchiveAvailable() {
return isAvailable(Library.LIBARCHIVE);
}
public boolean isEpubNativeAvailable() {
return isAvailable(Library.EPUB4J_NATIVE);
}
private record Probe(String name, CheckedBooleanSupplier fn) {}
@FunctionalInterface
private interface CheckedBooleanSupplier {
boolean get() throws Throwable;
}
}
@@ -0,0 +1,31 @@
package org.booklore.nativelib;
import org.springframework.stereotype.Component;
/**
* Spring-managed thin delegate over {@link NativeLibraries}.
*
* <p>Constructing this component eagerly triggers JVM-wide native loading
* through the serialized holder path once per process.
*/
@Component
public class NativeLibraryManager {
private final NativeLibraries libs = NativeLibraries.get();
public boolean isPdfiumAvailable() {
return libs.isPdfiumAvailable();
}
public boolean isLibArchiveAvailable() {
return libs.isLibArchiveAvailable();
}
public boolean isEpubNativeAvailable() {
return libs.isEpubNativeAvailable();
}
public boolean isAvailable(NativeLibraries.Library library) {
return libs.isAvailable(library);
}
}
@@ -3,9 +3,9 @@ package org.booklore.service;
import com.github.gotson.nightcompress.Archive;
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.booklore.nativelib.NativeLibraries;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
@@ -27,34 +27,15 @@ public class ArchiveService {
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 {
return Archive.isAvailable();
} catch (Throwable e) {
return false;
}
}
// Route through the JVM-wide serialized native loader.
private final boolean available = NativeLibraries.get().isLibArchiveAvailable();
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");
@@ -62,7 +43,7 @@ public class ArchiveService {
}
public static boolean isAvailable() {
return Archive.isAvailable();
return NativeLibraries.get().isLibArchiveAvailable();
}
public record Entry(String name, long size) {}