diff --git a/modules/cache-postgres/src/main/java/org/fireflyframework/cache/adapter/postgres/PostgresCacheAdapter.java b/modules/cache-postgres/src/main/java/org/fireflyframework/cache/adapter/postgres/PostgresCacheAdapter.java index 9a26bf81a..828f2a775 100644 --- a/modules/cache-postgres/src/main/java/org/fireflyframework/cache/adapter/postgres/PostgresCacheAdapter.java +++ b/modules/cache-postgres/src/main/java/org/fireflyframework/cache/adapter/postgres/PostgresCacheAdapter.java @@ -25,6 +25,8 @@ import io.r2dbc.spi.Statement; import io.r2dbc.spi.ValidationDepth; import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; +import org.fireflyframework.cache.exception.CacheException; import org.fireflyframework.cache.core.CacheHealth; import org.fireflyframework.cache.core.CacheStats; import org.fireflyframework.cache.core.CacheType; @@ -71,6 +73,7 @@ public class PostgresCacheAdapter implements CacheAdapter { private final PostgresCacheConfig config; private final CacheSerializer serializer; private final String qualifiedTable; + private final CacheOperationPolicy operationPolicy; private final AtomicLong requestCount = new AtomicLong(); private final AtomicLong hitCount = new AtomicLong(); @@ -93,6 +96,16 @@ public PostgresCacheAdapter(String cacheName, PostgresCacheConfig config, CacheSerializer serializer, String serviceNamespace) { + this(cacheName, connectionFactory, config, serializer, serviceNamespace, CacheOperationPolicy.LEGACY); + } + + public PostgresCacheAdapter(String cacheName, + ConnectionFactory connectionFactory, + PostgresCacheConfig config, + CacheSerializer serializer, + String serviceNamespace, + CacheOperationPolicy policy) { + this.operationPolicy = java.util.Objects.requireNonNull(policy, "Cache operation policy required"); config.validate(cacheName, serviceNamespace); String featurePrefix = config.effectiveKeyPrefix(serviceNamespace); this.cacheName = cacheName; @@ -147,6 +160,7 @@ private String extractOriginalKey(String cacheKey) { */ private byte[] toBytes(Object value) { Object serialized = serializer.serialize(value); + if (primaryOnly() && serialized == null) throw new CacheException("Cache serialization returned no value"); if (serialized instanceof byte[] bytes) { return bytes; } @@ -154,6 +168,9 @@ private byte[] toBytes(Object value) { return str.getBytes(StandardCharsets.UTF_8); } // Primitives/Numbers are returned as-is by JsonCacheSerializer; stringify them. + if (primaryOnly() && !(serialized instanceof Number || serialized instanceof Boolean || serialized instanceof Character)) { + throw new CacheException("Cache serialization returned an unsupported representation"); + } return String.valueOf(serialized).getBytes(StandardCharsets.UTF_8); } @@ -166,6 +183,7 @@ private V fromBytes(byte[] bytes, Class valueType) { private byte[] readBytes(Readable row, String column) { Object raw = row.get(column); if (raw == null) { + if (primaryOnly()) throw new CacheException("Stored cache bytes are missing"); return null; } if (raw instanceof byte[] bytes) { @@ -173,9 +191,10 @@ private byte[] readBytes(Readable row, String column) { } if (raw instanceof java.nio.ByteBuffer buf) { byte[] out = new byte[buf.remaining()]; - buf.get(out); + (primaryOnly() ? buf.duplicate() : buf).get(out); return out; } + if (primaryOnly()) throw new CacheException("Unsupported stored cache byte representation"); return raw.toString().getBytes(StandardCharsets.UTF_8); } @@ -184,8 +203,10 @@ private byte[] readBytes(Readable row, String column) { * connection is released afterward. */ private Mono withConnection(java.util.function.Function> work) { + Mono acquired = Mono.from(connectionFactory.create()); + if (primaryOnly()) acquired = acquired.switchIfEmpty(Mono.error(new CacheException("Cache connection acquisition completed empty"))); return Mono.usingWhen( - Mono.from(connectionFactory.create()), + acquired, work::apply, Connection::close, (conn, err) -> Mono.from(conn.close()).then(Mono.error(err)), @@ -199,38 +220,45 @@ public Mono> get(K key) { @Override public Mono> get(K key, Class valueType) { - String fullKey = buildKey(key); - long start = System.nanoTime(); - requestCount.incrementAndGet(); - String sql = "SELECT value FROM " + qualifiedTable - + " WHERE cache_name = $1 AND cache_key = $2" - + " AND (expires_at IS NULL OR expires_at > NOW())"; - return withConnection(conn -> { - Statement st = conn.createStatement(sql) - .bind("$1", storageCacheName) - .bind("$2", fullKey); - return Flux.from(st.execute()) - .flatMap(result -> result.map((row, meta) -> readBytes(row, "value"))) - .next(); - }).map(bytes -> { - try { - V value = fromBytes(bytes, valueType); - hitCount.incrementAndGet(); - totalLoadTime.addAndGet(System.nanoTime() - start); - return Optional.ofNullable(value); - } catch (Exception e) { - log.warn("Failed to deserialize cached value for key present={} in cache '{}': type={}", - key != null, LogFields.text(cacheName), LogFields.errorType(e)); + return operation(() -> { + String fullKey = buildKey(key); + long start = System.nanoTime(); + requestCount.incrementAndGet(); + String sql = "SELECT value FROM " + qualifiedTable + + " WHERE cache_name = $1 AND cache_key = $2" + + " AND (expires_at IS NULL OR expires_at > NOW())"; + return withConnection(conn -> { + Statement st = conn.createStatement(sql) + .bind("$1", storageCacheName) + .bind("$2", fullKey); + return results(st) + .flatMap(result -> result.map((row, meta) -> readBytes(row, "value"))) + .next(); + }).map(bytes -> { + try { + V value = fromBytes(bytes, valueType); + if (primaryOnly() && (value == null || !valueType.isInstance(value))) { + throw new CacheException("Stored cache value does not match the requested type"); + } + hitCount.incrementAndGet(); + totalLoadTime.addAndGet(System.nanoTime() - start); + return Optional.ofNullable(value); + } catch (Exception e) { + if (primaryOnly()) throw new CacheException("Cannot decode cached value", e); + log.warn("Failed to deserialize cached value for key present={} in cache '{}': type={}", + key != null, LogFields.text(cacheName), LogFields.errorType(e)); + missCount.incrementAndGet(); + return Optional.empty(); + } + }).switchIfEmpty(Mono.fromSupplier(() -> { missCount.incrementAndGet(); return Optional.empty(); - } - }).switchIfEmpty(Mono.fromSupplier(() -> { - missCount.incrementAndGet(); - return Optional.empty(); - })).onErrorResume(e -> { - log.warn("Error reading key present={} from cache '{}': type={}", key != null, LogFields.text(cacheName), LogFields.errorType(e)); - missCount.incrementAndGet(); - return Mono.just(Optional.empty()); + })).onErrorResume(e -> { + if (primaryOnly()) return Mono.error(e); + log.warn("Error reading key present={} from cache '{}': type={}", key != null, LogFields.text(cacheName), LogFields.errorType(e)); + missCount.incrementAndGet(); + return Mono.just(Optional.empty()); + }); }); } @@ -241,40 +269,43 @@ public Mono put(K key, V value) { @Override public Mono put(K key, V value, Duration ttl) { - String fullKey = buildKey(key); - return Mono.fromCallable(() -> toBytes(value)) - .flatMap(bytes -> { - boolean hasTtl = ttl != null && !ttl.isZero() && !ttl.isNegative(); - return withConnection(conn -> { - Statement st; - if (hasTtl) { - String insertSql = "INSERT INTO " + qualifiedTable - + " (cache_name, cache_key, value, expires_at, created_at)" - + " VALUES ($1, $2, $3, pg_catalog.clock_timestamp() + ($4 || ' milliseconds')::interval, pg_catalog.clock_timestamp())" - + " ON CONFLICT (cache_name, cache_key) DO UPDATE" - + " SET value = EXCLUDED.value, expires_at = pg_catalog.clock_timestamp() + ($4 || ' milliseconds')::interval, created_at = pg_catalog.clock_timestamp()"; - st = conn.createStatement(insertSql) - .bind("$1", storageCacheName) - .bind("$2", fullKey) - .bind("$3", bytes) - .bind("$4", String.valueOf(ttl.toMillis())); - } else { - String insertSql = "INSERT INTO " + qualifiedTable - + " (cache_name, cache_key, value, expires_at, created_at)" - + " VALUES ($1, $2, $3, NULL, pg_catalog.clock_timestamp())" - + " ON CONFLICT (cache_name, cache_key) DO UPDATE" - + " SET value = EXCLUDED.value, expires_at = NULL, created_at = pg_catalog.clock_timestamp()"; - st = conn.createStatement(insertSql) - .bind("$1", storageCacheName) - .bind("$2", fullKey) - .bind("$3", bytes); - } - return rowsUpdated(st); - }).doOnNext(count -> { - if (count != 1) throw new IllegalStateException("PostgreSQL cache put requires exactly one affected row"); - putCount.incrementAndGet(); - }).then(); - }); + return operation(() -> { + if (primaryOnly() && value == null) return Mono.error(new CacheException("Non-null cache value required")); + String fullKey = buildKey(key); + return Mono.fromCallable(() -> toBytes(value)) + .flatMap(bytes -> { + boolean hasTtl = ttl != null && !ttl.isZero() && !ttl.isNegative(); + return withConnection(conn -> { + Statement st; + if (hasTtl) { + String insertSql = "INSERT INTO " + qualifiedTable + + " (cache_name, cache_key, value, expires_at, created_at)" + + " VALUES ($1, $2, $3, pg_catalog.clock_timestamp() + ($4 || ' milliseconds')::interval, pg_catalog.clock_timestamp())" + + " ON CONFLICT (cache_name, cache_key) DO UPDATE" + + " SET value = EXCLUDED.value, expires_at = pg_catalog.clock_timestamp() + ($4 || ' milliseconds')::interval, created_at = pg_catalog.clock_timestamp()"; + st = conn.createStatement(insertSql) + .bind("$1", storageCacheName) + .bind("$2", fullKey) + .bind("$3", bytes) + .bind("$4", String.valueOf(ttl.toMillis())); + } else { + String insertSql = "INSERT INTO " + qualifiedTable + + " (cache_name, cache_key, value, expires_at, created_at)" + + " VALUES ($1, $2, $3, NULL, pg_catalog.clock_timestamp())" + + " ON CONFLICT (cache_name, cache_key) DO UPDATE" + + " SET value = EXCLUDED.value, expires_at = NULL, created_at = pg_catalog.clock_timestamp()"; + st = conn.createStatement(insertSql) + .bind("$1", storageCacheName) + .bind("$2", fullKey) + .bind("$3", bytes); + } + return rowsUpdated(st); + }).doOnNext(count -> { + if (count != 1) throw new IllegalStateException("PostgreSQL cache put requires exactly one affected row"); + putCount.incrementAndGet(); + }).then(); + }); + }); } @Override @@ -284,143 +315,162 @@ public Mono putIfAbsent(K key, V value) { @Override public Mono putIfAbsent(K key, V value, Duration ttl) { - String fullKey = buildKey(key); - return Mono.fromCallable(() -> toBytes(value)) - .flatMap(bytes -> { - boolean hasTtl = ttl != null && !ttl.isZero() && !ttl.isNegative(); - String clock = "pg_catalog.clock_timestamp()"; - String expires = hasTtl ? clock + " + ($4 || ' milliseconds')::interval" : "NULL"; - String sql = "INSERT INTO " + qualifiedTable + " AS cache_entry" - + " (cache_name, cache_key, value, expires_at, created_at)" - + " VALUES ($1, $2, $3, " + expires + ", " + clock + ")" - + " ON CONFLICT (cache_name, cache_key) DO UPDATE" - + " SET value = EXCLUDED.value, expires_at = " + expires + ", created_at = " + clock - + " WHERE cache_entry.expires_at IS NOT NULL" - + " AND cache_entry.expires_at <= " + clock; - return withConnection(conn -> { - Statement st = conn.createStatement(sql) - .bind("$1", storageCacheName) - .bind("$2", fullKey) - .bind("$3", bytes); - if (hasTtl) { - st = st.bind("$4", String.valueOf(ttl.toMillis())); - } - return rowsUpdated(st); - }).map(n -> { - if (n != 0 && n != 1) { - throw new IllegalStateException("PostgreSQL cache insertion requires zero or one affected row"); - } - if (n == 1) putCount.incrementAndGet(); - return n == 1; + return operation(() -> { + if (primaryOnly() && value == null) return Mono.error(new CacheException("Non-null cache value required")); + String fullKey = buildKey(key); + return Mono.fromCallable(() -> toBytes(value)) + .flatMap(bytes -> { + boolean hasTtl = ttl != null && !ttl.isZero() && !ttl.isNegative(); + String clock = "pg_catalog.clock_timestamp()"; + String expires = hasTtl ? clock + " + ($4 || ' milliseconds')::interval" : "NULL"; + String sql = "INSERT INTO " + qualifiedTable + " AS cache_entry" + + " (cache_name, cache_key, value, expires_at, created_at)" + + " VALUES ($1, $2, $3, " + expires + ", " + clock + ")" + + " ON CONFLICT (cache_name, cache_key) DO UPDATE" + + " SET value = EXCLUDED.value, expires_at = " + expires + ", created_at = " + clock + + " WHERE cache_entry.expires_at IS NOT NULL" + + " AND cache_entry.expires_at <= " + clock; + return withConnection(conn -> { + Statement st = conn.createStatement(sql) + .bind("$1", storageCacheName) + .bind("$2", fullKey) + .bind("$3", bytes); + if (hasTtl) { + st = st.bind("$4", String.valueOf(ttl.toMillis())); + } + return rowsUpdated(st); + }).map(n -> { + if (n != 0 && n != 1) { + throw new IllegalStateException("PostgreSQL cache insertion requires zero or one affected row"); + } + if (n == 1) putCount.incrementAndGet(); + return n == 1; + }); }); - }); + }); } @Override public Mono evict(K key) { - String fullKey = buildKey(key); - String sql = "DELETE FROM " + qualifiedTable + " WHERE cache_name = $1 AND cache_key = $2"; - return withConnection(conn -> rowsUpdated(conn.createStatement(sql) - .bind("$1", storageCacheName) - .bind("$2", fullKey))) - .map(n -> { - boolean removed = n > 0; - if (removed) { - evictionCount.incrementAndGet(); - } - return removed; - }) - .onErrorResume(e -> { - log.warn("Error evicting key present={} from cache '{}': type={}", key != null, LogFields.text(cacheName), LogFields.errorType(e)); - return Mono.just(false); - }); + return operation(() -> { + String fullKey = buildKey(key); + String sql = "DELETE FROM " + qualifiedTable + " WHERE cache_name = $1 AND cache_key = $2"; + return withConnection(conn -> rowsUpdated(conn.createStatement(sql) + .bind("$1", storageCacheName) + .bind("$2", fullKey))) + .map(n -> { + if (primaryOnly() && n != 0 && n != 1) throw new CacheException("Cache eviction returned an invalid count"); + boolean removed = n > 0; + if (removed) { + evictionCount.incrementAndGet(); + } + return removed; + }) + .onErrorResume(e -> { + if (primaryOnly()) return Mono.error(e); + log.warn("Error evicting key present={} from cache '{}': type={}", key != null, LogFields.text(cacheName), LogFields.errorType(e)); + return Mono.just(false); + }); + }); } @Override public Mono clear() { - String sql = "DELETE FROM " + qualifiedTable + " WHERE cache_name = $1"; - return withConnection(conn -> rowsUpdated(conn.createStatement(sql).bind("$1", storageCacheName))) - .doOnNext(evictionCount::addAndGet) - .then(); + return operation(() -> { + String sql = "DELETE FROM " + qualifiedTable + " WHERE cache_name = $1"; + return withConnection(conn -> rowsUpdated(conn.createStatement(sql).bind("$1", storageCacheName))) + .doOnNext(evictionCount::addAndGet) + .then(); + }); } @Override public Mono evictByPrefix(String keyPrefixToMatch) { - String fullPrefix = literalLikePrefix(buildKey(keyPrefixToMatch)); - String sql = "DELETE FROM " + qualifiedTable - + " WHERE cache_name = $1 AND cache_key LIKE $2 || '%' ESCAPE E'\\\\'"; - return withConnection(conn -> rowsUpdated(conn.createStatement(sql) - .bind("$1", storageCacheName) - .bind("$2", fullPrefix))) - .doOnNext(evictionCount::addAndGet); + return operation(() -> { + String fullPrefix = literalLikePrefix(buildKey(keyPrefixToMatch)); + String sql = "DELETE FROM " + qualifiedTable + + " WHERE cache_name = $1 AND cache_key LIKE $2 || '%' ESCAPE E'\\\\'"; + return withConnection(conn -> rowsUpdated(conn.createStatement(sql) + .bind("$1", storageCacheName) + .bind("$2", fullPrefix))) + .doOnNext(evictionCount::addAndGet); + }); } @Override public Mono exists(K key) { - String fullKey = buildKey(key); - String sql = "SELECT 1 FROM " + qualifiedTable - + " WHERE cache_name = $1 AND cache_key = $2" - + " AND (expires_at IS NULL OR expires_at > NOW())"; - return withConnection(conn -> Flux.from(conn.createStatement(sql) - .bind("$1", storageCacheName) - .bind("$2", fullKey) - .execute()) - .flatMap(result -> result.map((row, meta) -> Boolean.TRUE)) - .next()) - .defaultIfEmpty(false) - .onErrorResume(e -> { - log.warn("Error checking existence of key present={} in cache '{}': type={}", - key != null, LogFields.text(cacheName), LogFields.errorType(e)); - return Mono.just(false); - }); + return operation(() -> { + String fullKey = buildKey(key); + String sql = "SELECT 1 FROM " + qualifiedTable + + " WHERE cache_name = $1 AND cache_key = $2" + + " AND (expires_at IS NULL OR expires_at > NOW())"; + return withConnection(conn -> results(conn.createStatement(sql) + .bind("$1", storageCacheName) + .bind("$2", fullKey)) + .flatMap(result -> result.map((row, meta) -> Boolean.TRUE)) + .next()) + .defaultIfEmpty(false) + .onErrorResume(e -> { + if (primaryOnly()) return Mono.error(e); + log.warn("Error checking existence of key present={} in cache '{}': type={}", + key != null, LogFields.text(cacheName), LogFields.errorType(e)); + return Mono.just(false); + }); + }); } @Override @SuppressWarnings("unchecked") public Mono> keys() { - String sql = "SELECT cache_key FROM " + qualifiedTable - + " WHERE cache_name = $1 AND (expires_at IS NULL OR expires_at > NOW())"; - return withConnection(conn -> Flux.from(conn.createStatement(sql) - .bind("$1", storageCacheName) - .execute()) - .flatMap(result -> result.map((row, meta) -> (String) row.get("cache_key"))) - .map(this::extractOriginalKey) - .map(k -> (K) k) - .collect(HashSet::new, Set::add)) - .map(set -> (Set) set); + return operation(() -> { + String sql = "SELECT cache_key FROM " + qualifiedTable + + " WHERE cache_name = $1 AND (expires_at IS NULL OR expires_at > NOW())"; + return withConnection(conn -> results(conn.createStatement(sql) + .bind("$1", storageCacheName)) + .flatMap(result -> result.map((row, meta) -> (String) row.get("cache_key"))) + .map(this::extractOriginalKey) + .map(k -> (K) k) + .collect(HashSet::new, Set::add)) + .map(set -> (Set) set); + }); } @Override public Mono size() { - String sql = "SELECT COUNT(*) AS cnt FROM " + qualifiedTable - + " WHERE cache_name = $1 AND (expires_at IS NULL OR expires_at > NOW())"; - return withConnection(conn -> Flux.from(conn.createStatement(sql) - .bind("$1", storageCacheName) - .execute()) - .flatMap(result -> result.map((row, meta) -> { - Number n = (Number) row.get("cnt"); - return n == null ? 0L : n.longValue(); - })) - .next()) - .defaultIfEmpty(0L); + return operation(() -> { + String sql = "SELECT COUNT(*) AS cnt FROM " + qualifiedTable + + " WHERE cache_name = $1 AND (expires_at IS NULL OR expires_at > NOW())"; + return withConnection(conn -> results(conn.createStatement(sql) + .bind("$1", storageCacheName)) + .flatMap(result -> result.map((row, meta) -> { + Number n = (Number) row.get("cnt"); + if (primaryOnly() && (n == null || n.longValue() < 0)) throw new CacheException("Cache size returned an invalid count"); + return n == null ? 0L : n.longValue(); + })) + .next()) + .switchIfEmpty(primaryOnly() ? Mono.error(new CacheException("Cache size completed without a result")) : Mono.empty()) + .defaultIfEmpty(0L); + }); } @Override public Mono getStats() { - return size().map(entryCount -> CacheStats.builder() - .requestCount(requestCount.get()) - .hitCount(hitCount.get()) - .missCount(missCount.get()) - .loadCount(putCount.get()) - .evictionCount(evictionCount.get()) - .entryCount(entryCount) - .averageLoadTime(hitCount.get() > 0 ? (double) totalLoadTime.get() / hitCount.get() : 0.0) - .estimatedSize(0) - .capturedAt(Instant.now()) - .cacheType(CacheType.POSTGRES) - .cacheName(cacheName) - .build()) - .onErrorReturn(CacheStats.empty(CacheType.POSTGRES, cacheName)); + return operation(() -> { + Mono stats = size().map(entryCount -> CacheStats.builder() + .requestCount(requestCount.get()) + .hitCount(hitCount.get()) + .missCount(missCount.get()) + .loadCount(putCount.get()) + .evictionCount(evictionCount.get()) + .entryCount(entryCount) + .averageLoadTime(hitCount.get() > 0 ? (double) totalLoadTime.get() / hitCount.get() : 0.0) + .estimatedSize(0) + .capturedAt(Instant.now()) + .cacheType(CacheType.POSTGRES) + .cacheName(cacheName) + .build()); + return primaryOnly() ? stats : stats.onErrorReturn(CacheStats.empty(CacheType.POSTGRES, cacheName)); + }); } @Override @@ -473,7 +523,37 @@ public void close() { log.info("Closing PostgreSQL cache adapter '{}'", LogFields.text(cacheName)); } + @Override + public CacheOperationPolicy operationPolicy() { + return operationPolicy; + } + + private boolean primaryOnly() { + return operationPolicy == CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS; + } + + private Mono operation(java.util.function.Supplier> work) { + if (!primaryOnly()) return work.get(); + return Mono.defer(() -> { + Mono result = work.get(); + return result == null ? Mono.error(new CacheException("Cache operation returned no publisher")) : result; + }); + } + + private Flux results(Statement statement) { + Flux results = Flux.from(statement.execute()); + return primaryOnly() ? results.single().flux() : results; + } + private Mono rowsUpdated(Statement statement) { + if (primaryOnly()) { + return results(statement).single() + .flatMap(result -> Flux.from(result.getRowsUpdated()).single()) + .map(count -> { + if (count < 0) throw new CacheException("Cache update returned an invalid count"); + return count.longValue(); + }); + } return Flux.from(statement.execute()) .flatMap(result -> Mono.from(result.getRowsUpdated())) .map(Number::longValue) diff --git a/modules/cache-postgres/src/main/java/org/fireflyframework/cache/factory/PostgresCacheHelper.java b/modules/cache-postgres/src/main/java/org/fireflyframework/cache/factory/PostgresCacheHelper.java index 65c5ae006..4b94784c1 100644 --- a/modules/cache-postgres/src/main/java/org/fireflyframework/cache/factory/PostgresCacheHelper.java +++ b/modules/cache-postgres/src/main/java/org/fireflyframework/cache/factory/PostgresCacheHelper.java @@ -21,6 +21,7 @@ import org.fireflyframework.cache.adapter.postgres.PostgresCacheAdapter; import org.fireflyframework.cache.adapter.postgres.PostgresCacheConfig; import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; import org.fireflyframework.cache.properties.CacheProperties; import org.fireflyframework.cache.serialization.CacheSerializer; import org.fireflyframework.cache.serialization.JsonCacheSerializer; @@ -58,6 +59,19 @@ public static CacheAdapter createPostgresCacheAdapter(String cacheName, Object r2dbcConnectionFactory, CacheProperties properties, ObjectMapper objectMapper) { + return createPostgresCacheAdapter(cacheName, keyPrefix, defaultTtl, r2dbcConnectionFactory, + properties, objectMapper, CacheOperationPolicy.LEGACY); + } + + /** Constructs an independent adapter with the explicitly selected operation policy. */ + public static CacheAdapter createPostgresCacheAdapter(String cacheName, + String keyPrefix, + Duration defaultTtl, + Object r2dbcConnectionFactory, + CacheProperties properties, + ObjectMapper objectMapper, + CacheOperationPolicy policy) { + java.util.Objects.requireNonNull(policy, "Cache operation policy required"); CacheSerializer serializer = new JsonCacheSerializer(objectMapper); CacheProperties.PostgresConfig postgres = properties.getPostgres(); @@ -78,6 +92,6 @@ public static CacheAdapter createPostgresCacheAdapter(String cacheName, config.validate(cacheName, serviceNamespace); ConnectionFactory connectionFactory = (ConnectionFactory) r2dbcConnectionFactory; PostgresCacheInitializer.initialize(connectionFactory, postgres, config); - return new PostgresCacheAdapter(cacheName, connectionFactory, config, serializer, serviceNamespace); + return new PostgresCacheAdapter(cacheName, connectionFactory, config, serializer, serviceNamespace, policy); } } diff --git a/modules/cache-postgres/src/main/java/org/fireflyframework/cache/spi/providers/PostgresProvider.java b/modules/cache-postgres/src/main/java/org/fireflyframework/cache/spi/providers/PostgresProvider.java index 172b13619..31b8bfbbf 100644 --- a/modules/cache-postgres/src/main/java/org/fireflyframework/cache/spi/providers/PostgresProvider.java +++ b/modules/cache-postgres/src/main/java/org/fireflyframework/cache/spi/providers/PostgresProvider.java @@ -17,6 +17,7 @@ package org.fireflyframework.cache.spi.providers; import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; import org.fireflyframework.cache.core.CacheType; import org.fireflyframework.cache.factory.PostgresCacheHelper; import org.fireflyframework.cache.spi.CacheProviderFactory; @@ -59,4 +60,14 @@ public CacheAdapter create(String cacheName, String keyPrefix, Duration defaultT ctx.properties, ctx.objectMapper); } + @Override + public CacheAdapter create(String cacheName, String keyPrefix, Duration defaultTtl, + ProviderContext ctx, CacheOperationPolicy policy) { + java.util.Objects.requireNonNull(policy, "Cache operation policy required"); + if (policy == CacheOperationPolicy.LEGACY) return create(cacheName, keyPrefix, defaultTtl, ctx); + if (!isAvailable(ctx)) throw new IllegalStateException("The selected PostgreSQL cache provider is not configured"); + return PostgresCacheHelper.createPostgresCacheAdapter(cacheName, keyPrefix, defaultTtl, + ctx.r2dbcConnectionFactory, ctx.properties, ctx.objectMapper, policy); + } + } diff --git a/modules/cache-postgres/src/test/java/org/fireflyframework/cache/adapter/postgres/PostgresPrimaryOnlyPolicyTest.java b/modules/cache-postgres/src/test/java/org/fireflyframework/cache/adapter/postgres/PostgresPrimaryOnlyPolicyTest.java new file mode 100644 index 000000000..d84f53cb3 --- /dev/null +++ b/modules/cache-postgres/src/test/java/org/fireflyframework/cache/adapter/postgres/PostgresPrimaryOnlyPolicyTest.java @@ -0,0 +1,98 @@ +package org.fireflyframework.cache.adapter.postgres; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.r2dbc.spi.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.function.BiFunction; +import org.fireflyframework.cache.core.*; +import org.fireflyframework.cache.serialization.JsonCacheSerializer; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.*; +import reactor.test.StepVerifier; + +class PostgresPrimaryOnlyPolicyTest { + final ConnectionFactory factory=mock(ConnectionFactory.class); + final Connection connection=mock(Connection.class); + final Statement statement=mock(Statement.class,RETURNS_SELF); + final Result result=mock(Result.class); + final Row row=mock(Row.class); + @SuppressWarnings({"rawtypes","unchecked"}) + PostgresPrimaryOnlyPolicyTest() { + doReturn(Mono.just(connection)).when(factory).create();when(connection.close()).thenReturn(Mono.empty()); + when(connection.createStatement(anyString())).thenReturn(statement);doReturn(Flux.just(result)).when(statement).execute(); + when(result.getRowsUpdated()).thenReturn(Mono.just(1L)); + when(row.get("value")).thenReturn("value".getBytes(StandardCharsets.UTF_8)); + when(result.map(any(BiFunction.class))).thenAnswer(call->Flux.just(((BiFunction)call.getArgument(0)).apply(row,mock(RowMetadata.class)))); + } + PostgresCacheAdapter strict() {return new PostgresCacheAdapter("policy",factory,PostgresCacheConfig.builder().keyPrefix("service").build(),new JsonCacheSerializer(new ObjectMapper()),"service",CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS);} + PostgresCacheAdapter legacy() {return new PostgresCacheAdapter("policy",factory,PostgresCacheConfig.builder().keyPrefix("service").build(),new JsonCacheSerializer(new ObjectMapper()));} + @Test void acquireFailureIsNotAMissFalseOrSuccessfulWrite() { + doReturn(Mono.error(new IllegalStateException("controlled acquire failure"))).when(factory).create();var cache=strict(); + for(var operation:List.of(cache.get("key",String.class),cache.exists("key"),cache.evict("key"),cache.put("key","value"),cache.clear(),cache.getStats())) + StepVerifier.create(operation).expectError().verify(); + } + @Test void emptyAcquisitionCannotImplyMissConflictOrCompletion() { + doReturn(Mono.empty()).when(factory).create();var cache=strict(); + for(var operation:List.of(cache.get("key",String.class),cache.exists("key"),cache.putIfAbsent("key","value"),cache.put("key","value"),cache.clear())) + StepVerifier.create(operation).expectError().verify(); + } + @Test void statementFailureDoesNotBecomeEvictionFalseOrMissingValue() { + doReturn(Flux.error(new IllegalStateException("controlled statement failure"))).when(statement).execute();var cache=strict(); + StepVerifier.create(cache.get("key",String.class)).expectError().verify();StepVerifier.create(cache.evict("key")).expectError().verify(); + StepVerifier.create(cache.exists("key")).expectError().verify(); + } + @Test void deserializeFailureIsNotAMiss() { + when(row.get("value")).thenReturn("{".getBytes(StandardCharsets.UTF_8)); + StepVerifier.create(strict().get("key",Map.class)).expectError().verify(); + } + @Test void nullDecodeAndUnsupportedReadableTypeRefuse() { + when(row.get("value")).thenReturn("null".getBytes(StandardCharsets.UTF_8)); + StepVerifier.create(strict().get("key",Map.class)).expectError().verify(); + when(row.get("value")).thenReturn(new Object());StepVerifier.create(strict().get("key",String.class)).expectError().verify(); + } + @Test void releaseFailurePreventsValueOrVoidSuccess() { + when(connection.close()).thenReturn(Mono.error(new IllegalStateException("controlled release failure"))); + StepVerifier.create(strict().get("key",String.class)).expectError().verify();StepVerifier.create(strict().put("key","value")).expectError().verify(); + } + @SuppressWarnings({"rawtypes","unchecked"}) + @Test void successfulNoRowReadAndExistingEntryRemainDistinctFromFailure() { + when(result.map(any(BiFunction.class))).thenReturn(Flux.empty()); + StepVerifier.create(strict().get("key",String.class)).expectNext(Optional.empty()).verifyComplete(); + StepVerifier.create(strict().exists("key")).expectNext(false).verifyComplete(); + when(result.getRowsUpdated()).thenReturn(Mono.just(0L));StepVerifier.create(strict().putIfAbsent("key","value")).expectNext(false).verifyComplete(); + } + @Test void emptyOrInvalidUpdateResultCannotBecomeFalseOrCompletion() { + when(result.getRowsUpdated()).thenReturn(Mono.empty()); + StepVerifier.create(strict().putIfAbsent("key","value")).expectError().verify();StepVerifier.create(strict().clear()).expectError().verify(); + doReturn(Flux.empty()).when(statement).execute();StepVerifier.create(strict().evict("key")).expectError().verify(); + } + @Test void absentStatementResultCannotMasqueradeAsASuccessfulRead() { + doReturn(Flux.empty()).when(statement).execute();var cache=strict(); + for(var operation:List.of(cache.get("key",String.class),cache.exists("key"),cache.keys(),cache.size())) + StepVerifier.create(operation).expectError().verify(); + } + @Test void nullWritesRefuseBeforeAnyConnectionAcquisition() { + StepVerifier.create(strict().put("key",null)).expectError().verify();StepVerifier.create(strict().putIfAbsent("key",null)).expectError().verify();verifyNoInteractions(factory); + } + @Test void missingOrUnsupportedSerializedValueRefusesBeforeAcquisition() { + var serializer=mock(org.fireflyframework.cache.serialization.CacheSerializer.class); + var cache=new PostgresCacheAdapter("policy",factory,PostgresCacheConfig.builder().keyPrefix("service").build(),serializer,"service",CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + StepVerifier.create(cache.put("key","value")).expectError().verify(); + when(serializer.serialize("value")).thenReturn(new Object());StepVerifier.create(cache.put("key","value")).expectError().verify();verifyNoInteractions(factory); + } + @Test void directStrictAssemblyFailureIsReactive() { + var cache=strict();assertThatCode(()->cache.get(null,String.class)).doesNotThrowAnyException(); + StepVerifier.create(cache.get(null,String.class)).expectError().verify(); + } + @Test void independentLegacyInstanceRetainsRecoveryInsteadOfInheritingStrictState() { + doReturn(Mono.error(new IllegalStateException("controlled same-backend failure"))).when(factory).create(); + assertThat(legacy().operationPolicy()).isEqualTo(CacheOperationPolicy.LEGACY); + assertThat(strict().operationPolicy()).isEqualTo(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + StepVerifier.create(legacy().get("key",String.class)).expectNext(Optional.empty()).verifyComplete(); + StepVerifier.create(strict().get("key",String.class)).expectError().verify(); + } +} diff --git a/modules/cache-postgres/src/test/java/org/fireflyframework/cache/factory/PostgresPrimaryOnlyWiringTest.java b/modules/cache-postgres/src/test/java/org/fireflyframework/cache/factory/PostgresPrimaryOnlyWiringTest.java new file mode 100644 index 000000000..22b1bd06c --- /dev/null +++ b/modules/cache-postgres/src/test/java/org/fireflyframework/cache/factory/PostgresPrimaryOnlyWiringTest.java @@ -0,0 +1,39 @@ +package org.fireflyframework.cache.factory; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.r2dbc.spi.*; +import java.time.Duration; +import java.util.function.BiFunction; +import org.fireflyframework.cache.core.*; +import org.fireflyframework.cache.properties.CacheProperties; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import reactor.core.publisher.*; + +class PostgresPrimaryOnlyWiringTest { + final CacheProperties properties=new CacheProperties(); + final ConnectionFactory factory=mock(ConnectionFactory.class); + final Connection connection=mock(Connection.class); + final Statement statement=mock(Statement.class,RETURNS_SELF); + final Result result=mock(Result.class); + @SuppressWarnings({"rawtypes","unchecked"}) + PostgresPrimaryOnlyWiringTest(){properties.getPostgres().setKeyPrefix("service");doReturn(Mono.just(connection)).when(factory).create();when(connection.close()).thenReturn(Mono.empty());when(connection.createStatement(anyString())).thenReturn(statement);doReturn(Flux.just(result)).when(statement).execute();when(result.map(any(BiFunction.class))).thenReturn(Flux.empty());} + @Test void genuineProviderHelperAdapterChainRetainsStrictPolicyWithoutSmartOrL1(){ + properties.getSmart().setEnabled(true);properties.getCaffeine().setEnabled(true); + var manager=new CacheManagerFactory(properties,new ObjectMapper(),null,null,null,factory).createCacheManager( + "policy",CacheType.POSTGRES,"service:policy",Duration.ofMinutes(1),"policy test","test",CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + assertThat(manager.operationPolicy()).isEqualTo(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + var primary=(CacheAdapter)ReflectionTestUtils.getField(manager,"primaryCache"); + assertThat(primary).isInstanceOf(org.fireflyframework.cache.adapter.postgres.PostgresCacheAdapter.class); + assertThat(primary.operationPolicy()).isEqualTo(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + assertThat(ReflectionTestUtils.getField(manager,"fallbackCache")).isNull();verify(connection).close(); + } + @Test void oldAndExplicitHelperOverloadsConstructIndependentPolicies(){ + var legacy=PostgresCacheHelper.createPostgresCacheAdapter("legacy","service:legacy",Duration.ofMinutes(1),factory,properties,new ObjectMapper()); + var strict=PostgresCacheHelper.createPostgresCacheAdapter("strict","service:strict",Duration.ofMinutes(1),factory,properties,new ObjectMapper(),CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + assertThat(legacy.operationPolicy()).isEqualTo(CacheOperationPolicy.LEGACY);assertThat(strict.operationPolicy()).isEqualTo(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + } +} diff --git a/modules/cache/README.md b/modules/cache/README.md index 66e75ea62..7d2146c7a 100644 --- a/modules/cache/README.md +++ b/modules/cache/README.md @@ -6,6 +6,8 @@ Use a common cache API with a PostgreSQL default and explicit local or distribut Depend on the core abstraction, inject FireflyCacheManager or use CacheAdapter, and choose a provider through firefly.cache. Provider discovery and selection live in the core; add only the external provider library you need. +For an explicitly selected primary without L1/fallback and with operation failures propagated, see [Primary-only operations](docs/PRIMARY_ONLY_OPERATIONS.md). This opt-in source addition preserves legacy defaults and requires a matching qualified framework release. + [Module guide](../../docs/site/modules/cache.md) · [Jafly README](../../README.md) · [Module catalog](../../docs/site/modules/index.md) ## In the onboarding service diff --git a/modules/cache/docs/PRIMARY_ONLY_OPERATIONS.md b/modules/cache/docs/PRIMARY_ONLY_OPERATIONS.md new file mode 100644 index 000000000..19e50aff3 --- /dev/null +++ b/modules/cache/docs/PRIMARY_ONLY_OPERATIONS.md @@ -0,0 +1,45 @@ +# Primary-only operations with explicit failure propagation + +This opt-in API is a source addition for a matching future qualified framework release. It is not part of immutable26.10.23. All framework modules/adapters use the same release train; do not mix this cache API into an older reactor or assume publication from source tests. + +Use the policy when a caller must distinguish a successful cache miss/conflict from an unavailable backend or failed operation. Existing factory/manager constructors and global defaults remain LEGACY and retain their current fallback/error recovery. Choosing POSTGRES alone does not select this new policy: the legacy smart setting can still enable an L1. + +## Construct one explicit primary + +The application supplies a configured CacheManagerFactory and the separately configured PostgreSQL cache provider, service namespace and technical connection factory. This fragment is not a complete deployment configuration: + +```java +import java.time.Duration; +import org.fireflyframework.cache.core.CacheOperationPolicy; +import org.fireflyframework.cache.core.CacheType; + +var cache = factory.createCacheManager( + "guard-state", CacheType.POSTGRES, "service:guard-state", Duration.ofMinutes(1), + "Application-owned guarded cache state", "application", + CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); +``` + +This construction selects exactly one explicit provider. AUTO and NOOP refuse. Smart/L1 and fallback settings are not applied to this instance, even if globally enabled. No operation selects a different provider based on isAvailable/getHealth. Capability comes from the provider's explicit policy-aware construction contract; a cache type or health response cannot prove it. Provider construction failures propagate instead of falling back. + +PostgreSQL is the recommended and first supported built-in provider. Caffeine, Redis, Hazelcast and JCache remain explicit unsupported choices for this policy until their provider implementations opt in and are qualified. Their legacy operation behavior is unchanged. Old third-party providers inherit a default refusal for the new policy; they must implement it deliberately. A policy-configured adapter without a policy-configured manager is insufficient: old FireflyCacheManager constructors still select LEGACY. Prefer the policy-aware factory overload. + +## Observe operations honestly + +| Operation result | Meaning in this policy | +| --- | --- | +| Optional.empty from get | Successful backend query returned no current value. | +| false from exists/evict/putIfAbsent | Successful backend operation reported no match/removal/insertion, as applicable. | +| Completed put/clear | The provider completed the operation and resource-release publisher; no value is expected. | +| Error | Acquisition, SQL/driver, codec, unsupported result or resource-release failed. It is not converted into a miss, false, empty collection, zero size or completed write. | + +Absent publishers, empty required value publishers and invalid result shapes refuse. A Void operation legitimately completes without a value; an emitted value is unsupported. PostgreSQL refuses empty acquisition/update-result publishers and invalid affected counts, while retaining its existing atomic insertion and TTL SQL. Null stored values and unsupported/null decodes refuse in this policy instead of being presented as misses. Use the typed get overload for the representation the actual serializer supports. Legacy null/zero/negative explicit-TTL semantics and all existing storage/namespace/role rules are unchanged. + +An operation error can follow an applied mutation, for example when resource release fails after a write. Error propagation does not establish rollback or authorize a new unrelated retry. The consumer owns its failure handling and any required operation identity/reconciliation. The framework adds no Identity-specific logic or domain business state. + +getHealth/isAvailable remain diagnostics and must not authorize a later data operation. A DOWN diagnostic is explicitly unhealthy, not a successful authority check. Existing diagnostic error fields are not a new general privacy-safe HTTP contract. The serializer logging correction emits fixed metadata/error type and retains the original exception/cause behavior for application handling; it does not promise that arbitrary caller logging is safe. + +## Limits and qualification + +No distributed freshness, linearizability, quorum, durable commit, revocation, lock or business-transaction guarantee is implied. Backend topology/protocol and the consuming authority design remain decisive. No new SQL/schema/grant, role bootstrap or automatic external service is introduced. + +The module tests cover existing APIs and defaults, explicit provider construction, partial ServiceLoader discovery, R2DBC failure and resource-release publishers, and serializer log channels. PostgreSQL topology, roles, restart behavior, and consumer recovery still require validation in the deployment that uses this API. Source qualification does not establish a published release or consumer adoption. diff --git a/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheAdapter.java b/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheAdapter.java index 62c98c7f5..e312c1a29 100644 --- a/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheAdapter.java +++ b/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheAdapter.java @@ -38,6 +38,12 @@ */ public interface CacheAdapter { + /** Declares the immutable policy implemented by this adapter, not its current health. */ + default CacheOperationPolicy operationPolicy() { + return CacheOperationPolicy.LEGACY; + } + + /** * Retrieves a value from the cache. * diff --git a/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheOperationPolicy.java b/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheOperationPolicy.java new file mode 100644 index 000000000..651657e1e --- /dev/null +++ b/modules/cache/src/main/java/org/fireflyframework/cache/core/CacheOperationPolicy.java @@ -0,0 +1,23 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.cache.core; + +/** Per-instance operation behavior; no backend freshness or commit guarantee is implied. */ +public enum CacheOperationPolicy { + LEGACY, + PRIMARY_ONLY_PROPAGATE_ERRORS +} diff --git a/modules/cache/src/main/java/org/fireflyframework/cache/factory/CacheManagerFactory.java b/modules/cache/src/main/java/org/fireflyframework/cache/factory/CacheManagerFactory.java index 0e56a0e7a..ae70c94c3 100644 --- a/modules/cache/src/main/java/org/fireflyframework/cache/factory/CacheManagerFactory.java +++ b/modules/cache/src/main/java/org/fireflyframework/cache/factory/CacheManagerFactory.java @@ -20,6 +20,7 @@ import org.fireflyframework.cache.adapter.caffeine.CaffeineCacheAdapter; import org.fireflyframework.cache.adapter.caffeine.CaffeineCacheConfig; import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; import org.fireflyframework.cache.core.CacheType; import org.fireflyframework.cache.manager.FireflyCacheManager; import org.fireflyframework.cache.properties.CacheProperties; @@ -58,6 +59,7 @@ public class CacheManagerFactory { private java.util.List providerFactories; + private boolean providerDiscoveryComplete; private final CacheProperties properties; private final ObjectMapper objectMapper; @@ -274,6 +276,44 @@ public FireflyCacheManager createCacheManager(String cacheName, return new FireflyCacheManager(primaryCache, fallbackCache); } + /** Creates an explicitly selected primary with an immutable operation policy. */ + public FireflyCacheManager createCacheManager(String cacheName, + CacheType cacheType, + String keyPrefix, + Duration defaultTtl, + String description, + String requestedBy, + CacheOperationPolicy policy) { + java.util.Objects.requireNonNull(policy, "Cache operation policy required"); + if (policy == CacheOperationPolicy.LEGACY) { + return createCacheManager(cacheName, cacheType, keyPrefix, defaultTtl, description, requestedBy); + } + if (cacheType == null || cacheType == CacheType.AUTO || cacheType == CacheType.NOOP) { + throw new IllegalArgumentException("An explicit storage backend is required for primary-only operations"); + } + if (!providerDiscoveryComplete) { + throw new IllegalStateException("Cache provider discovery did not complete"); + } + var candidates = providerFactories.stream().filter(provider -> provider.getType() == cacheType).toList(); + if (candidates.size() != 1) { + throw new IllegalStateException("Exactly one provider for the selected cache backend is required"); + } + var context = new org.fireflyframework.cache.spi.CacheProviderFactory.ProviderContext( + properties, objectMapper, redisConnectionFactory, hazelcastInstance, jcacheManager, postgresFactoryFor(cacheType)); + CacheAdapter primary = candidates.getFirst().create(cacheName, keyPrefix, defaultTtl, context, policy); + if (primary == null) throw new IllegalStateException("The selected provider returned no cache adapter"); + try { + if (primary.getCacheType() != cacheType) { + throw new IllegalStateException("The selected provider must construct the requested cache backend"); + } + return new FireflyCacheManager(primary, null, policy); + } catch (RuntimeException | Error failure) { + try { primary.close(); } + catch (RuntimeException | Error cleanup) { if (cleanup != failure) failure.addSuppressed(cleanup); } + throw failure; + } + } + /** * Detects the caller class from the stack trace. */ @@ -329,7 +369,8 @@ private java.util.List load var loader = java.util.ServiceLoader.load(org.fireflyframework.cache.spi.CacheProviderFactory.class); loader.forEach(list::add); list.sort(java.util.Comparator.comparingInt(org.fireflyframework.cache.spi.CacheProviderFactory::priority)); - } catch (Throwable ignored) { } + providerDiscoveryComplete = true; + } catch (Throwable ignored) { providerDiscoveryComplete = false; } return list; } diff --git a/modules/cache/src/main/java/org/fireflyframework/cache/manager/FireflyCacheManager.java b/modules/cache/src/main/java/org/fireflyframework/cache/manager/FireflyCacheManager.java index 3557b2302..a48434c99 100644 --- a/modules/cache/src/main/java/org/fireflyframework/cache/manager/FireflyCacheManager.java +++ b/modules/cache/src/main/java/org/fireflyframework/cache/manager/FireflyCacheManager.java @@ -19,6 +19,8 @@ import org.fireflyframework.kernel.logging.LogFields; import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; +import org.fireflyframework.cache.exception.CacheException; import org.fireflyframework.cache.core.CacheHealth; import org.fireflyframework.cache.core.CacheStats; import org.fireflyframework.cache.core.CacheType; @@ -50,6 +52,7 @@ public class FireflyCacheManager implements CacheAdapter { private final CacheAdapter primaryCache; private final CacheAdapter fallbackCache; + private final CacheOperationPolicy operationPolicy; private volatile boolean closed = false; /** @@ -68,6 +71,15 @@ public FireflyCacheManager(CacheAdapter cache) { * @param fallbackCache optional fallback cache adapter (can be null) */ public FireflyCacheManager(CacheAdapter primaryCache, CacheAdapter fallbackCache) { + this(primaryCache, fallbackCache, CacheOperationPolicy.LEGACY); + } + + public FireflyCacheManager(CacheAdapter primaryCache, CacheAdapter fallbackCache, CacheOperationPolicy policy) { + this.operationPolicy = java.util.Objects.requireNonNull(policy, "Cache operation policy required"); + if (policy == CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS + && (primaryCache == null || fallbackCache != null || primaryCache.operationPolicy() != policy)) { + throw new IllegalArgumentException("A policy-configured primary without fallback is required"); + } this.primaryCache = primaryCache; this.fallbackCache = fallbackCache; // Logging moved to CacheManagerFactory for single consolidated log @@ -79,6 +91,7 @@ public FireflyCacheManager(CacheAdapter primaryCache, CacheAdapter fallbackCache @Override public Mono> get(K key) { + if (primaryOnly()) { return requiredPrimary(cache -> cache.get(key), Optional.class); } return getActiveCache().get(key) .onErrorResume(e -> { log.error("Error during get operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -88,6 +101,7 @@ public Mono> get(K key) { @Override public Mono> get(K key, Class valueType) { + if (primaryOnly()) { return requiredPrimary(cache -> cache.get(key, valueType), Optional.class); } return getActiveCache().get(key, valueType) .onErrorResume(e -> { log.error("Error during get operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -97,6 +111,7 @@ public Mono> get(K key, Class valueType) { @Override public Mono put(K key, V value) { + if (primaryOnly()) { return primaryCompletion(cache -> cache.put(key, value)); } return getActiveCache().put(key, value) .onErrorResume(e -> { log.error("Error during put operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -106,6 +121,7 @@ public Mono put(K key, V value) { @Override public Mono put(K key, V value, Duration ttl) { + if (primaryOnly()) { return primaryCompletion(cache -> cache.put(key, value, ttl)); } return getActiveCache().put(key, value, ttl) .onErrorResume(e -> { log.error("Error during put operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -115,6 +131,7 @@ public Mono put(K key, V value, Duration ttl) { @Override public Mono putIfAbsent(K key, V value) { + if (primaryOnly()) { return requiredPrimary(cache -> cache.putIfAbsent(key, value), Boolean.class); } return getActiveCache().putIfAbsent(key, value) .onErrorResume(e -> { log.error("Error during putIfAbsent operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -124,6 +141,7 @@ public Mono putIfAbsent(K key, V value) { @Override public Mono putIfAbsent(K key, V value, Duration ttl) { + if (primaryOnly()) { return requiredPrimary(cache -> cache.putIfAbsent(key, value, ttl), Boolean.class); } return getActiveCache().putIfAbsent(key, value, ttl) .onErrorResume(e -> { log.error("Error during putIfAbsent operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -133,6 +151,7 @@ public Mono putIfAbsent(K key, V value, Duration ttl) { @Override public Mono evict(K key) { + if (primaryOnly()) { return requiredPrimary(cache -> cache.evict(key), Boolean.class); } return getActiveCache().evict(key) .onErrorResume(e -> { log.error("Error during evict operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -142,6 +161,7 @@ public Mono evict(K key) { @Override public Mono clear() { + if (primaryOnly()) { return primaryCompletion(CacheAdapter::clear); } return getActiveCache().clear() .onErrorResume(e -> { log.error("Error clearing cache: type={}", LogFields.errorType(e)); @@ -151,6 +171,7 @@ public Mono clear() { @Override public Mono exists(K key) { + if (primaryOnly()) { return requiredPrimary(cache -> cache.exists(key), Boolean.class); } return getActiveCache().exists(key) .onErrorResume(e -> { log.error("Error during exists operation for key present={}: type={}", key != null, LogFields.errorType(e)); @@ -160,6 +181,7 @@ public Mono exists(K key) { @Override public Mono> keys() { + if (primaryOnly()) { return requiredPrimary(cache -> cache.keys(), Set.class); } return getActiveCache().keys() .onErrorResume(e -> { log.error("Error getting keys: type={}", LogFields.errorType(e)); @@ -169,6 +191,7 @@ public Mono> keys() { @Override public Mono size() { + if (primaryOnly()) { return requiredPrimary(CacheAdapter::size, Long.class).map(this::nonnegativeCount); } return getActiveCache().size() .onErrorResume(e -> { log.error("Error getting size: type={}", LogFields.errorType(e)); @@ -178,26 +201,31 @@ public Mono size() { @Override public Mono getStats() { + if (primaryOnly()) { return requiredPrimary(CacheAdapter::getStats, CacheStats.class); } return getActiveCache().getStats(); } @Override public CacheType getCacheType() { + if (primaryOnly()) { return primary().getCacheType(); } return getActiveCache().getCacheType(); } @Override public String getCacheName() { + if (primaryOnly()) { return primary().getCacheName(); } return getActiveCache().getCacheName(); } @Override public boolean isAvailable() { + if (primaryOnly()) { return !closed && primaryCache.isAvailable(); } return !closed && getActiveCache().isAvailable(); } @Override public Mono getHealth() { + if (primaryOnly()) { return requiredPrimary(CacheAdapter::getHealth, CacheHealth.class); } return getActiveCache().getHealth(); } @@ -208,6 +236,10 @@ public void close() { } closed = true; + if (primaryOnly()) { + primaryCache.close(); + return; + } log.info("Closing Firefly Cache Manager"); try { @@ -233,6 +265,53 @@ public void close() { // Helper Methods // ================================ + @Override + public CacheOperationPolicy operationPolicy() { + return operationPolicy; + } + + @Override + public Mono evictByPrefix(String prefix) { + return primaryOnly() + ? requiredPrimary(cache -> cache.evictByPrefix(prefix), Long.class).map(this::nonnegativeCount) + : CacheAdapter.super.evictByPrefix(prefix); + } + + private boolean primaryOnly() { + return operationPolicy == CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS; + } + + private CacheAdapter primary() { + if (closed) throw new IllegalStateException("Cache manager is closed"); + return primaryCache; + } + + private Mono primaryOperation(java.util.function.Function> operation) { + return Mono.defer(() -> { + Mono result = operation.apply(primary()); + return result == null ? Mono.error(new CacheException("Cache operation returned no publisher")) : result; + }); + } + + private Mono requiredPrimary(java.util.function.Function> operation, Class resultType) { + return primaryOperation(operation) + .map(value -> { + if (!resultType.isInstance(value)) throw new CacheException("Cache operation returned an unsupported result"); + return value; + }) + .switchIfEmpty(Mono.error(new CacheException("Cache operation completed without a result"))); + } + + private Mono primaryCompletion(java.util.function.Function> operation) { + Mono result = primaryOperation(operation); + return result.flatMap(value -> Mono.error(new CacheException("Cache completion emitted an unsupported result"))).then(); + } + + private long nonnegativeCount(long count) { + if (count < 0) throw new CacheException("Cache operation returned an invalid count"); + return count; + } + /** * Gets the currently active cache, with fallback support. * diff --git a/modules/cache/src/main/java/org/fireflyframework/cache/serialization/JsonCacheSerializer.java b/modules/cache/src/main/java/org/fireflyframework/cache/serialization/JsonCacheSerializer.java index 07999ee9c..f6f83ae10 100644 --- a/modules/cache/src/main/java/org/fireflyframework/cache/serialization/JsonCacheSerializer.java +++ b/modules/cache/src/main/java/org/fireflyframework/cache/serialization/JsonCacheSerializer.java @@ -16,6 +16,8 @@ package org.fireflyframework.cache.serialization; +import org.fireflyframework.kernel.logging.LogFields; + import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import lombok.extern.slf4j.Slf4j; @@ -55,8 +57,7 @@ public Object serialize(Object object) throws SerializationException { try { return objectMapper.writeValueAsString(object); } catch (Exception e) { - log.error("Failed to serialize object of type {} to JSON: {}", - object.getClass().getName(), e.getMessage(), e); + log.error("Cache serialization failed: type={}", LogFields.errorType(e)); throw new SerializationException("Failed to serialize object to JSON", e); } } @@ -78,8 +79,7 @@ public T deserialize(Object data, Class type) throws SerializationExcepti try { return objectMapper.readValue(jsonString, type); } catch (Exception e) { - log.error("Failed to deserialize JSON string to type {}: {}", - type.getName(), e.getMessage(), e); + log.error("Cache deserialization failed: type={}", LogFields.errorType(e)); throw new SerializationException("Failed to deserialize JSON to object", e); } } @@ -94,8 +94,7 @@ public T deserialize(Object data, Class type) throws SerializationExcepti String json = objectMapper.writeValueAsString(data); return objectMapper.readValue(json, type); } catch (Exception e) { - log.error("Failed to convert object of type {} to type {} via JSON: {}", - data.getClass().getName(), type.getName(), e.getMessage(), e); + log.error("Cache conversion failed: type={}", LogFields.errorType(e)); throw new SerializationException("Failed to convert object via JSON", e); } } diff --git a/modules/cache/src/main/java/org/fireflyframework/cache/spi/CacheProviderFactory.java b/modules/cache/src/main/java/org/fireflyframework/cache/spi/CacheProviderFactory.java index 1877c307c..fa9e0482f 100644 --- a/modules/cache/src/main/java/org/fireflyframework/cache/spi/CacheProviderFactory.java +++ b/modules/cache/src/main/java/org/fireflyframework/cache/spi/CacheProviderFactory.java @@ -23,6 +23,7 @@ import org.fireflyframework.cache.adapter.caffeine.CaffeineCacheAdapter; import org.fireflyframework.cache.adapter.caffeine.CaffeineCacheConfig; import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; import org.fireflyframework.cache.core.CacheType; import org.fireflyframework.cache.properties.CacheProperties; @@ -50,6 +51,16 @@ public interface CacheProviderFactory { */ CacheAdapter create(String cacheName, String keyPrefix, Duration defaultTtl, ProviderContext ctx); + /** A provider must explicitly implement non-legacy operation behavior. */ + default CacheAdapter create(String cacheName, String keyPrefix, Duration defaultTtl, + ProviderContext ctx, CacheOperationPolicy policy) { + java.util.Objects.requireNonNull(policy, "Cache operation policy required"); + if (policy != CacheOperationPolicy.LEGACY) { + throw new UnsupportedOperationException("Cache provider does not support the requested operation policy"); + } + return create(cacheName, keyPrefix, defaultTtl, ctx); + } + /** Context passed to providers. */ class ProviderContext { public final CacheProperties properties; diff --git a/modules/cache/src/test/java/org/fireflyframework/cache/factory/PrimaryOnlyCacheFactoryTest.java b/modules/cache/src/test/java/org/fireflyframework/cache/factory/PrimaryOnlyCacheFactoryTest.java new file mode 100644 index 000000000..8bc07ba6f --- /dev/null +++ b/modules/cache/src/test/java/org/fireflyframework/cache/factory/PrimaryOnlyCacheFactoryTest.java @@ -0,0 +1,67 @@ +package org.fireflyframework.cache.factory; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.Duration; +import java.util.*; +import org.fireflyframework.cache.core.*; +import org.fireflyframework.cache.properties.CacheProperties; +import org.fireflyframework.cache.spi.CacheProviderFactory; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +class PrimaryOnlyCacheFactoryTest { + final CacheProperties properties=new CacheProperties(); + CacheManagerFactory factory(CacheProviderFactory... providers) { + var factory=new CacheManagerFactory(properties,new ObjectMapper(),null,null,null); + ReflectionTestUtils.setField(factory,"providerFactories",List.of(providers));return factory; + } + org.fireflyframework.cache.manager.FireflyCacheManager create(CacheManagerFactory factory,CacheType type) { + return factory.createCacheManager("policy",type, + "service:policy",Duration.ofMinutes(1),"primary-only test","test",CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + } + static class LegacyProvider implements CacheProviderFactory { + int calls; + public CacheType getType(){return CacheType.POSTGRES;} + public int priority(){return 1;} + public boolean isAvailable(ProviderContext context){throw new AssertionError("Metadata cannot establish policy capability");} + public CacheAdapter create(String name,String prefix,Duration ttl,ProviderContext context){calls++;throw new AssertionError("Legacy creation must not be used");} + } + static class ExplicitProvider extends LegacyProvider { + final CacheAdapter adapter=mock(CacheAdapter.class); + ExplicitProvider(){when(adapter.operationPolicy()).thenReturn(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS);when(adapter.getCacheType()).thenReturn(CacheType.POSTGRES);} + public CacheAdapter create(String name,String prefix,Duration ttl,ProviderContext context,CacheOperationPolicy policy){calls++;return adapter;} + } + @Test void smartAndCaffeineCannotWrapAnExplicitPrimaryOnlyAdapter() { + properties.getSmart().setEnabled(true);properties.getCaffeine().setEnabled(true);var provider=new ExplicitProvider(); + var manager=create(factory(provider),CacheType.POSTGRES);assertThat(ReflectionTestUtils.getField(manager,"primaryCache")).isSameAs(provider.adapter); + assertThat(ReflectionTestUtils.getField(manager,"fallbackCache")).isNull();assertThat(provider.calls).isEqualTo(1); + assertThat(manager.operationPolicy()).isEqualTo(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + } + @Test void automaticAndNoopBackendChoicesRefuse() { + for(var type:List.of(CacheType.AUTO,CacheType.NOOP))assertThatThrownBy(()->create(factory(new ExplicitProvider()),type)).isInstanceOf(IllegalArgumentException.class); + } + @Test void missingOrAmbiguousProviderRefuses() { + assertThatThrownBy(()->create(factory(),CacheType.POSTGRES)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(()->create(factory(new ExplicitProvider(),new ExplicitProvider()),CacheType.POSTGRES)).isInstanceOf(IllegalStateException.class); + } + @Test void oldProviderDefaultExplicitlyRefusesWithoutLegacyCreation() { + var provider=new LegacyProvider();assertThatThrownBy(()->create(factory(provider),CacheType.POSTGRES)).isInstanceOf(UnsupportedOperationException.class);assertThat(provider.calls).isZero(); + } + @Test void nullOrUnconfiguredAdapterCannotBeAccepted() { + var provider=new ExplicitProvider();when(provider.adapter.operationPolicy()).thenReturn(CacheOperationPolicy.LEGACY); + assertThatThrownBy(()->create(factory(provider),CacheType.POSTGRES)).isInstanceOf(IllegalArgumentException.class);verify(provider.adapter).close(); + var empty=new ExplicitProvider(){@Override public CacheAdapter create(String n,String p,Duration t,ProviderContext c,CacheOperationPolicy policy){return null;}}; + assertThatThrownBy(()->create(factory(empty),CacheType.POSTGRES)).isInstanceOf(IllegalStateException.class); + } + @Test void currentlyUnsupportedBuiltinProviderRefusesExplicitly() { + assertThatThrownBy(()->create(factory(new org.fireflyframework.cache.spi.providers.CaffeineProvider()),CacheType.CAFFEINE)) + .isInstanceOf(UnsupportedOperationException.class); + } + @Test void providerCannotReturnADifferentBackend() { + var provider=new ExplicitProvider();when(provider.adapter.getCacheType()).thenReturn(CacheType.CAFFEINE); + assertThatThrownBy(()->create(factory(provider),CacheType.POSTGRES)).isInstanceOf(IllegalStateException.class);verify(provider.adapter).close(); + } + +} diff --git a/modules/cache/src/test/java/org/fireflyframework/cache/factory/PrimaryOnlyServiceDiscoveryTest.java b/modules/cache/src/test/java/org/fireflyframework/cache/factory/PrimaryOnlyServiceDiscoveryTest.java new file mode 100644 index 000000000..3e6c3b3e5 --- /dev/null +++ b/modules/cache/src/test/java/org/fireflyframework/cache/factory/PrimaryOnlyServiceDiscoveryTest.java @@ -0,0 +1,197 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.cache.factory; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.fireflyframework.cache.core.CacheAdapter; +import org.fireflyframework.cache.core.CacheOperationPolicy; +import org.fireflyframework.cache.core.CacheType; +import org.fireflyframework.cache.manager.FireflyCacheManager; +import org.fireflyframework.cache.properties.CacheProperties; +import org.fireflyframework.cache.spi.CacheProviderFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@Execution(ExecutionMode.SAME_THREAD) +public class PrimaryOnlyServiceDiscoveryTest { + private static final String SERVICE = "META-INF/services/" + CacheProviderFactory.class.getName(); + private static final String MISSING = "missing.fixture.ProviderFactory"; + private static final AtomicInteger STRICT_CREATES = new AtomicInteger(); + private static final AtomicInteger LEGACY_CREATES = new AtomicInteger(); + private static final AtomicInteger RESOLVERS = new AtomicInteger(); + private static final AtomicInteger SECOND_CONSTRUCTORS = new AtomicInteger(); + @TempDir Path temporary; + private int resourceNumber; + + @BeforeEach void reset() { + STRICT_CREATES.set(0); LEGACY_CREATES.set(0); RESOLVERS.set(0); SECOND_CONSTRUCTORS.set(0); + } + + @Test void completeSingleProviderConstructsStrictOnce() throws Exception { + withServices(List.of(FirstProvider.class.getName()), factory -> { + var manager = strict(factory); + try { assertEquals(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS, manager.operationPolicy()); } + finally { manager.close(); } + assertEquals(1, STRICT_CREATES.get()); assertEquals(1, RESOLVERS.get()); + }); + } + + @Test void matchingThenMissingThenSecondMatchingRefusesBeforeAdapterOrFactoryResolution() throws Exception { + withServices(List.of(FirstProvider.class.getName(), MISSING, SecondProvider.class.getName()), this::incomplete); + assertEquals(0, SECOND_CONSTRUCTORS.get()); + } + + @Test void matchingThenThrowingConstructorThenSecondMatchingRefusesBeforeCreate() throws Exception { + withServices(List.of(FirstProvider.class.getName(), ThrowingConstructor.class.getName(), SecondProvider.class.getName()), this::incomplete); + assertEquals(0, SECOND_CONSTRUCTORS.get()); + } + + @Test void missingFirstEntryRefusesWithoutCreatingAnyAdapter() throws Exception { + withServices(List.of(MISSING, FirstProvider.class.getName()), this::incomplete); + } + + @Test void trailingMissingEntryCannotBeIgnoredAfterAUsableProvider() throws Exception { + withServices(List.of(FirstProvider.class.getName(), MISSING), this::incomplete); + } + + @Test void completeDuplicateBackendProvidersStillRefuseAsAmbiguous() throws Exception { + withServices(List.of(FirstProvider.class.getName(), SecondProvider.class.getName()), factory -> { + assertThrows(IllegalStateException.class, () -> strict(factory)); + assertEquals(0, STRICT_CREATES.get()); assertEquals(0, RESOLVERS.get()); + assertEquals(1, SECOND_CONSTRUCTORS.get()); + }); + } + + @Test void completeNonmatchingProviderDoesNotSatisfyRequestedBackend() throws Exception { + withServices(List.of(OtherBackend.class.getName()), factory -> { + var error = assertThrows(IllegalStateException.class, () -> strict(factory)); + assertTrue(error.getMessage().contains("Exactly one")); + assertEquals(0, STRICT_CREATES.get()); assertEquals(0, RESOLVERS.get()); + }); + } + + @Test void completeEmptyDiscoveryRefusesAsMissingInsteadOfPretendingIncomplete() throws Exception { + withServices(List.of(), factory -> { + var error = assertThrows(IllegalStateException.class, () -> strict(factory)); + assertTrue(error.getMessage().contains("Exactly one")); + assertEquals(0, STRICT_CREATES.get()); assertEquals(0, RESOLVERS.get()); + }); + } + + @Test void failedPrioritySortCannotLeaveAnApparentlyUniqueStrictProvider() throws Exception { + withServices(List.of(FirstProvider.class.getName(), ThrowingPriority.class.getName()), this::incomplete); + } + + @Test void legacyStillUsesItsPreviouslyRetainedPartialProviderList() throws Exception { + withServices(List.of(FirstProvider.class.getName(), MISSING, SecondProvider.class.getName()), factory -> { + var manager = factory.createCacheManager("fixture", CacheType.POSTGRES, "fixture:", Duration.ofMinutes(1)); + try { assertEquals(CacheOperationPolicy.LEGACY, manager.operationPolicy()); } + finally { manager.close(); } + assertEquals(1, LEGACY_CREATES.get()); assertEquals(0, STRICT_CREATES.get()); + }); + } + + @Test void aNewCompleteFactoryIsNotPoisonedByAnotherFactorysFailedDiscovery() throws Exception { + withServices(List.of(FirstProvider.class.getName(), MISSING), this::incomplete); + withServices(List.of(FirstProvider.class.getName()), factory -> { + var manager = strict(factory); manager.close(); + assertEquals(1, STRICT_CREATES.get()); + }); + } + + @Test void repeatedSameServiceClassUsesRealServiceLoaderDeduplication() throws Exception { + withServices(List.of(FirstProvider.class.getName(), FirstProvider.class.getName()), factory -> { + var manager = strict(factory); manager.close(); + assertEquals(1, STRICT_CREATES.get()); + }); + } + + private void incomplete(CacheManagerFactory factory) { + var error = assertThrows(IllegalStateException.class, () -> strict(factory)); + assertEquals("Cache provider discovery did not complete", error.getMessage()); + assertNull(error.getCause()); + assertEquals(0, STRICT_CREATES.get()); assertEquals(0, LEGACY_CREATES.get()); assertEquals(0, RESOLVERS.get()); + } + + private FireflyCacheManager strict(CacheManagerFactory factory) { + return factory.createCacheManager("fixture", CacheType.POSTGRES, "fixture:", Duration.ofMinutes(1), + "ServiceLoader completion fixture", "test", CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); + } + + private void withServices(List names, Consumer exercise) throws IOException { + Path root = temporary.resolve("services-" + resourceNumber++); + Path file = root.resolve(SERVICE); Files.createDirectories(file.getParent()); + Files.writeString(file, String.join("\n", names) + "\n", StandardCharsets.UTF_8); + ClassLoader previous = Thread.currentThread().getContextClassLoader(); + try (var loader = new URLClassLoader(new URL[]{root.toUri().toURL()}, previous) { + @Override public Enumeration getResources(String resource) throws IOException { + return resource.equals(SERVICE) ? findResources(resource) : super.getResources(resource); + } + }) { + Thread.currentThread().setContextClassLoader(loader); + var properties = new CacheProperties(); properties.getPostgres().setEnabled(true); + properties.getSmart().setEnabled(false); properties.getCaffeine().setEnabled(false); + var factory = new CacheManagerFactory(properties, new ObjectMapper(), null, null, null, null, + () -> { RESOLVERS.incrementAndGet(); return new Object(); }); + exercise.accept(factory); + } finally { Thread.currentThread().setContextClassLoader(previous); } + } + + // ServiceLoader requires publicly constructible provider classes; these are controlled SPI fixtures. + public abstract static class Provider implements CacheProviderFactory { + public CacheType getType() { return CacheType.POSTGRES; } + public int priority() { return 10; } + public boolean isAvailable(ProviderContext context) { return true; } + public CacheAdapter create(String name, String prefix, Duration ttl, ProviderContext context) { + LEGACY_CREATES.incrementAndGet(); return adapter(CacheOperationPolicy.LEGACY); + } + public CacheAdapter create(String name, String prefix, Duration ttl, ProviderContext context, CacheOperationPolicy policy) { + STRICT_CREATES.incrementAndGet(); return adapter(policy); + } + private CacheAdapter adapter(CacheOperationPolicy policy) { + var adapter = mock(CacheAdapter.class); when(adapter.getCacheType()).thenReturn(getType()); + when(adapter.operationPolicy()).thenReturn(policy); return adapter; + } + } + public static final class FirstProvider extends Provider { public FirstProvider() { } } + public static final class SecondProvider extends Provider { public SecondProvider() { SECOND_CONSTRUCTORS.incrementAndGet(); } } + public static final class ThrowingConstructor extends Provider { + public ThrowingConstructor() { throw new IllegalStateException("PRIVATE_PROVIDER_CONSTRUCTOR"); } + } + public static class OtherBackend extends Provider { public OtherBackend() { } @Override public CacheType getType() { return CacheType.CAFFEINE; } } + public static final class ThrowingPriority extends OtherBackend { + public ThrowingPriority() { } @Override public int priority() { throw new IllegalStateException("PRIVATE_PRIORITY_FAILURE"); } + } +} diff --git a/modules/cache/src/test/java/org/fireflyframework/cache/manager/LegacyCacheOperationCompatibilityTest.java b/modules/cache/src/test/java/org/fireflyframework/cache/manager/LegacyCacheOperationCompatibilityTest.java new file mode 100644 index 000000000..c9ec622b9 --- /dev/null +++ b/modules/cache/src/test/java/org/fireflyframework/cache/manager/LegacyCacheOperationCompatibilityTest.java @@ -0,0 +1,18 @@ +package org.fireflyframework.cache.manager; + +import static org.mockito.Mockito.*; +import java.util.Optional; +import org.fireflyframework.cache.core.CacheAdapter; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +/** Existing API controls can be compiled against674 and the candidate without new-policy symbols. */ +class LegacyCacheOperationCompatibilityTest { + final CacheAdapter adapter=mock(CacheAdapter.class); + final FireflyCacheManager manager=new FireflyCacheManager(adapter); + LegacyCacheOperationCompatibilityTest(){when(adapter.isAvailable()).thenReturn(true);} + @Test void oldReadFailureRecoveryRemainsAReportedMiss(){doReturn(Mono.error(new IllegalStateException("controlled failure"))).when(adapter).get("key");StepVerifier.create(manager.get("key")).expectNext(Optional.empty()).verifyComplete();} + @Test void oldWriteFailureRecoveryRemainsCompleted(){doReturn(Mono.error(new IllegalStateException("controlled failure"))).when(adapter).put("key","value");StepVerifier.create(manager.put("key","value")).verifyComplete();} + @Test void oldEvictionFailureRecoveryRemainsFalse(){when(adapter.evict("key")).thenReturn(Mono.error(new IllegalStateException("controlled failure")));StepVerifier.create(manager.evict("key")).expectNext(false).verifyComplete();} +} diff --git a/modules/cache/src/test/java/org/fireflyframework/cache/manager/PrimaryOnlyCacheManagerTest.java b/modules/cache/src/test/java/org/fireflyframework/cache/manager/PrimaryOnlyCacheManagerTest.java new file mode 100644 index 000000000..e28764082 --- /dev/null +++ b/modules/cache/src/test/java/org/fireflyframework/cache/manager/PrimaryOnlyCacheManagerTest.java @@ -0,0 +1,91 @@ +package org.fireflyframework.cache.manager; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import java.time.Duration; +import java.util.*; +import org.fireflyframework.cache.core.*; +import org.fireflyframework.cache.exception.CacheException; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +class PrimaryOnlyCacheManagerTest { + final CacheAdapter primary=mock(CacheAdapter.class); + PrimaryOnlyCacheManagerTest() { when(primary.operationPolicy()).thenReturn(CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); } + FireflyCacheManager manager() { return new FireflyCacheManager(primary,null,CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS); } + List> dataOperations(FireflyCacheManager manager) { + return List.of(manager.get("key"),manager.get("key",String.class),manager.put("key","value"), + manager.put("key","value",Duration.ofSeconds(1)),manager.putIfAbsent("key","value"), + manager.putIfAbsent("key","value",Duration.ofSeconds(1)),manager.evict("key"),manager.clear(), + manager.exists("key"),manager.keys(),manager.size(),manager.evictByPrefix("prefix"),manager.getStats()); + } + void answers(Mono answer) { + doReturn(answer).when(primary).get("key");doReturn(answer).when(primary).get("key",String.class); + doReturn(answer).when(primary).put("key","value");doReturn(answer).when(primary).put(eq("key"),eq("value"),any(Duration.class)); + doReturn(answer).when(primary).putIfAbsent("key","value");doReturn(answer).when(primary).putIfAbsent(eq("key"),eq("value"),any(Duration.class)); + doReturn(answer).when(primary).evict("key");doReturn(answer).when(primary).clear();doReturn(answer).when(primary).exists("key"); + doReturn(answer).when(primary).keys();doReturn(answer).when(primary).size();doReturn(answer).when(primary).evictByPrefix("prefix");doReturn(answer).when(primary).getStats(); + } + @Test void everyDataErrorPropagatesWithoutAvailabilityOrFallbackSelection() { + var failure=new IllegalStateException("controlled backend failure");answers(Mono.error(failure)); + for(var operation:dataOperations(manager()))StepVerifier.create(operation).expectErrorSatisfies(error->assertThat(error).isSameAs(failure)).verify(); + verify(primary,never()).isAvailable(); + } + @Test void requiredResultsCannotCompleteEmpty() { + answers(Mono.empty());var manager=manager(); + for(var operation:List.of(manager.get("key"),manager.get("key",String.class),manager.putIfAbsent("key","value"), + manager.putIfAbsent("key","value",Duration.ofSeconds(1)),manager.evict("key"),manager.exists("key"), + manager.keys(),manager.size(),manager.evictByPrefix("prefix"),manager.getStats())) + StepVerifier.create(operation).expectError(CacheException.class).verify(); + } + @Test void missingPublishersCannotBecomeSuccessfulCompletions() { + for(var operation:dataOperations(manager()))StepVerifier.create(operation).expectError(CacheException.class).verify(); + } + @Test void unsupportedResultShapesCannotBePresentedAsSuccess() { + answers(Mono.just("unsupported-result")); + for(var operation:dataOperations(manager()))StepVerifier.create(operation).expectError(CacheException.class).verify(); + } + @Test void synchronousAdapterFailureIsAReactiveFailure() { + var failure=new IllegalStateException("controlled assembly failure");when(primary.get("key")).thenThrow(failure); + assertThatCode(()->manager().get("key")).doesNotThrowAnyException(); + StepVerifier.create(manager().get("key")).expectErrorSatisfies(error->assertThat(error).isSameAs(failure)).verify(); + } + @Test void successfulMissAndNegativeResultRetainTheirMeaning() { + doReturn(Mono.just(Optional.empty())).when(primary).get("key");doReturn(Mono.just(false)).when(primary).exists("key"); + StepVerifier.create(manager().get("key")).expectNext(Optional.empty()).verifyComplete(); + StepVerifier.create(manager().exists("key")).expectNext(false).verifyComplete(); + } + @Test void successfulVoidCompletionRemainsSupported() { + doReturn(Mono.empty()).when(primary).put("key","value");doReturn(Mono.empty()).when(primary).clear(); + StepVerifier.create(manager().put("key","value")).verifyComplete();StepVerifier.create(manager().clear()).verifyComplete(); + } + @Test void unavailableMetadataCannotReselectThePinnedPrimary() { + when(primary.isAvailable()).thenReturn(false);doReturn(Mono.just(Optional.of("value"))).when(primary).get("key"); + StepVerifier.create(manager().get("key")).expectNext(Optional.of("value")).verifyComplete();verify(primary,never()).isAvailable(); + } + @Test void negativeSizeOrEvictionCountRefuses() { + when(primary.size()).thenReturn(Mono.just(-1L));when(primary.evictByPrefix("prefix")).thenReturn(Mono.just(-1L)); + StepVerifier.create(manager().size()).expectError(CacheException.class).verify(); + StepVerifier.create(manager().evictByPrefix("prefix")).expectError(CacheException.class).verify(); + } + @Test void unknownAdapterAndAnyFallbackRefuseStrictConstruction() { + var legacy=mock(CacheAdapter.class);when(legacy.operationPolicy()).thenReturn(CacheOperationPolicy.LEGACY); + assertThatThrownBy(()->new FireflyCacheManager(legacy,null,CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(()->new FireflyCacheManager(primary,legacy,CacheOperationPolicy.PRIMARY_ONLY_PROPAGATE_ERRORS)).isInstanceOf(IllegalArgumentException.class); + } + @Test void closeFailurePropagatesAndClosedInstanceRefusesDataOperations() { + var failure=new IllegalStateException("controlled close failure");doThrow(failure).when(primary).close();var manager=manager(); + assertThatThrownBy(manager::close).isSameAs(failure);StepVerifier.create(manager.get("key")).expectError(IllegalStateException.class).verify(); + } + @Test void missingHealthResultCannotPretendHealthy() { + StepVerifier.create(manager().getHealth()).expectError(CacheException.class).verify(); + when(primary.getHealth()).thenReturn(Mono.empty());StepVerifier.create(manager().getHealth()).expectError(CacheException.class).verify(); + } + @Test void legacyManagerKeepsExistingFailureRecovery() { + answers(Mono.error(new IllegalStateException("controlled legacy failure")));var legacy=new FireflyCacheManager(primary); + when(primary.isAvailable()).thenReturn(true);StepVerifier.create(legacy.get("key")).expectNext(Optional.empty()).verifyComplete(); + StepVerifier.create(legacy.put("key","value")).verifyComplete();assertThat(legacy.operationPolicy()).isEqualTo(CacheOperationPolicy.LEGACY); + } +} diff --git a/modules/cache/src/test/java/org/fireflyframework/cache/serialization/JsonCacheSerializerLoggingTest.java b/modules/cache/src/test/java/org/fireflyframework/cache/serialization/JsonCacheSerializerLoggingTest.java new file mode 100644 index 000000000..e099f74e2 --- /dev/null +++ b/modules/cache/src/test/java/org/fireflyframework/cache/serialization/JsonCacheSerializerLoggingTest.java @@ -0,0 +1,35 @@ +package org.fireflyframework.cache.serialization; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.slf4j.LoggerFactory; +import java.util.*; + +class JsonCacheSerializerLoggingTest { + static final String PRIVATE="PRIVATE_SECRET_VALUE"; + final Logger logger=(Logger)LoggerFactory.getLogger(JsonCacheSerializer.class); + final ListAppender events=new ListAppender<>(); + Level previousLevel;boolean previousAdditive; + @BeforeEach void capture(){previousLevel=logger.getLevel();previousAdditive=logger.isAdditive();logger.setLevel(Level.ERROR);logger.setAdditive(false);events.start();logger.addAppender(events);} + @AfterEach void release(){logger.detachAppender(events);events.stop();logger.setLevel(previousLevel);logger.setAdditive(previousAdditive);} + void safeEvent(){assertEquals(1,events.list.size());var event=events.list.getFirst();assertNull(event.getThrowableProxy());assertFalse(event.getMessage().contains(PRIVATE));assertFalse(event.getFormattedMessage().contains(PRIVATE));assertTrue(event.getFormattedMessage().contains("java.lang.IllegalStateException"));for(Object argument:event.getArgumentArray())assertFalse(String.valueOf(argument).contains(PRIVATE));} + @Test void serializeFailureRetainsCauseWithoutLoggingPayloadOrThrowable()throws Exception{ + var mapper=mock(ObjectMapper.class);var failure=new IllegalStateException(PRIVATE);when(mapper.writeValueAsString(any())).thenThrow(failure); + var exception=assertThrows(SerializationException.class,()->new JsonCacheSerializer(mapper).serialize(Map.of("secret",PRIVATE)));assertSame(failure,exception.getCause());safeEvent(); + } + @Test void stringDecodeFailureRetainsCauseWithoutLoggingPayloadOrThrowable()throws Exception{ + var mapper=mock(ObjectMapper.class);var failure=new IllegalStateException(PRIVATE);when(mapper.readValue(eq(PRIVATE),eq(Map.class))).thenThrow(failure); + var exception=assertThrows(SerializationException.class,()->new JsonCacheSerializer(mapper).deserialize(PRIVATE,Map.class));assertSame(failure,exception.getCause());safeEvent(); + } + @Test void conversionFailureRetainsCauseWithoutLoggingPayloadOrThrowable()throws Exception{ + var mapper=mock(ObjectMapper.class);var failure=new IllegalStateException(PRIVATE);when(mapper.writeValueAsString(any())).thenThrow(failure); + var exception=assertThrows(SerializationException.class,()->new JsonCacheSerializer(mapper).deserialize(Map.of("secret",PRIVATE),List.class));assertSame(failure,exception.getCause());safeEvent(); + } +}