diff --git a/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunInProcessTest.java b/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunInProcessTest.java index 05eb219db1..b67ab3de34 100644 --- a/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunInProcessTest.java +++ b/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunInProcessTest.java @@ -29,7 +29,8 @@ @ConfigurationParameter(key = OBJECT_FACTORY_PROPERTY_NAME, value = "io.cucumber.picocontainer.PicoFactory") @IncludeTags("in-process") // large-integers reads 2^53-1 via 32-bit getInteger; Long scenarios: open-feature/flagd-testbed#379 -@ExcludeTags({"unixsocket", "fractional-v1", "fractional-v2", "deprecated", "large-integers"}) +// the test harness image has no "resolve" launchpad config yet +@ExcludeTags({"unixsocket", "fractional-v1", "fractional-v2", "deprecated", "large-integers", "resolve"}) @Testcontainers public class RunInProcessTest { diff --git a/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunRpcTest.java b/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunRpcTest.java index 4fe721d093..57dfbba279 100644 --- a/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunRpcTest.java +++ b/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/RunRpcTest.java @@ -29,7 +29,8 @@ @ConfigurationParameter(key = OBJECT_FACTORY_PROPERTY_NAME, value = "io.cucumber.picocontainer.PicoFactory") @IncludeTags({"rpc"}) // large-integers reads 2^53-1 via 32-bit getInteger; Long scenarios: open-feature/flagd-testbed#379 -@ExcludeTags({"unixsocket", "fractional-v1", "fractional-v2", "deprecated", "large-integers"}) +// flagd in the test harness image does not support resolve yet +@ExcludeTags({"unixsocket", "fractional-v1", "fractional-v2", "deprecated", "large-integers", "resolve"}) @Testcontainers public class RunRpcTest { diff --git a/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/steps/ProviderSteps.java b/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/steps/ProviderSteps.java index ae170982f4..f915d7f812 100644 --- a/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/steps/ProviderSteps.java +++ b/providers/flagd/src/test/java/dev/openfeature/contrib/providers/flagd/e2e/steps/ProviderSteps.java @@ -116,8 +116,9 @@ public void setupProvider(String providerType) throws InterruptedException { flagdConfig = "ssl"; break; case "metadata": - flagdConfig = "metadata"; + case "resolve": if (State.resolverType == Config.Resolver.FILE) { + // file mode reads the harness flag file directly, so it doesn't need a flagd config FlagdOptions build = state.builder.build(); String selector = build.getSelector(); String replace = selector.replace("rawflags/", ""); @@ -125,6 +126,7 @@ public void setupProvider(String providerType) throws InterruptedException { .port(UNAVAILABLE_PORT) .offlineFlagSourcePath(new File("test-harness/flags/" + replace).getAbsolutePath()); } else { + flagdConfig = providerType; state.builder.port(ContainerUtil.getPort(container, State.resolverType)); } break; diff --git a/providers/flagd/test-harness b/providers/flagd/test-harness index 9d8dace5df..952a05ff47 160000 --- a/providers/flagd/test-harness +++ b/providers/flagd/test-harness @@ -1 +1 @@ -Subproject commit 9d8dace5df1acc0949cd20195c7b9bfc2156f4e3 +Subproject commit 952a05ff4787696a18218b069674f77dd2900494 diff --git a/tools/flagd-core/schemas b/tools/flagd-core/schemas index 1daf5ff56b..19c66c1846 160000 --- a/tools/flagd-core/schemas +++ b/tools/flagd-core/schemas @@ -1 +1 @@ -Subproject commit 1daf5ff56b48d582187d59e35d48c6e191c23839 +Subproject commit 19c66c1846bfceb35cedc5f6126a81063abbf40b diff --git a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/FlagdCore.java b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/FlagdCore.java index aa9e34a2b2..36ffd5ada1 100644 --- a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/FlagdCore.java +++ b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/FlagdCore.java @@ -8,6 +8,7 @@ import dev.openfeature.contrib.tools.flagd.core.model.FlagParser; import dev.openfeature.contrib.tools.flagd.core.model.FlagParsingResult; import dev.openfeature.contrib.tools.flagd.core.targeting.Operator; +import dev.openfeature.contrib.tools.flagd.core.targeting.ResolveResult; import dev.openfeature.contrib.tools.flagd.core.targeting.TargetingRuleException; import dev.openfeature.sdk.ErrorCode; import dev.openfeature.sdk.EvaluationContext; @@ -23,6 +24,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; @@ -208,7 +210,7 @@ private ProviderEvaluation resolve(Class type, String key, T defaultVa return ProviderEvaluation.builder() .errorMessage("flag: " + key + " not found") .errorCode(ErrorCode.FLAG_NOT_FOUND) - .flagMetadata(getFlagMetadata(currentFlagSetMetadata, null)) + .flagMetadata(getFlagMetadata(currentFlagSetMetadata, null, null)) .build(); } @@ -217,12 +219,13 @@ private ProviderEvaluation resolve(Class type, String key, T defaultVa return ProviderEvaluation.builder() .value(defaultValue) .reason(Reason.DISABLED.toString()) - .flagMetadata(getFlagMetadata(currentFlagSetMetadata, flag)) + .flagMetadata(getFlagMetadata(currentFlagSetMetadata, flag, null)) .build(); } final String resolvedVariant; final String reason; + Map ruleMetadata = null; if (EMPTY_TARGETING_STRING.equals(flag.getTargeting())) { resolvedVariant = flag.getDefaultVariant(); @@ -233,6 +236,11 @@ private ProviderEvaluation resolve(Class type, String key, T defaultVa if (jsonResolved == null) { resolvedVariant = flag.getDefaultVariant(); reason = Reason.DEFAULT.toString(); + } else if (jsonResolved instanceof ResolveResult) { + final ResolveResult resolved = (ResolveResult) jsonResolved; + resolvedVariant = resolved.getVariant(); + reason = resolved.getReason() != null ? resolved.getReason() : Reason.TARGETING_MATCH.toString(); + ruleMetadata = resolved.getMetadata(); } else { resolvedVariant = jsonResolved.toString(); // convert to string to support shorthand reason = Reason.TARGETING_MATCH.toString(); @@ -251,7 +259,7 @@ private ProviderEvaluation resolve(Class type, String key, T defaultVa return ProviderEvaluation.builder() .value(defaultValue) .reason(Reason.DEFAULT.toString()) - .flagMetadata(getFlagMetadata(currentFlagSetMetadata, flag)) + .flagMetadata(getFlagMetadata(currentFlagSetMetadata, flag, null)) .build(); } @@ -278,7 +286,7 @@ private ProviderEvaluation resolve(Class type, String key, T defaultVa .value((T) value) .variant(resolvedVariant) .reason(reason) - .flagMetadata(getFlagMetadata(currentFlagSetMetadata, flag)) + .flagMetadata(getFlagMetadata(currentFlagSetMetadata, flag, ruleMetadata)) .build(); } @@ -339,21 +347,14 @@ private static TypeMismatchError mismatch(String key, double value, String why) return new TypeMismatchError(message); } - private static ImmutableMetadata getFlagMetadata(Map currentFlagSetMetadata, FeatureFlag flag) { + // later sources overwrite earlier ones: flag set, then flag, then the resolve rule + private static ImmutableMetadata getFlagMetadata( + Map currentFlagSetMetadata, FeatureFlag flag, Map ruleMetadata) { ImmutableMetadata.ImmutableMetadataBuilder metadataBuilder = ImmutableMetadata.builder(); - - if (currentFlagSetMetadata != null) { - for (Map.Entry entry : currentFlagSetMetadata.entrySet()) { - addEntryToMetadataBuilder(metadataBuilder, entry.getKey(), entry.getValue()); - } - } - - if (flag != null && flag.getMetadata() != null) { - for (Map.Entry entry : flag.getMetadata().entrySet()) { - addEntryToMetadataBuilder(metadataBuilder, entry.getKey(), entry.getValue()); - } - } - + Stream.of(currentFlagSetMetadata, flag != null ? flag.getMetadata() : null, ruleMetadata) + .filter(Objects::nonNull) + .flatMap(metadata -> metadata.entrySet().stream()) + .forEach(entry -> addEntryToMetadataBuilder(metadataBuilder, entry.getKey(), entry.getValue())); return metadataBuilder.build(); } diff --git a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Fractional.java b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Fractional.java index 71dc4112f0..144c3c9f13 100644 --- a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Fractional.java +++ b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Fractional.java @@ -208,14 +208,19 @@ protected final void finalize() { throw new JsonLogicException("Fraction property needs at least one element", jsonPath); } - // variant must be a primitive (string, number, boolean) or null; + // variant must be a primitive (string, number, boolean), null, or a resolve result; // nested JSONLogic expressions are pre-evaluated to these types Object first = array.get(0); - if (first instanceof String || first instanceof Number || first instanceof Boolean || first == null) { + if (first instanceof String + || first instanceof Number + || first instanceof Boolean + || first instanceof ResolveResult + || first == null) { variant = first; } else { throw new JsonLogicException( - "First element of the fraction property must resolve to a string, number, boolean, or null", + "First element of the fraction property must resolve to a string, number, boolean, null, " + + "or resolve", jsonPath); } diff --git a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Operator.java b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Operator.java index fbb4024a00..0fd8d71a56 100644 --- a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Operator.java +++ b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Operator.java @@ -39,6 +39,7 @@ public Operator(boolean compileExpressions) { jsonLogicHandler.addOperation(new SemVer()); jsonLogicHandler.addOperation(new StringComp(StringComp.Type.STARTS_WITH)); jsonLogicHandler.addOperation(new StringComp(StringComp.Type.ENDS_WITH)); + jsonLogicHandler.addOperation(new Resolve()); } /** diff --git a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Resolve.java b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Resolve.java new file mode 100644 index 0000000000..6f240efd92 --- /dev/null +++ b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/Resolve.java @@ -0,0 +1,95 @@ +package dev.openfeature.contrib.tools.flagd.core.targeting; + +import io.github.jamsesso.jsonlogic.evaluator.expressions.PreEvaluatedArgumentsExpression; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; + +/** + * Terminal {@code resolve} operation: {@code ["variant", "reason"?, [["key", value], ...]?]}. + * Selects a variant and optionally overrides the reason and adds rule metadata. Placement is enforced by the + * targeting schema; malformed computed arguments return null, so the flag falls back to its default variant. + */ +@Slf4j +class Resolve implements PreEvaluatedArgumentsExpression { + + // flag set metadata keys a rule can't override; the schema only catches literal keys + private static final Set RESERVED_KEYS = Set.of("flagSetId", "version"); + + @Override + public String key() { + return "resolve"; + } + + @Override + public Object evaluate(List arguments, Object data, String jsonPath) { + if (arguments.isEmpty() || arguments.size() > 3) { + log.debug("resolve takes 1 to 3 arguments"); + return null; + } + + // coerce like a plain targeting result + final Object variant = arguments.get(0); + if (!(variant instanceof String || variant instanceof Boolean || variant instanceof Number)) { + log.debug("resolve variant must be a string, boolean, or number"); + return null; + } + + final Object reason = arguments.size() > 1 ? arguments.get(1) : null; + if (reason != null && !(reason instanceof String)) { + log.debug("resolve reason must be a string or null"); + return null; + } + + final Map metadata = new HashMap<>(); + final Object pairs = arguments.size() > 2 ? arguments.get(2) : null; + if (pairs != null && !addMetadata(pairs, metadata)) { + return null; + } + + return new ResolveResult(variant.toString(), (String) reason, metadata); + } + + private static boolean addMetadata(Object pairs, Map metadata) { + if (!(pairs instanceof List)) { + log.debug("resolve metadata must be an array of [key, value] pairs"); + return false; + } + for (Object pair : (List) pairs) { + final List entry = pair instanceof List ? (List) pair : List.of(); + if (entry.size() != 2 || !(entry.get(0) instanceof String)) { + log.debug("resolve metadata pair must be a [string, value] array"); + return false; + } + final Object value = entry.get(1); + final Object metadataValue = value instanceof Number ? metadataNumber((Number) value) : value; + if (!(metadataValue instanceof String + || metadataValue instanceof Boolean + || metadataValue instanceof Number)) { + log.debug("resolve metadata value must be a string, finite number, or boolean"); + return false; + } + final String key = (String) entry.get(0); + if (!RESERVED_KEYS.contains(key)) { + metadata.put(key, metadataValue); + } + } + return true; + } + + /** + * JsonLogic yields doubles, so whole numbers become ints like they are in flag metadata. + * NaN and Infinity (e.g. a computed 1/0) can't be encoded as JSON, so they return null. + */ + private static Object metadataNumber(Number value) { + final double number = value.doubleValue(); + if (!Double.isFinite(number)) { + return null; + } + final boolean wholeInt = + number == Math.rint(number) && number >= Integer.MIN_VALUE && number <= Integer.MAX_VALUE; + return wholeInt ? (Object) (int) number : number; + } +} diff --git a/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/ResolveResult.java b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/ResolveResult.java new file mode 100644 index 0000000000..28acc081aa --- /dev/null +++ b/tools/flagd-core/src/main/java/dev/openfeature/contrib/tools/flagd/core/targeting/ResolveResult.java @@ -0,0 +1,24 @@ +package dev.openfeature.contrib.tools.flagd.core.targeting; + +import java.util.Collections; +import java.util.Map; +import lombok.Getter; + +/** + * Result of the terminal {@code resolve} operation. No JSON input decodes to this type, so evaluation + * context data cannot forge one. + */ +@Getter +public final class ResolveResult { + private final String variant; + /** Overrides the evaluation reason; {@code null} keeps {@code TARGETING_MATCH}. */ + private final String reason; + /** Rule metadata, merged over flag-set and flag metadata. */ + private final Map metadata; + + ResolveResult(String variant, String reason, Map metadata) { + this.variant = variant; + this.reason = reason; + this.metadata = Collections.unmodifiableMap(metadata); + } +} diff --git a/tools/flagd-core/src/main/resources/flagd/schemas/targeting.json b/tools/flagd-core/src/main/resources/flagd/schemas/targeting.json index f8dd7544fa..3cc7435504 100644 --- a/tools/flagd-core/src/main/resources/flagd/schemas/targeting.json +++ b/tools/flagd-core/src/main/resources/flagd/schemas/targeting.json @@ -13,6 +13,15 @@ }, { "$ref": "#/definitions/anyRule" + }, + { + "$ref": "#/definitions/resolveRule" + }, + { + "$ref": "#/definitions/terminalIfRule" + }, + { + "$ref": "#/definitions/terminalFractionalRule" } ], "definitions": { @@ -23,7 +32,7 @@ "type": "null" }, { - "description": "When returned from rules, booleans are converted to strings (\"true\"/\"false\"), and used to as keys to retrieve the associated value from the \"variants\" object. Be sure that the returned string is present as a key in the variants!", + "description": "When returned from rules, booleans are coerced to strings (\"true\"/\"false\"), and used as keys to retrieve the associated value from the \"variants\" object. Be sure that the returned string is present as a key in the variants!", "type": "boolean" }, { @@ -63,7 +72,7 @@ }, { "type": "array", - "$comment": "this is to support the form of var with a default... there seems to be a bug here, where ajv gives a warning (not an error) because maxItems doesn't equal the number of entries in items, though this is valid in this case", + "$comment": "this is to support the form of var with a default. ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", "minItems": 1, "items": [ { @@ -171,6 +180,7 @@ "additionalProperties": false, "properties": { "if": { + "$comment": "no resolve here; this if may be consumed. see terminalIfRule for the version used in terminal positions.", "title": "If Operator", "description": "The if statement takes 1 or more arguments: a condition (\"if\"), what to do if its true (\"then\", optional, defaults to returning true), and what to do if its false (\"else\", optional, defaults to returning false). Note that the else condition can be used as an else-if statement by adding additional arguments.", "$ref": "#/definitions/variadicOp" @@ -455,13 +465,14 @@ } }, "fractionalWeightArg": { + "$comment": "no resolve in the variant here; this fractional may be consumed. see terminalFractionalWeightArg. ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", "description": "Distribution for all possible variants, with their associated weighting.", "type": "array", "minItems": 1, "maxItems": 2, "items": [ { - "description": "If this bucket is randomly selected, this JSONLogic will be evaluated, and the result will be used as the variant key to return from the variants map.", + "description": "The variant for this bucket. Every bucket's variant is evaluated; the result from the selected bucket is used as the variant key to return from the variants map.", "$ref": "#/definitions/args" }, { @@ -481,7 +492,7 @@ "fractionalOp": { "type": "array", "minItems": 1, - "$comment": "there seems to be a bug here, where ajv gives a warning (not an error) because maxItems doesn't equal the number of entries in items, though this is valid in this case", + "$comment": "ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", "items": [ { "description": "Bucketing value used in pseudorandom assignment; should be a string that is unique and stable for each subject of flag evaluation. Defaults to a concatenation of the flagKey and targetingKey.", @@ -535,6 +546,235 @@ } } }, + "terminalResultArg": { + "$comment": "a terminal position is one whose value becomes the final targeting result. if/fractional are terminal when they're: 1) the root, 2) in a then/else branch of a terminal if, or 3) in a bucket variant of a terminal fractional. this definition is what makes that recursive. anyOf, not oneOf: a plain if/fractional matches both args and the terminal rule, and oneOf would reject it when it's mixed with resolve.", + "anyOf": [ + { + "$ref": "#/definitions/args" + }, + { + "$ref": "#/definitions/resolveRule" + }, + { + "$ref": "#/definitions/terminalIfRule" + }, + { + "$ref": "#/definitions/terminalFractionalRule" + } + ] + }, + "terminalIfRule": { + "$comment": "if whose then/else branches are terminal, so resolve is accepted there; the anyRule if uses plain args, so resolve is rejected when the if is consumed (e.g. inside ==). the first condition (index 0) uses plain args, unless it's the only argument, which JSON Logic returns as the result. else-if conditions (index 2, 4, ...) can't be told apart from branches, so they aren't enforced.", + "type": "object", + "additionalProperties": false, + "properties": { + "if": { + "title": "If Operator", + "description": "The if statement takes 1 or more arguments: a condition (\"if\"), what to do if its true (\"then\", optional, defaults to returning true), and what to do if its false (\"else\", optional, defaults to returning false). Note that the else condition can be used as an else-if statement by adding additional arguments. The \"then\" and \"else\" results may also be a \"resolve\". The first condition can't be a \"resolve\", unless it's the only argument (which is returned as the result).", + "type": "array", + "minItems": 1, + "anyOf": [ + { + "maxItems": 1, + "items": { + "$ref": "#/definitions/terminalResultArg" + } + }, + { + "$comment": "ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", + "minItems": 2, + "items": [ + { + "$ref": "#/definitions/args" + } + ], + "additionalItems": { + "$ref": "#/definitions/terminalResultArg" + } + } + ] + } + } + }, + "terminalFractionalWeightArg": { + "$comment": "ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", + "description": "Distribution for all possible variants, with their associated weighting. The variant may also be a \"resolve\".", + "type": "array", + "minItems": 1, + "maxItems": 2, + "items": [ + { + "description": "The variant for this bucket. Every bucket's variant is evaluated; the result from the selected bucket is used as the variant key to return from the variants map.", + "$ref": "#/definitions/terminalResultArg" + }, + { + "description": "Weighted distribution for this variant key. Must be a non-negative integer. Can be a JSONLogic expression that evaluates to a number (e.g. for time-based progressive rollouts); computed negative weights are clamped to 0 at evaluation time. The total weight sum across all variants must not exceed 2,147,483,647.", + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "$ref": "#/definitions/anyRule" + } + ] + } + ] + }, + "terminalFractionalOp": { + "type": "array", + "minItems": 1, + "$comment": "ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", + "items": [ + { + "description": "Bucketing value used in pseudorandom assignment; should be a string that is unique and stable for each subject of flag evaluation. Defaults to a concatenation of the flagKey and targetingKey.", + "$ref": "#/definitions/anyRule" + }, + { + "$ref": "#/definitions/terminalFractionalWeightArg" + }, + { + "$ref": "#/definitions/terminalFractionalWeightArg" + } + ], + "additionalItems": { + "$ref": "#/definitions/terminalFractionalWeightArg" + } + }, + "terminalFractionalShorthandOp": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/terminalFractionalWeightArg" + } + }, + "terminalFractionalRule": { + "$comment": "fractional whose bucket variants are terminal, so resolve is accepted there; the bucketing value and weights are consumed, so they stay anyRule. the anyRule fractional uses plain args for variants, so resolve is rejected when the fractional is consumed (e.g. inside ==).", + "type": "object", + "additionalProperties": false, + "properties": { + "fractional": { + "title": "Fractional Operation", + "description": "Deterministic, pseudorandom fractional distribution. Bucket variants may also be a \"resolve\".", + "oneOf": [ + { + "$ref": "#/definitions/terminalFractionalOp" + }, + { + "$ref": "#/definitions/terminalFractionalShorthandOp" + } + ] + } + } + }, + "resolveRule": { + "$comment": "deliberately not part of anyRule, so resolve is rejected anywhere its result would be consumed (e.g. inside == or cat). the schema is the only place position is checked; implementations don't re-check, so cases the schema can't enforce (else-if conditions, $ref) are undefined behavior.", + "type": "object", + "additionalProperties": false, + "required": [ + "resolve" + ], + "properties": { + "resolve": { + "$comment": "ajv strict mode (strictTuples) warns about tuple-form items unless minItems and maxItems both equal the tuple length (or additionalItems is false); the length is intentionally variable here, so the warning is expected and harmless.", + "title": "Resolve Operation", + "description": "Terminates targeting with a variant, and optionally a custom reason and metadata for the branch that fired. Only valid as the whole targeting rule, as a result of an \"if\", or as a \"fractional\" bucket variant.", + "type": "array", + "minItems": 1, + "maxItems": 3, + "items": [ + { + "$comment": "literal numbers are rejected, but the schema can't check the type of a computed variant, so implementations coerce whatever it returns (numbers included, undefined behavior), like plain targeting results.", + "description": "The variant key to resolve; equivalent to returning the plain string. Be sure that the variant is present as a key in the variants!", + "oneOf": [ + { + "type": "string" + }, + { + "description": "Booleans are coerced to strings (\"true\"/\"false\"), and used as keys to retrieve the associated value from the \"variants\" object.", + "type": "boolean" + }, + { + "description": "Computed variants are coerced like plain targeting results; booleans become \"true\"/\"false\", and the behavior of numbers is not defined.", + "$ref": "#/definitions/anyRule" + } + ] + }, + { + "description": "Optional free-form reason, overriding the \"TARGETING_MATCH\" reason for this branch. A null reason keeps \"TARGETING_MATCH\".", + "oneOf": [ + { + "type": [ + "string", + "null" + ] + }, + { + "$ref": "#/definitions/anyRule" + } + ] + }, + { + "description": "Optional metadata as [key, value] pairs, merged over flag set and flag metadata (rule values win). \"details\" is a well-known key, explaining why this branch fired. The list and each pair may also be a JSONLogic expression.", + "oneOf": [ + { + "$ref": "#/definitions/anyRule" + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "$ref": "#/definitions/anyRule" + }, + { + "type": "array", + "minItems": 2, + "maxItems": 2, + "items": [ + { + "$comment": "reserved names are only checked for literal keys; a computed key can't be checked here.", + "description": "Metadata key; may also be a JSONLogic expression. \"flagSetId\" and \"version\" are reserved for flag set metadata and can't be overridden; computed keys are not checked for reserved names.", + "oneOf": [ + { + "type": "string", + "not": { + "enum": [ + "flagSetId", + "version" + ] + } + }, + { + "$ref": "#/definitions/anyRule" + } + ] + }, + { + "oneOf": [ + { + "type": [ + "string", + "number", + "boolean" + ] + }, + { + "$ref": "#/definitions/anyRule" + } + ] + } + ] + } + ] + } + } + ] + } + ] + } + } + }, "args": { "oneOf": [ { diff --git a/tools/flagd-core/src/test/java/dev/openfeature/contrib/tools/flagd/core/FlagdCoreResolveTest.java b/tools/flagd-core/src/test/java/dev/openfeature/contrib/tools/flagd/core/FlagdCoreResolveTest.java new file mode 100644 index 0000000000..19e50d33ba --- /dev/null +++ b/tools/flagd-core/src/test/java/dev/openfeature/contrib/tools/flagd/core/FlagdCoreResolveTest.java @@ -0,0 +1,160 @@ +package dev.openfeature.contrib.tools.flagd.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import dev.openfeature.sdk.EvaluationContext; +import dev.openfeature.sdk.ImmutableContext; +import dev.openfeature.sdk.ImmutableStructure; +import dev.openfeature.sdk.ProviderEvaluation; +import dev.openfeature.sdk.Value; +import dev.openfeature.sdk.exceptions.GeneralError; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +class FlagdCoreResolveTest { + + // valid arguments for the "computed" flag + private static final Map COMPUTED_CTX = Map.of( + "variant", new Value("on"), + "reason", new Value("SPLIT"), + "key", new Value("share"), + "hits", new Value(1), + "total", new Value(4)); + + private static FlagdCore core(boolean compile) throws Exception { + FlagdCore core = new FlagdCore(false, compile); + core.setFlags(TestUtils.getFlagsFromResource("flags/resolve-flags.json")); + return core; + } + + private static ProviderEvaluation eval(boolean compile, String key, Map ctx) + throws Exception { + return core(compile).resolveStringValue(key, "fallback", new ImmutableContext(ctx)); + } + + private static void assertResult(ProviderEvaluation result, String variant, String reason) { + assertThat(result.getValue()).isEqualTo(variant); + assertThat(result.getVariant()).isEqualTo(variant); + assertThat(result.getReason()).isEqualTo(reason); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void terminalPositionsSelectTheVariant(boolean compile) throws Exception { + assertResult(eval(compile, "whole-rule", Map.of()), "on", "TARGETING_MATCH"); + assertResult(eval(compile, "single-clause-if", Map.of()), "on", "ALLOWLIST"); + assertResult(eval(compile, "ref", Map.of()), "on", "ALLOWLIST"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void reasonIsFreeForm(boolean compile) throws Exception { + assertResult(eval(compile, "fallback-reason", Map.of()), "on", "FALLBACK"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void eachNestedBranchTagsTheEvaluation(boolean compile) throws Exception { + for (List c : List.of( + List.of("a", "on", "ALLOWLIST", "a"), + List.of("b", "on", "SPLIT", "b"), + List.of("z", "off", "FALLTHROUGH", "rest"))) { + ProviderEvaluation result = eval(compile, "nested-if", Map.of("customerId", new Value(c.get(0)))); + assertResult(result, c.get(1), c.get(2)); + assertThat(result.getFlagMetadata().getString("details")).isEqualTo(c.get(3)); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void eachFractionalBucketTagsTheEvaluation(boolean compile) throws Exception { + for (boolean treatment : new boolean[] {true, false}) { + ProviderEvaluation result = + eval(compile, "fractional-buckets", Map.of("treatment", new Value(treatment))); + assertResult(result, treatment ? "on" : "off", "SPLIT"); + assertThat(result.getFlagMetadata().getString("details")).isEqualTo(treatment ? "treatment" : "holdback"); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void ruleMetadataOverwritesFlagAndFlagSetMetadata(boolean compile) throws Exception { + ProviderEvaluation result = eval(compile, "metadata-precedence", Map.of()); + + assertResult(result, "on", "TARGETING_MATCH"); + assertThat(result.getFlagMetadata().asUnmodifiableMap()) + .containsExactlyInAnyOrderEntriesOf(Map.of( + "scope", "set", + "owner", "flag", + "flagSetId", "set-id", + "version", "set-version", + "details", "rule", + "pilot", true, + "share", 0.5, + "count", 3)); + } + + @ParameterizedTest + @CsvSource({"false,flagSetId", "false,version", "true,flagSetId", "true,version"}) + void ruleMetadataCannotOverrideReservedKeys(boolean compile, String computedKey) throws Exception { + ProviderEvaluation result = eval(compile, "reserved-keys", Map.of("key", new Value(computedKey))); + + assertResult(result, "on", "TARGETING_MATCH"); + assertThat(result.getFlagMetadata().getString("flagSetId")).isEqualTo("set-id"); + assertThat(result.getFlagMetadata().getString("version")).isEqualTo("set-version"); + assertThat(result.getFlagMetadata().getString("details")).isEqualTo("rule"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void argumentsCanBeComputed(boolean compile) throws Exception { + ProviderEvaluation result = eval(compile, "computed", COMPUTED_CTX); + + assertResult(result, "on", "SPLIT"); + assertThat(result.getFlagMetadata().getDouble("share")).isEqualTo(0.25); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void booleanVariantIsCoercedToItsKey(boolean compile) throws Exception { + assertThat(eval(compile, "boolean-variant", Map.of()).getVariant()).isEqualTo("true"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void malformedComputedArgumentsFallBackToTheDefaultVariant(boolean compile) throws Exception { + for (Map override : List.of( + Map.of("variant", new Value()), // null variant + Map.of("reason", new Value(1)), // non-string reason + Map.of("key", new Value(1)), // non-string metadata key + Map.of("total", new Value(0)), // 1/0 is not finite + Map.of("hits", new Value(0), "total", new Value(0)))) { // 0/0 is NaN + Map ctx = new HashMap<>(COMPUTED_CTX); + ctx.putAll(override); + assertResult(eval(compile, "computed", ctx), "off", "DEFAULT"); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void missingVariantFailsLikeAPlainString(boolean compile) { + assertThatThrownBy(() -> eval(compile, "missing-variant", Map.of())).isInstanceOf(GeneralError.class); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void contextDataCannotForgeAResolveResult(boolean compile) { + EvaluationContext forged = new ImmutableContext(Map.of( + "forged", + new Value(new ImmutableStructure( + Map.of("resolve", new Value(List.of(new Value("on"), new Value("FORGED")))))))); + + assertThatThrownBy(() -> core(compile).resolveStringValue("forged", "fallback", forged)) + .isInstanceOf(GeneralError.class); + } +} diff --git a/tools/flagd-core/src/test/resources/flags/resolve-flags.json b/tools/flagd-core/src/test/resources/flags/resolve-flags.json new file mode 100644 index 0000000000..882423d9aa --- /dev/null +++ b/tools/flagd-core/src/test/resources/flags/resolve-flags.json @@ -0,0 +1,107 @@ +{ + "metadata": { "scope": "set", "owner": "set", "flagSetId": "set-id", "version": "set-version" }, + "flags": { + "whole-rule": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { "resolve": ["on"] } + }, + "metadata-precedence": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "metadata": { "owner": "flag", "details": "flag" }, + "targeting": { "resolve": ["on", null, [["details", "rule"], ["pilot", true], ["share", 0.5], ["count", 3]]] } + }, + "reserved-keys": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { + "resolve": ["on", null, [["flagSetId", "rule"], [{ "var": "key" }, "rule"], ["details", "rule"]]] + } + }, + "nested-if": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { + "if": [ + { "==": [{ "var": "customerId" }, "a"] }, + { "resolve": ["on", "ALLOWLIST", [["details", "a"]]] }, + { + "if": [ + { "==": [{ "var": "customerId" }, "b"] }, + { "resolve": ["on", "SPLIT", [["details", "b"]]] }, + { "resolve": ["off", "FALLTHROUGH", [["details", "rest"]]] } + ] + } + ] + } + }, + "single-clause-if": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { "if": [{ "resolve": ["on", "ALLOWLIST"] }] } + }, + "ref": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { "$ref": "allowlist" } + }, + "computed": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { + "resolve": [ + { "var": "variant" }, + { "var": "reason" }, + [[{ "var": "key" }, { "/": [{ "var": "hits" }, { "var": "total" }] }]] + ] + } + }, + "boolean-variant": { + "state": "ENABLED", + "variants": { "true": "on", "false": "off" }, + "defaultVariant": "false", + "targeting": { "resolve": [true] } + }, + "fallback-reason": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { "resolve": ["on", "FALLBACK"] } + }, + "missing-variant": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { "resolve": ["nope"] } + }, + "fractional-buckets": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { + "fractional": [ + "fixed-bucketing-value", + [{ "resolve": ["on", "SPLIT", [["details", "treatment"]]] }, { "if": [{ "var": "treatment" }, 1, 0] }], + [{ "resolve": ["off", "SPLIT", [["details", "holdback"]]] }, { "if": [{ "var": "treatment" }, 0, 1] }] + ] + } + }, + "forged": { + "state": "ENABLED", + "variants": { "on": "on", "off": "off" }, + "defaultVariant": "off", + "targeting": { "var": "forged" } + } + }, + "$evaluators": { + "allowlist": { "resolve": ["on", "ALLOWLIST"] } + } +}