diff --git a/core/pkg/evaluator/fractional.go b/core/pkg/evaluator/fractional.go index 8059395e2..24042807f 100644 --- a/core/pkg/evaluator/fractional.go +++ b/core/pkg/evaluator/fractional.go @@ -32,7 +32,7 @@ type fractionalEvaluationDistribution struct { } type fractionalEvaluationVariant struct { - variant any // string, bool, number or nil + variant any // string, bool, number, nil or *resolveResult weight int32 } @@ -212,7 +212,8 @@ func parseFractionalEvaluationDistributions(values []any, data any, logger *logg } // JSONLogic pre-evaluates all arguments before they reach fractional. - // Pre-evaluated operators become primitive values (strings, numbers, etc.), never map[string]any nodes. + // Pre-evaluated operators become primitive values (strings, numbers, etc.) or a resolve result, + // never map[string]any nodes. var variant any switch v := distributionArray[0].(type) { case string: @@ -223,8 +224,11 @@ func parseFractionalEvaluationDistributions(values []any, data any, logger *logg variant = v case nil: variant = nil + case *resolveResult: + variant = v default: - return nil, fmt.Errorf("flag %q: first element of distribution element must be a string, bool, number, or nil", flagKey) + return nil, fmt.Errorf( + "flag %q: first element of distribution element must be a string, bool, number, nil, or resolve", flagKey) } weight := int64(1) diff --git a/core/pkg/evaluator/hot_path_logging_test.go b/core/pkg/evaluator/hot_path_logging_test.go index 124072695..ca001fba3 100644 --- a/core/pkg/evaluator/hot_path_logging_test.go +++ b/core/pkg/evaluator/hot_path_logging_test.go @@ -51,6 +51,14 @@ func TestHotPathLoggingIsDebugOnly(t *testing.T) { targeting: `{"fractional": [["on", 50], ["off", 50]]}`, context: map[string]any{"targetingKey": ""}, }, + "resolve absent variant property": { + targeting: `{"resolve": [{"var": "variant"}]}`, + context: map[string]any{}, + }, + "resolve non-finite metadata": { + targeting: `{"resolve": ["on", null, [["share", {"/": [{"var": "hits"}, 0]}]]]}`, + context: map[string]any{"hits": 1}, + }, "$flagd in context": { targeting: `{"if": [{"==": [{"var": "email"}, "abc"]}, "on", "off"]}`, context: map[string]any{"$flagd": map[string]any{"flagKey": "spoofed"}}, diff --git a/core/pkg/evaluator/json.go b/core/pkg/evaluator/json.go index 95ef96027..0d6f96309 100644 --- a/core/pkg/evaluator/json.go +++ b/core/pkg/evaluator/json.go @@ -1,7 +1,6 @@ package evaluator import ( - "bytes" "context" "encoding/json" "errors" @@ -170,6 +169,9 @@ func NewResolver(store store.IStore, logger *logger.Logger, jsonEvalTracer trace jsonlogic.AddOperator(StartsWithEvaluationName, NewStringComparisonEvaluator(logger).StartsWithEvaluation) jsonlogic.AddOperator(EndsWithEvaluationName, NewStringComparisonEvaluator(logger).EndsWithEvaluation) jsonlogic.AddOperator(SemVerEvaluationName, NewSemVerComparison(logger).SemVerEvaluation) + resolveEvaluator := NewResolveEvaluator(logger) + jsonlogic.AddOperator(resolveOperatorName, resolveEvaluator.Evaluate) + jsonlogic.AddOperator(ResolveEvaluationName, resolveEvaluator.rejectFromContext) return Resolver{store: store, Logger: logger, tracer: jsonEvalTracer} } @@ -373,12 +375,13 @@ func resolve[T constraints](ctx context.Context, reqID string, key string, conte return value, variant, reason, metadata, err } - if reason == model.FallbackReason { + // flagd's own fallback and disabled results carry no variant; a resolve rule may use these reasons too + if reason == model.FallbackReason && variant == "" { var zero T return zero, variant, model.FallbackReason, metadata, nil } - if reason == model.DisabledReason { + if reason == model.DisabledReason && variant == "" { var zero T return zero, "", model.DisabledReason, metadata, nil } @@ -442,16 +445,27 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ErrorReason) } - var result bytes.Buffer // evaluate JsonLogic rules to determine the variant - err = jsonlogic.Apply(bytes.NewReader(targetingBytes), bytes.NewReader(b), &result) + output, err := applyTargeting(targetingBytes, b) + if err != nil { + je.Logger.ErrorWithID(reqID, fmt.Sprintf("error applying targeting rules: %s", err)) + return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ParseErrorCode) + } + + // a Go value no JSON input can produce, so context data cannot forge it + if resolved, ok := output.(*resolveResult); ok { + variant, reason, metadata, err := je.applyResolveResult(reqID, flagKey, flag, metadata, resolved) + return variant, flag.Variants, reason, metadata, err + } + + result, err := json.Marshal(output) if err != nil { je.Logger.ErrorWithID(reqID, fmt.Sprintf("error applying targeting rules: %s", err)) return "", flag.Variants, model.ErrorReason, metadata, errors.New(model.ParseErrorCode) } // check if string is "null" before we strip quotes, so we can differentiate between JSON null and "null" - trimmed := strings.TrimSpace(result.String()) + trimmed := strings.TrimSpace(string(result)) if trimmed == "null" { if flag.DefaultVariant == "" { @@ -489,6 +503,20 @@ func (je *Resolver) evaluateVariant(ctx context.Context, reqID string, flagKey s return flag.DefaultVariant, flag.Variants, model.StaticReason, metadata, nil } +// applyTargeting is jsonlogic.Apply without the final encode, so operators can return Go values +func applyTargeting(rule, data []byte) (any, error) { + var parsedRule, parsedData any + if err := json.Unmarshal(rule, &parsedRule); err != nil { + return nil, err + } + if err := json.Unmarshal(data, &parsedData); err != nil { + return nil, err + } + // parsedData comes from json.Unmarshal, so it cannot hold resolveOperatorName; only the rule's own resolve + // calls reach the operator + return jsonlogic.ApplyInterface(bindResolveOperator(parsedRule), parsedData) +} + func setFlagdProperties( log *logger.Logger, context map[string]any, diff --git a/core/pkg/evaluator/resolve.go b/core/pkg/evaluator/resolve.go new file mode 100644 index 000000000..88d27350a --- /dev/null +++ b/core/pkg/evaluator/resolve.go @@ -0,0 +1,226 @@ +package evaluator + +import ( + "encoding/json" + "errors" + "fmt" + "math" + + "github.com/open-feature/flagd/core/pkg/logger" + "github.com/open-feature/flagd/core/pkg/model" + "go.uber.org/zap" +) + +const ResolveEvaluationName = "resolve" + +// resolveOperatorName is the operator the rule's own resolve calls are bound to before evaluation. +// JsonLogic re-applies a map that some operators (if, reduce...) get back from a branch, so a context value like +// {"resolve": [...]} is dispatched as an operator call. The invalid UTF-8 byte keeps that from reaching this +// operator: json.Unmarshal replaces it with U+FFFD, so no decoded context key can equal this name. +const resolveOperatorName = ResolveEvaluationName + "\xff" + +// reservedMetadataKeys belong to flag set metadata. The schema rejects them as literal rule metadata keys; this +// also skips computed ones. +var reservedMetadataKeys = map[string]struct{}{"flagSetId": {}, "version": {}} + +// resolveResult is what the operator returns. JsonLogic passes it through if untouched (it only +// re-applies maps), and since no JSON input decodes to it, context data cannot forge one. +// A nil reason keeps TARGETING_MATCH. +type resolveResult struct { + variant string + reason *string + metadata map[string]any +} + +// ResolveEvaluator implements the terminal resolve operator. +// It selects a variant and optionally overrides the evaluation reason and metadata. +type ResolveEvaluator struct { + Logger *logger.Logger +} + +func NewResolveEvaluator(log *logger.Logger) *ResolveEvaluator { + return &ResolveEvaluator{Logger: log} +} + +// Evaluate returns a *resolveResult. Arguments are already evaluated by JsonLogic. +// Malformed evaluated arguments return null, like the other custom operators, so the flag falls back to its +// default variant. +func (re *ResolveEvaluator) Evaluate(values, _ any) any { + parsed, err := parseEvaluatedResolve(values) + if err != nil { + re.Logger.Debug("resolve evaluation failed", zap.Error(err)) + return nil + } + return parsed +} + +// rejectFromContext handles "resolve" calls that are left after bindResolveOperator, which can only come from +// context data. It returns null, so the flag falls back to its default variant. +func (re *ResolveEvaluator) rejectFromContext(_, _ any) any { + re.Logger.Debug("ignoring resolve operator supplied by evaluation context") + return nil +} + +// bindResolveOperator renames the rule's resolve calls to resolveOperatorName, in place. Only single-key maps are +// operator calls; JsonLogic returns larger maps as literal data without evaluating them, so their contents are left +// unchanged. Call it only on a freshly decoded rule, never on context data. +func bindResolveOperator(rule any) any { + switch node := rule.(type) { + case map[string]any: + if len(node) != 1 { + return rule + } + if args, ok := node[ResolveEvaluationName]; ok { + delete(node, ResolveEvaluationName) + node[resolveOperatorName] = args + } + for _, value := range node { + bindResolveOperator(value) + } + case []any: + for _, item := range node { + bindResolveOperator(item) + } + } + return rule +} + +func parseEvaluatedResolve(values any) (*resolveResult, error) { + args, ok := values.([]any) + if !ok || len(args) < 1 || len(args) > 3 { + return nil, errors.New("resolve arguments must be an array of 1 to 3 items") + } + + variant, err := resolveVariantKey(args[0]) + if err != nil { + return nil, err + } + parsed := &resolveResult{variant: variant} + + if len(args) >= 2 && args[1] != nil { + reason, ok := args[1].(string) + if !ok { + return nil, errors.New("resolve reason must be a string or null") + } + parsed.reason = &reason + } + + if len(args) == 3 && args[2] != nil { + metadata, err := parseEvaluatedMetadata(args[2]) + if err != nil { + return nil, err + } + parsed.metadata = metadata + } + return parsed, nil +} + +// resolveVariantKey coerces the variant like a plain targeting result: booleans become "true"/"false", and numbers +// take their JSON form (unofficially, as for plain results) +func resolveVariantKey(value any) (string, error) { + switch v := value.(type) { + case string: + return v, nil + case bool, float64, float32, int, int32, int64, uint, uint32, uint64: + encoded, err := json.Marshal(v) + if err != nil { + return "", fmt.Errorf("resolve variant %v has no variant key: %w", v, err) + } + return string(encoded), nil + default: + return "", errors.New("resolve variant must be a string, boolean, or number") + } +} + +func parseEvaluatedMetadata(value any) (map[string]any, error) { + pairs, ok := value.([]any) + if !ok { + return nil, errors.New("resolve metadata must be an array of [key, value] pairs") + } + metadata := make(map[string]any, len(pairs)) + for _, pair := range pairs { + key, raw, err := metadataPair(pair) + if err != nil { + return nil, err + } + primitive, ok := metadataPrimitive(raw) + if !ok { + return nil, errors.New("resolve metadata value must be a string, finite number, or boolean") + } + metadata[key] = primitive + } + if len(metadata) == 0 { + return nil, nil + } + return metadata, nil +} + +func metadataPair(pair any) (string, any, error) { + items, ok := pair.([]any) + if !ok || len(items) != 2 { + return "", nil, errors.New("resolve metadata pair must be a [key, value] array") + } + key, ok := items[0].(string) + if !ok { + return "", nil, errors.New("resolve metadata key must be a string") + } + return key, items[1], nil +} + +// metadataPrimitive rejects NaN and ±Inf (e.g. a computed 1/0): JSON can't encode them, so returning them would +// fail OFREP and Connect JSON responses, taking a whole bulk response with them +func metadataPrimitive(value any) (any, bool) { + switch n := value.(type) { + case string, bool: + return n, true + case float64: + return n, isFinite(n) + case float32: + return float64(n), isFinite(float64(n)) + case int: + return float64(n), true + case int32: + return float64(n), true + case int64: + return float64(n), true + case uint: + return float64(n), true + case uint32: + return float64(n), true + case uint64: + return float64(n), true + default: + return nil, false + } +} + +func isFinite(f float64) bool { + return !math.IsNaN(f) && !math.IsInf(f, 0) +} + +func (je *Resolver) applyResolveResult( + reqID, flagKey string, flag model.Flag, metadata map[string]any, parsed *resolveResult, +) (variant, reason string, meta map[string]any, err error) { + if metadata == nil { + metadata = map[string]any{} + } + // variant keys are non-empty, and an empty variant is how flagd marks its own fallback and disabled + // results, so an empty one is always missing + if _, exists := flag.Variants[parsed.variant]; !exists || parsed.variant == "" { + je.Logger.ErrorWithID(reqID, fmt.Sprintf( + "invalid or missing variant: %s for flagKey: %s, variant is not valid", parsed.variant, flagKey)) + return "", model.ErrorReason, metadata, errors.New(model.GeneralErrorCode) + } + for key, value := range parsed.metadata { + if _, reserved := reservedMetadataKeys[key]; reserved { + je.Logger.DebugWithID(reqID, fmt.Sprintf("ignoring reserved resolve metadata key: %s", key)) + continue + } + metadata[key] = value + } + reason = model.TargetingMatchReason + if parsed.reason != nil { + reason = *parsed.reason + } + return parsed.variant, reason, metadata, nil +} diff --git a/core/pkg/evaluator/resolve_test.go b/core/pkg/evaluator/resolve_test.go new file mode 100644 index 000000000..f398ebc63 --- /dev/null +++ b/core/pkg/evaluator/resolve_test.go @@ -0,0 +1,557 @@ +package evaluator + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + + "github.com/open-feature/flagd/core/pkg/logger" + "github.com/open-feature/flagd/core/pkg/model" + "github.com/open-feature/flagd/core/pkg/store" + "github.com/open-feature/flagd/core/pkg/sync" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestResolveEvaluation(t *testing.T) { + const source = "testSource" + ctx := context.Background() + nestedBranches := resolveFlag(`{ + "if": [ + {"==": [{"var": "id"}, "a"]}, + {"resolve": ["red", "ALLOWLIST", [["details", "customer-a"]]]}, + {"==": [{"var": "id"}, "b"]}, + {"resolve": ["red", "SPLIT", [["details", "customer-b"]]]}, + {"resolve": ["blue", "FALLTHROUGH", [["details", "else"]]]} + ] + }`) + + tests := map[string]struct { + flags string + metadata model.Metadata + flagKey string + context map[string]any + value string + variant string + reason string + meta map[string]any + err error + }{ + "whole rule selects variant and keeps targeting match": { + flags: resolveFlag(`{"resolve": ["red"]}`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + }, + "custom reason": { + flags: resolveFlag(`{"resolve": ["blue", "ALLOWLIST"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: "ALLOWLIST", + }, + // the reason is free-form; flagd's own reason names must not change the value or variant + "FALLBACK reason keeps value and variant": { + flags: resolveFlag(`{"resolve": ["blue", "FALLBACK"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.FallbackReason, + }, + "DISABLED reason keeps value and variant": { + flags: resolveFlag(`{"resolve": ["blue", "DISABLED"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.DisabledReason, + }, + "ERROR reason keeps value and variant": { + flags: resolveFlag(`{"resolve": ["blue", "ERROR"]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.ErrorReason, + }, + "null reason keeps targeting match and merges metadata": { + flags: resolveFlag(`{"resolve": ["green", null, [["details", "pilot"]]]}`), + flagKey: "color", + value: "#00FF00", + variant: "green", + reason: model.TargetingMatchReason, + meta: map[string]any{"details": "pilot"}, + }, + "rule metadata wins over flag and flag set": { + flags: `{ + "metadata": {"details": "set", "owner": "set"}, + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "blue": "#0000FF", "green": "#00FF00", "yellow": "#FFFF00"}, + "metadata": {"details": "flag", "version": "flag"}, + "targeting": {"resolve": ["red", "ALLOWLIST", [["details", "rule"], ["onlyRule", true]]]} + } + } + }`, + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "ALLOWLIST", + meta: map[string]any{ + "details": "rule", + "owner": "set", + "version": "flag", + "onlyRule": true, + }, + }, + // the first two branches serve the same variant, so only the reason and details tell them apart + "nested if first branch": { + flags: nestedBranches, + flagKey: "color", + context: map[string]any{"id": "a"}, + value: "#FF0000", + variant: "red", + reason: "ALLOWLIST", + meta: map[string]any{"details": "customer-a"}, + }, + "nested if second branch": { + flags: nestedBranches, + flagKey: "color", + context: map[string]any{"id": "b"}, + value: "#FF0000", + variant: "red", + reason: "SPLIT", + meta: map[string]any{"details": "customer-b"}, + }, + "nested if else branch": { + flags: nestedBranches, + flagKey: "color", + context: map[string]any{"id": "z"}, + value: "#0000FF", + variant: "blue", + reason: "FALLTHROUGH", + meta: map[string]any{"details": "else"}, + }, + "single if clause is terminal": { + flags: resolveFlag(`{"if": [{"resolve": ["green", "ALLOWLIST"]}]}`), + flagKey: "color", + value: "#00FF00", + variant: "green", + reason: "ALLOWLIST", + }, + // a fixed bucketing value and zero weights pick the bucket deterministically + "fractional bucket variant is terminal": { + flags: resolveFlag(`{"fractional": ["key", + [{"resolve": ["red", "SPLIT", [["details", "treatment"]]]}, 1], + [{"resolve": ["blue", "SPLIT", [["details", "holdback"]]]}, 0] + ]}`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "SPLIT", + meta: map[string]any{"details": "treatment"}, + }, + "fractional mixes plain and resolve buckets": { + flags: resolveFlag(`{"fractional": ["key", [{"resolve": ["red", "SPLIT"]}, 0], ["blue", 1]]}`), + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: model.TargetingMatchReason, + }, + "fractional in an if result": { + flags: resolveFlag(`{"if": [true, + {"fractional": ["key", [{"resolve": ["green", "SPLIT", [["details", "treatment"]]]}, 1]]}, + "blue" + ]}`), + flagKey: "color", + value: "#00FF00", + variant: "green", + reason: "SPLIT", + meta: map[string]any{"details": "treatment"}, + }, + "computed variant reason and details": { + flags: resolveFlag(`{ + "resolve": [ + {"if": [true, "red", "blue"]}, + {"cat": ["ALLOW", "LIST"]}, + [["details", {"cat": ["us-", {"var": "bucket"}]}]] + ] + }`), + flagKey: "color", + context: map[string]any{"bucket": "10pct"}, + value: "#FF0000", + variant: "red", + reason: "ALLOWLIST", + meta: map[string]any{"details": "us-10pct"}, + }, + "boolean variant is coerced like a plain result": { + flags: coercedKeysFlag(`{"resolve": [true, "BETA"]}`), + flagKey: "coerced", + value: "#00FF00", + variant: "true", + reason: "BETA", + }, + "computed number variant is coerced like a plain result": { + flags: coercedKeysFlag(`{"resolve": [{"var": "pick"}]}`), + flagKey: "coerced", + context: map[string]any{"pick": 1}, + value: "#0000FF", + variant: "1", + reason: model.TargetingMatchReason, + }, + "computed metadata list": { + flags: resolveFlag(`{"resolve": ["red", null, {"var": "meta"}]}`), + flagKey: "color", + context: map[string]any{"meta": []any{[]any{"details", "from-context"}}}, + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + meta: map[string]any{"details": "from-context"}, + }, + "computed metadata pair": { + flags: resolveFlag(`{"resolve": ["red", null, [{"var": "pair"}]]}`), + flagKey: "color", + context: map[string]any{"pair": []any{"details", "from-context"}}, + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + meta: map[string]any{"details": "from-context"}, + }, + "computed metadata key": { + flags: resolveFlag(`{"resolve": ["red", null, [[{"cat": ["az-", {"var": "zone"}]}, "served"]]]}`), + flagKey: "color", + context: map[string]any{"zone": "a"}, + value: "#FF0000", + variant: "red", + reason: model.TargetingMatchReason, + meta: map[string]any{"az-a": "served"}, + }, + "numeric and boolean metadata": { + flags: resolveFlag(`{"resolve": ["red", "SPLIT", [["percent", 10], ["enabled", false]]]}`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "SPLIT", + meta: map[string]any{"percent": float64(10), "enabled": false}, + }, + "missing variant matches a plain string miss": { + flags: resolveFlag(`{"resolve": ["missing"]}`), + flagKey: "color", + reason: model.ErrorReason, + err: errors.New(model.GeneralErrorCode), + }, + // a multi-key object is literal data to JsonLogic, so a "resolve" key nested in it must not be bound + "literal data keeps a nested resolve key": { + flags: resolveFlag(`{ + "if": [ + {"some": [ + [{"payload": {"resolve": "eu"}, "tag": 1}], + {"==": [{"var": "payload.resolve"}, "eu"]} + ]}, + {"resolve": ["red", "EU"]}, + "blue" + ] + }`), + flagKey: "color", + value: "#FF0000", + variant: "red", + reason: "EU", + }, + "shared evaluator inlines a terminal resolve": { + flags: `{ + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "blue": "#0000FF", "green": "#00FF00", "yellow": "#FFFF00"}, + "targeting": {"$ref": "picked"} + } + }, + "$evaluators": {"picked": {"resolve": ["blue", "ALLOWLIST"]}} + }`, + flagKey: "color", + value: "#0000FF", + variant: "blue", + reason: "ALLOWLIST", + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{source}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: tt.flags, Source: source})) + + value, variant, reason, metadata, err := je.ResolveStringValue(ctx, "default", tt.flagKey, tt.context) + assert.Equal(t, tt.value, value) + assert.Equal(t, tt.variant, variant) + assert.Equal(t, tt.reason, reason) + assert.Equal(t, tt.err, err) + for key, want := range tt.meta { + assert.Equal(t, want, metadata[key]) + } + }) + } +} + +// flagSetId and version belong to flag set metadata, so rule metadata can't override or add them, literal or computed +func TestResolveReservedMetadataKeys(t *testing.T) { + const withSetMetadata = `{ + "metadata": {"flagSetId": "set", "version": "1"}, + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": {"red": "#FF0000", "yellow": "#FFFF00"}, + "targeting": %s + } + } + }` + literal := `{"resolve": ["red", null, [["flagSetId", "rule"], ["version", "rule"], ["details", "rule"]]]}` + computed := `{"resolve": ["red", null, [ + [{"cat": ["flagSet", "Id"]}, "rule"], [{"var": "key"}, "rule"], ["details", "rule"] + ]]}` + + tests := map[string]struct { + flags string + want map[string]any + }{ + "literal keys keep flag set values": { + flags: fmt.Sprintf(withSetMetadata, literal), + want: map[string]any{"flagSetId": "set", "version": "1"}, + }, + "computed keys keep flag set values": { + flags: fmt.Sprintf(withSetMetadata, computed), + want: map[string]any{"flagSetId": "set", "version": "1"}, + }, + "literal keys are not added": {flags: resolveFlag(literal)}, + "computed keys are not added": {flags: resolveFlag(computed)}, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: tt.flags, Source: "testSource"})) + + _, variant, _, metadata, err := je.ResolveStringValue( + context.Background(), "default", "color", map[string]any{"key": "version"}) + require.NoError(t, err) + assert.Equal(t, "red", variant) + assert.Equal(t, "rule", metadata["details"]) + for _, key := range []string{"flagSetId", "version"} { + if want, ok := tt.want[key]; ok { + assert.Equal(t, want, metadata[key]) + } else { + assert.NotContains(t, metadata, key) + } + } + }) + } +} + +func TestResolveRuntimeErrors(t *testing.T) { + tests := map[string]struct { + targeting string + context map[string]any + err error + }{ + // an empty variant fails like any missing variant, so a FALLBACK reason cannot make it look like flagd's own + "empty variant": { + targeting: `{"resolve": ["", "FALLBACK"]}`, + err: errors.New(model.GeneralErrorCode), + }, + "computed empty variant": { + targeting: `{"resolve": [{"var": "pick"}, "FALLBACK"]}`, + context: map[string]any{"pick": ""}, + err: errors.New(model.GeneralErrorCode), + }, + // context data shaped like an operator result must not be treated as one + "context cannot forge a resolve result": { + targeting: `{"var": "pick"}`, + context: map[string]any{"pick": map[string]any{ + "variant": "red", "reason": "INJECTED", "metadata": map[string]any{"flagSetId": "spoofed"}, + }}, + err: errors.New(model.GeneralErrorCode), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(tt.targeting), Source: "testSource"})) + + _, variant, reason, metadata, err := je.ResolveStringValue(context.Background(), "default", "color", tt.context) + assert.Empty(t, variant) + assert.Equal(t, model.ErrorReason, reason) + assert.Equal(t, tt.err, err) + assert.NotContains(t, metadata, "flagSetId") + _, encodeErr := json.Marshal(metadata) + assert.NoError(t, encodeErr, "metadata must stay JSON-encodable") + }) + } +} + +// a single-key context map like {"resolve": [...]} returned from a branch must never reach the real resolve +// operator. jsonlogic before v3.10.2 re-applies such maps as operator calls (the flag then falls back to its +// default variant); later versions return them as values (an invalid variant). Either way the context's variant, +// reason and metadata must not come through. +func TestResolveContextCannotInvokeResolve(t *testing.T) { + injected := map[string]any{"pick": map[string]any{ + "resolve": []any{"red", "INJECTED", []any{[]any{"flagSetId", "spoofed"}}}, + }} + + tests := map[string]string{ + "nested if": `{"if": [true, {"var": "pick"}, "blue"]}`, + "nested if else": `{"if": [false, "blue", {"var": "pick"}]}`, + "inside resolve": `{"resolve": [{"if": [true, {"var": "pick"}, "blue"]}]}`, + } + + for name, targeting := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(targeting), Source: "testSource"})) + + _, variant, reason, metadata, _ := je.ResolveStringValue(context.Background(), "default", "color", injected) + assert.NotEqual(t, "red", variant) + assert.NotEqual(t, "INJECTED", reason) + assert.NotContains(t, metadata, "flagSetId") + }) + } +} + +// malformed computed arguments return null like the other custom operators, so the default variant is selected +func TestResolveMalformedComputedArguments(t *testing.T) { + tests := map[string]struct { + targeting string + context map[string]any + }{ + "null variant": {targeting: `{"resolve": [{"var": "pick"}]}`}, + "object variant": { + targeting: `{"resolve": [{"var": "pick"}]}`, + context: map[string]any{"pick": map[string]any{"a": 1}}, + }, + "non-string reason": {targeting: `{"resolve": ["red", {"var": "why"}]}`, context: map[string]any{"why": 1}}, + "non-primitive metadata": { + targeting: `{"resolve": ["red", null, [["details", {"var": "obj"}]]]}`, + context: map[string]any{"obj": map[string]any{"a": 1}}, + }, + "inside an if result": {targeting: `{"if": [true, {"resolve": [{"var": "pick"}]}, "blue"]}`}, + "inside a fractional bucket": { + targeting: `{"fractional": ["key", [{"resolve": [{"var": "pick"}]}, 1], ["blue", 0]]}`, + }, + "+Inf metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 1, "total": 0}}, + "NaN metadata": {targeting: nonFiniteMetadataRule, context: map[string]any{"hits": 0, "total": 0}}, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + require.NoError(t, je.SetState(sync.DataSync{FlagData: resolveFlag(tt.targeting), Source: "testSource"})) + + value, variant, reason, metadata, err := je.ResolveStringValue(context.Background(), "default", "color", tt.context) + require.NoError(t, err) + assert.Equal(t, "#FFFF00", value) + assert.Equal(t, "yellow", variant) + assert.Equal(t, model.DefaultReason, reason) + assert.NotContains(t, metadata, "share") + assert.NotContains(t, metadata, "details") + }) + } +} + +// a computed ratio that is +Inf for total 0 and NaN for 0/0 +const nonFiniteMetadataRule = `{"resolve": ["red", "SPLIT", [["share", {"/": [{"var": "hits"}, {"var": "total"}]}]]]}` + +// one flag with non-finite computed metadata must not break encoding of a bulk evaluation +func TestResolveNonFiniteMetadataInBulk(t *testing.T) { + log := logger.NewLogger(nil, false) + s, err := store.NewStore(log, []string{"testSource"}) + require.NoError(t, err) + je := NewJSON(log, s) + flags := `{"flags": { + "ratio": {"state": "ENABLED", "defaultVariant": "red", "variants": {"red": "#FF0000"}, + "targeting": ` + nonFiniteMetadataRule + `}, + "sibling": {"state": "ENABLED", "defaultVariant": "on", "variants": {"on": true, "off": false}} + }}` + require.NoError(t, je.SetState(sync.DataSync{FlagData: flags, Source: "testSource"})) + + values, _, err := je.ResolveAllValues(context.Background(), "default", map[string]any{"hits": 1, "total": 0}) + require.NoError(t, err) + require.Len(t, values, 2) + + _, err = json.Marshal(values) + require.NoError(t, err) + for _, value := range values { + if value.FlagKey == "sibling" { + assert.Equal(t, true, value.Value) + assert.NoError(t, value.Error) + } + if value.FlagKey == "ratio" { + assert.NoError(t, value.Error) + assert.Equal(t, model.DefaultReason, value.Reason) + assert.NotContains(t, value.Metadata, "share") + } + } +} + +func TestParseEvaluatedResolve(t *testing.T) { + reason := "ALLOWLIST" + parsed, err := parseEvaluatedResolve([]any{"red", reason, []any{[]any{"details", "x"}, []any{"n", 2}}}) + require.NoError(t, err) + assert.Equal(t, "red", parsed.variant) + require.NotNil(t, parsed.reason) + assert.Equal(t, reason, *parsed.reason) + assert.Equal(t, map[string]any{"details": "x", "n": float64(2)}, parsed.metadata) + + _, err = parseEvaluatedResolve([]any{"red", nil, "nope"}) + require.Error(t, err) +} + +func resolveFlag(targeting string) string { + return `{ + "flags": { + "color": { + "state": "ENABLED", + "defaultVariant": "yellow", + "variants": { + "red": "#FF0000", + "blue": "#0000FF", + "green": "#00FF00", + "yellow": "#FFFF00" + }, + "targeting": ` + targeting + ` + } + } + }` +} + +// coercedKeysFlag has variants named "true", "false" and "1", which only a coerced variant can select +func coercedKeysFlag(targeting string) string { + return `{ + "flags": { + "coerced": { + "state": "ENABLED", + "defaultVariant": "false", + "variants": {"true": "#00FF00", "false": "#FF0000", "1": "#0000FF"}, + "targeting": ` + targeting + ` + } + } + }` +} diff --git a/core/pkg/service/ofrep/models.go b/core/pkg/service/ofrep/models.go index 2f656ae2e..93d85d9d3 100644 --- a/core/pkg/service/ofrep/models.go +++ b/core/pkg/service/ofrep/models.go @@ -78,8 +78,9 @@ func BulkEvaluationResponseFrom(resolutions []evaluator.AnyValue, metadata model } func SuccessResponseFrom(result evaluator.AnyValue) EvaluationSuccess { - // if reason is fallback, we want to omit the value and variant from the response, and set reason to default - if result.Reason == model.FallbackReason { + // if reason is fallback, we want to omit the value and variant from the response, and set reason to default. + // flagd's own fallback and disabled results carry no variant; a resolve rule may use these reasons too + if result.Reason == model.FallbackReason && result.Variant == "" { return EvaluationSuccess{ Value: nil, // not marshalled due to omitempty Key: result.FlagKey, @@ -89,7 +90,7 @@ func SuccessResponseFrom(result evaluator.AnyValue) EvaluationSuccess { } } // if reason is disabled, we want to omit the value and variant from the response - if result.Reason == model.DisabledReason { + if result.Reason == model.DisabledReason && result.Variant == "" { return EvaluationSuccess{ Value: nil, // not marshalled due to omitempty Key: result.FlagKey, diff --git a/core/pkg/service/ofrep/models_test.go b/core/pkg/service/ofrep/models_test.go index a8dfdc0a8..dcd8eb01d 100644 --- a/core/pkg/service/ofrep/models_test.go +++ b/core/pkg/service/ofrep/models_test.go @@ -442,3 +442,28 @@ func TestZeroValuesAreMarshaled(t *testing.T) { }) } } + +// a resolve rule may return flagd's own reason names; with a variant set, the result is returned as-is +func TestSuccessResultRuleReasonWithVariant(t *testing.T) { + for _, reason := range []string{model.FallbackReason, model.DisabledReason} { + t.Run(reason, func(t *testing.T) { + success := SuccessResponseFrom(evaluator.AnyValue{ + Value: "#0000FF", + Variant: "blue", + Reason: reason, + FlagKey: "color", + Metadata: map[string]interface{}{}, + }) + + if success.Value != "#0000FF" { + t.Errorf("expected value #0000FF, got %v", success.Value) + } + if success.Variant != "blue" { + t.Errorf("expected variant blue, got %v", success.Variant) + } + if success.Reason != reason { + t.Errorf("expected reason %v, got %v", reason, success.Reason) + } + }) + } +} diff --git a/docs/architecture-decisions/targeting-variant-metadata.md b/docs/architecture-decisions/targeting-variant-metadata.md index b68f61256..47ffa0a18 100644 --- a/docs/architecture-decisions/targeting-variant-metadata.md +++ b/docs/architecture-decisions/targeting-variant-metadata.md @@ -3,7 +3,7 @@ status: accepted author: Parth Suthar created: 2026-07-30 -updated: 2026-10-16 +updated: 2026-11-16 --- # Per-evaluation metadata from targeting rules @@ -51,12 +51,14 @@ Add a `resolve` operator to `schemas/json/targeting.json`, alongside `fractional ### Arguments -- **`variant`** (1st): string. The only **required** argument, and the exact equivalent of the plain-string return: `"red"` and `{ "resolve": ["red"] }` are interchangeable terminals selecting the variant `red`. +- **`variant`** (1st): string. The only **required** argument, and the exact equivalent of the plain-string return: `"red"` and `{ "resolve": ["red"] }` are interchangeable terminals selecting the variant `red`. Like a plain-string return, a boolean is coerced to `"true"`/`"false"`; the behavior of numbers is not defined. - **`reason`** (2nd): string or `null`, optional. Free-form, operator-defined; overrides the top-level evaluation `reason` for this branch. The schema does not constrain it to an enum (see [Narrowing the coarse `reason`](#narrowing-the-coarse-reason)). - **`metadata`** (3rd): array of `[key, value]` pairs, optional, shallow. Values are restricted to `string | number | boolean`, matching flag and flag-set metadata. - **`details`**: a well-known metadata key: free-text explanation of why this branch fired. -`resolve` is **terminal**: it is only valid as the whole targeting rule, or as a result branch of `if` / `?:` (recursively). Implementations reject it anywhere else when the flag is loaded, so its result always passes through to the resolver unchanged. +Every argument may be computed with JsonLogic: the variant, the reason, and the metadata list, its pairs, their keys, and their values. + +`resolve` is **terminal**: it is only valid as the whole targeting rule, as a result branch of `if`, or as the variant of a `fractional` bucket (recursively). The targeting schema rejects it anywhere else, so its result always passes through to the resolver unchanged; like any other configuration that doesn't conform to the schema, misplaced `resolve` is undefined behavior. ### Evaluator changes @@ -144,7 +146,7 @@ Each branch tags the evaluation with the rule that fired: ### Example — nested `if` with a fractional split -`fractional` returns a plain string (`"on"` or `"off"`), and both are truthy under JsonLogic — so it can't be used directly as an `if` condition; wrapping it in `==` against a target bucket label makes it a real boolean: +A `fractional` bucket's variant is a terminal position too, so each bucket can carry its own reason and metadata. The bucket a user lands in depends only on the bucketing value and the weights, so wrapping a variant in `resolve` doesn't move anyone: ```json { @@ -152,21 +154,10 @@ Each branch tags the evaluation with the rule that fired: "if": [ { "==": [{ "var": "locale" }, "en-US"] }, { - "if": [ - { - "==": [ - { - "fractional": [ - { "var": "targetingKey" }, - ["on", 10], - ["off", 90] - ] - }, - "on" - ] - }, - { "resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]] }, - { "resolve": ["off", "SPLIT_FALLTHROUGH", [["details", "us-holdback"]]] } + "fractional": [ + { "var": "targetingKey" }, + [{ "resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]] }, 10], + [{ "resolve": ["off", "SPLIT_FALLTHROUGH", [["details", "us-holdback"]]] }, 90] ] }, { "resolve": ["off", "FALLTHROUGH", [["details", "non-us-off"]]] } @@ -238,4 +229,3 @@ Those scenarios run across the gRPC, OFREP, and in-process paths that `test/inte ## Open questions - **Config version.** Proposal: bump the targeting/flags schema to `v0.1` and gate the new terminus on it, leaving `v0` untouched for existing fleets. Sequencing of the hosted schema at `flagd.dev` is covered in the migration warning above. -- **Fractional buckets.** `fractional` returns a variant string directly, so it can't tag the picked bucket with metadata without a separate operator extension (e.g. an optional third element per weight tuple). Proposal: defer — ship the base `resolve` operator first. Nesting metadata into fractional is meaningfully more complicated and shouldn't block this. diff --git a/docs/reference/custom-operations/fractional-operation.md b/docs/reference/custom-operations/fractional-operation.md index fb2c91808..33b946089 100644 --- a/docs/reference/custom-operations/fractional-operation.md +++ b/docs/reference/custom-operations/fractional-operation.md @@ -95,6 +95,7 @@ This value should typically be something that remains consistent for the duratio The seed is typically the flagKey so that experiments running across different flags are statistically independent, however, you can also specify another seed to either align or further decouple your allocations across different feature flags or use-cases. The other elements in the array are nested arrays with the first element representing a variant and the second being the relative weight for this option. There is no limit to the number of elements. +A variant can also be a [`resolve`](./resolve-operation.md) operation, so each bucket can carry its own reason and metadata. > [!NOTE] > Previous versions of the `fractional` operation used percentage-based weights that had to sum to 100 and were limited to 1% precision. diff --git a/docs/reference/custom-operations/resolve-operation.md b/docs/reference/custom-operations/resolve-operation.md new file mode 100644 index 000000000..fd7d6a82f --- /dev/null +++ b/docs/reference/custom-operations/resolve-operation.md @@ -0,0 +1,101 @@ +--- +description: flagd resolve custom operation +--- + +# Resolve Operation + +`resolve` ends a targeting rule with a variant, and optionally a custom reason and metadata for the branch that fired. + +`"red"` and `{ "resolve": ["red"] }` select the same variant. + +The variant is coerced like a plain targeting result: booleans become `"true"` or `"false"`, and the behavior of numbers is not defined. + +A missing or null reason keeps `TARGETING_MATCH`. + +The reason is free-form: any string is passed through as the evaluation reason, including flagd's own reasons such as `FALLBACK` or `DISABLED`. + +Metadata is a shallow list of `[key, value]` pairs. + +Values are strings, numbers, or booleans. + +Rule metadata overwrites flag metadata, which overwrites flag set metadata. + +`flagSetId` and `version` are reserved for flag set metadata and can't be overridden. + +`resolve` is terminal. + +It is valid as the whole targeting rule, as a result of `if`, or as the variant of a `fractional` bucket, as in the [example below](#fractional-split). + +The [targeting schema](../schema.md) rejects `resolve` anywhere else, such as inside `==`, `cat`, or the bucketing value or weight of `fractional`, and rejects malformed literal arguments. + +Like any other configuration that doesn't conform to the schema, flagd logs a warning at load, and the evaluation result is undefined. + +Every argument may be computed with other operators, such as `var` or `cat`: the variant, the reason, and the metadata list, its pairs, their keys, and their values. + +When a computed argument is malformed, such as an object variant or a metadata number that is `NaN` or infinite, `resolve` returns null like the other custom operations, and the flag falls back to its default variant. + +Older flagd binaries do not know this operator. + +Upgrade flagd before a configuration starts using `resolve`. + +```json +{ + "resolve": [ + "on", + "SPLIT_RANDOM", + [["details", "us-10pct-rollout"]] + ] +} +``` + +## Example + +```json +{ + "flags": { + "acceptable-feature-stability": { + "state": "ENABLED", + "defaultVariant": "ga", + "variants": { + "alpha": "alpha", + "beta": "beta", + "ga": "ga" + }, + "targeting": { + "if": [ + { "===": [{ "var": "customerId" }, "customer-A"] }, + { + "resolve": [ + "alpha", + "TARGETING_MATCH", + [["details", "explicit allowlist for enterprise pilot"]] + ] + }, + { "in": [{ "var": "customerId" }, ["customer-B1", "customer-B2"]] }, + { "resolve": ["beta", "TARGETING_MATCH"] }, + { "resolve": ["ga", "FALLTHROUGH"] } + ] + } + } + } +} +``` + +The `alpha` and `beta` branches both say why they matched. + +The final branch selects `ga` with reason `FALLTHROUGH`. + +## Fractional split + +```json +{ + "fractional": [ + [{ "resolve": ["on", "SPLIT", [["details", "treatment"]]] }, 10], + [{ "resolve": ["off", "SPLIT", [["details", "holdback"]]] }, 90] + ] +} +``` + +Each bucket reports which one fired. + +Wrapping a bucket's variant in `resolve` does not change which bucket a user lands in. diff --git a/docs/reference/flag-definitions.md b/docs/reference/flag-definitions.md index f2408993f..6ee3168b4 100644 --- a/docs/reference/flag-definitions.md +++ b/docs/reference/flag-definitions.md @@ -392,11 +392,13 @@ Consistent with built-in JsonLogic operators, flagd's custom operators return fa | `starts_with` | Attribute starts with the specified value | string | Logic: `#!json { "starts_with" : [ "192.168.0.1", "192.168"] }`
Result: `true`

Logic: `#!json { "starts_with" : [ "10.0.0.1", "192.168"] }`
Result: `false`
Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | `ends_with` | Attribute ends with the specified value | string | Logic: `#!json { "ends_with" : [ "noreply@example.com", "@example.com"] }`
Result: `true`

Logic: `#!json { ends_with" : [ "noreply@example.com", "@test.com"] }`
Result: `false`
Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | `sem_ver` | Attribute matches a semantic versioning condition | string (valid [semver](https://semver.org/)) | Logic: `#!json {"sem_ver": ["1.1.2", ">=", "1.0.0"]}`
Result: `true`

Additional documentation can be found [here](./custom-operations/semver-operation.md). | +| `resolve` | Ends targeting with a variant, optional reason, and metadata | string or boolean variant; reason string or null; metadata pairs of string, number, or boolean | Logic: `#!json {"resolve": ["on", "SPLIT_RANDOM", [["details", "us-10pct-rollout"]]]}`
Result: variant `on`, reason `SPLIT_RANDOM`, metadata `details`

Additional documentation can be found [here](./custom-operations/resolve-operation.md). | !!! info "Error handling in custom operations" flagd's custom operations return `null` on invalid or unexpected inputs, consistent with how built-in JsonLogic operations represent no-value returns, for example how `var` treats missing keys. When used inside an `if`, `null` is falsy, so evaluation falls through to the else branch rather than producing a false positive match. + `resolve` is the exception: it is only valid in a terminal position, which the targeting schema enforces. #### Targeting key diff --git a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go index 1a3d68bd3..b29d3ff32 100644 --- a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go +++ b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2.go @@ -273,13 +273,14 @@ func resolveV2[T constraints](ctx context.Context, logger *logger.Logger, resolv spanFromContext := trace.SpanFromContext(ctx) spanFromContext.SetAttributes(telemetry.SemConvFeatureFlagAttributes(flagKey, variant)...) - switch reason { - case model.FallbackReason: + // flagd's own fallback and disabled results carry no variant; a resolve rule may use these reasons too + switch { + case reason == model.FallbackReason && variant == "": if err := setReasonOnlyV2(resp, model.DefaultReason, metadata); err != nil { logger.ErrorWithID(reqID, err.Error()) return fmt.Errorf("error setting fallback response: %w", err) } - case model.DisabledReason: + case reason == model.DisabledReason && variant == "": if err := setReasonOnlyV2(resp, model.DisabledReason, metadata); err != nil { logger.ErrorWithID(reqID, err.Error()) return fmt.Errorf("error setting disabled response: %w", err) diff --git a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go index 9e543614b..06a2339c4 100644 --- a/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go +++ b/flagd/pkg/service/flag-evaluation/flag_evaluator_v2_test.go @@ -124,6 +124,36 @@ func TestFlagEvaluationServiceV2_Fallback(t *testing.T) { } } +// TestFlagEvaluationServiceV2_RuleReasonWithVariant tests that a resolve rule may return flagd's own +// reason names: with a variant set, the result is returned as-is instead of as a fallback or disabled flag. +func TestFlagEvaluationServiceV2_RuleReasonWithVariant(t *testing.T) { + for _, reason := range []string{model.FallbackReason, model.DisabledReason} { + t.Run(reason, func(t *testing.T) { + ctrl := gomock.NewController(t) + eval := mock.NewMockIEvaluator(ctrl) + metrics, _ := getMetricReader() + s := NewFlagEvaluationServiceV2( + logger.NewLogger(nil, false), eval, &eventingConfiguration{}, + metrics, nil, nil, 0, + ) + eval.EXPECT().ResolveBooleanValue(gomock.Any(), gomock.Any(), "flag", gomock.Any()).Return( + true, "on", reason, metadata, nil, + ) + + got, err := s.ResolveBoolean(context.Background(), connect.NewRequest(&evalV2.ResolveBooleanRequest{ + FlagKey: "flag", Context: &structpb.Struct{}, + })) + + require.NoError(t, err) + require.NotNil(t, got.Msg.Value) + require.True(t, *got.Msg.Value) + require.NotNil(t, got.Msg.Variant) + require.Equal(t, "on", *got.Msg.Variant) + require.Equal(t, reason, got.Msg.Reason) + }) + } +} + func TestInvalidSelector_FlagEvaluationServiceV2(t *testing.T) { ctrl := gomock.NewController(t) eval := mock.NewMockIEvaluator(ctrl) diff --git a/mkdocs.yml b/mkdocs.yml index 6317f7213..d65a6e7b1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -108,6 +108,7 @@ nav: - 'Definition Overview': 'reference/flag-definitions.md' - 'Custom Operations': - 'Fractional': 'reference/custom-operations/fractional-operation.md' + - 'Resolve': 'reference/custom-operations/resolve-operation.md' - 'Semantic Version': 'reference/custom-operations/semver-operation.md' - 'String Comparison': 'reference/custom-operations/string-comparison-operation.md' - 'Schema': 'reference/schema.md'