Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();

Expand All @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}

}
Original file line number Diff line number Diff line change
@@ -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<Row,RowMetadata,Object>)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();
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
2 changes: 2 additions & 0 deletions modules/cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 45 additions & 0 deletions modules/cache/docs/PRIMARY_ONLY_OPERATIONS.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
Loading
Loading