diff --git a/README.md b/README.md index b6af8d417..faf634597 100644 --- a/README.md +++ b/README.md @@ -120,16 +120,17 @@ See [here](https://javadoc.io/doc/dev.openfeature/sdk/latest/) for the Javadocs. ## 🌟 Features -| Status | Features | Description | -| ------ | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -| ✅ | [Providers](#providers) | Integrate with a commercial, open source, or in-house feature management tool. | -| ✅ | [Targeting](#targeting) | Contextually-aware flag evaluation using [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context). | -| ✅ | [Hooks](#hooks) | Add functionality to various stages of the flag evaluation life-cycle. | -| ✅ | [Logging](#logging) | Integrate with popular logging packages. | -| ✅ | [Named clients](#named-clients) | Utilize multiple providers in a single application. | -| ✅ | [Eventing](#eventing) | React to state changes in the provider or flag management system. | -| ✅ | [Shutdown](#shutdown) | Gracefully clean up a provider during application shutdown. | -| ✅ | [Extending](#extending) | Extend OpenFeature with custom providers and hooks. | +| Status | Features | Description | +| ------ |-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| +| ✅ | [Providers](#providers) | Integrate with a commercial, open source, or in-house feature management tool. | +| ✅ | [Targeting](#targeting) | Contextually-aware flag evaluation using [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context). | +| ✅ | [Hooks](#hooks) | Add functionality to various stages of the flag evaluation life-cycle. | +| ✅ | [Logging](#logging) | Integrate with popular logging packages. | +| ✅ | [Named clients](#named-clients) | Utilize multiple providers in a single application. | +| ✅ | [Eventing](#eventing) | React to state changes in the provider or flag management system. | +| ✅ | [Shutdown](#shutdown) | Gracefully clean up a provider during application shutdown. | +| ✅ | [Transaction Context Propagation](#transaction-context-propagation) | Set a specific [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context) for a transaction (e.g. an HTTP request or a thread). | +| ✅ | [Extending](#extending) | Extend OpenFeature with custom providers and hooks. | Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌ diff --git a/src/main/java/dev/openfeature/sdk/NoOpTransactionContextPropagator.java b/src/main/java/dev/openfeature/sdk/NoOpTransactionContextPropagator.java new file mode 100644 index 000000000..f6499f4a6 --- /dev/null +++ b/src/main/java/dev/openfeature/sdk/NoOpTransactionContextPropagator.java @@ -0,0 +1,24 @@ +package dev.openfeature.sdk; + +/** + * A {@link TransactionContextPropagator} that simply returns null. + */ +public class NoOpTransactionContextPropagator implements TransactionContextPropagator { + + /** + * {@inheritDoc} + * @return null + */ + @Override + public EvaluationContext getTransactionContext() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public void setTransactionContext(EvaluationContext evaluationContext) { + + } +} diff --git a/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java b/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java index a7ba42b31..c7b9c0145 100644 --- a/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java +++ b/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java @@ -27,11 +27,13 @@ public class OpenFeatureAPI implements EventBus { private ProviderRepository providerRepository; private EventSupport eventSupport; private EvaluationContext evaluationContext; + private TransactionContextPropagator transactionContextPropagator; protected OpenFeatureAPI() { apiHooks = new ArrayList<>(); providerRepository = new ProviderRepository(); eventSupport = new EventSupport(); + transactionContextPropagator = new NoOpTransactionContextPropagator(); } private static class SingletonHolder { @@ -96,6 +98,46 @@ public EvaluationContext getEvaluationContext() { } } + /** + * Return the transaction context propagator. + */ + public TransactionContextPropagator getTransactionContextPropagator() { + try (AutoCloseableLock __ = lock.readLockAutoCloseable()) { + return this.transactionContextPropagator; + } + } + + /** + * Sets the transaction context propagator. + * + * @throws IllegalArgumentException if {@code transactionContextPropagator} is null + */ + public void setTransactionContextPropagator(TransactionContextPropagator transactionContextPropagator) { + if (transactionContextPropagator == null) { + throw new IllegalArgumentException("Transaction context propagator cannot be null"); + } + try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { + this.transactionContextPropagator = transactionContextPropagator; + } + } + + /** + * Returns the currently defined transaction context using the registered transaction + * context propagator. + * + * @return {@link EvaluationContext} The current transaction context + */ + public EvaluationContext getTransactionContext() { + return this.transactionContextPropagator.getTransactionContext(); + } + + /** + * Sets the transaction context using the registered transaction context propagator. + */ + void setTransactionContext(EvaluationContext evaluationContext) { + this.transactionContextPropagator.setTransactionContext(evaluationContext); + } + /** * Set the default provider. */ diff --git a/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java b/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java index 05d79d02d..22d1b66fd 100644 --- a/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java +++ b/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java @@ -105,9 +105,6 @@ private FlagEvaluationDetails evaluateFlag(FlagValueType type, String key FeatureProvider provider; try { - final EvaluationContext apiContext; - final EvaluationContext clientContext; - // openfeatureApi.getProvider() must be called once to maintain a consistent reference provider = openfeatureApi.getProvider(this.name); @@ -117,19 +114,9 @@ private FlagEvaluationDetails evaluateFlag(FlagValueType type, String key hookCtx = HookContext.from(key, type, this.getMetadata(), provider.getMetadata(), ctx, defaultValue); - // merge of: API.context, client.context, invocation.context - apiContext = openfeatureApi.getEvaluationContext() != null - ? openfeatureApi.getEvaluationContext() - : new ImmutableContext(); - clientContext = this.getEvaluationContext() != null - ? this.getEvaluationContext() - : new ImmutableContext(); - EvaluationContext ctxFromHook = hookSupport.beforeHooks(type, hookCtx, mergedHooks, hints); - EvaluationContext invocationCtx = ctx.merge(ctxFromHook); - - EvaluationContext mergedCtx = apiContext.merge(clientContext.merge(invocationCtx)); + EvaluationContext mergedCtx = mergeEvaluationContext(ctxFromHook, ctx); ProviderEvaluation providerEval = (ProviderEvaluation) createProviderEvaluation(type, key, defaultValue, provider, mergedCtx); @@ -157,6 +144,31 @@ private FlagEvaluationDetails evaluateFlag(FlagValueType type, String key return details; } + /** + * Merge hook and invocation contexts with API, transaction and client contexts. + * + * @param hookContext hook context + * @param invocationContext invocation context + * @return merged evaluation context + */ + private EvaluationContext mergeEvaluationContext( + EvaluationContext hookContext, + EvaluationContext invocationContext) { + final EvaluationContext apiContext = openfeatureApi.getEvaluationContext() != null + ? openfeatureApi.getEvaluationContext() + : new ImmutableContext(); + final EvaluationContext clientContext = this.getEvaluationContext() != null + ? this.getEvaluationContext() + : new ImmutableContext(); + final EvaluationContext transactionContext = openfeatureApi.getTransactionContext() != null + ? openfeatureApi.getTransactionContext() + : new ImmutableContext(); + + EvaluationContext mergedInvocationCtx = invocationContext.merge(hookContext); + + return apiContext.merge(transactionContext.merge(clientContext.merge(mergedInvocationCtx))); + } + private ProviderEvaluation createProviderEvaluation( FlagValueType type, String key, diff --git a/src/main/java/dev/openfeature/sdk/ThreadLocalTransactionContextPropagator.java b/src/main/java/dev/openfeature/sdk/ThreadLocalTransactionContextPropagator.java new file mode 100644 index 000000000..59f92ceba --- /dev/null +++ b/src/main/java/dev/openfeature/sdk/ThreadLocalTransactionContextPropagator.java @@ -0,0 +1,28 @@ +package dev.openfeature.sdk; + +/** + * A {@link ThreadLocalTransactionContextPropagator} is a transactional context propagator + * that uses a ThreadLocal to persist a transactional context for the duration of a single thread. + * + * @see TransactionContextPropagator + */ +public class ThreadLocalTransactionContextPropagator implements TransactionContextPropagator { + + private final ThreadLocal evaluationContextThreadLocal = new ThreadLocal<>(); + + /** + * {@inheritDoc} + */ + @Override + public EvaluationContext getTransactionContext() { + return this.evaluationContextThreadLocal.get(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setTransactionContext(EvaluationContext evaluationContext) { + this.evaluationContextThreadLocal.set(evaluationContext); + } +} diff --git a/src/main/java/dev/openfeature/sdk/TransactionContextPropagator.java b/src/main/java/dev/openfeature/sdk/TransactionContextPropagator.java new file mode 100644 index 000000000..05f7d3eb8 --- /dev/null +++ b/src/main/java/dev/openfeature/sdk/TransactionContextPropagator.java @@ -0,0 +1,27 @@ +package dev.openfeature.sdk; + +/** + * {@link TransactionContextPropagator} is responsible for persisting a transactional context + * for the duration of a single transaction. + * Examples of potential transaction specific context include: a user id, user agent, IP. + * Transaction context is merged with evaluation context prior to flag evaluation. + *

+ * The precedence of merging context can be seen in + * the specification. + *

+ */ +public interface TransactionContextPropagator { + + /** + * Returns the currently defined transaction context using the registered transaction + * context propagator. + * + * @return {@link EvaluationContext} The current transaction context + */ + EvaluationContext getTransactionContext(); + + /** + * Sets the transaction context. + */ + void setTransactionContext(EvaluationContext evaluationContext); +} diff --git a/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java b/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java index e2e008818..60b6ee136 100644 --- a/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java +++ b/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java @@ -302,41 +302,107 @@ public void initialize(EvaluationContext evaluationContext) throws Exception { @Specification(number="3.2.1.1", text="The API, Client and invocation MUST have a method for supplying evaluation context.") @Specification(number="3.2.2.1", text="The API MUST have a method for setting the global evaluation context.") - @Specification(number="3.2.3", text="Evaluation context MUST be merged in the order: API (global; lowest precedence) - client - invocation - before hooks (highest precedence), with duplicate values being overwritten.") + @Specification(number="3.2.3", text="Evaluation context MUST be merged in the order: API (global; lowest precedence) -> transaction -> client -> invocation -> before hooks (highest precedence), with duplicate values being overwritten.") @Test void multi_layer_context_merges_correctly() { DoSomethingProvider provider = new DoSomethingProvider(); FeatureProviderTestUtils.setFeatureProvider(provider); + TransactionContextPropagator transactionContextPropagator = new ThreadLocalTransactionContextPropagator(); + api.setTransactionContextPropagator(transactionContextPropagator); - Map attributes = new HashMap<>(); - attributes.put("common", new Value("1")); - attributes.put("common2", new Value("1")); - attributes.put("api", new Value("2")); - EvaluationContext apiCtx = new ImmutableContext(attributes); + Map apiAttributes = new HashMap<>(); + apiAttributes.put("common1", new Value("1")); + apiAttributes.put("common2", new Value("1")); + apiAttributes.put("common3", new Value("1")); + apiAttributes.put("api", new Value("1")); + EvaluationContext apiCtx = new ImmutableContext(apiAttributes); api.setEvaluationContext(apiCtx); + Map transactionAttributes = new HashMap<>(); + // overwrite value from api context + transactionAttributes.put("common1", new Value("2")); + transactionAttributes.put("common4", new Value("2")); + transactionAttributes.put("common5", new Value("2")); + transactionAttributes.put("transaction", new Value("2")); + EvaluationContext transactionCtx = new ImmutableContext(transactionAttributes); + + api.setTransactionContext(transactionCtx); + Client c = api.getClient(); - Map attributes1 = new HashMap<>(); - attributes.put("common", new Value("3")); - attributes.put("common2", new Value("3")); - attributes.put("client", new Value("4")); - attributes.put("common", new Value("5")); - attributes.put("invocation", new Value("6")); - EvaluationContext clientCtx = new ImmutableContext(attributes); + Map clientAttributes = new HashMap<>(); + // overwrite value from api context + clientAttributes.put("common2", new Value("3")); + // overwrite value from transaction context + clientAttributes.put("common4", new Value("3")); + clientAttributes.put("common6", new Value("3")); + clientAttributes.put("client", new Value("3")); + EvaluationContext clientCtx = new ImmutableContext(clientAttributes); c.setEvaluationContext(clientCtx); - EvaluationContext invocationCtx = new ImmutableContext(); + Map invocationAttributes = new HashMap<>(); + // overwrite value from api context + invocationAttributes.put("common3", new Value("4")); + // overwrite value from transaction context + invocationAttributes.put("common5", new Value("4")); + // overwrite value from api client context + invocationAttributes.put("common6", new Value("4")); + invocationAttributes.put("invocation", new Value("4")); + EvaluationContext invocationCtx = new ImmutableContext(invocationAttributes); // dosomethingprovider inverts this value. assertTrue(c.getBooleanValue("key", false, invocationCtx)); EvaluationContext merged = provider.getMergedContext(); - assertEquals("6", merged.getValue("invocation").asString()); - assertEquals("5", merged.getValue("common").asString(), "invocation merge is incorrect"); - assertEquals("4", merged.getValue("client").asString()); + assertEquals("1", merged.getValue("api").asString()); + assertEquals("2", merged.getValue("transaction").asString()); + assertEquals("3", merged.getValue("client").asString()); + assertEquals("4", merged.getValue("invocation").asString()); + assertEquals("2", merged.getValue("common1").asString(), "transaction merge is incorrect"); assertEquals("3", merged.getValue("common2").asString(), "api client merge is incorrect"); - assertEquals("2", merged.getValue("api").asString()); + assertEquals("4", merged.getValue("common3").asString(), "invocation merge is incorrect"); + assertEquals("3", merged.getValue("common4").asString(), "api client merge is incorrect"); + assertEquals("4", merged.getValue("common5").asString(), "invocation merge is incorrect"); + assertEquals("4", merged.getValue("common6").asString(), "invocation merge is incorrect"); + + } + + @Specification(number="3.3.1.1", text="The API SHOULD have a method for setting a transaction context propagator.") + @Test void setting_transaction_context_propagator() { + DoSomethingProvider provider = new DoSomethingProvider(); + FeatureProviderTestUtils.setFeatureProvider(provider); + + TransactionContextPropagator transactionContextPropagator = new ThreadLocalTransactionContextPropagator(); + api.setTransactionContextPropagator(transactionContextPropagator); + assertEquals(transactionContextPropagator, api.getTransactionContextPropagator()); + } + + @Specification(number="3.3.1.2.1", text="The API MUST have a method for setting the evaluation context of the transaction context propagator for the current transaction.") + @Test void setting_transaction_context() { + DoSomethingProvider provider = new DoSomethingProvider(); + FeatureProviderTestUtils.setFeatureProvider(provider); + + TransactionContextPropagator transactionContextPropagator = new ThreadLocalTransactionContextPropagator(); + api.setTransactionContextPropagator(transactionContextPropagator); + + Map attributes = new HashMap<>(); + attributes.put("common", new Value("1")); + EvaluationContext transactionContext = new ImmutableContext(attributes); + + api.setTransactionContext(transactionContext); + assertEquals(transactionContext, transactionContextPropagator.getTransactionContext()); + } + + @Specification(number="3.3.1.2.2", text="A transaction context propagator MUST have a method for setting the evaluation context of the current transaction.") + @Specification(number="3.3.1.2.3", text="A transaction context propagator MUST have a method for getting the evaluation context of the current transaction.") + @Test void transaction_context_propagator_setting_context() { + TransactionContextPropagator transactionContextPropagator = new ThreadLocalTransactionContextPropagator(); + + Map attributes = new HashMap<>(); + attributes.put("common", new Value("1")); + EvaluationContext transactionContext = new ImmutableContext(attributes); + transactionContextPropagator.setTransactionContext(transactionContext); + assertEquals(transactionContext, transactionContextPropagator.getTransactionContext()); } @Specification(number="1.3.4", text="The client SHOULD guarantee the returned value of any typed flag evaluation method is of the expected type. If the value returned by the underlying provider implementation does not match the expected type, it's to be considered abnormal execution, and the supplied default value should be returned.") @@ -355,6 +421,7 @@ public void initialize(EvaluationContext evaluationContext) throws Exception { @Specification(number="1.3.2.1", text="The client MUST provide methods for typed flag evaluation, including boolean, numeric, string, and structure, with parameters flag key (string, required), default value (boolean | number | string | structure, required), and evaluation options (optional), which returns the flag value.") @Specification(number="3.2.2.2", text="The Client and invocation MUST NOT have a method for supplying evaluation context.") @Specification(number="3.2.4.1", text="When the global evaluation context is set, the on context changed handler MUST run.") + @Specification(number="3.3.2.1", text="The API MUST NOT have a method for setting a transaction context propagator.") @Test void not_applicable_for_dynamic_context() {} } diff --git a/src/test/java/dev/openfeature/sdk/LockingTest.java b/src/test/java/dev/openfeature/sdk/LockingTest.java index f58795ad0..ddfa9c079 100644 --- a/src/test/java/dev/openfeature/sdk/LockingTest.java +++ b/src/test/java/dev/openfeature/sdk/LockingTest.java @@ -185,6 +185,20 @@ void getContextShouldReadLockAndUnlock() { verify(apiLock.readLock()).unlock(); } + @Test + void setTransactionalContextPropagatorShouldWriteLockAndUnlock() { + api.setTransactionContextPropagator(new NoOpTransactionContextPropagator()); + verify(apiLock.writeLock()).lock(); + verify(apiLock.writeLock()).unlock(); + } + + @Test + void getTransactionalContextPropagatorShouldReadLockAndUnlock() { + api.getTransactionContextPropagator(); + verify(apiLock.readLock()).lock(); + verify(apiLock.readLock()).unlock(); + } + @Test void clearHooksShouldWriteLockAndUnlock() { diff --git a/src/test/java/dev/openfeature/sdk/NoOpTransactionContextPropagatorTest.java b/src/test/java/dev/openfeature/sdk/NoOpTransactionContextPropagatorTest.java new file mode 100644 index 000000000..1f91451ae --- /dev/null +++ b/src/test/java/dev/openfeature/sdk/NoOpTransactionContextPropagatorTest.java @@ -0,0 +1,23 @@ +package dev.openfeature.sdk; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class NoOpTransactionContextPropagatorTest { + + NoOpTransactionContextPropagator contextPropagator = new NoOpTransactionContextPropagator(); + + @Test + public void emptyTransactionContext() { + EvaluationContext result = contextPropagator.getTransactionContext(); + assertNull(result); + } + + @Test + public void setTransactionContext() { + EvaluationContext firstContext = new ImmutableContext(); + contextPropagator.setTransactionContext(firstContext); + assertNull(contextPropagator.getTransactionContext()); + } +} \ No newline at end of file diff --git a/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java b/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java index e19a10aec..63a1dadd6 100644 --- a/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java +++ b/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java @@ -73,4 +73,9 @@ void settingDefaultProviderToNullErrors() { void settingNamedClientProviderToNullErrors() { assertThatCode(() -> api.setProvider(CLIENT_NAME, null)).isInstanceOf(IllegalArgumentException.class); } + + @Test + void settingTransactionalContextPropagatorToNullErrors() { + assertThatCode(() -> api.setTransactionContextPropagator(null)).isInstanceOf(IllegalArgumentException.class); + } } diff --git a/src/test/java/dev/openfeature/sdk/ThreadLocalTransactionContextPropagatorTest.java b/src/test/java/dev/openfeature/sdk/ThreadLocalTransactionContextPropagatorTest.java new file mode 100644 index 000000000..00b63c8a1 --- /dev/null +++ b/src/test/java/dev/openfeature/sdk/ThreadLocalTransactionContextPropagatorTest.java @@ -0,0 +1,57 @@ +package dev.openfeature.sdk; + +import lombok.SneakyThrows; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.Callable; +import java.util.concurrent.FutureTask; + +import static org.junit.jupiter.api.Assertions.*; + +public class ThreadLocalTransactionContextPropagatorTest { + + ThreadLocalTransactionContextPropagator contextPropagator = new ThreadLocalTransactionContextPropagator(); + + @Test + public void setTransactionContextOneThread() { + EvaluationContext firstContext = new ImmutableContext(); + contextPropagator.setTransactionContext(firstContext); + assertSame(firstContext, contextPropagator.getTransactionContext()); + EvaluationContext secondContext = new ImmutableContext(); + contextPropagator.setTransactionContext(secondContext); + assertNotSame(firstContext, contextPropagator.getTransactionContext()); + assertSame(secondContext, contextPropagator.getTransactionContext()); + } + + @Test + public void emptyTransactionContext() { + EvaluationContext result = contextPropagator.getTransactionContext(); + assertNull(result); + } + + @SneakyThrows + @Test + public void setTransactionContextTwoThreads() { + EvaluationContext firstContext = new ImmutableContext(); + EvaluationContext secondContext = new ImmutableContext(); + + Callable callable = () -> { + assertNull(contextPropagator.getTransactionContext()); + contextPropagator.setTransactionContext(secondContext); + EvaluationContext transactionContext = contextPropagator.getTransactionContext(); + assertSame(secondContext, transactionContext); + return transactionContext; + }; + contextPropagator.setTransactionContext(firstContext); + EvaluationContext firstThreadContext = contextPropagator.getTransactionContext(); + assertSame(firstContext, firstThreadContext); + + FutureTask futureTask = new FutureTask<>(callable); + Thread thread = new Thread(futureTask); + thread.start(); + EvaluationContext secondThreadContext = futureTask.get(); + + assertSame(secondContext, secondThreadContext); + assertSame(firstContext, firstThreadContext); + } +} \ No newline at end of file