From 48efff74b7c2e98d4ff69b2b5453e44d7a2d77f8 Mon Sep 17 00:00:00 2001 From: brios <127139797+balazs-szucs@users.noreply.github.com> Date: Fri, 24 Apr 2026 10:31:38 +0200 Subject: [PATCH] refactor(nativelib): implement JVM-wide native library availability checks and management (#790) --- backend/build.gradle.kts | 2 +- .../booklore/nativelib/NativeLibraries.java | 155 ++++++++++++++++++ .../nativelib/NativeLibraryManager.java | 31 ++++ .../org/booklore/service/ArchiveService.java | 27 +-- .../test/EpubNativeAvailableCondition.java | 26 +++ .../test/PdfiumAvailableCondition.java | 25 ++- 6 files changed, 227 insertions(+), 39 deletions(-) create mode 100644 backend/src/main/java/org/booklore/nativelib/NativeLibraries.java create mode 100644 backend/src/main/java/org/booklore/nativelib/NativeLibraryManager.java create mode 100644 backend/src/test/java/org/booklore/test/EpubNativeAvailableCondition.java diff --git a/backend/build.gradle.kts b/backend/build.gradle.kts index cbd4554df..f459b5d97 100644 --- a/backend/build.gradle.kts +++ b/backend/build.gradle.kts @@ -120,7 +120,7 @@ dependencies { annotationProcessor("org.projectlombok:lombok:1.18.46") // --- Book & Image Processing --- - val pdfium4jVersion = if (useLocalLibs) "+" else "0.14.0" + val pdfium4jVersion = if (useLocalLibs) "+" else "0.15.0" implementation("org.grimmory:pdfium4j:$pdfium4jVersion") runtimeOnly("org.grimmory:pdfium4j:$pdfium4jVersion:${pdfiumNativesClassifier()}") diff --git a/backend/src/main/java/org/booklore/nativelib/NativeLibraries.java b/backend/src/main/java/org/booklore/nativelib/NativeLibraries.java new file mode 100644 index 000000000..f23fe1305 --- /dev/null +++ b/backend/src/main/java/org/booklore/nativelib/NativeLibraries.java @@ -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. + * + *

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 PROBES; + + static { + Map 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 status; + + private NativeLibraries() { + Map result = new LinkedHashMap<>(); + for (Map.Entry 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 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; + } +} diff --git a/backend/src/main/java/org/booklore/nativelib/NativeLibraryManager.java b/backend/src/main/java/org/booklore/nativelib/NativeLibraryManager.java new file mode 100644 index 000000000..84ea5e774 --- /dev/null +++ b/backend/src/main/java/org/booklore/nativelib/NativeLibraryManager.java @@ -0,0 +1,31 @@ +package org.booklore.nativelib; + +import org.springframework.stereotype.Component; + +/** + * Spring-managed thin delegate over {@link NativeLibraries}. + * + *

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); + } +} diff --git a/backend/src/main/java/org/booklore/service/ArchiveService.java b/backend/src/main/java/org/booklore/service/ArchiveService.java index 305278272..d03e645f4 100644 --- a/backend/src/main/java/org/booklore/service/ArchiveService.java +++ b/backend/src/main/java/org/booklore/service/ArchiveService.java @@ -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) {} diff --git a/backend/src/test/java/org/booklore/test/EpubNativeAvailableCondition.java b/backend/src/test/java/org/booklore/test/EpubNativeAvailableCondition.java new file mode 100644 index 000000000..6b53ad884 --- /dev/null +++ b/backend/src/test/java/org/booklore/test/EpubNativeAvailableCondition.java @@ -0,0 +1,26 @@ +package org.booklore.test; + +import org.booklore.nativelib.NativeLibraries; +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +/** + * Enables tests only when epub4j-native binaries are available on the current + * platform. + * + *

Delegates to the JVM-wide native-library loader singleton. + */ +public class EpubNativeAvailableCondition implements ExecutionCondition { + + private static final ConditionEvaluationResult ENABLED = + ConditionEvaluationResult.enabled("epub4j-native library is available"); + + private static final ConditionEvaluationResult DISABLED = + ConditionEvaluationResult.disabled("epub4j-native library not available on this platform"); + + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + return NativeLibraries.get().isEpubNativeAvailable() ? ENABLED : DISABLED; + } +} diff --git a/backend/src/test/java/org/booklore/test/PdfiumAvailableCondition.java b/backend/src/test/java/org/booklore/test/PdfiumAvailableCondition.java index 70dd12615..f331b9979 100644 --- a/backend/src/test/java/org/booklore/test/PdfiumAvailableCondition.java +++ b/backend/src/test/java/org/booklore/test/PdfiumAvailableCondition.java @@ -1,31 +1,26 @@ package org.booklore.test; -import org.grimmory.pdfium4j.PdfiumLibrary; +import org.booklore.nativelib.NativeLibraries; import org.junit.jupiter.api.extension.ConditionEvaluationResult; import org.junit.jupiter.api.extension.ExecutionCondition; import org.junit.jupiter.api.extension.ExtensionContext; +/** + * Enables tests only when PDFium native binaries are available on the current + * platform. + * + *

Delegates to the JVM-wide native-library loader singleton. + */ public class PdfiumAvailableCondition implements ExecutionCondition { private static final ConditionEvaluationResult ENABLED = ConditionEvaluationResult.enabled("PDFium native library is available"); - private static final Boolean AVAILABLE = probe(); - - private static Boolean probe() { - try { - PdfiumLibrary.initialize(); - return true; - } catch (Exception | UnsatisfiedLinkError e) { - return false; - } - } + private static final ConditionEvaluationResult DISABLED = + ConditionEvaluationResult.disabled("PDFium native library not available on this platform"); @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { - if (Boolean.TRUE.equals(AVAILABLE)) { - return ENABLED; - } - return ConditionEvaluationResult.disabled("PDFium native library not available on this platform"); + return NativeLibraries.get().isPdfiumAvailable() ? ENABLED : DISABLED; } }