-
Notifications
You must be signed in to change notification settings - Fork 94
feat: Add custom regex_match string comparison #1822
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
leth
wants to merge
1
commit into
open-feature:main
Choose a base branch
from
leth:regex_match
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,21 @@ | ||
| package evaluator | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "regexp" | ||
| "strings" | ||
|
|
||
| "github.com/open-feature/flagd/core/pkg/logger" | ||
| "github.com/open-feature/flagd/core/pkg/store" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| const ( | ||
| StartsWithEvaluationName = "starts_with" | ||
| EndsWithEvaluationName = "ends_with" | ||
| RegexMatchEvaluationName = "regex_match" | ||
| ) | ||
|
|
||
| type StringComparisonEvaluator struct { | ||
|
|
@@ -123,3 +128,133 @@ func parseStringComparisonEvaluationData(values interface{}) (string, string, er | |
|
|
||
| return property, targetValue, nil | ||
| } | ||
|
|
||
| type RegexMatchEvaluator struct { | ||
| Logger *logger.Logger | ||
| // RegexCache caches compiled regex patterns for reuse | ||
| RegexCache *map[string]*regexp.Regexp | ||
| // PrevRegexCache holds the previous cache to allow for cache retention across config reloads | ||
| PrevRegexCache *map[string]*regexp.Regexp | ||
| } | ||
|
|
||
| func NewRegexMatchEvaluator(log *logger.Logger, s store.IStore) *RegexMatchEvaluator { | ||
| self := &RegexMatchEvaluator{ | ||
| Logger: log, | ||
| RegexCache: &map[string]*regexp.Regexp{}, | ||
| PrevRegexCache: &map[string]*regexp.Regexp{}, | ||
| } | ||
|
|
||
| watcher := make(chan store.FlagQueryResult, 1) | ||
| go func() { | ||
| for range watcher { | ||
| // On config change, rotate the regex caches | ||
| // If the current cache is empty, do nothing, to keep the previous cache intact in case it is still helpful | ||
| if len(*self.RegexCache) == 0 { | ||
| continue | ||
| } | ||
| self.PrevRegexCache = self.RegexCache | ||
| self.RegexCache = &map[string]*regexp.Regexp{} | ||
| } | ||
| }() | ||
| selector := store.NewSelector("") | ||
| s.Watch(context.Background(), &selector, watcher) | ||
|
|
||
| return self | ||
| } | ||
|
|
||
| // RegexMatchEvaluation checks if the given property matches a certain regex pattern. | ||
| // It returns 'true', if the value of the given property matches the pattern, 'false' if not. | ||
| // As an example, it can be used in the following way inside an 'if' evaluation: | ||
| // | ||
| // { | ||
| // "if": [ | ||
| // { | ||
| // "regex_match": [{"var": "email"}, ".*@faas\\.com"] | ||
| // }, | ||
| // "red", null | ||
| // ] | ||
| // } | ||
| // | ||
| // This rule can be applied to the following data object, where the evaluation will resolve to 'true': | ||
| // | ||
| // { "email": "[email protected]" } | ||
| // | ||
| // Note that the 'regex_match' evaluation rule must contain two or three items, all of which resolve to a | ||
| // string value. | ||
| // The first item is the property to check, the second item is the regex pattern to match against, | ||
| // and an optional third item can contain regex flags (e.g. "i" for case-insensitive matching). | ||
| func (rme *RegexMatchEvaluator) RegexMatchEvaluation(values, _ interface{}) interface{} { | ||
| propertyValue, pattern, flags, err := parseRegexMatchEvaluationData(values) | ||
| if err != nil { | ||
| rme.Logger.Error("error parsing regex_match evaluation data: %v", zap.Error(err)) | ||
| return false | ||
| } | ||
|
|
||
| re, err := rme.getRegex(pattern, flags) | ||
| if err != nil { | ||
| rme.Logger.Error("error compiling regex pattern: %v", zap.Error(err)) | ||
| return false | ||
| } | ||
|
|
||
| return re.MatchString(propertyValue) | ||
| } | ||
|
|
||
| var validFlagsStringRe *regexp.Regexp = regexp.MustCompile("[imsU]+") | ||
|
|
||
| func parseRegexMatchEvaluationData(values interface{}) (string, string, string, error) { | ||
| parsed, ok := values.([]interface{}) | ||
| if !ok { | ||
| return "", "", "", errors.New("regex_match evaluation is not an array") | ||
| } | ||
|
|
||
| if len(parsed) != 2 && len(parsed) != 3 { | ||
| return "", "", "", errors.New("regex_match evaluation must contain a value, a regex pattern, and (optionally) regex flags") | ||
| } | ||
|
|
||
| property, ok := parsed[0].(string) | ||
| if !ok { | ||
| return "", "", "", errors.New("regex_match evaluation: property did not resolve to a string value") | ||
| } | ||
|
|
||
| pattern, ok := parsed[1].(string) | ||
| if !ok { | ||
| return "", "", "", errors.New("regex_match evaluation: pattern did not resolve to a string value") | ||
| } | ||
|
|
||
| flags := "" | ||
| if (len(parsed) == 3) { | ||
| flags, ok = parsed[2].(string) | ||
| if !ok { | ||
| return "", "", "", errors.New("regex_match evaluation: flags did not resolve to a string value") | ||
| } | ||
| if !validFlagsStringRe.MatchString(flags) { | ||
| return "", "", "", errors.New("regex_match evaluation: flags value is invalid") | ||
| } | ||
| } | ||
|
|
||
| return property, pattern, flags, nil | ||
| } | ||
|
|
||
| func (rme *RegexMatchEvaluator) getRegex(pattern string, flags string) (*regexp.Regexp, error) { | ||
| finalPattern := pattern | ||
| if flags != "" { | ||
| finalPattern = fmt.Sprintf("(?%s)%s", flags, pattern) | ||
| } | ||
|
|
||
| if cached, exists := (*rme.RegexCache)[finalPattern]; exists { | ||
| return cached, nil | ||
| } | ||
|
|
||
| // Check previous cache to allow for cache retention across config reloads | ||
| if cached, exists := (*rme.PrevRegexCache)[finalPattern]; exists { | ||
| (*rme.RegexCache)[finalPattern] = cached | ||
| delete(*rme.PrevRegexCache, finalPattern) | ||
| return cached, nil | ||
| } | ||
|
|
||
| regexp, err := regexp.Compile(finalPattern) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return regexp, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -431,3 +431,191 @@ func Test_parseStringComparisonEvaluationData(t *testing.T) { | |
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestJSONEvaluator_regexMatchEvaluation(t *testing.T) { | ||
| const source = "testSource" | ||
| var sources = []string{source} | ||
| ctx := context.Background() | ||
|
|
||
| tests := map[string]struct { | ||
| flags []model.Flag | ||
| flagKey string | ||
| context map[string]any | ||
| expectedValue string | ||
| expectedVariant string | ||
| expectedReason string | ||
| expectedError error | ||
| }{ | ||
| "two strings provided - match": { | ||
| flags: []model.Flag{{ | ||
| Key: "headerColor", | ||
| State: "ENABLED", | ||
| DefaultVariant: "red", | ||
| Variants: colorVariants, | ||
| Targeting: []byte(`{ | ||
| "if": [ | ||
| { | ||
| "regex_match": ["[email protected]", ".*"] | ||
| }, | ||
| "red", null | ||
| ] | ||
| }`), | ||
| }, | ||
| }, | ||
| flagKey: "headerColor", | ||
| context: map[string]any{}, | ||
| expectedVariant: "red", | ||
| expectedValue: "#FF0000", | ||
| expectedReason: model.TargetingMatchReason, | ||
| }, | ||
| "resolve target property using nested operation - match": { | ||
| flags: []model.Flag{{ | ||
| Key: "headerColor", | ||
| State: "ENABLED", | ||
| DefaultVariant: "red", | ||
| Variants: colorVariants, | ||
| Targeting: []byte(`{ | ||
| "if": [ | ||
| { | ||
| "regex_match": [{"var": "email"}, ".*@.*"] | ||
| }, | ||
| "red", null | ||
| ] | ||
| }`), | ||
| }, | ||
| }, | ||
| flagKey: "headerColor", | ||
| context: map[string]any{ | ||
| "email": "[email protected]", | ||
| }, | ||
| expectedVariant: "red", | ||
| expectedValue: "#FF0000", | ||
| expectedReason: model.TargetingMatchReason, | ||
| }, | ||
| "two strings provided - no match": { | ||
| flags: []model.Flag{{ | ||
| Key: "headerColor", | ||
| State: "ENABLED", | ||
| DefaultVariant: "red", | ||
| Variants: colorVariants, | ||
| Targeting: []byte(`{ | ||
| "if": [ | ||
| { | ||
| "regex_match": ["[email protected]", ".*FAAS.*"] | ||
| }, | ||
| "red", "green" | ||
| ] | ||
| }`), | ||
| }, | ||
| }, | ||
| flagKey: "headerColor", | ||
| context: map[string]any{ | ||
| "email": "[email protected]", | ||
| }, | ||
| expectedVariant: "green", | ||
| expectedValue: "#00FF00", | ||
| expectedReason: model.TargetingMatchReason, | ||
| }, | ||
| "three strings provided - match": { | ||
| flags: []model.Flag{{ | ||
| Key: "headerColor", | ||
| State: "ENABLED", | ||
| DefaultVariant: "red", | ||
| Variants: colorVariants, | ||
| Targeting: []byte(`{ | ||
| "if": [ | ||
| { | ||
| "regex_match": ["[email protected]", ".*FAAS.*", "i"] | ||
| }, | ||
| "red", null | ||
| ] | ||
| }`), | ||
| }, | ||
| }, | ||
| flagKey: "headerColor", | ||
| context: map[string]any{}, | ||
| expectedVariant: "red", | ||
| expectedValue: "#FF0000", | ||
| expectedReason: model.TargetingMatchReason, | ||
| }, | ||
| "resolve target property using nested operation - no match": { | ||
| flags: []model.Flag{{ | ||
| Key: "headerColor", | ||
| State: "ENABLED", | ||
| DefaultVariant: "red", | ||
| Variants: colorVariants, | ||
| Targeting: []byte(`{ | ||
| "if": [ | ||
| { | ||
| "regex_match": [{"var": "email"}, "nope"] | ||
| }, | ||
| "red", "green" | ||
| ] | ||
| }`), | ||
| }, | ||
| }, | ||
| flagKey: "headerColor", | ||
| context: map[string]any{ | ||
| "email": "[email protected]", | ||
| }, | ||
| expectedVariant: "green", | ||
| expectedValue: "#00FF00", | ||
| expectedReason: model.TargetingMatchReason, | ||
| }, | ||
| "error during parsing - return default": { | ||
| flags: []model.Flag{{ | ||
| Key: "headerColor", | ||
| State: "ENABLED", | ||
| DefaultVariant: "red", | ||
| Variants: colorVariants, | ||
| Targeting: []byte(`{ | ||
| "if": [ | ||
| { | ||
| "regex_match": "no-array" | ||
| }, | ||
| "red", "green" | ||
| ] | ||
| }`), | ||
| }, | ||
| }, | ||
| flagKey: "headerColor", | ||
| context: map[string]any{ | ||
| "email": "[email protected]", | ||
| }, | ||
| expectedVariant: "green", | ||
| expectedValue: "#00FF00", | ||
| expectedReason: model.TargetingMatchReason, | ||
| }, | ||
| } | ||
|
|
||
| const reqID = "default" | ||
| for name, tt := range tests { | ||
| t.Run(name, func(t *testing.T) { | ||
| log := logger.NewLogger(nil, false) | ||
| s, err := store.NewStore(log, sources) | ||
| if err != nil { | ||
| t.Fatalf("NewStore failed: %v", err) | ||
| } | ||
| je := NewJSON(log, s) | ||
| je.store.Update(source, tt.flags, model.Metadata{}) | ||
|
|
||
| value, variant, reason, _, err := resolve[string](ctx, reqID, tt.flagKey, tt.context, je.evaluateVariant) | ||
|
|
||
| if value != tt.expectedValue { | ||
| t.Errorf("expected value '%s', got '%s'", tt.expectedValue, value) | ||
| } | ||
|
|
||
| if variant != tt.expectedVariant { | ||
| t.Errorf("expected variant '%s', got '%s'", tt.expectedVariant, variant) | ||
| } | ||
|
|
||
| if reason != tt.expectedReason { | ||
| t.Errorf("expected reason '%s', got '%s'", tt.expectedReason, reason) | ||
| } | ||
|
|
||
| if err != tt.expectedError { | ||
| t.Errorf("expected err '%v', got '%v'", tt.expectedError, err) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -245,12 +245,13 @@ These are custom operations specific to flagd and flagd providers. | |
| They are purpose-built extensions to JsonLogic in order to support common feature flag use cases. | ||
| Consistent with built-in JsonLogic operators, flagd's custom operators return falsy/nullish values with invalid inputs. | ||
|
|
||
| | Function | Description | Context attribute type | Example | | ||
| | ---------------------------------- | --------------------------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | `fractional` (_available v0.6.4+_) | Deterministic, pseudorandom fractional distribution | string (bucketing value) | Logic: `#!json { "fractional" : [ { "var": "email" }, [ "red" , 50], [ "green" , 50 ] ] }` <br>Result: Pseudo randomly `red` or `green` based on the evaluation context property `email`.<br><br>Additional documentation can be found [here](./custom-operations/fractional-operation.md). | | ||
| | `starts_with` | Attribute starts with the specified value | string | Logic: `#!json { "starts_with" : [ "192.168.0.1", "192.168"] }`<br>Result: `true`<br><br>Logic: `#!json { "starts_with" : [ "10.0.0.1", "192.168"] }`<br>Result: `false`<br>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" : [ "[email protected]", "@example.com"] }`<br>Result: `true`<br><br>Logic: `#!json { ends_with" : [ "[email protected]", "@test.com"] }`<br>Result: `false`<br>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"]}`<br>Result: `true`<br><br>Additional documentation can be found [here](./custom-operations/semver-operation.md). | | ||
| | Function | Description | Context attribute type | Example | | ||
| | ---------------------------------- | --------------------------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | `fractional` (_available v0.6.4+_) | Deterministic, pseudorandom fractional distribution | string (bucketing value) | Logic: `#!json { "fractional" : [ { "var": "email" }, [ "red" , 50], [ "green" , 50 ] ] }` <br>Result: Pseudo randomly `red` or `green` based on the evaluation context property `email`.<br><br>Additional documentation can be found [here](./custom-operations/fractional-operation.md). | | ||
| | `starts_with` | Attribute starts with the specified value | string | Logic: `#!json { "starts_with" : [ "192.168.0.1", "192.168"] }`<br>Result: `true`<br><br>Logic: `#!json { "starts_with" : [ "10.0.0.1", "192.168"] }`<br>Result: `false`<br>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" : [ "[email protected]", "@example.com"] }`<br>Result: `true`<br><br>Logic: `#!json { ends_with" : [ "[email protected]", "@test.com"] }`<br>Result: `false`<br>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"]}`<br>Result: `true`<br><br>Additional documentation can be found [here](./custom-operations/semver-operation.md). | | ||
| | `regex_match` (_available TBD_) | Attribute matches the specified regular expression | string | Logic: `#!json { "regex_match" : [ "[email protected]", ".*@example.com"] }`<br>Result: `true`<br><br>Logic: `#!json { regex_match" : [ "[email protected]", ".*@test.com"] }`<br>Result: `false`<br>Additional documentation can be found [here](./custom-operations/string-comparison-operation.md). | | ||
|
|
||
| #### Targeting key | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I couldn't figure out what the correct selector value should be here!