#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
perf: lazy-load Type3 font payloads (#8584)
brios51ecc9dc444a
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.javaindex 457d2c9c8a..7468bdbc3a 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.java@@ -5,6 +5,7 @@ import java.io.InputStream;import java.util.ArrayList;import java.util.Base64;import java.util.Collections;+import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;@@ -38,10 +39,12 @@ public class Type3FontLibrary {private final Map<String, Type3FontLibraryEntry> signatureIndex = new ConcurrentHashMap<>();private final Map<String, Type3FontLibraryEntry> aliasIndex = new ConcurrentHashMap<>();+ private final Map<String, Type3FontLibraryPayload> payloadCache = new HashMap<>();private List<Type3FontLibraryEntry> entries = List.of();@jakarta.annotation.PostConstructvoid initialise() {+ payloadCache.clear();if (applicationProperties.getPdfEditor() != null&& applicationProperties.getPdfEditor().getType3() != null&& applicationProperties.getPdfEditor().getType3().getLibrary() != null) {@@ -176,9 +179,9 @@ public class Type3FontLibrary {.label(rawEntry.label != null ? rawEntry.label : rawEntry.id).signatures(normalizeList(rawEntry.signatures)).aliases(normalizeList(rawEntry.aliases))- .program(loadPayload(rawEntry.program))- .webProgram(loadPayload(rawEntry.webProgram))- .pdfProgram(loadPayload(rawEntry.pdfProgram))+ .program(loadPayloadCached(rawEntry.program))+ .webProgram(loadPayloadCached(rawEntry.webProgram))+ .pdfProgram(loadPayloadCached(rawEntry.pdfProgram)).source(rawEntry.source);if (rawEntry.glyphCoverage != null && !rawEntry.glyphCoverage.isEmpty()) {for (Integer codePoint : rawEntry.glyphCoverage) {@@ -197,14 +200,38 @@ public class Type3FontLibrary {}}+ private Type3FontLibraryPayload loadPayloadCached(RawPayload payload) throws IOException {+ if (payload == null) {+ return null;+ }+ if (payload.base64 != null && !payload.base64.isBlank()) {+ return loadPayload(payload);+ }+ try {+ if (payload.resource == null || payload.resource.isBlank()) {+ return loadPayload(payload);+ }+ String key = payload.resource + "|" + payload.format;+ Type3FontLibraryPayload cached = payloadCache.get(key);+ if (cached != null) {+ return cached;+ }+ Type3FontLibraryPayload loaded = loadPayload(payload);+ if (loaded != null) {+ payloadCache.put(key, loaded);+ }+ return loaded;+ } catch (IOException ex) {+ log.warn("[TYPE3] Failed to load Type3 payload: {}", ex.getMessage());+ return null;+ }+ }+private Type3FontLibraryPayload loadPayload(RawPayload payload) throws IOException {if (payload == null) {return null;}- String base64;if (payload.base64 != null && !payload.base64.isBlank()) {- // Validate the base64 string without wasteful full decode- // Only decode a small prefix to verify encoding is validtry {byte[] probe =Base64.getDecoder()@@ -218,18 +245,16 @@ public class Type3FontLibrary {log.warn("[TYPE3] Invalid base64 payload in Type3 library: {}", ex.getMessage());return null;}- // Keep the original base64 string directly — avoids 3x memory pressure- base64 = payload.base64;+ return new Type3FontLibraryPayload(payload.base64, normalizeFormat(payload.format));} else if (payload.resource != null && !payload.resource.isBlank()) {- byte[] data = loadResourceBytes(payload.resource);- if (data == null || data.length == 0) {- return null;+ String resolved = resolveLocation(payload.resource);+ Resource res = resourceLoader.getResource(resolved);+ if (!res.exists()) {+ throw new IOException("Resource not found: " + resolved);}- base64 = Base64.getEncoder().encodeToString(data);- } else {- return null;+ return new Type3FontLibraryPayload(res, normalizeFormat(payload.format));}- return new Type3FontLibraryPayload(base64, normalizeFormat(payload.format));+ return null;}private byte[] loadResourceBytes(String location) throws IOException {diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.javaindex 45f7a3d99d..9edfc8e239 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.java@@ -1,13 +1,104 @@package stirling.software.SPDF.service.pdfjson.type3.library;-import lombok.Value;+import java.io.IOException;+import java.io.InputStream;+import java.util.Base64;+import java.util.Objects;+import java.util.concurrent.TimeUnit;-@Value+import org.springframework.core.io.Resource;++import lombok.extern.slf4j.Slf4j;++@Slf4jpublic class Type3FontLibraryPayload {- String base64;- String format;+ private static final long FAILURE_RETRY_DELAY_NANOS = TimeUnit.SECONDS.toNanos(1);++ private final String directBase64;+ private final Resource resource;+ private final String format;+ private volatile String cachedBase64;+ private volatile long retryAfterNanos;++ public Type3FontLibraryPayload(String base64, String format) {+ this.directBase64 = base64;+ this.resource = null;+ this.format = format;+ }++ public Type3FontLibraryPayload(Resource resource, String format) {+ this.directBase64 = null;+ this.resource = resource;+ this.format = format;+ }++ public String getBase64() {+ if (directBase64 != null) {+ return directBase64;+ }+ if (resource == null) {+ return null;+ }+ if (System.nanoTime() < retryAfterNanos) {+ return null;+ }+ if (cachedBase64 == null) {+ synchronized (this) {+ if (cachedBase64 == null) {+ if (System.nanoTime() < retryAfterNanos) {+ return null;+ }+ try (InputStream is = resource.getInputStream()) {+ byte[] bytes = is.readAllBytes();+ if (bytes.length == 0) {+ retryAfterNanos = System.nanoTime() + FAILURE_RETRY_DELAY_NANOS;+ return null;+ }+ cachedBase64 = Base64.getEncoder().encodeToString(bytes);+ retryAfterNanos = 0;+ } catch (IOException e) {+ retryAfterNanos = System.nanoTime() + FAILURE_RETRY_DELAY_NANOS;+ log.warn(+ "[TYPE3] Failed to read Type3 payload {}: {}",+ resource.getDescription(),+ e.getMessage());+ return null;+ }+ }+ }+ }+ return cachedBase64;+ }++ public String getFormat() {+ return format;+ }public boolean hasPayload() {- return base64 != null && !base64.isBlank();+ if (directBase64 != null) {+ return !directBase64.isBlank();+ }+ return resource != null && resource.exists();+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ Type3FontLibraryPayload that = (Type3FontLibraryPayload) o;+ // Compare descriptors only: resolving base64 reads and encodes the whole font file, so+ // equality must never trigger it.+ return Objects.equals(directBase64, that.directBase64)+ && Objects.equals(describe(resource), describe(that.resource))+ && Objects.equals(format, that.format);+ }++ @Override+ public int hashCode() {+ return Objects.hash(directBase64, describe(resource), format);+ }++ private static String describe(Resource resource) {+ return resource == null ? null : resource.getDescription();}}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.javaindex fc2db78a38..a3a88765bc 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.java@@ -1,8 +1,13 @@package stirling.software.SPDF.service.pdfjson.type3.library;import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.Mockito.*;++import java.io.ByteArrayInputStream;+import java.io.IOException;import org.junit.jupiter.api.Test;+import org.springframework.core.io.Resource;class Type3FontLibraryPayloadTest {@@ -14,7 +19,7 @@ class Type3FontLibraryPayloadTest {@Testvoid hasPayload_nullBase64_returnsFalse() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload(null, "ttf");+ Type3FontLibraryPayload payload = new Type3FontLibraryPayload((String) null, "ttf");assertFalse(payload.hasPayload());}@@ -52,6 +57,28 @@ class Type3FontLibraryPayloadTest {assertEquals(a.hashCode(), b.hashCode());}+ @Test+ void getBase64_ioFailure_cooldownsThenRetries() throws Exception {+ Resource resource = mock(Resource.class);+ when(resource.getDescription()).thenReturn("test-resource");+ when(resource.getInputStream())+ .thenThrow(new IOException("first read"))+ .thenReturn(new ByteArrayInputStream(new byte[] {1, 2, 3}));+ Type3FontLibraryPayload payload = new Type3FontLibraryPayload(resource, "ttf");++ assertNull(payload.getBase64());+ assertNull(payload.getBase64());+ verify(resource, times(1)).getInputStream();++ java.lang.reflect.Field retryAfterNanos =+ Type3FontLibraryPayload.class.getDeclaredField("retryAfterNanos");+ retryAfterNanos.setAccessible(true);+ retryAfterNanos.setLong(payload, 0);++ assertEquals("AQID", payload.getBase64());+ verify(resource, times(2)).getInputStream();+ }+@Testvoid valueSemantics_different() {Type3FontLibraryPayload a = new Type3FontLibraryPayload("AQID", "ttf");diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.javaindex 8cd556753c..1383bb2c5e 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.java@@ -63,6 +63,23 @@ class Type3FontLibraryTest {return m.invoke(library, args);}+ private Object rawPayload(Class<?> type, String resource, String format, String base64)+ throws Exception {+ java.lang.reflect.Constructor<?> constructor = type.getDeclaredConstructor();+ constructor.setAccessible(true);+ Object payload = constructor.newInstance();+ java.lang.reflect.Field resourceField = type.getDeclaredField("resource");+ resourceField.setAccessible(true);+ resourceField.set(payload, resource);+ java.lang.reflect.Field formatField = type.getDeclaredField("format");+ formatField.setAccessible(true);+ formatField.set(payload, format);+ java.lang.reflect.Field base64Field = type.getDeclaredField("base64");+ base64Field.setAccessible(true);+ base64Field.set(payload, base64);+ return payload;+ }+@Nested@DisplayName("initialise()")class Initialise {@@ -199,6 +216,47 @@ class Type3FontLibraryTest {assertFalse(library.isLoaded());}+ @Test+ @DisplayName("direct base64 payloads are not confused by a shared resource key")+ void loadPayloadCached_directBase64_bypassesResourceCache() throws Exception {+ Type3FontLibrary library =+ newLibrary(new DefaultResourceLoader(), new ApplicationProperties());+ Class<?> rawType = Class.forName(Type3FontLibrary.class.getName() + "$RawPayload");+ Object first = rawPayload(rawType, "type3/library/fonts/missing.ttf", "ttf", "AQID");+ Object second = rawPayload(rawType, "type3/library/fonts/missing.ttf", "ttf", "BAUG");+ Method method = Type3FontLibrary.class.getDeclaredMethod("loadPayloadCached", rawType);+ method.setAccessible(true);++ Type3FontLibraryPayload firstLoaded =+ (Type3FontLibraryPayload) method.invoke(library, first);+ Type3FontLibraryPayload secondLoaded =+ (Type3FontLibraryPayload) method.invoke(library, second);++ assertEquals("AQID", firstLoaded.getBase64());+ assertEquals("BAUG", secondLoaded.getBase64());+ }++ @Test+ @DisplayName("missing sibling resource keeps a valid direct payload")+ void initialise_missingSiblingResource_keepsEntry() throws Exception {+ String json =+ "[{\"id\":\"mixed\",\"label\":\"Mixed\","+ + "\"program\":{\"resource\":\"type3/library/fonts/missing.ttf\","+ + "\"format\":\"ttf\"},"+ + "\"webProgram\":{\"base64\":\"AQID\",\"format\":\"ttf\"}}]";+ ResourceLoader loader = spy(new DefaultResourceLoader());+ Resource indexResource = mock(Resource.class);+ when(loader.getResource("classpath:/mixed.json")).thenReturn(indexResource);+ when(indexResource.exists()).thenReturn(true);+ when(indexResource.getInputStream())+ .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));++ Type3FontLibrary library = newLibrary(loader, propsWithIndex("classpath:/mixed.json"));+ invokeInitialise(library);++ assertTrue(library.isLoaded());+ }+@Test@DisplayName("resource-based payload is read and re-encoded to base64")void initialise_resourcePayload_loaded() throws Exception {