-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.go
561 lines (501 loc) · 20.1 KB
/
client.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
package statsig
import (
"errors"
"net/http"
"strings"
"time"
)
// An instance of a StatsigClient for interfacing with Statsig Feature Gates, Dynamic Configs, Experiments, and Event Logging
type Client struct {
sdkKey string
evaluator *evaluator
logger *logger
transport *transport
errorBoundary *errorBoundary
options *Options
diagnostics *diagnostics
}
// Initializes a Statsig Client with the given sdkKey
func NewClient(sdkKey string) *Client {
return NewClientWithOptions(sdkKey, &Options{})
}
// Initializes a Statsig Client with the given sdkKey and options
func NewClientWithOptions(sdkKey string, options *Options) *Client {
client, _ := newClientImpl(sdkKey, options)
return client
}
// Initializes a Statsig Client with the given sdkKey and options
// returning the initialized client and details of initialization
func NewClientWithDetails(sdkKey string, options *Options) (*Client, InitializeDetails) {
client, context := newClientImpl(sdkKey, options)
return client, InitializeDetails{
Duration: time.Since(context.Start),
Success: context.Success,
Error: context.Error,
Source: context.Source,
}
}
func newClientImpl(sdkKey string, options *Options) (*Client, *initContext) {
context := newInitContext()
diagnostics := newDiagnostics(options)
diagnostics.initialize().overall().start().mark()
errorBoundary := newErrorBoundary(sdkKey, options, diagnostics)
if !options.LocalMode && !strings.HasPrefix(sdkKey, "secret") {
err := errors.New(InvalidSDKKeyError)
panic(err)
}
transport := newTransport(sdkKey, options)
logger := newLogger(transport, options, diagnostics, errorBoundary)
evaluator := newEvaluator(transport, errorBoundary, options, diagnostics, sdkKey)
client := &Client{
sdkKey: sdkKey,
evaluator: evaluator,
logger: logger,
transport: transport,
errorBoundary: errorBoundary,
options: options,
diagnostics: diagnostics,
}
if options.InitTimeout > 0 {
channel := make(chan *Client, 1)
go func() {
client.init(context)
channel <- client
}()
select {
case res := <-channel:
diagnostics.initialize().overall().end().success(true).mark()
return res, context
case <-time.After(options.InitTimeout):
Logger().LogStep(StatsigProcessInitialize, "Timed out")
diagnostics.initialize().overall().end().success(false).reason("timeout").mark()
client.initInBackground()
ctx := context.copy() // Goroutines are not terminated upon timeout. Clone context to avoid race condition on setting Error
ctx.setError(errors.New("Timed out"))
return client, ctx
}
} else {
client.init(context)
}
diagnostics.initialize().overall().end().success(true).mark()
return client, context
}
func (c *Client) init(context *initContext) {
c.evaluator.initialize(context)
c.evaluator.store.mu.RLock()
defer c.evaluator.store.mu.RUnlock()
context.setSuccess(c.evaluator.store.source != SourceUninitialized)
context.setSource(c.evaluator.store.source)
}
func (c *Client) initInBackground() {
c.evaluator.store.startPolling()
}
// Checks the value of a Feature Gate for the given user
func (c *Client) CheckGate(user User, gate string) bool {
return c.errorBoundary.captureCheckGate(func(context *evalContext) FeatureGate {
return c.checkGateImpl(user, gate, context)
}, &evalContext{Caller: "checkGate", ConfigName: gate}).Value
}
// Checks the value of a Feature Gate for the given user without logging an exposure event
func (c *Client) CheckGateWithExposureLoggingDisabled(user User, gate string) bool {
return c.errorBoundary.captureCheckGate(func(context *evalContext) FeatureGate {
return c.checkGateImpl(user, gate, context)
}, &evalContext{Caller: "checkGateWithExposureLoggingDisabled", ConfigName: gate, DisableLogExposures: true}).Value
}
// Get the Feature Gate for the given user
func (c *Client) GetGate(user User, gate string) FeatureGate {
return c.errorBoundary.captureCheckGate(func(context *evalContext) FeatureGate {
return c.checkGateImpl(user, gate, context)
}, &evalContext{Caller: "getGate", ConfigName: gate})
}
// Checks the value of a Feature Gate for the given user without logging an exposure event
func (c *Client) GetGateWithExposureLoggingDisabled(user User, gate string) FeatureGate {
return c.errorBoundary.captureCheckGate(func(context *evalContext) FeatureGate {
return c.checkGateImpl(user, gate, context)
}, &evalContext{Caller: "getGateWithExposureLoggingDisabled", ConfigName: gate, DisableLogExposures: true})
}
// Logs an exposure event for the dynamic config
func (c *Client) ManuallyLogGateExposure(user User, gate string) {
c.errorBoundary.captureVoid(func(context *evalContext) {
if !c.verifyUser(user) {
return
}
user = normalizeUser(user, *c.options)
res := c.evaluator.evalGate(user, gate, context)
c.logger.logGateExposure(user, gate, res, context)
}, &evalContext{Caller: "logGateExposure", ConfigName: gate, IsManualExposure: true})
}
// Gets the DynamicConfig value for the given user
func (c *Client) GetConfig(user User, config string) DynamicConfig {
return c.errorBoundary.captureGetConfig(func(context *evalContext) DynamicConfig {
return c.getConfigImpl(user, config, context)
}, &evalContext{Caller: "getConfig", ConfigName: config})
}
// Gets the DynamicConfig value for the given user without logging an exposure event
func (c *Client) GetConfigWithExposureLoggingDisabled(user User, config string) DynamicConfig {
return c.errorBoundary.captureGetConfig(func(context *evalContext) DynamicConfig {
return c.getConfigImpl(user, config, context)
}, &evalContext{Caller: "getConfigWithExposureLoggingDisabled", ConfigName: config, DisableLogExposures: true})
}
// Logs an exposure event for the config
func (c *Client) ManuallyLogConfigExposure(user User, config string) {
c.errorBoundary.captureVoid(func(context *evalContext) {
if !c.verifyUser(user) {
return
}
user = normalizeUser(user, *c.options)
res := c.evaluator.evalConfig(user, config, context)
c.logger.logConfigExposure(user, config, res, context)
}, &evalContext{Caller: "logConfigExposure", ConfigName: config, IsManualExposure: true})
}
// Gets the layer name of an Experiment
func (c *Client) GetExperimentLayer(experiment string) (string, bool) {
return c.errorBoundary.captureGetExperimentLayer(func(context *evalContext) (string, bool) {
return c.evaluator.store.getExperimentLayer(experiment)
}, &evalContext{Caller: "getExperimentLayer", ConfigName: experiment})
}
// Gets the DynamicConfig value of an Experiment for the given user
func (c *Client) GetExperiment(user User, experiment string) DynamicConfig {
return c.errorBoundary.captureGetConfig(func(context *evalContext) DynamicConfig {
return c.getConfigImpl(user, experiment, context)
}, &evalContext{Caller: "getExperiment", ConfigName: experiment, IsExperiment: true})
}
// Gets the DynamicConfig value of an Experiment for the given user without logging an exposure event
func (c *Client) GetExperimentWithExposureLoggingDisabled(user User, experiment string) DynamicConfig {
return c.errorBoundary.captureGetConfig(func(context *evalContext) DynamicConfig {
return c.getConfigImpl(user, experiment, context)
}, &evalContext{Caller: "getExperimentWithExposureLoggingDisabled", ConfigName: experiment, IsExperiment: true, DisableLogExposures: true})
}
// Gets the DynamicConfig value of an Experiment for the given user with configurable options
func (c *Client) GetExperimentWithOptions(user User, experiment string, options *GetExperimentOptions) DynamicConfig {
return c.errorBoundary.captureGetConfig(func(context *evalContext) DynamicConfig {
return c.getConfigImpl(user, experiment, context)
}, &evalContext{
Caller: "getExperimentWithOptions",
ConfigName: experiment,
IsExperiment: true,
DisableLogExposures: options.DisableLogExposures,
PersistedValues: options.PersistedValues,
})
}
// Logs an exposure event for the experiment
func (c *Client) ManuallyLogExperimentExposure(user User, experiment string) {
c.ManuallyLogConfigExposure(user, experiment)
}
func (c *Client) GetUserPersistedValues(user User, idType string) UserPersistedValues {
return c.errorBoundary.captureGetUserPersistedValues(func(context *errorContext) UserPersistedValues {
persistedValues := c.evaluator.persistentStorageUtils.load(user, idType)
if persistedValues == nil {
return make(UserPersistedValues)
} else {
return persistedValues
}
}, &errorContext{Caller: "GetUserPersistedValues"})
}
// Gets the Layer object for the given user
func (c *Client) GetLayer(user User, layer string) Layer {
return c.errorBoundary.captureGetLayer(func(context *evalContext) Layer {
return c.getLayerImpl(user, layer, context)
}, &evalContext{Caller: "getLayer", ConfigName: layer})
}
// Gets the Layer object for the given user without logging an exposure event
func (c *Client) GetLayerWithExposureLoggingDisabled(user User, layer string) Layer {
return c.errorBoundary.captureGetLayer(func(context *evalContext) Layer {
return c.getLayerImpl(user, layer, context)
}, &evalContext{Caller: "getLayerWithExposureLoggingDisabled", ConfigName: layer, DisableLogExposures: true})
}
// Gets the Layer object for the given user with configurable options
func (c *Client) GetLayerWithOptions(user User, layer string, options *GetLayerOptions) Layer {
return c.errorBoundary.captureGetLayer(func(context *evalContext) Layer {
return c.getLayerImpl(user, layer, context)
}, &evalContext{
Caller: "getLayerWithOptions",
ConfigName: layer,
DisableLogExposures: options.DisableLogExposures,
PersistedValues: options.PersistedValues,
})
}
// Logs an exposure event for the parameter in the given layer
func (c *Client) ManuallyLogLayerParameterExposure(user User, layer string, parameter string) {
c.errorBoundary.captureVoid(func(context *evalContext) {
if !c.verifyUser(user) {
return
}
user = normalizeUser(user, *c.options)
res := c.evaluator.evalLayer(user, layer, context)
config := NewLayer(layer, res.JsonValue, res.RuleID, res.GroupName, nil, res.ConfigDelegate)
c.logger.logLayerExposure(user, *config, parameter, res, context)
}, &evalContext{Caller: "logLayerParameterExposure", ConfigName: layer, IsManualExposure: true})
}
// Logs an event to Statsig for analysis in the Statsig Console
func (c *Client) LogEvent(event Event) {
c.errorBoundary.captureVoid(func(context *evalContext) {
event.User = normalizeUser(event.User, *c.options)
if event.EventName == "" {
return
}
c.logger.logCustom(event)
}, &evalContext{Caller: "logEvent"})
}
// Override the value of a Feature Gate for the given user
func (c *Client) OverrideGate(gate string, val bool) {
c.errorBoundary.captureVoid(func(context *evalContext) {
c.evaluator.OverrideGate(gate, val)
}, &evalContext{Caller: "overrideGate", ConfigName: gate})
}
// Override the DynamicConfig value for the given user
func (c *Client) OverrideConfig(config string, val map[string]interface{}) {
c.errorBoundary.captureVoid(func(context *evalContext) {
c.evaluator.OverrideConfig(config, val)
}, &evalContext{Caller: "overrideConfig", ConfigName: config})
}
// Override the Layer value for the given user
func (c *Client) OverrideLayer(layer string, val map[string]interface{}) {
c.errorBoundary.captureVoid(func(context *evalContext) {
c.evaluator.OverrideLayer(layer, val)
}, &evalContext{Caller: "overrideLayer", ConfigName: layer})
}
func (c *Client) LogImmediate(events []Event) (*http.Response, error) {
if len(events) > 500 {
err := errors.New(EventBatchSizeError)
return nil, err
}
events_processed := make([]interface{}, 0)
for _, event := range events {
event.User = normalizeUser(event.User, *c.options)
events_processed = append(events_processed, event)
}
return c.transport.log_event(events_processed, nil, RequestOptions{})
}
func (c *Client) GetClientInitializeResponse(user User, clientKey string, includeLocalOverrides bool) ClientInitializeResponse {
options := &GCIROptions{
IncludeLocalOverrides: includeLocalOverrides,
ClientKey: clientKey,
HashAlgorithm: "sha256",
}
return c.GetClientInitializeResponseImpl(user, options)
}
func (c *Client) GetClientInitializeResponseWithOptions(user User, options *GCIROptions) ClientInitializeResponse {
return c.GetClientInitializeResponseImpl(user, options)
}
func (c *Client) GetClientInitializeResponseImpl(user User, options *GCIROptions) ClientInitializeResponse {
return c.errorBoundary.captureGetClientInitializeResponse(func(context *evalContext) ClientInitializeResponse {
if !c.verifyUser(user) {
return *new(ClientInitializeResponse)
}
user = normalizeUser(user, *c.options)
response := c.evaluator.getClientInitializeResponse(user, context)
if response.Time == 0 {
c.errorBoundary.logExceptionWithContext(
errors.New("empty response from server"),
errorContext{evalContext: context},
)
}
return response
}, &evalContext{
Caller: "getClientInitializeResponse",
IncludeLocalOverrides: options.IncludeLocalOverrides,
ClientKey: options.ClientKey,
TargetAppID: options.TargetAppID,
Hash: options.HashAlgorithm,
})
}
func (c *Client) verifyUser(user User) bool {
if user.UserID == "" && len(user.CustomIDs) == 0 {
err := errors.New(EmptyUserError)
Logger().LogError(err)
return false
}
return true
}
// Cleans up Statsig, persisting any Event Logs and cleanup processes
// Using any method is undefined after Shutdown() has been called
func (c *Client) Shutdown() {
c.errorBoundary.captureVoid(func(context *evalContext) {
c.logger.flush(true)
c.evaluator.shutdown()
}, &evalContext{Caller: "shutdown"})
}
type GetExperimentOptions struct {
DisableLogExposures bool
PersistedValues UserPersistedValues
}
type GetLayerOptions struct {
DisableLogExposures bool
PersistedValues UserPersistedValues
}
type gateResponse struct {
Name string `json:"name"`
Value bool `json:"value"`
RuleID string `json:"rule_id"`
}
type configResponse struct {
Name string `json:"name"`
Value map[string]interface{} `json:"value"`
RuleID string `json:"rule_id"`
}
type checkGateInput struct {
GateName string `json:"gateName"`
User User `json:"user"`
StatsigMetadata statsigMetadata `json:"statsigMetadata"`
}
type getConfigInput struct {
ConfigName string `json:"configName"`
User User `json:"user"`
StatsigMetadata statsigMetadata `json:"statsigMetadata"`
}
func (c *Client) checkGateImpl(user User, name string, context *evalContext) FeatureGate {
if !c.verifyUser(user) {
return *NewGate(name, false, "", "", nil)
}
user = normalizeUser(user, *c.options)
res := c.evaluator.evalGate(user, name, context)
if res.FetchFromServer {
serverRes := fetchGate(user, name, c.transport)
res = &evalResult{Value: serverRes.Value, RuleID: serverRes.RuleID}
} else {
exposure := c.logger.getGateExposureWithEvaluationDetails(user, name, res, context)
if !context.DisableLogExposures {
c.logger.logExposure(*exposure)
}
if c.options.EvaluationCallbacks.GateEvaluationCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.GateEvaluationCallback(name, res.Value, exposure)
} else {
c.options.EvaluationCallbacks.GateEvaluationCallback(name, res.Value, nil)
}
}
if c.options.EvaluationCallbacks.ExposureCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.ExposureCallback(name, exposure)
} else {
c.options.EvaluationCallbacks.ExposureCallback(name, nil)
}
}
}
return *NewGate(name, res.Value, res.RuleID, res.GroupName, res.EvaluationDetails)
}
func (c *Client) getConfigImpl(user User, name string, context *evalContext) DynamicConfig {
if !c.verifyUser(user) {
return *NewConfig(name, nil, "", "", nil)
}
user = normalizeUser(user, *c.options)
res := c.evaluator.evalConfig(user, name, context)
config := *NewConfig(name, res.JsonValue, res.RuleID, res.GroupName, res.EvaluationDetails)
if res.FetchFromServer {
res = c.fetchConfigFromServer(user, name)
config = *NewConfig(name, res.JsonValue, res.RuleID, res.GroupName, res.EvaluationDetails)
} else {
exposure := c.logger.getConfigExposureWithEvaluationDetails(user, name, res, context)
if !context.DisableLogExposures {
c.logger.logExposure(*exposure)
}
if context.IsExperiment && c.options.EvaluationCallbacks.ExperimentEvaluationCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.ExperimentEvaluationCallback(name, config, exposure)
} else {
c.options.EvaluationCallbacks.ExperimentEvaluationCallback(name, config, nil)
}
} else if c.options.EvaluationCallbacks.ConfigEvaluationCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.ConfigEvaluationCallback(name, config, exposure)
} else {
c.options.EvaluationCallbacks.ConfigEvaluationCallback(name, config, nil)
}
}
if c.options.EvaluationCallbacks.ExposureCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.ExposureCallback(name, exposure)
} else {
c.options.EvaluationCallbacks.ExposureCallback(name, nil)
}
}
}
return config
}
func (c *Client) getLayerImpl(user User, name string, context *evalContext) Layer {
if !c.verifyUser(user) {
return *NewLayer(name, nil, "", "", nil, "")
}
user = normalizeUser(user, *c.options)
res := c.evaluator.evalLayer(user, name, context)
if res.FetchFromServer {
res = c.fetchConfigFromServer(user, name)
}
logFunc := func(layer Layer, parameterName string) {
exposure := c.logger.getLayerExposureWithEvaluationDetails(user, layer, parameterName, res, context)
if !context.DisableLogExposures {
c.logger.logExposure(*exposure)
}
if c.options.EvaluationCallbacks.LayerEvaluationCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.LayerEvaluationCallback(name, parameterName, DynamicConfig{layer.configBase}, exposure)
} else {
c.options.EvaluationCallbacks.LayerEvaluationCallback(name, parameterName, DynamicConfig{layer.configBase}, nil)
}
}
if c.options.EvaluationCallbacks.ExposureCallback != nil {
if c.options.EvaluationCallbacks.IncludeDisabledExposures || !context.DisableLogExposures {
c.options.EvaluationCallbacks.ExposureCallback(name, exposure)
} else {
c.options.EvaluationCallbacks.ExposureCallback(name, nil)
}
}
}
return *NewLayer(name, res.JsonValue, res.RuleID, res.GroupName, &logFunc, res.ConfigDelegate)
}
func fetchGate(user User, gateName string, t *transport) gateResponse {
input := &checkGateInput{
GateName: gateName,
User: user,
StatsigMetadata: t.metadata,
}
var res gateResponse
_, err := t.post("/check_gate", input, &res, RequestOptions{}, nil)
if err != nil {
return gateResponse{
Name: gateName,
Value: false,
RuleID: "",
}
}
return res
}
func fetchConfig(user User, configName string, t *transport) configResponse {
input := &getConfigInput{
ConfigName: configName,
User: user,
StatsigMetadata: t.metadata,
}
var res configResponse
_, err := t.post("/get_config", input, &res, RequestOptions{}, nil)
if err != nil {
return configResponse{
Name: configName,
RuleID: "",
}
}
return res
}
func normalizeUser(user User, options Options) User {
env := make(map[string]string)
// Copy to avoid data race. We modify the map below.
for k, v := range options.Environment.Params {
env[k] = v
}
if options.Environment.Tier != "" {
env["tier"] = options.Environment.Tier
}
for k, v := range user.StatsigEnvironment {
env[k] = v
}
user.StatsigEnvironment = env
return user
}
func (c *Client) fetchConfigFromServer(user User, configName string) *evalResult {
serverRes := fetchConfig(user, configName, c.transport)
return &evalResult{
JsonValue: serverRes.Value,
RuleID: serverRes.RuleID,
}
}