-
Notifications
You must be signed in to change notification settings - Fork 18
/
ldclient.go
1301 lines (1188 loc) · 55.3 KB
/
ldclient.go
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 ldclient
import (
gocontext "context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"reflect"
"time"
"github.com/launchdarkly/go-server-sdk/v7/internal/datasystem"
"github.com/launchdarkly/go-server-sdk/v7/subsystems"
"github.com/launchdarkly/go-sdk-common/v3/ldcontext"
"github.com/launchdarkly/go-sdk-common/v3/ldlog"
"github.com/launchdarkly/go-sdk-common/v3/ldmigration"
"github.com/launchdarkly/go-sdk-common/v3/ldreason"
"github.com/launchdarkly/go-sdk-common/v3/ldvalue"
ldevents "github.com/launchdarkly/go-sdk-events/v3"
ldeval "github.com/launchdarkly/go-server-sdk-evaluation/v3"
"github.com/launchdarkly/go-server-sdk-evaluation/v3/ldmodel"
"github.com/launchdarkly/go-server-sdk/v7/interfaces"
"github.com/launchdarkly/go-server-sdk/v7/interfaces/flagstate"
"github.com/launchdarkly/go-server-sdk/v7/internal"
"github.com/launchdarkly/go-server-sdk/v7/internal/bigsegments"
"github.com/launchdarkly/go-server-sdk/v7/internal/datakinds"
"github.com/launchdarkly/go-server-sdk/v7/internal/hooks"
"github.com/launchdarkly/go-server-sdk/v7/ldcomponents"
"github.com/launchdarkly/go-server-sdk/v7/subsystems/ldstoreimpl"
)
// Version is the SDK version.
const Version = internal.SDKVersion
// highWaitForDuration represents the maximum amount of time that the client should be
// told to wait when initializing above which we emit a log message warning the user of excessive wait time.
const highWaitForDuration = 60 * time.Second
const (
boolVarFuncName = "LDClient.BoolVariation"
intVarFuncName = "LDClient.IntVariation"
floatVarFuncName = "LDClient.Float64Variation"
stringVarFuncName = "LDClient.StringVariation"
jsonVarFuncName = "LDClient.JSONVariation"
boolVarExFuncName = "LDClient.BoolVariationCtx"
intVarExFuncName = "LDClient.IntVariationCtx"
floatVarExFuncName = "LDClient.Float64VariationCtx"
stringVarExFuncName = "LDClient.StringVariationCtx"
jsonVarExFuncName = "LDClient.JSONVariationCtx"
boolVarDetailFuncName = "LDClient.BoolVariationDetail"
intVarDetailFuncName = "LDClient.IntVariationDetail"
floatVarDetailFuncName = "LDClient.Float64VariationDetail"
stringVarDetailFuncName = "LDClient.StringVariationDetail"
jsonVarDetailFuncName = "LDClient.JSONVariationDetail"
boolVarDetailExFuncName = "LDClient.BoolVariationDetailCtx"
intVarDetailExFuncName = "LDClient.IntVariationDetailCtx"
floatVarDetailExFuncName = "LDClient.Float64VariationDetailCtx"
stringVarDetailExFuncName = "LDClient.StringVariationDetailCtx"
jsonVarDetailExFuncName = "LDClient.JSONVariationDetailCtx"
migrationVarFuncName = "LDClient.MigrationVariation"
migrationVarExFuncName = "LDClient.MigrationVariationCtx"
)
// dataSystem represents the requirements the client has for storing/retrieving/detecting changes related
// to the SDK's data model.
type dataSystem interface {
DataSourceStatusBroadcaster() *internal.Broadcaster[interfaces.DataSourceStatus]
DataSourceStatusProvider() interfaces.DataSourceStatusProvider
DataStoreStatusBroadcaster() *internal.Broadcaster[interfaces.DataStoreStatus]
DataStoreStatusProvider() interfaces.DataStoreStatusProvider
FlagChangeEventBroadcaster() *internal.Broadcaster[interfaces.FlagChangeEvent]
// Start starts the data system; the given channel will be closed when the system has reached an initial state
// (either permanently failed, e.g. due to bad auth, or succeeded, where Initialized() == true).
Start(closeWhenReady chan struct{})
// Stop halts the data system. Should be called when the client is closed to stop any long-running operations.
Stop() error
// Store returns a read-only accessor for the data model.
Store() subsystems.ReadOnlyStore
// DataAvailability indicates what form of data is available.
DataAvailability() datasystem.DataAvailability
}
var (
_ dataSystem = &datasystem.FDv1{}
)
// LDClient is the LaunchDarkly client.
//
// This object evaluates feature flags, generates analytics events, and communicates with
// LaunchDarkly services. Applications should instantiate a single instance for the lifetime
// of their application and share it wherever feature flags need to be evaluated; all LDClient
// methods are safe to be called concurrently from multiple goroutines.
//
// Some advanced client features are grouped together in API facades that are accessed through
// an LDClient method, such as [LDClient.GetDataSourceStatusProvider].
//
// When an application is shutting down or no longer needs to use the LDClient instance, it
// should call [LDClient.Close] to ensure that all of its connections and goroutines are shut down and
// that any pending analytics events have been delivered.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/server-side/go
type LDClient struct {
sdkKey string
loggers ldlog.Loggers
eventProcessor ldevents.EventProcessor
evaluator ldeval.Evaluator
dataSystem dataSystem
flagTracker interfaces.FlagTracker
bigSegmentStoreStatusBroadcaster *internal.Broadcaster[interfaces.BigSegmentStoreStatus]
bigSegmentStoreStatusProvider interfaces.BigSegmentStoreStatusProvider
bigSegmentStoreWrapper *ldstoreimpl.BigSegmentStoreWrapper
eventsDefault eventsScope
eventsWithReasons eventsScope
withEventsDisabled interfaces.LDClientInterface
logEvaluationErrors bool
offline bool
hookRunner *hooks.Runner
}
// Initialization errors
var (
// MakeClient and MakeCustomClient will return this error if the SDK was not able to establish a
// LaunchDarkly connection within the specified time interval. In this case, the LDClient will still
// continue trying to connect in the background.
ErrInitializationTimeout = errors.New("timeout encountered waiting for LaunchDarkly client initialization")
// MakeClient and MakeCustomClient will return this error if the SDK detected an error that makes it
// impossible for a LaunchDarkly connection to succeed. Currently, the only such condition is if the
// SDK key is invalid, since an invalid SDK key will never become valid.
ErrInitializationFailed = errors.New("LaunchDarkly client initialization failed")
// This error is returned by the Variation/VariationDetail methods if feature flags are not available
// because the client has not successfully initialized. In this case, the result value will be whatever
// default value was specified by the application.
ErrClientNotInitialized = errors.New("feature flag evaluation called before LaunchDarkly client initialization completed") //nolint:lll
)
// MakeClient creates a new client instance that connects to LaunchDarkly with the default configuration.
//
// For advanced configuration options, use [MakeCustomClient]. Calling MakeClient is exactly equivalent to
// calling MakeCustomClient with the config parameter set to an empty value, ld.Config{}.
//
// The client will begin attempting to connect to LaunchDarkly as soon as you call this constructor. The
// constructor will return when it successfully connects, or when the timeout set by the waitFor parameter
// expires, whichever comes first.
//
// If the connection succeeded, the first return value is the client instance, and the error value is nil.
//
// If the timeout elapsed without a successful connection, it still returns a client instance-- in an
// uninitialized state, where feature flags will return default values-- and the error value is
// [ErrInitializationTimeout]. In this case, it will still continue trying to connect in the background.
//
// If there was an unrecoverable error such that it cannot succeed by retrying-- for instance, the SDK key is
// invalid-- it will return a client instance in an uninitialized state, and the error value is
// [ErrInitializationFailed].
//
// If you set waitFor to zero, the function will return immediately after creating the client instance, and
// do any further initialization in the background.
//
// The only time it returns nil instead of a client instance is if the client cannot be created at all due to
// an invalid configuration. This is rare, but could happen if for instance you specified a custom TLS
// certificate file that did not contain a valid certificate.
//
// For more about the difference between an initialized and uninitialized client, and other ways to monitor
// the client's status, see [LDClient.Initialized] and [LDClient.GetDataSourceStatusProvider].
func MakeClient(sdkKey string, waitFor time.Duration) (*LDClient, error) {
// COVERAGE: this constructor cannot be called in unit tests because it uses the default base
// URI and will attempt to make a live connection to LaunchDarkly.
return MakeCustomClient(sdkKey, Config{}, waitFor)
}
// MakeCustomClient creates a new client instance that connects to LaunchDarkly with a custom configuration.
//
// The config parameter allows customization of all SDK properties; some of these are represented directly as
// fields in Config, while others are set by builder methods on a more specific configuration object. See
// [Config] for details.
//
// Unless it is configured to be offline with Config.Offline or [ldcomponents.ExternalUpdatesOnly], the client
// will begin attempting to connect to LaunchDarkly as soon as you call this constructor. The constructor will
// return when it successfully connects, or when the timeout set by the waitFor parameter expires, whichever
// comes first.
//
// If the connection succeeded, the first return value is the client instance, and the error value is nil.
//
// If the timeout elapsed without a successful connection, it still returns a client instance-- in an
// uninitialized state, where feature flags will return default values-- and the error value is
// [ErrInitializationTimeout]. In this case, it will still continue trying to connect in the background.
//
// If there was an unrecoverable error such that it cannot succeed by retrying-- for instance, the SDK key is
// invalid-- it will return a client instance in an uninitialized state, and the error value is
// [ErrInitializationFailed].
//
// If you set waitFor to zero, the function will return immediately after creating the client instance, and
// do any further initialization in the background.
//
// The only time it returns nil instead of a client instance is if the client cannot be created at all due to
// an invalid configuration. This is rare, but could happen if for instance you specified a custom TLS
// certificate file that did not contain a valid certificate.
//
// For more about the difference between an initialized and uninitialized client, and other ways to monitor
// the client's status, see [LDClient.Initialized] and [LDClient.GetDataSourceStatusProvider].
func MakeCustomClient(sdkKey string, config Config, waitFor time.Duration) (*LDClient, error) {
// Ensure that any intermediate components we create will be disposed of if we return an error
client := &LDClient{sdkKey: sdkKey}
clientValid := false
defer func() {
if !clientValid {
_ = client.Close()
}
}()
closeWhenReady := make(chan struct{})
eventProcessorFactory := getEventProcessorFactory(config)
clientContext, err := newClientContextFromConfig(sdkKey, config)
if err != nil {
return nil, err
}
// Do not create a diagnostics manager if diagnostics are disabled, or if we're not using the standard event processor.
if !config.DiagnosticOptOut {
if reflect.TypeOf(eventProcessorFactory) == reflect.TypeOf(ldcomponents.SendEvents()) {
clientContext.DiagnosticsManager = createDiagnosticsManager(clientContext, sdkKey, config, waitFor)
}
}
loggers := clientContext.GetLogging().Loggers
loggers.Infof("Starting LaunchDarkly client %s", Version)
client.loggers = loggers
client.logEvaluationErrors = clientContext.GetLogging().LogEvaluationErrors
client.offline = config.Offline
system, err := datasystem.NewFDv1(config.Offline, config.DataStore, config.DataSource, clientContext)
if err != nil {
return nil, err
}
client.dataSystem = system
bigSegments := config.BigSegments
if bigSegments == nil {
bigSegments = ldcomponents.BigSegments(nil)
}
bsConfig, err := bigSegments.Build(clientContext)
if err != nil {
return nil, err
}
bsStore := bsConfig.GetStore()
client.bigSegmentStoreStatusBroadcaster = internal.NewBroadcaster[interfaces.BigSegmentStoreStatus]()
if bsStore != nil {
client.bigSegmentStoreWrapper = ldstoreimpl.NewBigSegmentStoreWrapperWithConfig(
ldstoreimpl.BigSegmentsConfigurationProperties{
Store: bsStore,
StartPolling: true,
StatusPollInterval: bsConfig.GetStatusPollInterval(),
StaleAfter: bsConfig.GetStaleAfter(),
ContextCacheSize: bsConfig.GetContextCacheSize(),
ContextCacheTime: bsConfig.GetContextCacheTime(),
},
client.bigSegmentStoreStatusBroadcaster.Broadcast,
loggers,
)
client.bigSegmentStoreStatusProvider = bigsegments.NewBigSegmentStoreStatusProviderImpl(
client.bigSegmentStoreWrapper.GetStatus,
client.bigSegmentStoreStatusBroadcaster,
)
} else {
client.bigSegmentStoreStatusProvider = bigsegments.NewBigSegmentStoreStatusProviderImpl(
nil, client.bigSegmentStoreStatusBroadcaster,
)
}
dataProvider := ldstoreimpl.NewDataStoreEvaluatorDataProvider(client.dataSystem.Store(), loggers)
evalOptions := []ldeval.EvaluatorOption{
ldeval.EvaluatorOptionErrorLogger(client.loggers.ForLevel(ldlog.Error)),
}
if client.bigSegmentStoreWrapper != nil {
evalOptions = append(evalOptions, ldeval.EvaluatorOptionBigSegmentProvider(client.bigSegmentStoreWrapper))
}
client.evaluator = ldeval.NewEvaluatorWithOptions(dataProvider, evalOptions...)
client.eventProcessor, err = eventProcessorFactory.Build(clientContext)
if err != nil {
return nil, err
}
if isNullEventProcessorFactory(eventProcessorFactory) {
client.eventsDefault = newDisabledEventsScope()
client.eventsWithReasons = newDisabledEventsScope()
} else {
client.eventsDefault = newEventsScope(client, false)
client.eventsWithReasons = newEventsScope(client, true)
}
// Pre-create the WithEventsDisabled object so that if an application ends up calling WithEventsDisabled
// frequently, it won't be causing an allocation each time.
client.withEventsDisabled = newClientEventsDisabledDecorator(client)
client.flagTracker = internal.NewFlagTrackerImpl(
client.dataSystem.FlagChangeEventBroadcaster(),
func(flagKey string, context ldcontext.Context, defaultValue ldvalue.Value) ldvalue.Value {
value, _ := client.JSONVariation(flagKey, context, defaultValue)
return value
},
)
client.hookRunner = hooks.NewRunner(loggers, config.Hooks)
clientValid = true
client.dataSystem.Start(closeWhenReady)
if waitFor > 0 && !client.offline {
loggers.Infof("Waiting up to %d milliseconds for LaunchDarkly client to start...",
waitFor/time.Millisecond)
// If you use a long duration and wait for the timeout, then any network delays will cause
// your application to wait a long time before continuing execution.
if waitFor > highWaitForDuration {
loggers.Warnf("Client was configured to block for up to %v milliseconds. "+
"We recommend blocking no longer than %v milliseconds", waitFor.Milliseconds(), highWaitForDuration.Milliseconds())
}
timeout := time.After(waitFor)
for {
select {
case <-closeWhenReady:
if client.dataSystem.DataAvailability() != datasystem.Refreshed {
loggers.Warn("LaunchDarkly client initialization failed")
return client, ErrInitializationFailed
}
loggers.Info("Initialized LaunchDarkly client")
return client, nil
case <-timeout:
loggers.Warn("Timeout encountered waiting for LaunchDarkly client initialization")
go func() { <-closeWhenReady }() // Don't block the DataSource when not waiting
return client, ErrInitializationTimeout
}
}
}
go func() { <-closeWhenReady }() // Don't block the DataSource when not waiting
return client, nil
}
// MigrationVariation returns the migration stage of the migration feature flag for the given evaluation context.
//
// Returns defaultStage if there is an error or if the flag doesn't exist.
func (client *LDClient) MigrationVariation(
key string, context ldcontext.Context, defaultStage ldmigration.Stage,
) (ldmigration.Stage, interfaces.LDMigrationOpTracker, error) {
return client.migrationVariation(gocontext.TODO(), key, context, defaultStage, client.eventsDefault,
migrationVarFuncName)
}
// MigrationVariationCtx returns the migration stage of the migration feature flag for the given evaluation context.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// Returns defaultStage if there is an error or if the flag doesn't exist.
func (client *LDClient) MigrationVariationCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultStage ldmigration.Stage,
) (ldmigration.Stage, interfaces.LDMigrationOpTracker, error) {
return client.migrationVariation(ctx, key, context, defaultStage, client.eventsDefault, migrationVarExFuncName)
}
func (client *LDClient) migrationVariation(
ctx gocontext.Context,
key string, context ldcontext.Context, defaultStage ldmigration.Stage, eventsScope eventsScope, method string,
) (ldmigration.Stage, interfaces.LDMigrationOpTracker, error) {
defaultStageAsValue := ldvalue.String(string(defaultStage))
detail, flag, err := client.hookRunner.RunEvaluation(
ctx,
key,
context,
defaultStageAsValue,
method,
func() (ldreason.EvaluationDetail, *ldmodel.FeatureFlag, error) {
detail, flag, err := client.variationAndFlag(key, context, defaultStageAsValue, true,
eventsScope)
if err != nil {
// Detail will already contain the default.
// We do not have an error on the flag-not-found case.
return detail, flag, nil
}
_, err = ldmigration.ParseStage(detail.Value.StringValue())
if err != nil {
detail = ldreason.NewEvaluationDetailForError(ldreason.EvalErrorWrongType, ldvalue.String(string(defaultStage)))
return detail, flag, fmt.Errorf("%s; returning default stage %s", err, defaultStage)
}
return detail, flag, err
},
)
tracker := NewMigrationOpTracker(key, flag, context, detail, defaultStage)
// Stage will have already been parsed and defaulted.
stage, _ := ldmigration.ParseStage(detail.Value.StringValue())
return stage, tracker, err
}
// Identify reports details about an evaluation context.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/identify#go
func (client *LDClient) Identify(context ldcontext.Context) error {
if client.eventsDefault.disabled {
return nil
}
if err := context.Err(); err != nil {
client.loggers.Warnf("Identify called with invalid context: %s", err)
return nil // Don't return an error value because we didn't in the past and it might confuse users
}
// Identify events should always sample
evt := client.eventsDefault.factory.NewIdentifyEventData(ldevents.Context(context), ldvalue.NewOptionalInt(1))
client.eventProcessor.RecordIdentifyEvent(evt)
return nil
}
// TrackEvent reports an event associated with an evaluation context.
//
// The eventName parameter is defined by the application and will be shown in analytics reports;
// it normally corresponds to the event name of a metric that you have created through the
// LaunchDarkly dashboard. If you want to associate additional data with this event, use [TrackData]
// or [TrackMetric].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/events#go
func (client *LDClient) TrackEvent(eventName string, context ldcontext.Context) error {
return client.TrackData(eventName, context, ldvalue.Null())
}
// TrackData reports an event associated with an evaluation context, and adds custom data.
//
// The eventName parameter is defined by the application and will be shown in analytics reports;
// it normally corresponds to the event name of a metric that you have created through the
// LaunchDarkly dashboard.
//
// The data parameter is a value of any JSON type, represented with the ldvalue.Value type, that
// will be sent with the event. If no such value is needed, use [ldvalue.Null]() (or call [TrackEvent]
// instead). To send a numeric value for experimentation, use [TrackMetric].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/events#go
func (client *LDClient) TrackData(eventName string, context ldcontext.Context, data ldvalue.Value) error {
if client.eventsDefault.disabled {
return nil
}
if err := context.Err(); err != nil {
client.loggers.Warnf("Track called with invalid context: %s", err)
return nil // Don't return an error value because we didn't in the past and it might confuse users
}
client.eventProcessor.RecordCustomEvent(
client.eventsDefault.factory.NewCustomEventData(
eventName,
ldevents.Context(context),
data,
false,
0,
ldvalue.NewOptionalInt(1),
))
return nil
}
// TrackMetric reports an event associated with an evaluation context, and adds a numeric value.
// This value is used by the LaunchDarkly experimentation feature in numeric custom metrics, and will also
// be returned as part of the custom event for Data Export.
//
// The eventName parameter is defined by the application and will be shown in analytics reports;
// it normally corresponds to the event name of a metric that you have created through the
// LaunchDarkly dashboard.
//
// The data parameter is a value of any JSON type, represented with the ldvalue.Value type, that
// will be sent with the event. If no such value is needed, use [ldvalue.Null]().
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/events#go
func (client *LDClient) TrackMetric(
eventName string,
context ldcontext.Context,
metricValue float64,
data ldvalue.Value,
) error {
if client.eventsDefault.disabled {
return nil
}
if err := context.Err(); err != nil {
client.loggers.Warnf("TrackMetric called with invalid context: %s", err)
return nil // Don't return an error value because we didn't in the past and it might confuse users
}
client.eventProcessor.RecordCustomEvent(
client.eventsDefault.factory.NewCustomEventData(
eventName,
ldevents.Context(context),
data,
true,
metricValue,
ldvalue.NewOptionalInt(1),
))
return nil
}
// TrackMigrationOp reports a migration operation event.
func (client *LDClient) TrackMigrationOp(event ldevents.MigrationOpEventData) error {
if client.eventsDefault.disabled {
return nil
}
client.eventProcessor.RecordMigrationOpEvent(event)
return nil
}
// IsOffline returns whether the LaunchDarkly client is in offline mode.
//
// This is only true if you explicitly set the Offline field to true in [Config], to force the client to
// be offline. It does not mean that the client is having a problem connecting to LaunchDarkly. To detect
// the status of a client that is configured to be online, use [LDClient.Initialized] or
// [LDClient.GetDataSourceStatusProvider].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/offline-mode#go
func (client *LDClient) IsOffline() bool {
return client.offline
}
// SecureModeHash generates the secure mode hash value for an evaluation context.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/secure-mode#go
func (client *LDClient) SecureModeHash(context ldcontext.Context) string {
key := []byte(client.sdkKey)
h := hmac.New(sha256.New, key)
_, _ = h.Write([]byte(context.FullyQualifiedKey()))
return hex.EncodeToString(h.Sum(nil))
}
// Initialized returns whether the LaunchDarkly client is initialized.
//
// If this value is true, it means the client has succeeded at some point in connecting to LaunchDarkly and
// has received feature flag data. It could still have encountered a connection problem after that point, so
// this does not guarantee that the flags are up to date; if you need to know its status in more detail, use
// [LDClient.GetDataSourceStatusProvider].
//
// Additionally, if the client was configured to be offline, this will always return true.
//
// If this value is false, it means the client has not yet connected to LaunchDarkly, or has permanently
// failed. See [MakeClient] for the reasons that this could happen. In this state, feature flag evaluations
// will always return default values-- unless you are using a database integration and feature flags had
// already been stored in the database by a successfully connected SDK in the past. You can use
// [LDClient.GetDataSourceStatusProvider] to get information on errors, or to wait for a successful retry.
func (client *LDClient) Initialized() bool {
if client.offline {
return true
}
return client.dataSystem.DataAvailability() != datasystem.Defaults
}
// Close shuts down the LaunchDarkly client. After calling this, the LaunchDarkly client
// should no longer be used. The method will block until all pending analytics events (if any)
// been sent.
func (client *LDClient) Close() error {
client.loggers.Info("Closing LaunchDarkly client")
// Normally all of the following components exist; but they could be nil if we errored out
// partway through the MakeCustomClient constructor, in which case we want to close whatever
// did get created so far.
if client.eventProcessor != nil {
_ = client.eventProcessor.Close()
}
if client.dataSystem != nil {
_ = client.dataSystem.Stop()
}
if client.bigSegmentStoreStatusBroadcaster != nil {
client.bigSegmentStoreStatusBroadcaster.Close()
}
if client.bigSegmentStoreWrapper != nil {
client.bigSegmentStoreWrapper.Close()
}
return nil
}
// Flush tells the client that all pending analytics events (if any) should be delivered as soon
// as possible. This flush is asynchronous, so this method will return before it is complete. To wait
// for the flush to complete, use [LDClient.FlushAndWait] instead (or, if you are done with the SDK,
// [LDClient.Close]).
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/flush#go
func (client *LDClient) Flush() {
client.eventProcessor.Flush()
}
// FlushAndWait tells the client to deliver any pending analytics events synchronously now.
//
// Unlike [LDClient.Flush], this method waits for event delivery to finish. The timeout parameter, if
// greater than zero, specifies the maximum amount of time to wait. If the timeout elapses before
// delivery is finished, the method returns early and returns false; in this case, the SDK may still
// continue trying to deliver the events in the background.
//
// If the timeout parameter is zero or negative, the method waits as long as necessary to deliver the
// events. However, the SDK does not retry event delivery indefinitely; currently, any network error
// or server error will cause the SDK to wait one second and retry one time, after which the events
// will be discarded so that the SDK will not keep consuming more memory for events indefinitely.
//
// The method returns true if event delivery either succeeded, or definitively failed, before the
// timeout elapsed. It returns false if the timeout elapsed.
//
// This method is also implicitly called if you call [LDClient.Close]. The difference is that
// FlushAndWait does not shut down the SDK client.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/flush#go
func (client *LDClient) FlushAndWait(timeout time.Duration) bool {
return client.eventProcessor.FlushBlocking(timeout)
}
// Loggers exposes the logging component used by the SDK.
//
// This allows users to easily log messages to a shared channel with the SDK.
func (client *LDClient) Loggers() interfaces.LDLoggers {
return client.loggers
}
// AllFlagsState returns an object that encapsulates the state of all feature flags for a given evaluation.
// context. This includes the flag values, and also metadata that can be used on the front end.
//
// The most common use case for this method is to bootstrap a set of client-side feature flags from a
// back-end service.
//
// You may pass any combination of [flagstate.ClientSideOnly], [flagstate.WithReasons], and
// [flagstate.DetailsOnlyForTrackedFlags] as optional parameters to control what data is included.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/all-flags#go
func (client *LDClient) AllFlagsState(context ldcontext.Context, options ...flagstate.Option) flagstate.AllFlags {
valid := true
if client.IsOffline() {
client.loggers.Warn("Called AllFlagsState in offline mode. Returning empty state")
valid = false
} else if client.dataSystem.DataAvailability() != datasystem.Refreshed {
if client.dataSystem.DataAvailability() == datasystem.Cached {
client.loggers.Warn("Called AllFlagsState before client initialization; using last known values from data store")
} else {
client.loggers.Warn("Called AllFlagsState before client initialization. Data store not available; returning empty state") //nolint:lll
valid = false
}
}
if !valid {
return flagstate.AllFlags{}
}
items, err := client.dataSystem.Store().GetAll(datakinds.Features)
if err != nil {
client.loggers.Warn("Unable to fetch flags from data store. Returning empty state. Error: " + err.Error())
return flagstate.AllFlags{}
}
clientSideOnly := false
for _, o := range options {
if o == flagstate.OptionClientSideOnly() {
clientSideOnly = true
break
}
}
state := flagstate.NewAllFlagsBuilder(options...)
for _, item := range items {
if item.Item.Item != nil {
if flag, ok := item.Item.Item.(*ldmodel.FeatureFlag); ok {
if clientSideOnly && !flag.ClientSideAvailability.UsingEnvironmentID {
continue
}
var prerequisites []string
result := client.evaluator.Evaluate(flag, context, func(event ldeval.PrerequisiteFlagEvent) {
if event.TargetFlagKey == flag.Key {
prerequisites = append(prerequisites, event.PrerequisiteFlag.Key)
}
})
state.AddFlag(
item.Key,
flagstate.FlagState{
Value: result.Detail.Value,
Variation: result.Detail.VariationIndex,
Reason: result.Detail.Reason,
Version: flag.Version,
TrackEvents: flag.TrackEvents || result.IsExperiment,
TrackReason: result.IsExperiment,
DebugEventsUntilDate: flag.DebugEventsUntilDate,
Prerequisites: prerequisites,
},
)
}
}
}
return state.Build()
}
// BoolVariation returns the value of a boolean feature flag for a given evaluation context.
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
// has no off variation.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) BoolVariation(key string, context ldcontext.Context, defaultVal bool) (bool, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.Bool(defaultVal), true,
client.eventsDefault, boolVarFuncName)
return detail.Value.BoolValue(), err
}
// BoolVariationDetail is the same as [LDClient.BoolVariation], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) BoolVariationDetail(
key string,
context ldcontext.Context,
defaultVal bool,
) (bool, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.Bool(defaultVal), true,
client.eventsWithReasons, boolVarDetailFuncName)
return detail.Value.BoolValue(), detail, err
}
// BoolVariationCtx is the same as [LDClient.BoolVariation], but accepts a context.Context.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
// has no off variation.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) BoolVariationCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal bool,
) (bool, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.Bool(defaultVal), true,
client.eventsDefault, boolVarExFuncName)
return detail.Value.BoolValue(), err
}
// BoolVariationDetailCtx is the same as [LDClient.BoolVariationCtx], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) BoolVariationDetailCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal bool,
) (bool, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.Bool(defaultVal), true,
client.eventsWithReasons, boolVarDetailExFuncName)
return detail.Value.BoolValue(), detail, err
}
// IntVariation returns the value of a feature flag (whose variations are integers) for the given evaluation
// context.
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
// has no off variation.
//
// If the flag variation has a numeric value that is not an integer, it is rounded toward zero (truncated).
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) IntVariation(key string, context ldcontext.Context, defaultVal int) (int, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.Int(defaultVal), true,
client.eventsDefault, intVarFuncName)
return detail.Value.IntValue(), err
}
// IntVariationDetail is the same as [LDClient.IntVariation], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) IntVariationDetail(
key string,
context ldcontext.Context,
defaultVal int,
) (int, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.Int(defaultVal), true,
client.eventsWithReasons, intVarDetailFuncName)
return detail.Value.IntValue(), detail, err
}
// IntVariationCtx is the same as [LDClient.IntVariation], but accepts a context.Context.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
// has no off variation.
//
// If the flag variation has a numeric value that is not an integer, it is rounded toward zero (truncated).
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) IntVariationCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal int,
) (int, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.Int(defaultVal), true,
client.eventsDefault, intVarExFuncName)
return detail.Value.IntValue(), err
}
// IntVariationDetailCtx is the same as [LDClient.IntVariationCtx], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) IntVariationDetailCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal int,
) (int, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.Int(defaultVal), true,
client.eventsWithReasons, intVarDetailExFuncName)
return detail.Value.IntValue(), detail, err
}
// Float64Variation returns the value of a feature flag (whose variations are floats) for the given evaluation
// context.
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
// has no off variation.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) Float64Variation(key string, context ldcontext.Context, defaultVal float64) (float64, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.Float64(defaultVal),
true, client.eventsDefault, floatVarFuncName)
return detail.Value.Float64Value(), err
}
// Float64VariationDetail is the same as [LDClient.Float64Variation], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) Float64VariationDetail(
key string,
context ldcontext.Context,
defaultVal float64,
) (float64, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.Float64(defaultVal),
true, client.eventsWithReasons, floatVarDetailFuncName)
return detail.Value.Float64Value(), detail, err
}
// Float64VariationCtx is the same as [LDClient.Float64Variation], but accepts a context.Context.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and
// has no off variation.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) Float64VariationCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal float64,
) (float64, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.Float64(defaultVal), true,
client.eventsDefault, floatVarExFuncName)
return detail.Value.Float64Value(), err
}
// Float64VariationDetailCtx is the same as [LDClient.Float64VariationCtx], but also returns further information about
// how the value was calculated. The "reason" data will also be included in analytics events.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) Float64VariationDetailCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal float64,
) (float64, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.Float64(defaultVal), true,
client.eventsWithReasons, floatVarDetailExFuncName)
return detail.Value.Float64Value(), detail, err
}
// StringVariation returns the value of a feature flag (whose variations are strings) for the given evaluation
// context.
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and has
// no off variation.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) StringVariation(key string, context ldcontext.Context, defaultVal string) (string, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.String(defaultVal), true,
client.eventsDefault, stringVarFuncName)
return detail.Value.StringValue(), err
}
// StringVariationDetail is the same as [LDClient.StringVariation], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) StringVariationDetail(
key string,
context ldcontext.Context,
defaultVal string,
) (string, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(gocontext.TODO(), key, context, ldvalue.String(defaultVal), true,
client.eventsWithReasons, stringVarDetailFuncName)
return detail.Value.StringValue(), detail, err
}
// StringVariationCtx is the same as [LDClient.StringVariation], but accepts a context.Context.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off and has
// no off variation.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) StringVariationCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal string,
) (string, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.String(defaultVal), true,
client.eventsDefault, stringVarExFuncName)
return detail.Value.StringValue(), err
}
// StringVariationDetailCtx is the same as [LDClient.StringVariationCtx], but also returns further information about how
// the value was calculated. The "reason" data will also be included in analytics events.
//
// Cancelling the context.Context will not cause the evaluation to be cancelled. The context.Context is used
// by hook implementations refer to [ldhooks.Hook].
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluation-reasons#go
func (client *LDClient) StringVariationDetailCtx(
ctx gocontext.Context,
key string,
context ldcontext.Context,
defaultVal string,
) (string, ldreason.EvaluationDetail, error) {
detail, _, err := client.variationWithHooks(ctx, key, context, ldvalue.String(defaultVal), true,
client.eventsWithReasons, stringVarDetailExFuncName)
return detail.Value.StringValue(), detail, err
}
// JSONVariation returns the value of a feature flag for the given evaluation context, allowing the value to
// be of any JSON type.
//
// The value is returned as an [ldvalue.Value], which can be inspected or converted to other types using
// methods such as [ldvalue.Value.GetType] and [ldvalue.Value.BoolValue]. The defaultVal parameter also uses this
// type. For instance, if the values for this flag are JSON arrays:
//
// defaultValAsArray := ldvalue.BuildArray().
// Add(ldvalue.String("defaultFirstItem")).
// Add(ldvalue.String("defaultSecondItem")).
// Build()
// result, err := client.JSONVariation(flagKey, context, defaultValAsArray)
// firstItemAsString := result.GetByIndex(0).StringValue() // "defaultFirstItem", etc.
//
// You can also use unparsed json.RawMessage values:
//
// defaultValAsRawJSON := ldvalue.Raw(json.RawMessage(`{"things":[1,2,3]}`))
// result, err := client.JSONVariation(flagKey, context, defaultValAsJSON
// resultAsRawJSON := result.AsRaw()
//
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off.
//
// For more information, see the Reference Guide: https://docs.launchdarkly.com/sdk/features/evaluating#go
func (client *LDClient) JSONVariation(