Skip to content
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

feat(ForcedDecisions): add forced-decisions APIs to OptimizelyUserContext #324

Merged
merged 20 commits into from
Oct 20, 2021
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ jobs:
- <<: *test
stage: 'Unit test'
env: GIMME_GO_VERSION=1.10.x
dist: focal
before_script:
# GO module was not introduced earlier. need symlink to search in GOPATH
- mkdir -p $GOPATH/src/github.com && pushd $GOPATH/src/github.com && ln -s $HOME/build/optimizely optimizely && popd
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.12
require (
github.com/google/uuid v1.1.1
github.com/hashicorp/go-multierror v1.1.0
github.com/json-iterator/go v1.1.7
github.com/json-iterator/go v1.1.12
github.com/pkg/errors v0.8.1
github.com/pkg/profile v1.3.0
github.com/stretchr/testify v1.4.0
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/U
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/profile v1.3.0 h1:OQIvuDgm00gWVWGTf4m4mCt6W1/0YqU7Ntg0mySWgaI=
Expand Down
34 changes: 29 additions & 5 deletions pkg/client/client.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/****************************************************************************
* Copyright 2019-2020, Optimizely, Inc. and contributors *
* Copyright 2019-2021, Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
Expand Down Expand Up @@ -28,6 +28,7 @@ import (
"github.com/optimizely/go-sdk/pkg/config"
"github.com/optimizely/go-sdk/pkg/decide"
"github.com/optimizely/go-sdk/pkg/decision"
pkgReasons "github.com/optimizely/go-sdk/pkg/decision/reasons"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason for this named package?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is because there are several properties named reasons throughout the code.

"github.com/optimizely/go-sdk/pkg/entities"
"github.com/optimizely/go-sdk/pkg/event"
"github.com/optimizely/go-sdk/pkg/logging"
Expand All @@ -52,7 +53,7 @@ type OptimizelyClient struct {
// CreateUserContext creates a context of the user for which decision APIs will be called.
// A user context will be created successfully even when the SDK is not fully configured yet.
func (o *OptimizelyClient) CreateUserContext(userID string, attributes map[string]interface{}) OptimizelyUserContext {
return newOptimizelyUserContext(o, userID, attributes)
return newOptimizelyUserContext(o, userID, attributes, nil)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why passing nil?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we don't have any instance of forcedDecisionService to pass since a new userContext is being created. In this case, newOptimizelyUserContext will create a forcedDecisionService internally by itself .

}

func (o *OptimizelyClient) decide(userContext OptimizelyUserContext, key string, options *decide.Options) OptimizelyDecision {
Expand All @@ -73,7 +74,9 @@ func (o *OptimizelyClient) decide(userContext OptimizelyUserContext, key string,
}
}()

decisionContext := decision.FeatureDecisionContext{}
decisionContext := decision.FeatureDecisionContext{
ForcedDecisionService: userContext.forcedDecisionService,
}
projectConfig, err := o.getProjectConfig()
if err != nil {
return NewErrorDecision(key, userContext, decide.GetDecideError(decide.SDKNotReady))
Expand All @@ -95,9 +98,30 @@ func (o *OptimizelyClient) decide(userContext OptimizelyUserContext, key string,
allOptions := o.getAllOptions(options)
decisionReasons := decide.NewDecisionReasons(&allOptions)
decisionContext.Variable = entities.Variable{}
var featureDecision decision.FeatureDecision
var reasons decide.DecisionReasons

featureDecision, reasons, err := o.DecisionService.GetFeatureDecision(decisionContext, usrContext, &allOptions)
decisionReasons.Append(reasons)
// To avoid cyclo-complexity warning
findRegularDecision := func() {
// regular decision
featureDecision, reasons, err = o.DecisionService.GetFeatureDecision(decisionContext, usrContext, &allOptions)
decisionReasons.Append(reasons)
}

// check forced-decisions first
// Passing empty rule-key because checking mapping with flagKey only
if userContext.forcedDecisionService != nil {
var variation *entities.Variation
variation, reasons, err = userContext.forcedDecisionService.FindValidatedForcedDecision(projectConfig, key, "", &allOptions)
decisionReasons.Append(reasons)
if err != nil {
findRegularDecision()
} else {
featureDecision = decision.FeatureDecision{Decision: decision.Decision{Reason: pkgReasons.ForcedDecisionFound}, Variation: variation, Source: decision.FeatureTest}
}
} else {
findRegularDecision()
}

if err != nil {
o.logger.Warning(fmt.Sprintf(`Received error while making a decision for feature "%s": %s`, key, err))
Expand Down
82 changes: 70 additions & 12 deletions pkg/client/optimizely_user_context.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/****************************************************************************
* Copyright 2020, Optimizely, Inc. and contributors *
* Copyright 2020-2021, Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
Expand All @@ -21,6 +21,7 @@ import (
"sync"

"github.com/optimizely/go-sdk/pkg/decide"
"github.com/optimizely/go-sdk/pkg/decision"
"github.com/optimizely/go-sdk/pkg/entities"
)

Expand All @@ -29,23 +30,24 @@ type OptimizelyUserContext struct {
UserID string `json:"userId"`
Attributes map[string]interface{} `json:"attributes"`

optimizely *OptimizelyClient
mutex *sync.RWMutex
optimizely *OptimizelyClient
forcedDecisionService *decision.ForcedDecisionService
mutex *sync.RWMutex
}

// returns an instance of the optimizely user context.
func newOptimizelyUserContext(optimizely *OptimizelyClient, userID string, attributes map[string]interface{}) OptimizelyUserContext {
func newOptimizelyUserContext(optimizely *OptimizelyClient, userID string, attributes map[string]interface{}, forcedDecisionService *decision.ForcedDecisionService) OptimizelyUserContext {
// store a copy of the provided attributes so it isn't affected by changes made afterwards.
if attributes == nil {
attributes = map[string]interface{}{}
}
attributesCopy := copyUserAttributes(attributes)

jaeopt marked this conversation as resolved.
Show resolved Hide resolved
return OptimizelyUserContext{
UserID: userID,
Attributes: attributesCopy,
optimizely: optimizely,
mutex: new(sync.RWMutex),
UserID: userID,
Attributes: attributesCopy,
optimizely: optimizely,
forcedDecisionService: forcedDecisionService,
mutex: new(sync.RWMutex),
}
}

Expand All @@ -66,6 +68,13 @@ func (o OptimizelyUserContext) GetUserAttributes() map[string]interface{} {
return copyUserAttributes(o.Attributes)
}

func (o OptimizelyUserContext) getForcedDecisionService() *decision.ForcedDecisionService {
if o.forcedDecisionService != nil {
return o.forcedDecisionService.CreateCopy()
}
return nil
}

// SetAttribute sets an attribute for a given key.
func (o *OptimizelyUserContext) SetAttribute(key string, value interface{}) {
o.mutex.Lock()
Expand All @@ -80,21 +89,21 @@ func (o *OptimizelyUserContext) SetAttribute(key string, value interface{}) {
// all data required to deliver the flag or experiment.
func (o *OptimizelyUserContext) Decide(key string, options []decide.OptimizelyDecideOptions) OptimizelyDecision {
// use a copy of the user context so that any changes to the original context are not reflected inside the decision
userContextCopy := newOptimizelyUserContext(o.GetOptimizely(), o.GetUserID(), o.GetUserAttributes())
userContextCopy := newOptimizelyUserContext(o.GetOptimizely(), o.GetUserID(), o.GetUserAttributes(), o.getForcedDecisionService())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we use "o.forcedDecisionService" here? We do not want to CreateCopy until SetForcedDecision is called.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My bad. It looks good as is :)

return o.optimizely.decide(userContextCopy, key, convertDecideOptions(options))
}

// DecideAll returns a key-map of decision results for all active flag keys with options.
func (o *OptimizelyUserContext) DecideAll(options []decide.OptimizelyDecideOptions) map[string]OptimizelyDecision {
// use a copy of the user context so that any changes to the original context are not reflected inside the decision
userContextCopy := newOptimizelyUserContext(o.GetOptimizely(), o.GetUserID(), o.GetUserAttributes())
userContextCopy := newOptimizelyUserContext(o.GetOptimizely(), o.GetUserID(), o.GetUserAttributes(), o.getForcedDecisionService())
return o.optimizely.decideAll(userContextCopy, convertDecideOptions(options))
}

// DecideForKeys returns a key-map of decision results for multiple flag keys and options.
func (o *OptimizelyUserContext) DecideForKeys(keys []string, options []decide.OptimizelyDecideOptions) map[string]OptimizelyDecision {
// use a copy of the user context so that any changes to the original context are not reflected inside the decision
userContextCopy := newOptimizelyUserContext(o.GetOptimizely(), o.GetUserID(), o.GetUserAttributes())
userContextCopy := newOptimizelyUserContext(o.GetOptimizely(), o.GetUserID(), o.GetUserAttributes(), o.getForcedDecisionService())
return o.optimizely.decideForKeys(userContextCopy, keys, convertDecideOptions(options))
}

Expand All @@ -108,6 +117,55 @@ func (o *OptimizelyUserContext) TrackEvent(eventKey string, eventTags map[string
return o.optimizely.Track(eventKey, userContext, eventTags)
}

// SetForcedDecision sets the forced decision (variation key) for a given flag and an optional rule.
// returns true if the forced decision has been set successfully.
func (o *OptimizelyUserContext) SetForcedDecision(flagKey, ruleKey, variationKey string) bool {
if _, err := o.optimizely.getProjectConfig(); err != nil {
o.optimizely.logger.Error("Optimizely instance is not valid, failing setForcedDecision call.", err)
return false
}
if o.forcedDecisionService == nil {
o.forcedDecisionService = decision.NewForcedDecisionService(o.GetUserID())
}
return o.forcedDecisionService.SetForcedDecision(flagKey, ruleKey, variationKey)
}

// GetForcedDecision returns the forced decision for a given flag and an optional rule
func (o *OptimizelyUserContext) GetForcedDecision(flagKey, ruleKey string) string {
if _, err := o.optimizely.getProjectConfig(); err != nil {
o.optimizely.logger.Error("Optimizely instance is not valid, failing getForcedDecision call.", err)
return ""
}
if o.forcedDecisionService == nil {
return ""
}
return o.forcedDecisionService.GetForcedDecision(flagKey, ruleKey)
}

// RemoveForcedDecision removes the forced decision for a given flag and an optional rule.
func (o *OptimizelyUserContext) RemoveForcedDecision(flagKey, ruleKey string) bool {
if _, err := o.optimizely.getProjectConfig(); err != nil {
o.optimizely.logger.Error("Optimizely instance is not valid, failing removeForcedDecision call.", err)
return false
}
if o.forcedDecisionService == nil {
return false
}
return o.forcedDecisionService.RemoveForcedDecision(flagKey, ruleKey)
}

// RemoveAllForcedDecisions removes all forced decisions bound to this user context.
func (o *OptimizelyUserContext) RemoveAllForcedDecisions() bool {
if _, err := o.optimizely.getProjectConfig(); err != nil {
o.optimizely.logger.Error("Optimizely instance is not valid, failing removeForcedDecision call.", err)
return false
}
if o.forcedDecisionService == nil {
return true
}
return o.forcedDecisionService.RemoveAllForcedDecisions()
}

func copyUserAttributes(attributes map[string]interface{}) (attributesCopy map[string]interface{}) {
if attributes != nil {
attributesCopy = make(map[string]interface{})
Expand Down
Loading