-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathposthog.go
More file actions
1548 lines (1345 loc) · 45.3 KB
/
posthog.go
File metadata and controls
1548 lines (1345 loc) · 45.3 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"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
json "github.com/goccy/go-json"
lru "github.com/hashicorp/golang-lru/v2"
)
const (
unimplementedError = "not implemented"
CACHE_DEFAULT_SIZE = 300_000
propertyGeoipDisable = "$geoip_disable"
// DefaultIdleConns is the default max idle connections for the HTTP client.
DefaultIdleConns = 100
// DefaultIdleConnsPerHost is the default max idle connections per host.
// This is higher than http.DefaultTransport's value of 2 to reduce
// connection churn when sending batches.
DefaultIdleConnsPerHost = 10
)
type EnqueueClient interface {
// Enqueue queues a message to be sent by the client when the conditions for a batch
// upload are met.
// This is the main method you'll be using, a typical flow would look like
// this:
//
// client := posthog.New(apiKey)
// ...
// client.Enqueue(posthog.Capture{ ... })
// ...
// client.Close()
//
// The method returns an error if the message queue could not be queued, which
// happens if the client was already closed at the time the method was
// called or if the message was malformed.
Enqueue(Message) error
}
// Client interface is the main API exposed by the posthog package.
// Values that satisfy this interface are returned by the client constructors
// provided by the package and provide a way to send messages via the HTTP API.
type Client interface {
io.Closer
EnqueueClient
// IsFeatureEnabled returns if a feature flag is on for a given user based on their distinct ID
IsFeatureEnabled(FeatureFlagPayload) (interface{}, error)
// GetFeatureFlag returns variant value if multivariant flag or otherwise a boolean indicating
// if the given flag is on or off for the user
GetFeatureFlag(FeatureFlagPayload) (interface{}, error)
// GetFeatureFlagResult returns the flag value and payload together.
// Use this instead of calling GetFeatureFlag and GetFeatureFlagPayload separately.
// Returns an error if the flag cannot be evaluated (e.g., flag missing or cannot be computed
// when using OnlyEvaluateLocally).
GetFeatureFlagResult(FeatureFlagPayload) (*FeatureFlagResult, error)
// GetFeatureFlagPayload returns feature flag's payload value matching key for user (supports multivariate flags).
// Deprecated: Use GetFeatureFlagResult instead, which returns both
// the flag value and payload while properly tracking feature flag usage.
GetFeatureFlagPayload(FeatureFlagPayload) (string, error)
// GetRemoteConfigPayload returns decrypted feature flag payload value for remote config flags.
GetRemoteConfigPayload(string) (string, error)
// GetAllFlags returns all flags for a user
GetAllFlags(FeatureFlagPayloadNoKey) (map[string]interface{}, error)
// EvaluateFlags returns a snapshot of feature-flag evaluations for the
// given distinct_id using at most one /flags request. Pass the returned
// snapshot to a Capture event via Capture.Flags to attach $feature/<key>
// properties without another network call. Calls to IsEnabled and GetFlag
// on the snapshot fire deduped $feature_flag_called events; GetFlagPayload
// does not.
//
// If the remote /flags request fails after some flags were resolved
// locally, EvaluateFlags returns a non-nil snapshot containing the
// locally-evaluated flags alongside the error so the caller can still
// branch on what was resolved.
EvaluateFlags(EvaluateFlagsPayload) (*FeatureFlagEvaluations, error)
// ReloadFeatureFlags forces a reload of feature flags
// NB: This is only available when using a PersonalApiKey
ReloadFeatureFlags() error
// GetFeatureFlags gets all feature flags, for testing only.
// NB: This is only available when using a PersonalApiKey
GetFeatureFlags() ([]FeatureFlag, error)
// CloseWithContext gracefully shuts down the client with the provided context.
// The context can be used to control the shutdown deadline.
CloseWithContext(context.Context) error
}
// preparedMessage bundles a pre-serialized message with the original APIMessage.
// The data field contains pre-serialized JSON for efficient batch building.
// The msg field retains the original APIMessage for callbacks.
// Size is obtained via len(data) - O(1) since json.RawMessage is []byte.
type preparedMessage struct {
data json.RawMessage // pre-serialized JSON for batch submission
msg APIMessage // original message for callbacks
}
// preparedBatch holds both raw data for efficient serialization and
// original API messages for callbacks.
type preparedBatch struct {
data []json.RawMessage // pre-serialized messages for batch submission
msgs []APIMessage // original messages for callbacks
}
type client struct {
Config
key string
// This channel is where the `Enqueue` method writes messages so they can be
// picked up and pushed by the backend goroutine taking care of applying the
// batching rules. Messages are pre-converted to APIMessage format with
// pre-computed size to avoid race conditions.
msgs chan preparedMessage
// Channel for sending batches to workers. Acts as both a queue and
// concurrency limiter - when full, new batches are shed via failure callback.
batches chan preparedBatch
// Tracks in-flight batches for graceful shutdown
inFlight atomic.Int64
// These two channels are used to synchronize the client shutting down when
// `Close` is called.
// The first channel is closed to signal the backend goroutine that it has
// to stop, then the second one is closed by the backend goroutine to signal
// that it has finished flushing all queued messages.
quit chan struct{}
shutdown chan struct{}
// Context and cancel function for graceful shutdown.
// When Close is called, the context is cancelled to signal all goroutines
// to stop, including in-flight HTTP requests.
ctx context.Context
cancel context.CancelFunc
// closeOnce ensures Close is idempotent
closeOnce sync.Once
// closed is set to true when the client is closed, used to fast-fail Enqueue
closed atomic.Bool
// This HTTP client is used to send requests to the backend, it uses the
// HTTP transport provided in the configuration.
http http.Client
// A background poller for fetching feature flags
featureFlagsPoller *FeatureFlagsPoller
distinctIdsFeatureFlagsReported *lru.Cache[flagUser, struct{}]
// Decider for feature flag methods
decider decider
}
type flagUser struct {
distinctID string
flagKey string
deviceID string
}
// Instantiate a new client that uses the write key passed as first argument to
// send messages to the backend.
// The client is created with the default configuration.
func New(apiKey string) Client {
// Here we can ignore the error because the default config is always valid.
c, _ := NewWithConfig(apiKey, Config{})
return c
}
// NewWithConfig instantiate a new client that uses the write key and configuration passed
// as arguments to send messages to the backend.
// The function will return an error if the configuration contained impossible
// values (like a negative flush interval for example).
// When the function returns an error the returned client will always be nil.
func NewWithConfig(apiKey string, config Config) (cli Client, err error) {
if err = config.Validate(); err != nil {
return
}
config = makeConfig(config)
apiKey = strings.TrimSpace(apiKey)
if len(apiKey) == 0 {
config.Logger.Errorf("posthog apiKey is empty after trimming whitespace; check your project API key")
}
reportedCache, err := lru.New[flagUser, struct{}](CACHE_DEFAULT_SIZE)
if err != nil && config.Logger != nil {
config.Logger.Errorf("Error creating cache for reported flags: %v", err)
}
// Channel sizing:
// - batches queue sized by MaxEnqueuedRequests (default 1000)
// - msgs queue sized to hold multiple batches worth of messages
batchesQueueSize := config.MaxEnqueuedRequests
msgQueueSize := max(100, config.BatchSize*10)
ctx, cancel := context.WithCancel(context.Background())
c := &client{
Config: config,
key: apiKey,
msgs: make(chan preparedMessage, msgQueueSize),
batches: make(chan preparedBatch, batchesQueueSize),
quit: make(chan struct{}),
shutdown: make(chan struct{}),
ctx: ctx,
cancel: cancel,
http: makeHttpClient(config.Transport, config.BatchUploadTimeout),
distinctIdsFeatureFlagsReported: reportedCache,
}
c.decider, err = newFlagsClient(apiKey, config.Endpoint, c.http, config.FeatureFlagRequestTimeout, c.Logger)
if err != nil {
return nil, fmt.Errorf("error creating flags client: %v", err)
}
if len(c.PersonalApiKey) > 0 {
c.featureFlagsPoller, err = newFeatureFlagsPoller(
c.key,
c.Config.PersonalApiKey,
c.Logger,
c.Endpoint,
c.http,
c.DefaultFeatureFlagsPollingInterval,
c.NextFeatureFlagsPollingTick,
c.FeatureFlagRequestTimeout,
c.decider,
c.Config.GetDisableGeoIP(),
)
if err != nil {
return nil, err
}
}
go c.loop()
cli = c
return
}
func makeHttpClient(transport http.RoundTripper, timeout time.Duration) http.Client {
// If no custom transport provided, clone DefaultTransport with tuned connection pool
if transport == nil {
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = DefaultIdleConns
t.MaxIdleConnsPerHost = DefaultIdleConnsPerHost
transport = t
}
httpClient := http.Client{
Transport: transport,
}
if supportsTimeout(transport) {
httpClient.Timeout = timeout
}
return httpClient
}
func dereferenceMessage(msg Message) Message {
switch m := msg.(type) {
case *Alias:
if m == nil {
return nil
}
return *m
case *Identify:
if m == nil {
return nil
}
return *m
case *GroupIdentify:
if m == nil {
return nil
}
return *m
case *Capture:
if m == nil {
return nil
}
return *m
case *Exception:
if m == nil {
return nil
}
return *m
}
return msg
}
func (c *client) Enqueue(msg Message) (err error) {
// Fast path: check if client is closed before doing any work
if c.closed.Load() {
return ErrClosed
}
msg = dereferenceMessage(msg)
if err = msg.Validate(); err != nil {
return
}
var ts = c.now()
// Helper to send prepared message with panic recovery
sendPrepared := func(prepared preparedMessage) {
defer func() {
// When the `msgs` channel is closed writing to it will trigger a panic.
// To avoid letting the panic propagate to the caller we recover from it
// and instead report that the client has been closed and shouldn't be
// used anymore.
if recover() != nil {
err = ErrClosed
}
}()
c.msgs <- prepared
}
switch m := msg.(type) {
case Alias:
m.Type = "alias"
m.Uuid = makeUUID(m.Uuid)
m.Timestamp = makeTimestamp(m.Timestamp, ts)
m.DisableGeoIP = c.GetDisableGeoIP()
data, apiMsg, serErr := prepareForSend(m)
if serErr != nil {
c.notifyFailure([]APIMessage{apiMsg}, serErr)
return
}
sendPrepared(preparedMessage{data: data, msg: apiMsg})
return
case Identify:
m.Type = "identify"
m.Uuid = makeUUID(m.Uuid)
m.Timestamp = makeTimestamp(m.Timestamp, ts)
m.DisableGeoIP = c.GetDisableGeoIP()
data, apiMsg, serErr := prepareForSend(m)
if serErr != nil {
c.notifyFailure([]APIMessage{apiMsg}, serErr)
return
}
sendPrepared(preparedMessage{data: data, msg: apiMsg})
return
case GroupIdentify:
m.Uuid = makeUUID(m.Uuid)
m.Timestamp = makeTimestamp(m.Timestamp, ts)
m.DisableGeoIP = c.GetDisableGeoIP()
data, apiMsg, serErr := prepareForSend(m)
if serErr != nil {
c.notifyFailure([]APIMessage{apiMsg}, serErr)
return
}
sendPrepared(preparedMessage{data: data, msg: apiMsg})
return
case Capture:
m.Type = "capture"
m.Uuid = makeUUID(m.Uuid)
m.Timestamp = makeTimestamp(m.Timestamp, ts)
if m.Flags != nil {
if m.shouldSendFeatureFlags() {
c.Warnf("[FEATURE FLAGS] Both Flags and SendFeatureFlags were set on Capture; using Flags and ignoring SendFeatureFlags.")
}
// Generated flag properties go down first so user-supplied
// Properties override them on conflict — matches the Python SDK's
// merge order so callers can manually overwrite $feature/<key>
// or $active_feature_flags if they need to.
m.Properties = m.Flags.eventProperties().Merge(m.Properties)
} else if m.shouldSendFeatureFlags() {
// Add all feature variants to event
personProperties := NewProperties()
groupProperties := map[string]Properties{}
opts := m.getFeatureFlagsOptions()
// Use custom properties if provided via options
if opts != nil {
if opts.PersonProperties != nil {
personProperties = opts.PersonProperties
}
if opts.GroupProperties != nil {
groupProperties = opts.GroupProperties
}
}
featureVariants, err := c.getFeatureVariantsWithOptions(m.DistinctId, m.Groups, personProperties, groupProperties, opts)
if err != nil {
c.Errorf("unable to get feature variants - %s", err)
}
if m.Properties == nil {
m.Properties = NewProperties()
}
for feature, variant := range featureVariants {
propKey := fmt.Sprintf("$feature/%s", feature)
m.Properties[propKey] = variant
}
// Add all feature flag keys to $active_feature_flags key
featureKeys := make([]string, len(featureVariants))
i := 0
for k := range featureVariants {
featureKeys[i] = k
i++
}
m.Properties["$active_feature_flags"] = featureKeys
}
if m.Properties == nil {
m.Properties = NewProperties()
}
m.Properties.Merge(c.DefaultEventProperties)
data, apiMsg, serErr := prepareForSend(m)
if serErr != nil {
c.notifyFailure([]APIMessage{apiMsg}, serErr)
return
}
sendPrepared(preparedMessage{data: data, msg: apiMsg})
return
case Exception:
m.Type = "exception"
m.Uuid = makeUUID(m.Uuid)
m.Timestamp = makeTimestamp(m.Timestamp, ts)
m.DisableGeoIP = c.GetDisableGeoIP()
data, apiMsg, serErr := prepareForSend(m)
if serErr != nil {
c.notifyFailure([]APIMessage{apiMsg}, serErr)
return
}
sendPrepared(preparedMessage{data: data, msg: apiMsg})
return
default:
err = fmt.Errorf("messages with custom types cannot be enqueued: %T", msg)
return
}
}
func (c *client) IsFeatureEnabled(flagConfig FeatureFlagPayload) (interface{}, error) {
if err := flagConfig.validate(); err != nil {
return false, err
}
result, err := c.GetFeatureFlag(flagConfig)
if err != nil {
return nil, err
}
return result, nil
}
func (c *client) ReloadFeatureFlags() error {
if c.featureFlagsPoller == nil {
err := fmt.Errorf("cannot use feature flags: %w", ErrNoPersonalAPIKey)
c.debugf(err.Error())
return err
}
c.featureFlagsPoller.ForceReload()
return nil
}
func (c *client) GetFeatureFlagPayload(flagConfig FeatureFlagPayload) (string, error) {
// Non-standard: This method historically left `SendFeatureFlagEvents` as nil.
// Once `flagConfig.validate()` is called, it sets it to true by default.
//
// To preserve historical behavior, we do not coerce to false, deviating from
// other SDKs that _do not_ send events from getFeatureFlagPayload calls.
result, err := c.GetFeatureFlagResult(flagConfig)
if err != nil {
if errors.Is(err, ErrFlagNotFound) {
return "", nil
}
return "", err
}
if result.RawPayload == nil {
return "", nil
}
return *result.RawPayload, nil
}
func (c *client) GetFeatureFlag(flagConfig FeatureFlagPayload) (interface{}, error) {
result, err := c.GetFeatureFlagResult(flagConfig)
if err != nil {
if errors.Is(err, ErrFlagNotFound) {
return false, nil
}
return nil, err
}
if result.Variant != nil {
return *result.Variant, nil
}
return result.Enabled, nil
}
func (c *client) GetFeatureFlagResult(flagConfig FeatureFlagPayload) (*FeatureFlagResult, error) {
return c.getFeatureFlagResultWithContext(context.Background(), flagConfig)
}
func (c *client) getFeatureFlagResultWithContext(ctx context.Context, flagConfig FeatureFlagPayload) (*FeatureFlagResult, error) {
// Check context before starting
if err := ctx.Err(); err != nil {
return nil, err
}
if err := flagConfig.validate(); err != nil {
return nil, err
}
var flagValue interface{}
var err error
// Use stack-allocated evalResult to avoid heap pointer allocation on the hot path
var evalResult featureFlagEvaluationResult
// payloadStr and variantStr hold values that will be stored in the result struct
var payloadStr string
var variantStr string
var hasPayload, hasVariant bool
var locallyEvaluated bool
if c.featureFlagsPoller != nil {
// Evaluate flag once to get both value and payload (avoids double evaluation)
combined := c.featureFlagsPoller.GetFeatureFlagWithPayload(flagConfig)
flagValue = combined.value
locallyEvaluated = combined.locallyEvaluated
err = combined.err
evalResult.Value = flagValue
evalResult.Err = err
if combined.payload != "" {
payloadStr = combined.payload
hasPayload = true
}
if v, ok := flagValue.(string); ok {
variantStr = v
hasVariant = true
}
} else {
// if there's no poller, get the feature flag from the flags endpoint
c.debugf("getting feature flag from flags endpoint")
locallyEvaluated = false
remoteResult := c.getFeatureFlagFromRemote(flagConfig.Key, flagConfig.DistinctId, flagConfig.DeviceId, flagConfig.Groups,
flagConfig.PersonProperties, flagConfig.GroupProperties)
evalResult = *remoteResult
flagValue = evalResult.Value
err = evalResult.Err
if f, ok := flagValue.(FlagDetail); ok {
flagValue = f.GetValue()
evalResult.Value = flagValue
ps := rawMessageToString(f.Metadata.Payload)
if ps != "" {
payloadStr = ps
hasPayload = true
}
if f.Variant != nil {
variantStr = *f.Variant
hasVariant = true
}
}
}
// Check context after flag evaluation
if ctx.Err() != nil {
return nil, ctx.Err()
}
if *flagConfig.SendFeatureFlagEvents {
var properties = NewProperties().
Set("$feature_flag", flagConfig.Key).
Set("$feature_flag_response", flagValue).
Set("locally_evaluated", locallyEvaluated)
if flagConfig.DeviceId != nil {
properties.Set("$device_id", *flagConfig.DeviceId)
}
if evalResult.RequestID != nil {
properties.Set("$feature_flag_request_id", *evalResult.RequestID)
}
if evalResult.EvaluatedAt != nil {
properties.Set("$feature_flag_evaluated_at", *evalResult.EvaluatedAt)
}
if evalResult.FlagDetail != nil {
properties.Set("$feature_flag_version", evalResult.FlagDetail.Metadata.Version)
properties.Set("$feature_flag_id", evalResult.FlagDetail.Metadata.ID)
if evalResult.FlagDetail.Reason != nil {
properties.Set("$feature_flag_reason", evalResult.FlagDetail.Reason.Description)
}
}
errorString := evalResult.GetErrorString()
if errorString != "" {
properties.Set("$feature_flag_error", errorString)
}
c.captureFlagCalledIfNeeded(flagConfig.DistinctId, flagConfig.Key, flagConfig.DeviceId, properties, flagConfig.Groups)
}
if flagValue == nil {
if evalResult.Err != nil {
return nil, evalResult.Err
}
if evalResult.FlagFailed {
return nil, fmt.Errorf("%w: '%s' failed to evaluate due to a transient error", ErrFlagNotFound, flagConfig.Key)
}
return nil, fmt.Errorf("%w: '%s' does not exist or is disabled", ErrFlagNotFound, flagConfig.Key)
}
enabled := false
switch v := flagValue.(type) {
case bool:
enabled = v
case string:
enabled = v != ""
}
// Build result with embedded string storage so RawPayload/Variant pointers
// reference fields within the same heap allocation (no separate string escapes).
result := &FeatureFlagResult{
Key: flagConfig.Key,
Enabled: enabled,
payloadStore: payloadStr,
variantStore: variantStr,
}
if hasPayload {
result.RawPayload = &result.payloadStore
}
if hasVariant {
result.Variant = &result.variantStore
}
return result, err
}
// captureFlagCalledIfNeeded fires a $feature_flag_called event if the
// (distinctId, key, deviceId) triple has not already been reported on this
// client. The caller is responsible for building the full properties dict;
// this helper only handles dedup and enqueue. It is shared by the legacy
// per-flag evaluation path and the FeatureFlagEvaluations snapshot path so
// both dedupe identically against the same per-distinct_id LRU cache.
func (c *client) captureFlagCalledIfNeeded(distinctId, key string, deviceId *string, properties Properties, groups Groups) {
deviceIDStr := ""
if deviceId != nil {
deviceIDStr = *deviceId
}
cacheKey := flagUser{distinctID: distinctId, flagKey: key, deviceID: deviceIDStr}
if c.distinctIdsFeatureFlagsReported.Contains(cacheKey) {
return
}
if err := c.Enqueue(Capture{
DistinctId: distinctId,
Event: "$feature_flag_called",
Properties: properties,
Groups: groups,
}); err == nil {
c.distinctIdsFeatureFlagsReported.Add(cacheKey, struct{}{})
}
}
func (c *client) GetRemoteConfigPayload(flagKey string) (string, error) {
return c.makeRemoteConfigRequest(flagKey)
}
// GetFeatureFlags returns all feature flag definitions used for local evaluation
// This is only available when using a PersonalApiKey. Not to be confused with
// GetAllFlags, which returns all flags and their values for a given user.
func (c *client) GetFeatureFlags() ([]FeatureFlag, error) {
if c.featureFlagsPoller == nil {
err := fmt.Errorf("cannot use feature flags: %w", ErrNoPersonalAPIKey)
c.Logger.Debugf(err.Error())
return nil, err
}
return c.featureFlagsPoller.GetFeatureFlags()
}
// GetAllFlags returns all flags and their values for a given user
// A flag value is either a boolean or a variant string (for multivariate flags)
// This first attempts local evaluation if a poller exists, otherwise it falls
// back to the flags endpoint
func (c *client) GetAllFlags(flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error) {
return c.getAllFlagsWithContext(context.Background(), flagConfig)
}
// getAllFlagsWithContext returns all flags and their values for a given user.
// The context can be used to control timeouts and cancellation.
// A flag value is either a boolean or a variant string (for multivariate flags)
func (c *client) getAllFlagsWithContext(ctx context.Context, flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error) {
// Check context before starting
if err := ctx.Err(); err != nil {
return nil, err
}
if err := flagConfig.validate(); err != nil {
return nil, err
}
var flagsValue map[string]interface{}
var err error
if c.featureFlagsPoller != nil {
// get feature flags from the poller, which uses the personal api key
// this is only available when using a PersonalApiKey
flagsValue, err = c.featureFlagsPoller.GetAllFlags(flagConfig)
} else {
// if there's no poller, get the feature flags from the flags endpoint
c.debugf("getting all feature flags from flags endpoint")
flagsValue, err = c.getAllFeatureFlagsFromRemote(flagConfig.DistinctId, flagConfig.DeviceId, flagConfig.Groups,
flagConfig.PersonProperties, flagConfig.GroupProperties)
}
// Check context after operation
if ctx.Err() != nil {
return nil, ctx.Err()
}
return flagsValue, err
}
// EvaluateFlagsPayload is the input to Client.EvaluateFlags.
type EvaluateFlagsPayload struct {
DistinctId string
DeviceId *string
Groups Groups
PersonProperties Properties
GroupProperties map[string]Properties
OnlyEvaluateLocally bool
// DisableGeoIP, when non-nil, overrides the client-level DisableGeoIP for
// this evaluation only.
DisableGeoIP *bool
// FlagKeys, when non-empty, trims the network call by asking the server
// to evaluate only the named flags (sent as flag_keys_to_evaluate).
// This is server-side filtering; use FeatureFlagEvaluations.Only to do
// client-side filtering of which flags are attached to events from an
// existing snapshot.
FlagKeys []string
}
func (c *client) EvaluateFlags(payload EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) {
host := c.featureFlagEvaluationsHost()
if payload.DistinctId == "" {
c.Warnf("EvaluateFlags called without a DistinctId — returning an empty snapshot")
return &FeatureFlagEvaluations{
host: host,
distinctId: "",
flags: map[string]evaluatedFlagRecord{},
accessed: map[string]struct{}{},
}, nil
}
if payload.Groups == nil {
payload.Groups = Groups{}
}
if payload.PersonProperties == nil {
payload.PersonProperties = NewProperties()
}
if payload.GroupProperties == nil {
payload.GroupProperties = map[string]Properties{}
}
disableGeoIP := c.GetDisableGeoIP()
if payload.DisableGeoIP != nil {
disableGeoIP = *payload.DisableGeoIP
}
records := make(map[string]evaluatedFlagRecord)
locallyEvaluated := make(map[string]struct{})
fallbackToRemote := true
if c.featureFlagsPoller != nil {
fallbackToRemote = c.populateLocalEvaluations(records, locallyEvaluated, payload)
}
var requestId string
var evaluatedAt *int64
var errorsWhileComputing bool
var quotaLimited bool
// remoteErr is returned alongside the snapshot when the /flags request
// fails, so callers still get any locally-evaluated flags collected above.
var remoteErr error
if fallbackToRemote && !payload.OnlyEvaluateLocally {
flagsResponse, err := c.decider.makeFlagsRequest(
payload.DistinctId,
payload.DeviceId,
payload.Groups,
payload.PersonProperties,
payload.GroupProperties,
disableGeoIP,
payload.FlagKeys,
)
if err != nil {
remoteErr = err
} else if flagsResponse != nil {
requestId = flagsResponse.RequestId
evaluatedAt = flagsResponse.EvaluatedAt
errorsWhileComputing = flagsResponse.ErrorsWhileComputingFlags
quotaLimited = c.isFeatureFlagsQuotaLimited(flagsResponse)
if !quotaLimited {
for key, detail := range flagsResponse.Flags {
if _, alreadyLocal := locallyEvaluated[key]; alreadyLocal {
continue
}
records[key] = recordFromFlagDetail(detail)
}
}
}
}
return &FeatureFlagEvaluations{
host: host,
distinctId: payload.DistinctId,
deviceId: payload.DeviceId,
groups: payload.Groups,
flags: records,
requestId: requestId,
evaluatedAt: evaluatedAt,
errorsWhileComputing: errorsWhileComputing,
quotaLimited: quotaLimited,
accessed: map[string]struct{}{},
}, remoteErr
}
// populateLocalEvaluations fills records with locally-resolved flags. It
// returns whether the caller should fall back to a remote /flags request to
// fill in the rest. The local-evaluation loop here mirrors
// FeatureFlagsPoller.GetAllFlags but stores the rich record needed to power
// $feature_flag_called events with locally_evaluated=true.
func (c *client) populateLocalEvaluations(records map[string]evaluatedFlagRecord, locallyEvaluated map[string]struct{}, payload EvaluateFlagsPayload) bool {
poller := c.featureFlagsPoller
featureFlags, err := poller.GetFeatureFlags()
if err != nil {
return true
}
if len(featureFlags) == 0 {
return true
}
flagKeyFilter := map[string]struct{}{}
for _, k := range payload.FlagKeys {
flagKeyFilter[k] = struct{}{}
}
cohorts := poller.getCohorts()
fallbackToRemote := false
const localReason = "Evaluated locally"
for _, storedFlag := range featureFlags {
if len(flagKeyFilter) > 0 {
if _, ok := flagKeyFilter[storedFlag.Key]; !ok {
continue
}
}
value, err := poller.computeFlagLocally(
storedFlag,
payload.DistinctId,
payload.DeviceId,
payload.Groups,
payload.PersonProperties,
payload.GroupProperties,
cohorts,
)
if err != nil {
c.debugf("Unable to compute flag '%s' locally - %s", storedFlag.Key, err)
fallbackToRemote = true
continue
}
record := evaluatedFlagRecord{
Key: storedFlag.Key,
LocallyEvaluated: true,
Reason: ptrString(localReason),
}
switch v := value.(type) {
case bool:
record.Enabled = v
case string:
record.Enabled = true
variant := v
record.Variant = &variant
default:
record.Enabled = false
}
if record.Enabled {
variantKey := "true"
if record.Variant != nil {
variantKey = *record.Variant
}
if rawPayload, ok := storedFlag.Filters.Payloads[variantKey]; ok {
if s := rawMessageToString(rawPayload); s != "" {
payloadStr := s
record.Payload = &payloadStr
}
}
}
records[storedFlag.Key] = record
locallyEvaluated[storedFlag.Key] = struct{}{}
}
return fallbackToRemote
}
// recordFromFlagDetail builds an evaluatedFlagRecord from a v4 FlagDetail.
func recordFromFlagDetail(detail FlagDetail) evaluatedFlagRecord {
record := evaluatedFlagRecord{
Key: detail.Key,
Enabled: detail.Enabled,
Variant: detail.Variant,
}
if detail.Failed != nil && *detail.Failed {
record.Enabled = false
errStr := FeatureFlagErrorEvaluationFailed
record.Error = &errStr
}
id := detail.Metadata.ID
record.ID = &id
version := detail.Metadata.Version
record.Version = &version
if detail.Reason != nil {
reason := detail.Reason.Description
record.Reason = &reason
}
if s := rawMessageToString(detail.Metadata.Payload); s != "" {
payloadStr := s
record.Payload = &payloadStr
}
return record
}
func ptrString(s string) *string { return &s }
// featureFlagEvaluationsHost wires the snapshot's callbacks to this client.
func (c *client) featureFlagEvaluationsHost() featureFlagEvaluationsHost {
return featureFlagEvaluationsHost{
captureFlagCalledIfNeeded: c.captureFlagCalledIfNeeded,
logger: c.Logger,
}
}
// Close gracefully shuts down the client, flushing any pending messages.
// If ShutdownTimeout is set to a positive duration, Close waits up to that
// duration for in-flight requests to complete. Otherwise, it waits indefinitely.
// Close is safe to call multiple times; subsequent calls return ErrClosed.
func (c *client) Close() error {
if c.ShutdownTimeout <= 0 {
// Zero or negative timeout means wait indefinitely (backward compatible)
return c.CloseWithContext(context.Background())
}
ctx, cancel := context.WithTimeout(context.Background(), c.ShutdownTimeout)
defer cancel()
return c.CloseWithContext(ctx)
}
// CloseWithContext gracefully shuts down the client with the provided context.
// The context can be used to control the shutdown deadline. If the context
// is cancelled before shutdown completes, in-flight requests may be aborted.
// CloseWithContext is safe to call multiple times; subsequent calls return ErrClosed.
func (c *client) CloseWithContext(ctx context.Context) error {
var err error
alreadyClosed := true
c.closeOnce.Do(func() {
alreadyClosed = false
// Mark as closed to fast-fail new Enqueue calls
c.closed.Store(true)
// Signal the batch loop to stop and drain
close(c.quit)
// Wait for shutdown with timeout from provided context
select {
case <-c.shutdown:
// Clean shutdown completed
c.debugf("shutdown completed successfully")
case <-ctx.Done():
// Timeout exceeded - cancel client context to abort in-flight requests
c.cancel()
err = fmt.Errorf("shutdown timeout: %w", ctx.Err())
c.Warnf("shutdown timeout exceeded, some messages may be lost")
// Wait for shutdown to acknowledge cancellation