feat: add `$flagd.timestamp` to json evaluator (#958)

<!-- Please use this template for your pull request. -->
<!-- Please use the sections that you need and delete other sections -->

## This PR
<!-- add the description of the PR here -->

Adds "timestamp" to the json evaluation context.


### Related Issues
<!-- add here the GitHub issue that this PR resolves if applicable -->

Related to #851. I am not sure we want to say that it closes the issue
though.

---------

Signed-off-by: Craig Pastro <pastro.craig@gmail.com>
Co-authored-by: Michael Beemer <beeme1mr@users.noreply.github.com>
Co-authored-by: Todd Baert <todd.baert@dynatrace.com>
This commit is contained in:
Craig Pastro 2023-10-11 06:46:46 -07:00 committed by GitHub
parent fee1558da4
commit a1b04e778d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 2 deletions

View File

@ -9,6 +9,7 @@ import (
"regexp"
"strconv"
"strings"
"time"
"github.com/diegoholiveira/jsonlogic/v3"
"github.com/open-feature/flagd/core/pkg/logger"
@ -38,7 +39,8 @@ const (
var regBrace *regexp.Regexp
type flagdProperties struct {
FlagKey string `json:"flagKey"`
FlagKey string `json:"flagKey"`
Timestamp int64 `json:"timestamp"`
}
func init() {
@ -321,7 +323,8 @@ func (je *JSONEvaluator) evaluateVariant(reqID string, flagKey string, context m
}
context = je.setFlagdProperties(context, flagdProperties{
FlagKey: flagKey,
FlagKey: flagKey,
Timestamp: time.Now().Unix(),
})
b, err := json.Marshal(context)

View File

@ -1248,4 +1248,36 @@ func TestFlagdAmbientProperties(t *testing.T) {
t.Fatalf("expected %s, got %s", model.TargetingMatchReason, reason)
}
})
t.Run("timestampIsInTheContext", func(t *testing.T) {
evaluator := eval.NewJSONEvaluator(logger.NewLogger(nil, false), store.NewFlags())
_, _, err := evaluator.SetState(sync.DataSync{FlagData: `{
"flags": {
"welcome-banner": {
"state": "ENABLED",
"variants": {
"true": true,
"false": false
},
"defaultVariant": "false",
"targeting": {
"<": [ 1696904426, { "var": "$flagd.timestamp" } ]
}
}
}
}`})
if err != nil {
t.Fatal(err)
}
value, variant, reason, _, err := evaluator.ResolveBooleanValue(context.Background(), "default", "welcome-banner", nil)
if err != nil {
t.Fatal(err)
}
if !value || variant != "true" || reason != model.TargetingMatchReason {
t.Fatal("timestamp was not in the context")
}
})
}