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: v2 evaluate boolean #1806

Merged
merged 13 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
3 changes: 3 additions & 0 deletions internal/cmd/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"go.flipt.io/flipt/internal/server/cache"
"go.flipt.io/flipt/internal/server/cache/memory"
"go.flipt.io/flipt/internal/server/cache/redis"
evaluation "go.flipt.io/flipt/internal/server/evaluation"
"go.flipt.io/flipt/internal/server/metadata"
middlewaregrpc "go.flipt.io/flipt/internal/server/middleware/grpc"
"go.flipt.io/flipt/internal/storage"
Expand Down Expand Up @@ -343,6 +344,8 @@ func NewGRPCServer(
register.Add(fliptserver.New(logger, store))
register.Add(metadata.NewServer(cfg, info))

register.Add(evaluation.New(logger, store))

// initialize grpc server
server.Server = grpc.NewServer(grpcOpts...)

Expand Down
13 changes: 10 additions & 3 deletions internal/cmd/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"go.flipt.io/flipt/internal/gateway"
"go.flipt.io/flipt/internal/info"
"go.flipt.io/flipt/rpc/flipt"
"go.flipt.io/flipt/rpc/flipt/evaluation"
"go.flipt.io/flipt/rpc/flipt/meta"
"go.flipt.io/flipt/ui"
"go.uber.org/zap"
Expand Down Expand Up @@ -54,9 +55,10 @@ func NewHTTPServer(
}
isConsole = cfg.Log.Encoding == config.LogEncodingConsole

r = chi.NewRouter()
api = gateway.NewGatewayServeMux(logger)
httpPort = cfg.Server.HTTPPort
r = chi.NewRouter()
api = gateway.NewGatewayServeMux(logger)
evaluateAPI = gateway.NewGatewayServeMux(logger)
httpPort = cfg.Server.HTTPPort
)

if cfg.Server.Protocol == config.HTTPS {
Expand All @@ -67,6 +69,10 @@ func NewHTTPServer(
return nil, fmt.Errorf("registering grpc gateway: %w", err)
}

if err := evaluation.RegisterEvaluationServiceHandler(ctx, evaluateAPI, conn); err != nil {
return nil, fmt.Errorf("registering grpc gateway: %w", err)
}

if cfg.Cors.Enabled {
cors := cors.New(cors.Options{
AllowedOrigins: cfg.Cors.AllowedOrigins,
Expand Down Expand Up @@ -128,6 +134,7 @@ func NewHTTPServer(
}

r.Mount("/api/v1", api)
r.Mount("/evaluate/v1", evaluateAPI)

// mount all authentication related HTTP components
// to the chi router.
Expand Down
166 changes: 166 additions & 0 deletions internal/server/evaluation/evaluation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package evaluation

import (
"context"
"errors"
"hash/crc32"

errs "go.flipt.io/flipt/errors"
fliptotel "go.flipt.io/flipt/internal/server/otel"
"go.flipt.io/flipt/internal/storage"
"go.flipt.io/flipt/rpc/flipt"
rpcEvaluation "go.flipt.io/flipt/rpc/flipt/evaluation"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
)

// Variant evaluates a request for a multi-variate flag and entity.
func (s *Server) Variant(ctx context.Context, v *rpcEvaluation.EvaluationRequest) (*rpcEvaluation.VariantEvaluationResponse, error) {
var ver = &rpcEvaluation.VariantEvaluationResponse{}

s.logger.Debug("variant", zap.Stringer("request", v))
if v.NamespaceKey == "" {
v.NamespaceKey = storage.DefaultNamespace
}

flag, err := s.store.GetFlag(ctx, v.NamespaceKey, v.FlagKey)
if err != nil {
var errnf errs.ErrNotFound

if errors.As(err, &errnf) {
ver.Reason = rpcEvaluation.EvaluationReason_FLAG_NOT_FOUND_EVALUATION_REASON
return ver, err
}

ver.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return ver, err
}

if flag.Type != flipt.FlagType_VARIANT_FLAG_TYPE {
ver.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return ver, err
}
yquansah marked this conversation as resolved.
Show resolved Hide resolved

resp, err := s.evaluator.Evaluate(ctx, &flipt.EvaluationRequest{
RequestId: v.RequestId,
FlagKey: v.FlagKey,
EntityId: v.EntityId,
Context: v.Context,
NamespaceKey: v.NamespaceKey,
})
if err != nil {
ver.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return ver, err
}

spanAttrs := []attribute.KeyValue{
fliptotel.AttributeNamespace.String(v.NamespaceKey),
fliptotel.AttributeFlag.String(v.FlagKey),
fliptotel.AttributeEntityID.String(v.EntityId),
fliptotel.AttributeRequestID.String(v.RequestId),
}

if resp != nil {
spanAttrs = append(spanAttrs,
fliptotel.AttributeMatch.Bool(resp.Match),
fliptotel.AttributeValue.String(resp.Value),
fliptotel.AttributeReason.String(resp.Reason.String()),
fliptotel.AttributeSegment.String(resp.SegmentKey),
)
}

ver.Match = resp.Match
ver.SegmentKey = resp.SegmentKey
ver.Reason = rpcEvaluation.EvaluationReason(resp.Reason)
ver.VariantKey = resp.Value
ver.VariantAttachment = resp.Attachment

// add otel attributes to span
span := trace.SpanFromContext(ctx)
span.SetAttributes(spanAttrs...)

s.logger.Debug("variant", zap.Stringer("response", resp))
return ver, nil
}

// Boolean evaluates a request for a boolean flag and entity.
func (s *Server) Boolean(ctx context.Context, r *rpcEvaluation.EvaluationRequest) (*rpcEvaluation.BooleanEvaluationResponse, error) {
resp := &rpcEvaluation.BooleanEvaluationResponse{}

flag, err := s.store.GetFlag(ctx, r.NamespaceKey, r.FlagKey)
if err != nil {
var errnf errs.ErrNotFound

if errors.As(err, &errnf) {
resp.Reason = rpcEvaluation.EvaluationReason_FLAG_NOT_FOUND_EVALUATION_REASON
return resp, err
}

resp.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return resp, err
}

if flag.Type != flipt.FlagType_BOOLEAN_FLAG_TYPE {
resp.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return resp, errs.ErrInvalidf("flag type %s invalid", flipt.FlagType_name[int32(flag.Type)])
}

rollouts, err := s.store.GetEvaluationRollouts(ctx, r.NamespaceKey, r.FlagKey)
if err != nil {
resp.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return resp, err
}

var lastRank int32

for _, rollout := range rollouts {
if rollout.Rank < lastRank {
resp.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return resp, errs.ErrInvalidf("rollout rank: %d detected out of order", rollout.Rank)
}

lastRank = rollout.Rank

if rollout.Percentage != nil {
// consistent hashing based on the entity id and flag key.
hash := crc32.ChecksumIEEE([]byte(r.EntityId + r.FlagKey))

normalizedValue := float32(int(hash) % 100)

// if this case does not hold, fall through to the next rollout.
if normalizedValue < rollout.Percentage.Percentage {
resp.Value = rollout.Percentage.Value
resp.Reason = rpcEvaluation.EvaluationReason_MATCH_EVALUATION_REASON
s.logger.Debug("percentage based matched", zap.Int("rank", int(rollout.Rank)), zap.String("rollout_type", "percentage"))

return resp, nil
}
} else if rollout.Segment != nil {
matched, err := s.evaluator.matchConstraints(r.Context, rollout.Segment.Constraints, rollout.Segment.SegmentMatchType)
if err != nil {
resp.Reason = rpcEvaluation.EvaluationReason_ERROR_EVALUATION_REASON
return resp, err
}

// if we don't match the segment, fall through to the next rollout.
if !matched {
continue
}

resp.Value = rollout.Segment.Value
resp.Reason = rpcEvaluation.EvaluationReason_MATCH_EVALUATION_REASON

s.logger.Debug("segment based matched", zap.Int("rank", int(rollout.Rank)), zap.String("segment", rollout.Segment.SegmentKey))

return resp, nil
}
}

// If we have exhausted all rollouts and we still don't have a match, return the default value.
resp.Reason = rpcEvaluation.EvaluationReason_DEFAULT_EVALUATION_REASON
resp.Value = flag.Enabled
s.logger.Debug("default rollout matched", zap.Bool("value", flag.Enabled))

return resp, nil
}
yquansah marked this conversation as resolved.
Show resolved Hide resolved
39 changes: 39 additions & 0 deletions internal/server/evaluation/evaluation_store_mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package evaluation

import (
"context"

"github.com/stretchr/testify/mock"
"go.flipt.io/flipt/internal/storage"
flipt "go.flipt.io/flipt/rpc/flipt"
)

var _ Storer = &evaluationStoreMock{}

type evaluationStoreMock struct {
mock.Mock
}

func (e *evaluationStoreMock) String() string {
return "mock"
}

func (e *evaluationStoreMock) GetFlag(ctx context.Context, namespaceKey, key string) (*flipt.Flag, error) {
args := e.Called(ctx, namespaceKey, key)
return args.Get(0).(*flipt.Flag), args.Error(1)
}

func (e *evaluationStoreMock) GetEvaluationRules(ctx context.Context, namespaceKey string, flagKey string) ([]*storage.EvaluationRule, error) {
args := e.Called(ctx, namespaceKey, flagKey)
return args.Get(0).([]*storage.EvaluationRule), args.Error(1)
}

func (e *evaluationStoreMock) GetEvaluationDistributions(ctx context.Context, ruleID string) ([]*storage.EvaluationDistribution, error) {
args := e.Called(ctx, ruleID)
return args.Get(0).([]*storage.EvaluationDistribution), args.Error(1)
}

func (e *evaluationStoreMock) GetEvaluationRollouts(ctx context.Context, namespaceKey, flagKey string) ([]*storage.EvaluationRollout, error) {
args := e.Called(ctx, namespaceKey, flagKey)
return args.Get(0).([]*storage.EvaluationRollout), args.Error(1)
}
Loading