File size: 4,356 Bytes
fea99b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package featuregate

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"slices"
	"strings"

	lru "github.com/hashicorp/golang-lru/v2"
	"github.com/samber/lo"

	"github.com/openmeterio/openmeter/pkg/framework/commonhttp"
	"github.com/openmeterio/openmeter/pkg/framework/operation"
)

type Gate interface {
	EvaluateBool(namespace, flag string, defaultValue bool) (bool, error)
}

func NewNoop() Gate {
	return Noop{}
}

type Noop struct{}

func (n Noop) EvaluateBool(string, string, bool) (bool, error) {
	return true, nil
}

var _ fmt.Stringer = (*FeatureFlag)(nil)

type FeatureFlag string

func (f FeatureFlag) String() string {
	return string(f)
}

const (
	CtxKeyCredits FeatureFlag = "om_ff_credits_enabled"
)

func ContextResolver() contextResolver {
	return contextResolver{}
}

type contextResolver struct{}

func (r contextResolver) Credits(ctx context.Context) bool {
	value, found := ctx.Value(CtxKeyCredits).(bool)
	if !found {
		return true
	}
	return value
}

type Flags map[FeatureFlag]string

func (f *Flags) Keys() []FeatureFlag {
	return []FeatureFlag{CtxKeyCredits}
}

func (f *Flags) Validate() error {
	if f == nil || len(*f) == 0 {
		return errors.New("featuregate is enabled but missing flags setup")
	}
	keys := f.Keys()

	for k := range *f {
		if !slices.Contains(keys, k) {
			return fmt.Errorf("invalid key: %s", k)
		}
	}

	return nil
}

func (f *Flags) Credits() string {
	if f == nil {
		return ""
	}
	value, ok := (*f)[CtxKeyCredits]
	if !ok {
		return ""
	}
	return value
}

const defaultCacheSize = 1024

func NewFeatureGateChecker(gate Gate, flags Flags, flagOverrides map[FeatureFlag]bool) *FeatureGateChecker {
	checker := &FeatureGateChecker{
		Gate:          gate,
		Flags:         flags,
		FlagOverrides: flagOverrides,
	}
	cacheSize := defaultCacheSize

	var err error
	checker.store, err = lru.New[string, bool](cacheSize)
	if err != nil {
		return checker
	}

	return checker
}

type FeatureGateChecker struct {
	Gate  Gate
	Flags Flags
	// FlagOverrides is used to handle config level feature setups
	// ex. if a feature is disabled on config level, then we are not going to call the feature gate
	FlagOverrides map[FeatureFlag]bool

	store *lru.Cache[string, bool]
}

func (h *FeatureGateChecker) Validate() error {
	if h == nil || h.Gate == nil {
		return errors.New("feature gate is required")
	}

	return nil
}

func (h *FeatureGateChecker) Enabled(ns string, flag string) (bool, error) {
	if h == nil {
		return true, nil
	}
	if h.Gate == nil {
		return true, nil
	}
	if flag == "" {
		return true, nil
	}

	cacheKey := strings.Join([]string{flag, ns}, "_")

	flagResult, cached := h.getFromCache(cacheKey)
	if !cached {
		enabled, err := h.Gate.EvaluateBool(ns, flag, false)
		if err != nil {
			return false, err
		}
		h.addToCache(cacheKey, enabled)
		return enabled, nil
	}

	return flagResult, nil
}

// getFromCache supposed to make cache fault tolerant
// so if store is not initialized, we return cache false
func (h FeatureGateChecker) getFromCache(key string) (bool, bool) {
	if h.store == nil {
		return false, false
	}

	return h.store.Get(key)
}

// addToCache supposed to make cache fault tolerant
// so if store is not initialized, we do an early exit
func (h FeatureGateChecker) addToCache(key string, value bool) {
	if h.store == nil {
		return
	}

	h.store.Add(key, value)
}

func NewMiddleware[Request any, Response any](getNamespace func(ctx context.Context) (string, bool), checker *FeatureGateChecker) operation.Middleware[Request, Response] {
	return func(next operation.Operation[Request, Response]) operation.Operation[Request, Response] {
		return func(ctx context.Context, request Request) (Response, error) {
			ns, ok := getNamespace(ctx)
			if !ok {
				return lo.Empty[Response](), commonhttp.NewHTTPError(http.StatusInternalServerError, errors.New("internal server error"))
			}

			for _, contextFlagKey := range lo.Union(lo.Keys(checker.Flags), lo.Keys(checker.FlagOverrides)) {
				if !checker.FlagOverrides[contextFlagKey] {
					ctx = context.WithValue(ctx, contextFlagKey, false)
					continue
				}
				configFlagKey := checker.Flags[contextFlagKey]
				result, err := checker.Enabled(ns, configFlagKey)
				if err != nil {
					return lo.Empty[Response](), err
				}
				ctx = context.WithValue(ctx, contextFlagKey, result)
			}

			return next(ctx, request)
		}
	}
}