-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinstance.go
More file actions
680 lines (573 loc) · 17.2 KB
/
instance.go
File metadata and controls
680 lines (573 loc) · 17.2 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package featurevisor
import (
"encoding/json"
"fmt"
)
// OverrideOptions contains options for overriding evaluation
type OverrideOptions struct {
Sticky *StickyFeatures
DefaultVariationValue *VariationValue
DefaultVariableValue VariableValue
}
// Options contains options for creating an instance
type Options struct {
Datafile interface{} // DatafileContent | string
Context Context
LogLevel *LogLevel
Logger *Logger
Sticky *StickyFeatures
Hooks []*Hook
}
// Featurevisor represents a Featurevisor SDK instance
type Featurevisor struct {
// from options
context Context
logger *Logger
sticky *StickyFeatures
// internally created
datafileReader *DatafileReader
hooksManager *HooksManager
emitter *Emitter
}
// NewFeaturevisor creates a new Featurevisor instance
func NewFeaturevisor(options Options) *Featurevisor {
// Set default context
context := Context{}
if options.Context != nil {
context = options.Context
}
// Set default logger
var logger *Logger
if options.Logger != nil {
logger = options.Logger
} else {
level := LogLevelInfo
if options.LogLevel != nil {
level = *options.LogLevel
}
logger = NewLogger(CreateLoggerOptions{Level: &level})
}
// Create hooks manager
hooksManager := NewHooksManager(HooksManagerOptions{
Logger: logger,
Hooks: options.Hooks,
})
// Create emitter
emitter := NewEmitter()
// Create datafile reader
emptyDatafile := DatafileContent{
SchemaVersion: "2",
Revision: "unknown",
Segments: make(map[SegmentKey]Segment),
Features: make(map[FeatureKey]Feature),
}
datafileReader := NewDatafileReader(DatafileReaderOptions{
Datafile: emptyDatafile,
Logger: logger,
})
// If datafile is provided, set it
if options.Datafile != nil {
datafileContent, err := parseDatafileInput(options.Datafile)
if err != nil {
logger.Error("could not parse datafile", LogDetails{"error": err})
} else {
datafileReader = NewDatafileReader(DatafileReaderOptions{
Datafile: datafileContent,
Logger: logger,
})
}
}
instance := &Featurevisor{
context: context,
logger: logger,
hooksManager: hooksManager,
emitter: emitter,
datafileReader: datafileReader,
sticky: options.Sticky,
}
logger.Info("Featurevisor SDK initialized", LogDetails{})
return instance
}
// SetLogLevel sets the log level
func (i *Featurevisor) SetLogLevel(level LogLevel) {
i.logger.SetLevel(level)
}
// SetDatafile sets the datafile
func (i *Featurevisor) SetDatafile(datafile interface{}) {
datafileContent, err := parseDatafileInput(datafile)
if err != nil {
i.logger.Error("could not parse datafile", LogDetails{"error": err})
return
}
newDatafileReader := NewDatafileReader(DatafileReaderOptions{
Datafile: datafileContent,
Logger: i.logger,
})
details := getParamsForDatafileSetEvent(i.datafileReader, newDatafileReader)
i.datafileReader = newDatafileReader
i.logger.Info("datafile set", details)
i.emitter.Trigger(EventNameDatafileSet, EventDetails(details))
}
// SetSticky sets sticky features
func (i *Featurevisor) SetSticky(sticky StickyFeatures, replace ...bool) {
replaceValue := false
if len(replace) > 0 {
replaceValue = replace[0]
}
previousStickyFeatures := StickyFeatures{}
if i.sticky != nil {
previousStickyFeatures = *i.sticky
}
if replaceValue {
i.sticky = &sticky
} else {
newSticky := StickyFeatures{}
if i.sticky != nil {
newSticky = *i.sticky
}
// Merge sticky features
for key, value := range sticky {
newSticky[key] = value
}
i.sticky = &newSticky
}
params := getParamsForStickySetEvent(previousStickyFeatures, *i.sticky, replaceValue)
i.logger.Info("sticky features set", params)
i.emitter.Trigger(EventNameStickySet, EventDetails(params))
}
// GetRevision returns the revision
func (i *Featurevisor) GetRevision() string {
return i.datafileReader.GetRevision()
}
// GetFeature returns a feature by key
func (i *Featurevisor) GetFeature(featureKey string) *Feature {
return i.datafileReader.GetFeature(FeatureKey(featureKey))
}
// AddHook adds a hook
func (i *Featurevisor) AddHook(hook *Hook) func() {
return i.hooksManager.Add(hook)
}
// On adds an event listener
func (i *Featurevisor) On(eventName EventName, callback EventCallback) Unsubscribe {
return i.emitter.On(eventName, callback)
}
// Close closes the instance
func (i *Featurevisor) Close() {
i.emitter.ClearAll()
}
// SetContext sets the context
func (i *Featurevisor) SetContext(context Context, replace ...bool) {
replaceValue := false
if len(replace) > 0 {
replaceValue = replace[0]
}
if replaceValue {
i.context = context
} else {
// Merge context
for key, value := range context {
i.context[key] = value
}
}
i.emitter.Trigger("context_set", map[string]interface{}{
"context": i.context,
"replaced": replaceValue,
})
if replaceValue {
i.logger.Debug("context replaced", LogDetails{"context": i.context})
} else {
i.logger.Debug("context updated", LogDetails{"context": i.context})
}
}
// GetContext returns the context
func (i *Featurevisor) GetContext(context Context) Context {
if context == nil {
return i.context
}
// Merge contexts
result := Context{}
for key, value := range i.context {
result[key] = value
}
for key, value := range context {
result[key] = value
}
return result
}
// Spawn creates a child instance
func (i *Featurevisor) Spawn(args ...interface{}) *FeaturevisorChild {
// Default values
contextValue := Context{}
optionsValue := OverrideOptions{}
// Parse variadic arguments
for _, arg := range args {
switch v := arg.(type) {
case Context:
contextValue = v
case OverrideOptions:
optionsValue = v
}
}
return NewFeaturevisorChild(ChildOptions{
Parent: i,
Context: i.GetContext(contextValue),
Sticky: optionsValue.Sticky,
})
}
// getEvaluationDependencies gets evaluation dependencies
func (i *Featurevisor) getEvaluationDependencies(context Context, options OverrideOptions) EvaluateDependencies {
var sticky *StickyFeatures
if options.Sticky != nil {
if i.sticky != nil {
// Merge sticky features
mergedSticky := StickyFeatures{}
for key, value := range *i.sticky {
mergedSticky[key] = value
}
for key, value := range *options.Sticky {
mergedSticky[key] = value
}
sticky = &mergedSticky
} else {
sticky = options.Sticky
}
} else {
sticky = i.sticky
}
return EvaluateDependencies{
Context: i.GetContext(context),
Logger: i.logger,
HooksManager: i.hooksManager,
DatafileReader: i.datafileReader,
Sticky: sticky,
DefaultVariationValue: options.DefaultVariationValue,
DefaultVariableValue: options.DefaultVariableValue,
}
}
// EvaluateFlag evaluates a feature flag
func (i *Featurevisor) EvaluateFlag(featureKey string, context Context, options OverrideOptions) Evaluation {
return EvaluateWithHooks(EvaluateOptions{
EvaluateParams: EvaluateParams{
Type: EvaluationTypeFlag,
FeatureKey: FeatureKey(featureKey),
},
EvaluateDependencies: i.getEvaluationDependencies(context, options),
})
}
// IsEnabled checks if a feature is enabled
func (i *Featurevisor) IsEnabled(featureKey string, args ...interface{}) bool {
defer func() {
if r := recover(); r != nil {
i.logger.Error("isEnabled", LogDetails{
"featureKey": featureKey,
"error": r,
})
}
}()
// Default values
contextValue := Context{}
optionsValue := OverrideOptions{}
// Parse variadic arguments
for _, arg := range args {
switch v := arg.(type) {
case Context:
contextValue = v
case OverrideOptions:
optionsValue = v
}
}
evaluation := i.EvaluateFlag(featureKey, contextValue, optionsValue)
if evaluation.Enabled != nil {
return *evaluation.Enabled
}
return false
}
// EvaluateVariation evaluates a feature variation
func (i *Featurevisor) EvaluateVariation(featureKey string, context Context, options OverrideOptions) Evaluation {
return EvaluateWithHooks(EvaluateOptions{
EvaluateParams: EvaluateParams{
Type: EvaluationTypeVariation,
FeatureKey: FeatureKey(featureKey),
},
EvaluateDependencies: i.getEvaluationDependencies(context, options),
})
}
// GetVariation gets a feature variation
func (i *Featurevisor) GetVariation(featureKey string, args ...interface{}) *string {
defer func() {
if r := recover(); r != nil {
i.logger.Error("getVariation", LogDetails{
"featureKey": featureKey,
"error": r,
})
}
}()
// Default values
contextValue := Context{}
optionsValue := OverrideOptions{}
// Parse variadic arguments
for _, arg := range args {
switch v := arg.(type) {
case Context:
contextValue = v
case OverrideOptions:
optionsValue = v
}
}
evaluation := i.EvaluateVariation(featureKey, contextValue, optionsValue)
if evaluation.VariationValue != nil {
// VariationValue is already a string type alias
variationValue := string(*evaluation.VariationValue)
return &variationValue
}
if evaluation.Variation != nil {
// Variation.Value is already a VariationValue (string)
variationValue := string(evaluation.Variation.Value)
return &variationValue
}
return nil
}
// EvaluateVariable evaluates a feature variable
func (i *Featurevisor) EvaluateVariable(featureKey string, variableKey VariableKey, context Context, options OverrideOptions) Evaluation {
return EvaluateWithHooks(EvaluateOptions{
EvaluateParams: EvaluateParams{
Type: EvaluationTypeVariable,
FeatureKey: FeatureKey(featureKey),
VariableKey: &variableKey,
},
EvaluateDependencies: i.getEvaluationDependencies(context, options),
})
}
// GetVariable gets a feature variable
func (i *Featurevisor) GetVariable(featureKey string, variableKey string, args ...interface{}) VariableValue {
defer func() {
if r := recover(); r != nil {
i.logger.Error("getVariable", LogDetails{
"featureKey": featureKey,
"variableKey": variableKey,
"error": r,
})
}
}()
// Default values
contextValue := Context{}
optionsValue := OverrideOptions{}
// Parse variadic arguments
for _, arg := range args {
switch v := arg.(type) {
case Context:
contextValue = v
case OverrideOptions:
optionsValue = v
}
}
evaluation := i.EvaluateVariable(featureKey, VariableKey(variableKey), contextValue, optionsValue)
if evaluation.VariableValue != nil {
// Handle JSON variables
if evaluation.VariableSchema != nil && evaluation.VariableSchema.Type == "json" {
if variableStr, ok := evaluation.VariableValue.(string); ok {
var parsedJSON interface{}
if err := json.Unmarshal([]byte(variableStr), &parsedJSON); err == nil {
return parsedJSON
} else {
// Log error if JSON parsing fails
i.logger.Error("could not parse JSON variable", LogDetails{
"featureKey": featureKey,
"variableKey": variableKey,
"error": err,
})
}
}
}
// Apply type conversion for default values
if evaluation.VariableSchema != nil && evaluation.Reason == EvaluationReasonVariableDefault {
return GetValueByType(evaluation.VariableValue, string(evaluation.VariableSchema.Type))
}
return evaluation.VariableValue
}
return nil
}
// GetVariableBoolean gets a boolean variable
func (i *Featurevisor) GetVariableBoolean(featureKey string, variableKey string, args ...interface{}) *bool {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
typedValue := GetValueByType(value, "boolean")
if boolValue, ok := typedValue.(bool); ok {
return &boolValue
}
return nil
}
// GetVariableString gets a string variable
func (i *Featurevisor) GetVariableString(featureKey string, variableKey string, args ...interface{}) *string {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
typedValue := GetValueByType(value, "string")
if stringValue, ok := typedValue.(string); ok {
return &stringValue
}
return nil
}
// GetVariableInteger gets an integer variable
func (i *Featurevisor) GetVariableInteger(featureKey string, variableKey string, args ...interface{}) *int {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
typedValue := GetValueByType(value, "integer")
if intValue, ok := typedValue.(int); ok {
return &intValue
}
return nil
}
// GetVariableDouble gets a double variable
func (i *Featurevisor) GetVariableDouble(featureKey string, variableKey string, args ...interface{}) *float64 {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
typedValue := GetValueByType(value, "double")
if floatValue, ok := typedValue.(float64); ok {
return &floatValue
}
return nil
}
// GetVariableArray gets an array variable
func (i *Featurevisor) GetVariableArray(featureKey string, variableKey string, args ...interface{}) []string {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
return ToTypedArray[string](GetValueByType(value, "array"))
}
// GetVariableObject gets an object variable
func (i *Featurevisor) GetVariableObject(featureKey string, variableKey string, args ...interface{}) map[string]interface{} {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
typedValue := ToTypedObject[map[string]interface{}](GetValueByType(value, "object"))
if typedValue == nil {
return nil
}
return *typedValue
}
// GetVariableJSON gets a JSON variable
func (i *Featurevisor) GetVariableJSON(featureKey string, variableKey string, args ...interface{}) interface{} {
value := i.GetVariable(featureKey, variableKey, args...)
if value == nil {
return nil
}
// JSON variables are already parsed in GetVariable
return value
}
// GetVariableArrayInto decodes an array variable into the provided pointer output.
// Supported argument order (after featureKey, variableKey): out OR context, out OR context, options, out.
func (i *Featurevisor) GetVariableArrayInto(featureKey string, variableKey string, args ...interface{}) error {
context, options, out, err := parseVariableIntoArgs(args...)
if err != nil {
return err
}
value := i.GetVariable(featureKey, variableKey, context, options)
if value == nil {
return decodeInto(nil, out)
}
arrayValue := GetValueByType(value, "array")
if arrayValue == nil {
return fmt.Errorf("variable %q is not an array", variableKey)
}
return decodeInto(arrayValue, out)
}
// GetVariableObjectInto decodes an object variable into the provided pointer output.
// Supported argument order (after featureKey, variableKey): out OR context, out OR context, options, out.
func (i *Featurevisor) GetVariableObjectInto(featureKey string, variableKey string, args ...interface{}) error {
context, options, out, err := parseVariableIntoArgs(args...)
if err != nil {
return err
}
value := i.GetVariable(featureKey, variableKey, context, options)
if value == nil {
return decodeInto(nil, out)
}
objectValue := GetValueByType(value, "object")
if objectValue == nil {
return fmt.Errorf("variable %q is not an object", variableKey)
}
return decodeInto(objectValue, out)
}
// GetAllEvaluations gets all evaluations for features
func (i *Featurevisor) GetAllEvaluations(context Context, featureKeys []string, options OverrideOptions) EvaluatedFeatures {
result := EvaluatedFeatures{}
keys := featureKeys
if len(keys) == 0 {
// Get all feature keys
allKeys := i.datafileReader.GetFeatureKeys()
keys = make([]string, len(allKeys))
for j, key := range allKeys {
keys[j] = string(key)
}
}
for _, featureKey := range keys {
// isEnabled
evaluatedFeature := EvaluatedFeature{
Enabled: i.IsEnabled(featureKey, context, options),
}
// variation
if i.datafileReader.HasVariations(FeatureKey(featureKey)) {
variation := i.GetVariation(featureKey, context, options)
if variation != nil {
evaluatedFeature.Variation = variation
}
}
// variables
variableKeys := i.datafileReader.GetVariableKeys(FeatureKey(featureKey))
if len(variableKeys) > 0 {
evaluatedFeature.Variables = make(map[VariableKey]VariableValue)
for _, variableKey := range variableKeys {
evaluatedFeature.Variables[variableKey] = i.GetVariable(
featureKey,
string(variableKey),
context,
options,
)
}
}
result[FeatureKey(featureKey)] = evaluatedFeature
}
return result
}
// CreateInstance creates a new Featurevisor instance
func CreateInstance(options Options) *Featurevisor {
return NewFeaturevisor(options)
}
func parseDatafileInput(datafile interface{}) (DatafileContent, error) {
var datafileContent DatafileContent
switch value := datafile.(type) {
case string:
if err := datafileContent.FromJSON(value); err != nil {
return DatafileContent{}, fmt.Errorf("invalid datafile string: %w", err)
}
return datafileContent, nil
case map[string]interface{}:
bytes, err := json.Marshal(value)
if err != nil {
return DatafileContent{}, fmt.Errorf("failed to marshal datafile map: %w", err)
}
if err := datafileContent.FromJSON(string(bytes)); err != nil {
return DatafileContent{}, fmt.Errorf("invalid datafile map: %w", err)
}
return datafileContent, nil
case DatafileContent:
return value, nil
case *DatafileContent:
if value == nil {
return DatafileContent{}, fmt.Errorf("datafile pointer is nil")
}
return *value, nil
default:
return DatafileContent{}, fmt.Errorf("unsupported datafile input type: %T", datafile)
}
}