-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfeature_manager.go
More file actions
379 lines (327 loc) · 11.8 KB
/
feature_manager.go
File metadata and controls
379 lines (327 loc) · 11.8 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package featuremanagement
import (
"fmt"
"log"
"os"
)
func init() {
os.Setenv("MS_FEATURE_MANAGEMENT_GO_VERSION", moduleVersion)
}
// FeatureManager is responsible for evaluating feature flags and their variants.
// It is the main entry point for interacting with the feature management library.
type FeatureManager struct {
featureProvider FeatureFlagProvider
featureFilters map[string]FeatureFilter
}
// Options configures the behavior of the FeatureManager.
type Options struct {
// Filters is a list of custom feature filters that will be used during feature flag evaluation.
// Each filter must implement the FeatureFilter interface.
Filters []FeatureFilter
}
// EvaluationResult contains information about a feature flag evaluation
type EvaluationResult struct {
// Feature contains the evaluated feature flag
Feature *FeatureFlag
// Enabled indicates the final state of the feature after evaluation
Enabled bool
// TargetingID is the identifier used for consistent targeting
TargetingID string
// Variant is the selected variant (if any)
Variant *Variant
// VariantAssignmentReason explains why the variant was assigned
VariantAssignmentReason VariantAssignmentReason
}
// NewFeatureManager creates and initializes a new instance of the FeatureManager.
// This is the entry point for using feature management functionality.
//
// Parameters:
// - provider: A FeatureFlagProvider that supplies feature flag definitions
// from a source such as Azure App Configuration or a local JSON file
// - *options: Configuration options for the FeatureManager, including custom filters
// for conditional feature evaluation
//
// Returns:
// - *FeatureManager: A configured feature manager instance ready for use
// - error: An error if initialization fails
func NewFeatureManager(provider FeatureFlagProvider, options *Options) (*FeatureManager, error) {
if provider == nil {
return nil, fmt.Errorf("feature provider cannot be nil")
}
if options == nil {
options = &Options{}
}
filters := []FeatureFilter{
&TargetingFilter{},
&TimeWindowFilter{},
}
filters = append(filters, options.Filters...)
featureFilters := make(map[string]FeatureFilter)
for _, filter := range filters {
if filter != nil {
featureFilters[filter.Name()] = filter
}
}
return &FeatureManager{
featureProvider: provider,
featureFilters: featureFilters,
}, nil
}
// IsEnabled determines if a feature flag is enabled.
// This is the primary method used to check feature flag state in application code.
//
// Parameters:
// - featureName: The name of the feature to evaluate
//
// Returns:
// - bool: true if the feature is enabled, false otherwise
// - error: An error if the feature flag cannot be found or evaluated
func (fm *FeatureManager) IsEnabled(featureName string) (bool, error) {
// Get the feature flag
featureFlag, err := fm.featureProvider.GetFeatureFlag(featureName)
if err != nil {
return false, fmt.Errorf("failed to get feature flag %s: %w", featureName, err)
}
res, err := fm.evaluateFeature(featureFlag, nil)
if err != nil {
return false, fmt.Errorf("failed to evaluate feature %s: %w", featureName, err)
}
return res.Enabled, nil
}
// IsEnabledWithAppContext determines if a feature flag is enabled for the given context.
// This version allows passing application-specific context for conditional evaluation.
//
// Parameters:
// - featureName: The name of the feature to evaluate
// - appContext: An optional context object for contextual evaluation
//
// Returns:
// - bool: true if the feature is enabled, false otherwise
// - error: An error if the feature flag cannot be found or evaluated
func (fm *FeatureManager) IsEnabledWithAppContext(featureName string, appContext any) (bool, error) {
// Get the feature flag
featureFlag, err := fm.featureProvider.GetFeatureFlag(featureName)
if err != nil {
return false, fmt.Errorf("failed to get feature flag %s: %w", featureName, err)
}
res, err := fm.evaluateFeature(featureFlag, appContext)
if err != nil {
return false, fmt.Errorf("failed to evaluate feature %s: %w", featureName, err)
}
return res.Enabled, nil
}
// GetVariant returns the assigned variant for a feature flag.
// This method is used for implementing multivariate feature flags, A/B testing,
// or feature configurations that change based on the user base and user interactions.
//
// Parameters:
// - featureName: The name of the feature to evaluate
// - appContext: An optional context object for contextual evaluation
//
// Returns:
// - Variant: The assigned variant with its name and configuration value. If no variant is assigned, this will be nil.
// - error: An error if the feature flag cannot be found or evaluated
func (fm *FeatureManager) GetVariant(featureName string, appContext any) (*Variant, error) {
// Get the feature flag
featureFlag, err := fm.featureProvider.GetFeatureFlag(featureName)
if err != nil {
return nil, fmt.Errorf("failed to get feature flag %s: %w", featureName, err)
}
res, err := fm.evaluateFeature(featureFlag, appContext)
if err != nil {
return nil, fmt.Errorf("failed to evaluate feature %s: %w", featureName, err)
}
return res.Variant, nil
}
// GetFeatureNames returns the names of all available features.
//
// Returns:
// - []string: A slice containing the names of all available features
func (fm *FeatureManager) GetFeatureNames() []string {
flags, err := fm.featureProvider.GetFeatureFlags()
if err != nil {
log.Printf("failed to get feature flag names: %v", err)
return nil
}
res := make([]string, 0, len(flags))
for i, flag := range flags {
res[i] = flag.ID
}
return res
}
func (fm *FeatureManager) isEnabled(featureFlag FeatureFlag, appContext any) (bool, error) {
// If the feature is not explicitly enabled, then it is disabled by default
if !featureFlag.Enabled {
return false, nil
}
// If there are no client filters, then the feature is enabled
if featureFlag.Conditions == nil || len(featureFlag.Conditions.ClientFilters) == 0 {
return true, nil
}
// Default requirement type is "Any"
requirementType := RequirementTypeAny
if featureFlag.Conditions.RequirementType != "" {
requirementType = featureFlag.Conditions.RequirementType
}
// Short circuit based on requirement type
// - When "All", feature is enabled if all filters match (short circuit on false)
// - When "Any", feature is enabled if any filter matches (short circuit on true)
shortCircuitEvalResult := requirementType == RequirementTypeAny
// Evaluate filters
for _, clientFilter := range featureFlag.Conditions.ClientFilters {
matchedFeatureFilter, exists := fm.featureFilters[clientFilter.Name]
if !exists {
log.Printf("Feature filter %s is not found", clientFilter.Name)
if requirementType == RequirementTypeAny {
// When "Any", skip missing filters and continue evaluating the rest
continue
}
// When "All", a missing filter means the feature cannot be enabled
return false, nil
}
// Create context with feature name and parameters
filterContext := FeatureFilterEvaluationContext{
FeatureName: featureFlag.ID,
Parameters: clientFilter.Parameters,
}
// Evaluate the filter
filterResult, err := matchedFeatureFilter.Evaluate(filterContext, appContext)
if err != nil {
return false, fmt.Errorf("error evaluating filter %s: %w", clientFilter.Name, err)
}
// Short circuit if we hit the condition
if filterResult == shortCircuitEvalResult {
return shortCircuitEvalResult, nil
}
}
// If we get here, we haven't short-circuited, so return opposite result
return !shortCircuitEvalResult, nil
}
func (fm *FeatureManager) evaluateFeature(featureFlag FeatureFlag, appContext any) (EvaluationResult, error) {
result := EvaluationResult{
Feature: &featureFlag,
}
// Validate feature flag format
if err := validateFeatureFlag(featureFlag); err != nil {
return result, fmt.Errorf("invalid feature flag: %w", err)
}
// Evaluate if feature is enabled
enabled, err := fm.isEnabled(featureFlag, appContext)
if err != nil {
return result, err
}
result.Enabled = enabled
var targetingContext *TargetingContext
if appContext != nil {
if tc, ok := appContext.(TargetingContext); ok {
result.TargetingID = tc.UserID
targetingContext = &tc
} else if tc, ok := appContext.(*TargetingContext); ok {
result.TargetingID = tc.UserID
targetingContext = tc
}
}
// Determine variant
var variantDef *VariantDefinition
reason := VariantAssignmentReasonNone
// Process variants if present
if len(featureFlag.Variants) > 0 {
if !result.Enabled {
reason = VariantAssignmentReasonDefaultWhenDisabled
if featureFlag.Allocation != nil && featureFlag.Allocation.DefaultWhenDisabled != "" {
variantDef = getVariant(featureFlag.Variants, featureFlag.Allocation.DefaultWhenDisabled)
}
} else {
// Enabled, assign based on allocation
if targetingContext != nil && featureFlag.Allocation != nil {
if variantAssignment, err := assignVariant(featureFlag, *targetingContext); variantAssignment != nil && err == nil {
variantDef = variantAssignment.Variant
reason = variantAssignment.Reason
}
}
// Allocation failed, assign default if specified
if variantDef == nil && reason == VariantAssignmentReasonNone {
reason = VariantAssignmentReasonDefaultWhenEnabled
if featureFlag.Allocation != nil && featureFlag.Allocation.DefaultWhenEnabled != "" {
variantDef = getVariant(featureFlag.Variants, featureFlag.Allocation.DefaultWhenEnabled)
}
}
}
}
// Set variant in result
if variantDef != nil {
result.Variant = &Variant{
Name: variantDef.Name,
ConfigurationValue: variantDef.ConfigurationValue,
}
}
result.VariantAssignmentReason = reason
// Apply status override from variant
if variantDef != nil && featureFlag.Enabled {
if variantDef.StatusOverride == StatusOverrideEnabled {
result.Enabled = true
} else if variantDef.StatusOverride == StatusOverrideDisabled {
result.Enabled = false
}
}
return result, nil
}
func getVariant(variants []VariantDefinition, name string) *VariantDefinition {
for _, v := range variants {
if v.Name == name {
return &v
}
}
return nil
}
type variantAssignment struct {
Variant *VariantDefinition
Reason VariantAssignmentReason
}
func getVariantAssignment(featureFlag FeatureFlag, variantName string, reason VariantAssignmentReason) *variantAssignment {
if variantName == "" {
return nil
}
variant := getVariant(featureFlag.Variants, variantName)
if variant == nil {
log.Printf("Variant %s not found in feature %s", variantName, featureFlag.ID)
return nil
}
return &variantAssignment{
Variant: variant,
Reason: reason,
}
}
func assignVariant(featureFlag FeatureFlag, targetingContext TargetingContext) (*variantAssignment, error) {
if len(featureFlag.Allocation.User) > 0 {
for _, userAlloc := range featureFlag.Allocation.User {
if isTargetedUser(targetingContext.UserID, userAlloc.Users) {
return getVariantAssignment(featureFlag, userAlloc.Variant, VariantAssignmentReasonUser), nil
}
}
}
if len(featureFlag.Allocation.Group) > 0 {
for _, groupAlloc := range featureFlag.Allocation.Group {
if isTargetedGroup(targetingContext.Groups, groupAlloc.Groups) {
return getVariantAssignment(featureFlag, groupAlloc.Variant, VariantAssignmentReasonGroup), nil
}
}
}
if len(featureFlag.Allocation.Percentile) > 0 {
for _, percentAlloc := range featureFlag.Allocation.Percentile {
hint := featureFlag.Allocation.Seed
if hint == "" {
hint = fmt.Sprintf("allocation\n%s", featureFlag.ID)
}
if ok, _ := isTargetedPercentile(targetingContext.UserID, hint, percentAlloc.From, percentAlloc.To); ok {
return getVariantAssignment(featureFlag, percentAlloc.Variant, VariantAssignmentReasonPercentile), nil
}
}
}
return &variantAssignment{
Variant: nil,
Reason: VariantAssignmentReasonNone,
}, nil
}