Repository navigation
Expand file tree
/
Copy pathfeatureflags.go
More file actions
3606 lines (3253 loc) · 126 KB
/
Copy pathfeatureflags.go
File metadata and controls
3606 lines (3253 loc) · 126 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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package posthog
import (
"bytes"
"context"
"crypto/sha1"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"reflect"
"regexp"
"regexp/syntax"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
json "github.com/goccy/go-json"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
// LONG_SCALE is the denominator used to normalize feature flag hash values.
LONG_SCALE = 0xfffffffffffffff
bucketingIdentifierDevice = "device_id"
)
var relativeDateRegex = regexp.MustCompile(`^-?([0-9]+)([hdwmy])$`)
// Common sentinel errors for matchProperty — reused to avoid allocating new
// InconclusiveMatchError structs on every evaluation of flags with missing properties.
var (
errMissingPropertyValue = &InconclusiveMatchError{msg: "Can't match properties without a given property value", Reason: UnresolvedFlagReasonMissingContext}
errInconclusiveMatch = newInconclusiveSentinels("Can't determine if feature flag is enabled or not with given properties")
errAmbiguousExactNumber = &InconclusiveMatchError{msg: "Can't match an integral JSON number locally because Go does not preserve whether it was an integer or float", Reason: UnresolvedFlagReasonUnsupportedDefinition}
errCohortPropertyValue = newInconclusiveSentinels("Can't match cohort without a given cohort property value")
errHoldoutMissingDeviceID = newInconclusiveSentinels("Can't evaluate a device-bucketed holdout without a device id")
errCohortRequiresServerEval = &RequiresServerEvaluationError{msg: "cohort not found in local cohorts - likely a static cohort that requires server evaluation", Reason: UnresolvedFlagReasonUnsupportedDefinition}
)
// regexCache caches compiled regexps for flag property matching.
// The set of patterns is bounded by the number of flag conditions (loaded once),
// so this cache grows proportionally and avoids re-compiling on every evaluation.
var regexCache sync.Map // map[string]*flagRegex
// A later matching condition cannot decide the variant while an earlier regex is unresolved.
var errRegexRequiresServer = &RequiresServerEvaluationError{msg: "Regex requires server evaluation", Reason: UnresolvedFlagReasonUnsupportedDefinition}
var errDependencyAggregationRequiresServer = &RequiresServerEvaluationError{msg: "Flag dependency requires different aggregation context", Reason: UnresolvedFlagReasonUnsupportedDefinition}
type flagRegex struct {
*regexp.Regexp
asciiClasses bool
}
// getOrCompileRegex caches only patterns whose syntax has shared service semantics.
func getOrCompileRegex(pattern string) (*flagRegex, error) {
if cached, ok := regexCache.Load(pattern); ok {
return cached.(*flagRegex), nil
}
asciiClasses, err := classifyFlagRegex(pattern)
if err != nil {
return nil, err
}
parsed, err := syntax.Parse(pattern, syntax.Perl)
if err != nil {
// These errors describe invalid shared syntax, not an RE2 capability limit.
syntaxErr := err.(*syntax.Error)
if syntaxErr.Code == syntax.ErrMissingRepeatArgument && strings.HasPrefix(syntaxErr.Expr, "{") {
return nil, errRegexRequiresServer
}
switch syntaxErr.Code {
case syntax.ErrInvalidRepeatSize:
minimum, maximum, bounded := strings.Cut(syntaxErr.Expr[1:len(syntaxErr.Expr)-1], ",")
if bounded {
min, minErr := strconv.ParseUint(minimum, 10, 32)
max, maxErr := strconv.ParseUint(maximum, 10, 32)
if minErr == nil && maxErr == nil && min > max {
return nil, err
}
}
// RE2 also uses this error for its smaller repetition-size limit.
return nil, errRegexRequiresServer
case syntax.ErrMissingBracket, syntax.ErrMissingParen, syntax.ErrUnexpectedParen,
syntax.ErrMissingRepeatArgument, syntax.ErrInvalidCharRange, syntax.ErrTrailingBackslash:
return nil, err
default:
return nil, errRegexRequiresServer
}
}
if hasRepeatedRegexAssertion(parsed) {
return nil, errRegexRequiresServer
}
r, err := regexp.Compile(pattern)
if err != nil {
return nil, errRegexRequiresServer
}
compiled := &flagRegex{Regexp: r, asciiClasses: asciiClasses}
// Concurrent stores of the same pattern are harmless.
regexCache.Store(pattern, compiled)
return compiled, nil
}
// RE2 shorthands are ASCII-only; Rust's are Unicode-aware (and include vertical tab).
// Nested sets and set operations can compile in RE2 with a different interpretation.
func classifyFlagRegex(pattern string) (asciiClasses bool, err error) {
inClass := false
classStart := 0
classHyphen := false
for i := 0; i < len(pattern); i++ {
previousClassHyphen := classHyphen
classHyphen = false
switch pattern[i] {
case '\\':
i++
if i == len(pattern) {
break
}
switch pattern[i] {
case 'd', 'D', 's', 'S', 'w', 'W':
if inClass && (previousClassHyphen || i+2 < len(pattern) && pattern[i+1] == '-' && pattern[i+2] != ']') {
return false, errRegexRequiresServer
}
asciiClasses = true
case '<', '>', 'b', 'B':
// Outside classes, even ASCII boundaries can exhaust the service's
// backtracking budget. Inside classes, RE2 lacks Rust's backspace.
return false, errRegexRequiresServer
case 'x':
if i+1 < len(pattern) && pattern[i+1] == '{' {
end := strings.IndexByte(pattern[i+2:], '}')
if end < 0 {
return asciiClasses, nil // Let the compiler categorize the malformed escape once.
}
i += end + 2
}
case 'p', 'P':
if i+1 < len(pattern) {
if pattern[i+1] == '{' {
end := strings.IndexByte(pattern[i+2:], '}')
if end < 0 {
return asciiClasses, nil
}
i += end + 2
} else {
i++
}
}
if inClass && (previousClassHyphen || i+2 < len(pattern) && pattern[i+1] == '-' && pattern[i+2] != ']') {
return false, errRegexRequiresServer
}
case 'A', 'z', 'a', 'f', 'n', 'r', 't', 'v':
default:
c := pattern[i]
if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
if c == 'q' { // Invalid in both engines.
return false, &syntax.Error{Code: syntax.ErrInvalidEscape, Expr: `\q`}
}
return false, errRegexRequiresServer
}
}
case '[':
if inClass {
if strings.HasPrefix(pattern[i:], "[:") {
if end := strings.Index(pattern[i+2:], ":]"); end >= 0 {
i += end + 3
if previousClassHyphen || i+2 < len(pattern) && pattern[i+1] == '-' && pattern[i+2] != ']' {
return false, errRegexRequiresServer
}
continue
}
}
return false, errRegexRequiresServer
}
inClass = true
classStart = i
case ']':
if inClass && (i == classStart+1 || i == classStart+2 && pattern[classStart+1] == '^') {
continue // A leading ] is a literal class member in both engines.
}
inClass = false
case '&', '-', '~':
if inClass && i+1 < len(pattern) && pattern[i+1] == pattern[i] {
return false, errRegexRequiresServer
}
classHyphen = inClass && pattern[i] == '-' && i > classStart+1 && !(i == classStart+2 && pattern[classStart+1] == '^')
case '{':
if !inClass {
end := i + 1
for end < len(pattern) && pattern[end] >= '0' && pattern[end] <= '9' {
end++
}
if end == i+1 || end-i > 2 && pattern[i+1] == '0' {
return false, errRegexRequiresServer
}
if end < len(pattern) && pattern[end] == ',' {
start := end + 1
end = start
for end < len(pattern) && pattern[end] >= '0' && pattern[end] <= '9' {
end++
}
if end-start > 1 && pattern[start] == '0' {
return false, errRegexRequiresServer
}
}
if end == len(pattern) || pattern[end] != '}' {
return false, errRegexRequiresServer
}
// Consume only digits and the optional comma, never search/split the suffix.
i = end - 1
}
}
}
return asciiClasses, nil
}
func regexAssertionOnly(r *syntax.Regexp) bool {
switch r.Op {
case syntax.OpEmptyMatch, syntax.OpBeginLine, syntax.OpEndLine, syntax.OpBeginText, syntax.OpEndText,
syntax.OpWordBoundary, syntax.OpNoWordBoundary:
return true
case syntax.OpCapture, syntax.OpConcat, syntax.OpAlternate:
for _, sub := range r.Sub {
if !regexAssertionOnly(sub) {
return false
}
}
return true
}
return false
}
func hasRepeatedRegexAssertion(r *syntax.Regexp) bool {
switch r.Op {
case syntax.OpStar, syntax.OpPlus, syntax.OpQuest, syntax.OpRepeat:
if regexAssertionOnly(r.Sub[0]) {
return true
}
}
for _, sub := range r.Sub {
if hasRepeatedRegexAssertion(sub) {
return true
}
}
return false
}
// flagsState holds the feature flag data that is atomically swapped during updates.
// This provides lock-free reads for the common path (flag evaluation).
type flagsState struct {
featureFlags []FeatureFlag
flagsByKey map[string]FeatureFlag // pre-built index for O(1) lookup, avoids rebuilding per evaluation
cohorts map[string]PropertyGroup
groups map[string]string
flagsEtag string
propertyMatchingVersion int
// minimalFlagCalledEvents is the server-controlled gate for minimal
// $feature_flag_called events, cached from the local-evaluation payload.
minimalFlagCalledEvents bool
// definitions is the payload these fields were decoded from, republished to the
// cache provider on 304 responses.
definitions json.RawMessage
}
// FeatureFlagsPoller periodically loads feature flag definitions for local evaluation.
// Applications normally interact with it through Client methods rather than constructing it directly.
type FeatureFlagsPoller struct {
// firstFeatureFlagRequestFinished is used to log feature flag usage before the first feature flag request is done.
// After the request the channel get closed.
firstFeatureFlagRequestFinished chan bool
shutdown chan bool
shutdownDone chan bool
forceReload chan reloadRequest
// ctx covers polling work; cancel aborts it when shutdown outlives its deadline.
ctx context.Context
cancel context.CancelFunc
// shutdownCtx is the context handed to the cache provider's Shutdown. Written
// before shutdown is closed, read by the polling goroutine after it observes that.
shutdownCtx context.Context
// state holds all flag-related data using atomic pointer for lock-free reads
state atomic.Pointer[flagsState]
personalApiKey string
projectApiKey string
localEvalUrl *url.URL
// Logger receives poller warnings and errors.
Logger Logger
// Endpoint is the PostHog API host used by the poller.
Endpoint string
http http.Client
nextPollTick func() time.Duration
flagTimeout time.Duration
decider decider
disableGeoIP bool
cacheProvider FlagDefinitionCacheProvider
// warnedUnresolvableFlags maps each flag key already warned about as never locally
// resolvable to the definition it was warned about at.
warnedUnresolvableMu sync.Mutex
warnedUnresolvableFlags map[string]unresolvableFlagFingerprint
}
type unresolvableFlagFingerprint struct {
reason UnresolvedFlagReason
definition [sha1.Size]byte
}
// FeatureFlag is a feature flag definition returned by the local evaluation endpoint.
type FeatureFlag struct {
// Key is the feature flag key.
Key string `json:"key"`
// EvaluationRuntime is the flag's configured runtime, or nil when unknown.
EvaluationRuntime *string `json:"evaluation_runtime"`
// RolloutPercentage is the top-level rollout percentage, when configured.
RolloutPercentage *float64 `json:"rollout_percentage"`
// Active reports whether the flag is active.
Active bool `json:"active"`
// Filters contains matching conditions, variants, and payloads.
Filters Filter `json:"filters"`
// EnsureExperienceContinuity indicates that the flag requires server-side continuity checks.
EnsureExperienceContinuity *bool `json:"ensure_experience_continuity"`
// BucketingIdentifier optionally selects the property used for hash bucketing.
BucketingIdentifier *string `json:"bucketing_identifier"`
// HasExperiment reports whether the flag is linked to an experiment.
// Nil when the server does not send it (older deployments).
HasExperiment *bool `json:"has_experiment"`
}
// Filter contains the targeting rules, variants, and payloads for a FeatureFlag.
type Filter struct {
// AggregationGroupTypeIndex identifies the group type for group-targeted flags.
AggregationGroupTypeIndex *uint8 `json:"aggregation_group_type_index"`
// Groups contains the ordered condition groups to evaluate.
Groups []FeatureFlagCondition `json:"groups"`
// EarlyExit, when true, stops local condition evaluation and returns a
// definitive disabled result as soon as a condition group matches its
// property filters (or has none) but the rollout percentage excludes the
// user, instead of falling through to later condition groups.
EarlyExit bool `json:"early_exit"`
// Multivariate contains variant definitions for multivariate flags.
Multivariate *Variants `json:"multivariate"`
// Holdout contains the experiment holdout configuration, when the flag has one.
Holdout *Holdout `json:"holdout"`
// FeatureEnrollment marks an early-access feature flag. The person's opt-in, stored in
// the person property `$feature_enrollment/<flag key>`, decides the flag before
// holdouts and release conditions.
FeatureEnrollment bool `json:"feature_enrollment"`
// Payloads maps flag values or variant keys to raw JSON payloads.
Payloads map[string]json.RawMessage `json:"payloads"`
// DecodedPayloads holds pre-decoded string versions of Payloads.
// Built once at flag load time to avoid per-evaluation json.Unmarshal / unquoting.
DecodedPayloads map[string]string `json:"-"`
// VariantLookupTable is pre-computed at flag load time to avoid per-evaluation
// slice allocation for multivariate flags.
VariantLookupTable []FlagVariantMeta `json:"-"`
}
// Variants contains all variants configured for a multivariate feature flag.
type Variants struct {
// Variants is the ordered list of possible flag variants.
Variants []FlagVariant `json:"variants"`
}
// Holdout is the experiment holdout configuration attached to a feature flag.
// Identifiers inside the holdout are excluded from the flag's release conditions
// and resolve to the synthetic variant "holdout-<id>".
type Holdout struct {
// ID identifies the holdout. It is rendered into the synthetic variant key.
ID interface{} `json:"id"`
// ExclusionPercentage is the share of identifiers held out, from 0 to 100.
ExclusionPercentage *float64 `json:"exclusion_percentage"`
}
// FlagVariant describes one multivariate feature flag variant.
type FlagVariant struct {
// Key is the stable variant key returned by flag evaluation.
Key string `json:"key"`
// Name is the display name for the variant.
Name string `json:"name"`
// RolloutPercentage is the percentage allocated to this variant.
RolloutPercentage *float64 `json:"rollout_percentage"`
}
// FeatureFlagCondition describes one condition group for a feature flag.
type FeatureFlagCondition struct {
// Properties are the targeting rules in this condition group.
Properties []FlagProperty `json:"properties"`
// RolloutPercentage is the rollout percentage for this condition group.
RolloutPercentage *float64 `json:"rollout_percentage"`
// Variant is the variant key forced by this condition group, when any.
Variant *string `json:"variant"`
// AggregationGroupTypeIndex identifies the group type for this condition group.
AggregationGroupTypeIndex *uint8 `json:"aggregation_group_type_index"`
}
// FlagProperty describes one property matcher in a feature flag or cohort condition.
type FlagProperty struct {
// Key is the property key to read.
Key string `json:"key"`
// Operator is the comparison operator, such as exact, is_not, or regex.
Operator string `json:"operator"`
// Value is the comparison value for Operator.
Value interface{} `json:"value"`
// Type is the property source. Supported values include "person", "group", "cohort", and "flag".
Type string `json:"type"`
// Negation inverts the property match when true.
Negation bool `json:"negation"`
// DependencyChain tracks feature flag dependencies while evaluating nested flag properties.
DependencyChain []string `json:"dependency_chain"`
}
// PropertyGroup describes a nested property group used by cohorts and flag conditions.
type PropertyGroup struct {
// Type is the boolean operator joining Values, such as AND or OR.
Type string `json:"type"`
// Values contains nested PropertyGroup values or FlagProperty values.
Values []any `json:"values"`
// ParsedValues holds pre-parsed typed values from Values.
// Built once at flag load time to avoid reconstructing FlagProperty/PropertyGroup
// from map[string]any on every cohort evaluation.
ParsedValues []parsedPropertyValue `json:"-"`
}
// parsedPropertyValue is a union holding either a nested PropertyGroup or a FlagProperty.
// Exactly one field is set. Avoids per-evaluation type assertion and reconstruction.
type parsedPropertyValue struct {
IsGroup bool
Group PropertyGroup
Property FlagProperty
}
// FlagVariantMeta is a precomputed hash range for a feature flag variant.
type FlagVariantMeta struct {
// ValueMin is the inclusive lower bound of the normalized hash range.
ValueMin float64
// ValueMax is the exclusive upper bound of the normalized hash range.
ValueMax float64
// Key is the variant key for this hash range.
Key string
}
// FeatureFlagsResponse is the wire-format response from the local evaluation endpoint.
type FeatureFlagsResponse struct {
// Flags contains feature flag definitions for local evaluation.
Flags []FeatureFlag `json:"flags"`
// GroupTypeMapping maps group type indexes to group type names.
GroupTypeMapping *map[string]string `json:"group_type_mapping"`
// Cohorts contains cohort definitions referenced by local feature flags.
Cohorts map[string]PropertyGroup `json:"cohorts"`
// MinimalFlagCalledEvents reports whether the server enabled minimal
// $feature_flag_called events for this project. The server sends it only
// when the gate is on; absence means full events.
MinimalFlagCalledEvents bool `json:"minimal_flag_called_events"`
}
// DecideRequestData is the legacy wire-format request body for flag decide calls.
type DecideRequestData struct {
// ApiKey is the PostHog project API key.
ApiKey string `json:"api_key"`
// DistinctId is the user distinct ID to evaluate flags for.
DistinctId string `json:"distinct_id"`
// Groups contains group identifiers for group-targeted flags.
Groups Groups `json:"groups"`
// PersonProperties overrides person properties for this evaluation.
PersonProperties Properties `json:"person_properties"`
// GroupProperties overrides group properties for this evaluation, keyed by group type.
GroupProperties map[string]Properties `json:"group_properties"`
}
// DecideResponse is the legacy wire-format response body for flag decide calls.
type DecideResponse struct {
// FeatureFlags contains evaluated flag values keyed by flag key.
FeatureFlags map[string]interface{} `json:"featureFlags"`
// FeatureFlagPayloads contains raw payloads keyed by flag key.
FeatureFlagPayloads map[string]json.RawMessage `json:"featureFlagPayloads"`
}
// UnresolvedFlagReason explains why local evaluation could not resolve a flag.
// Experience continuity and unsupported definitions come from the flag's
// definition, missing context from the evaluation call, and unresolved
// dependencies from a flag the definition depends on.
type UnresolvedFlagReason string
const (
// UnresolvedFlagReasonExperienceContinuity means the flag has experience continuity
// enabled, which local evaluation never resolves.
UnresolvedFlagReasonExperienceContinuity UnresolvedFlagReason = "experience_continuity"
// UnresolvedFlagReasonUnsupportedDefinition means the flag uses something local
// evaluation does not support, such as a static cohort, an unknown operator, a
// malformed value, or a missing or circular flag dependency.
UnresolvedFlagReasonUnsupportedDefinition UnresolvedFlagReason = "unsupported_definition"
// UnresolvedFlagReasonUnresolvedDependency means a flag this flag depends on has a
// loaded definition but local evaluation could not resolve it.
UnresolvedFlagReasonUnresolvedDependency UnresolvedFlagReason = "unresolved_dependency"
// UnresolvedFlagReasonMissingContext means the call did not pass a property, group
// property or device id the flag needs, or passed it in a form local evaluation
// cannot use.
UnresolvedFlagReasonMissingContext UnresolvedFlagReason = "missing_context"
)
// unresolvedFlagReasons lists the reasons in the order the spec reports them when
// more than one cause applies, so every SDK reports the same reason whatever order
// it inspects the filters in.
var unresolvedFlagReasons = [...]UnresolvedFlagReason{
UnresolvedFlagReasonExperienceContinuity,
UnresolvedFlagReasonUnsupportedDefinition,
UnresolvedFlagReasonUnresolvedDependency,
UnresolvedFlagReasonMissingContext,
}
func unresolvedReasonRank(reason UnresolvedFlagReason) int {
for rank, candidate := range unresolvedFlagReasons {
if candidate == reason {
return rank
}
}
return len(unresolvedFlagReasons)
}
// pickUnresolvedReason returns whichever of current and next comes first in the spec
// order. An empty current means no reason was recorded yet.
func pickUnresolvedReason(current, next UnresolvedFlagReason) UnresolvedFlagReason {
if next == "" {
// An error raised without a reason still leaves the flag unresolved, and the
// loops treat an empty reason as "nothing was inconclusive".
next = UnresolvedFlagReasonUnsupportedDefinition
}
if current == "" || unresolvedReasonRank(next) < unresolvedReasonRank(current) {
return next
}
return current
}
// unresolvedReasonOf returns the reason an inconclusive or server-required error carries.
func unresolvedReasonOf(err error) (UnresolvedFlagReason, bool) {
switch e := err.(type) {
case *InconclusiveMatchError:
return pickUnresolvedReason("", e.Reason), true
case *RequiresServerEvaluationError:
return pickUnresolvedReason("", e.Reason), true
}
return "", false
}
// inconclusiveSentinels holds one shared error per reason, so that merging reasons
// does not allocate on every evaluation.
type inconclusiveSentinels [len(unresolvedFlagReasons)]*InconclusiveMatchError
func newInconclusiveSentinels(msg string) *inconclusiveSentinels {
var sentinels inconclusiveSentinels
for rank, reason := range unresolvedFlagReasons {
sentinels[rank] = &InconclusiveMatchError{msg: msg, Reason: reason}
}
return &sentinels
}
func (s *inconclusiveSentinels) withReason(reason UnresolvedFlagReason) *InconclusiveMatchError {
rank := unresolvedReasonRank(reason)
if rank == len(s) {
rank = unresolvedReasonRank(UnresolvedFlagReasonUnsupportedDefinition)
}
return s[rank]
}
// InconclusiveMatchError indicates that local evaluation could not conclusively match a condition.
type InconclusiveMatchError struct {
msg string
// Reason is why local evaluation could not resolve the flag.
Reason UnresolvedFlagReason
}
// Error returns the inconclusive match message.
func (e *InconclusiveMatchError) Error() string {
return e.msg
}
// RequiresServerEvaluationError is returned when feature flag evaluation
// requires server-side data that is not available locally (e.g., static cohorts,
// experience continuity). This error should propagate immediately to trigger
// API fallback, unlike InconclusiveMatchError which allows trying other conditions.
type RequiresServerEvaluationError struct {
msg string
// Reason is why local evaluation could not resolve the flag.
Reason UnresolvedFlagReason
}
// Error returns the reason server-side evaluation is required.
func (e *RequiresServerEvaluationError) Error() string {
return e.msg
}
// withReason returns e, or a copy of it when reason outranks the reason e carries.
func (e *RequiresServerEvaluationError) withReason(reason UnresolvedFlagReason) *RequiresServerEvaluationError {
merged := pickUnresolvedReason(reason, e.Reason)
if merged == e.Reason {
return e
}
return &RequiresServerEvaluationError{msg: e.msg, Reason: merged}
}
// isServerEvalError returns true if err is a RequiresServerEvaluationError.
// Uses type assertion instead of errors.As to avoid pointer-variable heap escapes.
func isServerEvalError(err error) bool {
_, ok := err.(*RequiresServerEvaluationError)
return ok
}
// isInconclusiveError returns true if err is an InconclusiveMatchError.
func isInconclusiveError(err error) bool {
_, ok := err.(*InconclusiveMatchError)
return ok
}
// FeatureFlagResult represents the result of a feature flag evaluation,
// containing both the flag value and its payload.
type FeatureFlagResult struct {
// Key is the feature flag key that was evaluated
Key string
// Enabled indicates whether the feature flag evaluation determined
// the flag to be in an enabled state.
Enabled bool
// RawPayload is the serialized JSON payload associated with the flag variant.
// Nil if no payload is configured.
// Use GetPayloadAs to unmarshal the payload into a specific type.
RawPayload *string
// Variant is the variant key if this is a multivariate flag.
// Nil for boolean flags.
Variant *string
// payloadStore and variantStore hold the actual string values so that
// RawPayload/Variant can point into the same allocation as the struct itself,
// avoiding separate heap escapes for the *string pointers.
payloadStore string
variantStore string
}
// GetPayloadAs unmarshals the JSON payload into the provided type.
// Returns an error if the payload is empty or cannot be unmarshaled.
func (r *FeatureFlagResult) GetPayloadAs(v interface{}) error {
if r.RawPayload == nil || *r.RawPayload == "" {
return errors.New("no payload available")
}
return json.Unmarshal([]byte(*r.RawPayload), v)
}
// evaluateFlagDependency evaluates a flag dependency property according to the dependency chain algorithm
func (poller *FeatureFlagsPoller) evaluateFlagDependency(
property FlagProperty,
flagsByKey map[string]FeatureFlag,
evaluationCache map[string]interface{},
distinctId string,
deviceId *string,
properties Properties,
cohorts map[string]PropertyGroup,
aggregationGroupTypeIndex *uint8,
snapshots ...*flagsState,
) (bool, error) {
state := poller.evaluationState(snapshots)
if flagsByKey == nil || evaluationCache == nil {
// Cannot evaluate flag dependencies without required context
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency on '%s' without flagsByKey and evaluationCache", property.Key),
Reason: UnresolvedFlagReasonUnsupportedDefinition,
}
}
// A problem in the definitions of the chain outranks a dependency that is only
// inconclusive, so check the whole chain before evaluating any of it.
if err := flagDependencyDefinitionError(property, flagsByKey, aggregationGroupTypeIndex); err != nil {
if property.DependencyChain != nil && len(property.DependencyChain) == 0 && poller.Logger != nil {
poller.Logger.Debugf("Circular dependency detected for flag: %s", property.Key)
}
return false, err
}
dependencyChain := property.DependencyChain
// Evaluate all dependencies in the chain order
for _, depFlagKey := range dependencyChain {
if _, exists := evaluationCache[depFlagKey]; exists {
continue
}
depFlag := flagsByKey[depFlagKey]
// Check if the flag is active (same check as in computeFlagLocally)
if !depFlag.Active {
evaluationCache[depFlagKey] = false
} else {
// Dependencies must preserve the same server boundary as direct evaluation.
if depFlag.EnsureExperienceContinuity != nil && *depFlag.EnsureExperienceContinuity {
evaluationCache[depFlagKey] = nil
return false, &InconclusiveMatchError{msg: "Flag dependency has experience continuity enabled", Reason: UnresolvedFlagReasonUnresolvedDependency}
}
// Recursively evaluate the dependency
var result interface{}
var err error
if depFlag.Filters.FeatureEnrollment {
// Only a person-aggregated caller gets here, so these are the person's.
result, err = matchFeatureEnrollment(depFlag, properties)
} else {
result, err = poller.matchFeatureFlagProperties(depFlag, distinctId, deviceId, properties, cohorts, flagsByKey, evaluationCache, nil, nil, state)
}
if err != nil {
// Preserve server-required errors on repeated references instead of
// reducing them to a cached inconclusive value that cohorts can negate.
if isServerEvalError(err) {
return false, &RequiresServerEvaluationError{
msg: fmt.Sprintf("Cannot evaluate flag dependency '%s': %s", depFlagKey, err.Error()),
Reason: UnresolvedFlagReasonUnresolvedDependency,
}
}
evaluationCache[depFlagKey] = nil
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency '%s': %s", depFlagKey, err.Error()),
Reason: UnresolvedFlagReasonUnresolvedDependency,
}
}
evaluationCache[depFlagKey] = result
}
}
// Check if the dependency result matches the expected value and operator
cachedResult, exists := evaluationCache[property.Key]
if exists && cachedResult != nil {
match, err := checkFlagDependencyValue(property.Value, cachedResult)
if err != nil {
return false, err
}
return match, nil
}
// The main dependency couldn't be evaluated. A key missing from its own chain is
// malformed server data rather than an unresolved dependency.
reason := UnresolvedFlagReasonUnresolvedDependency
if !exists {
reason = UnresolvedFlagReasonUnsupportedDefinition
}
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Flag dependency '%s' could not be evaluated for value comparison", property.Key),
Reason: reason,
}
}
// flagDependencyDefinitionError reports a flag dependency filter that local evaluation
// cannot use whatever the call passes. Evaluation and the load-time warning share it so
// they agree on which dependencies are unsupported.
func flagDependencyDefinitionError(property FlagProperty, flagsByKey map[string]FeatureFlag, aggregationGroupTypeIndex *uint8) error {
switch {
case property.Value == nil:
return &InconclusiveMatchError{msg: fmt.Sprintf("Cannot evaluate flag dependency on '%s' without a value", property.Key), Reason: UnresolvedFlagReasonUnsupportedDefinition}
case property.Operator != "flag_evaluates_to":
return &InconclusiveMatchError{msg: fmt.Sprintf("Unsupported operator '%s' for flag dependency '%s'", property.Operator, property.Key), Reason: UnresolvedFlagReasonUnsupportedDefinition}
case property.DependencyChain == nil:
return &InconclusiveMatchError{msg: fmt.Sprintf("Flag dependency property for '%s' is missing required 'dependency_chain' field", property.Key), Reason: UnresolvedFlagReasonUnsupportedDefinition}
case len(property.DependencyChain) == 0:
// The server sends an empty chain for a circular dependency.
return &InconclusiveMatchError{msg: fmt.Sprintf("Circular dependency detected for flag '%s'", property.Key), Reason: UnresolvedFlagReasonUnsupportedDefinition}
}
return dependencyChainDefinitionError(property.DependencyChain, flagsByKey, aggregationGroupTypeIndex)
}
// dependencyChainDefinitionError reports a dependency with no loaded definition, or one
// that needs a different aggregation context than the dependent condition.
// Dependencies can reuse the caller's key and properties only for the same
// aggregation type. This runs before the evaluation cache is read so repeated cohort
// references cannot bypass the cross-type server boundary.
func dependencyChainDefinitionError(dependencyChain []string, flagsByKey map[string]FeatureFlag, aggregationGroupTypeIndex *uint8) error {
for _, depFlagKey := range dependencyChain {
depFlag, flagExists := flagsByKey[depFlagKey]
if !flagExists {
return &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency '%s' - flag not found in local flags", depFlagKey),
Reason: UnresolvedFlagReasonUnsupportedDefinition,
}
}
if !depFlag.Active {
continue
}
// Enrollment reads the person's properties and skips the release conditions, so only
// the caller's aggregation matters.
if depFlag.Filters.FeatureEnrollment {
if aggregationGroupTypeIndex != nil {
return errDependencyAggregationRequiresServer
}
continue
}
if !uint8PtrEqual(depFlag.Filters.AggregationGroupTypeIndex, aggregationGroupTypeIndex) {
return errDependencyAggregationRequiresServer
}
for _, condition := range depFlag.Filters.Groups {
if condition.AggregationGroupTypeIndex != nil && !uint8PtrEqual(condition.AggregationGroupTypeIndex, aggregationGroupTypeIndex) {
return errDependencyAggregationRequiresServer
}
}
}
return nil
}
// checkFlagDependencyValue checks if a flag dependency result matches the expected value and operator
func checkFlagDependencyValue(expectedValue interface{}, actualResult interface{}) (bool, error) {
// String variant case - check for exact match or boolean true
if actualStr, ok := actualResult.(string); ok && len(actualStr) > 0 {
if expectedBool, ok := expectedValue.(bool); ok {
// Any variant matches boolean true
return expectedBool, nil
} else if expectedStr, ok := expectedValue.(string); ok {
// variants are case-sensitive, hence our comparison is too
return actualStr == expectedStr, nil
} else {
return false, nil
}
}
// Boolean case - must match expected boolean value
if actualBool, ok := actualResult.(bool); ok {
if expectedBool, ok := expectedValue.(bool); ok {
return actualBool == expectedBool, nil
}
}
// Default case
return false, nil
}
func newFeatureFlagsPoller(
projectApiKey string,
personalApiKey string,
logger Logger,
endpoint string,
httpClient http.Client,
pollingInterval time.Duration,
nextPollTick func() time.Duration,
flagTimeout time.Duration,
decider decider,
disableGeoIP bool,
cacheProvider FlagDefinitionCacheProvider,
) (*FeatureFlagsPoller, error) {
localEvaluationEndpoint := "/flags/definitions"
localEvalURL, err := url.Parse(endpoint + localEvaluationEndpoint)
if err != nil {
return nil, fmt.Errorf("creating local evaluation URL - %w", err)
}
if nextPollTick == nil {
nextPollTick = func() time.Duration { return pollingInterval }
}
ctx, cancel := context.WithCancel(context.Background())
poller := FeatureFlagsPoller{
firstFeatureFlagRequestFinished: make(chan bool),
shutdown: make(chan bool),
shutdownDone: make(chan bool),
forceReload: make(chan reloadRequest),
ctx: ctx,
cancel: cancel,
personalApiKey: personalApiKey,
projectApiKey: projectApiKey,
localEvalUrl: localEvalURL,
Logger: logger,
Endpoint: endpoint,
http: httpClient,
nextPollTick: nextPollTick,
flagTimeout: flagTimeout,
decider: decider,
disableGeoIP: disableGeoIP,
cacheProvider: cacheProvider,
}
go poller.run()
return &poller, nil
}
func (poller *FeatureFlagsPoller) run() {
defer close(poller.shutdownDone)
_ = poller.fetchNewFeatureFlags()
close(poller.firstFeatureFlagRequestFinished)
for {
timer := time.NewTimer(poller.nextPollTick())
select {
case <-poller.shutdown:
timer.Stop()
poller.shutdownCacheProvider(poller.shutdownCtx)
return
case req := <-poller.forceReload:
timer.Stop()
req.finish(poller.fetchNewFeatureFlags())
case <-timer.C:
_ = poller.fetchNewFeatureFlags()
}
}
}
// fetchNewFeatureFlags refreshes the local feature flag definitions used for local
// evaluation. These should not be confused with the feature flags fetched from the
// flags API.
func (poller *FeatureFlagsPoller) fetchNewFeatureFlags() error {
if poller.shuttingDown() {
return ErrClosed
}
if poller.cacheProvider == nil {
return poller.fetchFlagDefinitions(false)
}
// Cache-only readers must not claim fetch leadership they cannot use.
if poller.personalApiKey == "" {
if poller.loadFlagDefinitionsFromCache() {
return nil
}
return errNoCachedFlagDefinitions
}
shouldFetch, err := poller.cacheProvider.ShouldFetchFlagDefinitions(poller.ctx)
if poller.shuttingDown() {
return ErrClosed
}
if err != nil {
poller.Logger.Errorf("[FEATURE FLAGS] Cache provider ShouldFetchFlagDefinitions failed, fetching from the API: %s", err)
shouldFetch = true
}
if !shouldFetch {
if poller.loadFlagDefinitionsFromCache() {
return nil
}
if poller.shuttingDown() {
return ErrClosed
}
if poller.state.Load() != nil {
return nil
}
// Without definitions local evaluation is impossible, so fetch anyway.
poller.Logger.Debugf("[FEATURE FLAGS] No definitions cached or in memory, fetching from the API")
}
return poller.fetchFlagDefinitions(shouldFetch)
}
// shuttingDown reports whether polling work was cancelled by a shutdown that
// outlived its deadline. No provider call may start after that.
func (poller *FeatureFlagsPoller) shuttingDown() bool {
return poller.ctx.Err() != nil
}
// loadFlagDefinitionsFromCache applies cached definitions and reports whether any
// were loaded.
func (poller *FeatureFlagsPoller) loadFlagDefinitionsFromCache() bool {
data, err := poller.cacheProvider.GetFlagDefinitions(poller.ctx)
if err != nil {
poller.Logger.Errorf("[FEATURE FLAGS] Cache provider GetFlagDefinitions failed: %s", err)
return false
}
if data == nil {
return false
}
decoded, err := decodeFlagDefinitions(data)
if err != nil {
poller.Logger.Errorf("[FEATURE FLAGS] Cache provider returned unusable flag definitions: %s", err)
return false
}
if decoded.Flags == nil {
poller.Logger.Errorf("[FEATURE FLAGS] Cache provider returned definitions without flags, treating as a miss")
return false
}
for i, flag := range decoded.Flags {
if flag.Key == "" {
poller.Logger.Errorf("[FEATURE FLAGS] Cache provider returned a flag without a key at index %d, treating as a miss", i)
return false
}
}
// The ETag is dropped: a later conditional request must not be answered with 304
// against an ETag whose payload this instance no longer holds.
poller.applyFlagDefinitions(data, decoded, "")
poller.Logger.Debugf("[FEATURE FLAGS] Loaded %d flag definitions from the external cache", len(decoded.Flags))
return true
}
// flagDefinitions is the SDK's decoded view of a definition snapshot. The original
// JSON is retained separately for cache publication.
type flagDefinitions struct {
FeatureFlagsResponse
// Only 2 enables explicit matching; missing and unknown versions stay legacy.
PropertyMatchingVersion int `json:"property_matching_version"`
}