forked from statsig-io/go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
450 lines (402 loc) · 14.7 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
package statsig
import (
"errors"
"fmt"
"net/http"
"strings"
)
// 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 {
diagnostics := newDiagnostics(options)
diagnostics.initialize().overall().start().mark()
if len(options.API) == 0 {
options.API = "https://statsigapi.net/v1"
}
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)
evaluator := newEvaluator(transport, errorBoundary, options, diagnostics, sdkKey)
diagnostics.initialize().overall().end().success(true).mark()
return &Client{
sdkKey: sdkKey,
evaluator: evaluator,
logger: logger,
transport: transport,
errorBoundary: errorBoundary,
options: options,
diagnostics: diagnostics,
}
}
// Checks the value of a Feature Gate for the given user
func (c *Client) CheckGate(user User, gate string) bool {
options := checkGateOptions{disableLogExposures: false}
return c.checkGateImpl(user, gate, options).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 {
options := checkGateOptions{disableLogExposures: true}
return c.checkGateImpl(user, gate, options).Value
}
// Get the Feature Gate for the given user
func (c *Client) GetGate(user User, gate string) FeatureGate {
options := checkGateOptions{disableLogExposures: false}
return c.checkGateImpl(user, gate, options)
}
// 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 {
options := checkGateOptions{disableLogExposures: true}
return c.checkGateImpl(user, gate, options)
}
// Logs an exposure event for the dynamic config
func (c *Client) ManuallyLogGateExposure(user User, gate string) {
c.errorBoundary.captureVoid(func() {
if !c.verifyUser(user) {
return
}
user = normalizeUser(user, *c.options)
res := c.evaluator.checkGate(user, gate)
context := &logContext{isManualExposure: true}
c.logger.logGateExposure(user, gate, res.Pass, res.RuleID, res.SecondaryExposures, res.EvaluationDetails, context)
})
}
// Gets the DynamicConfig value for the given user
func (c *Client) GetConfig(user User, config string) DynamicConfig {
options := &getConfigOptions{disableLogExposures: false}
context := getConfigImplContext{configOptions: options}
return c.getConfigImpl(user, config, context)
}
// Gets the DynamicConfig value for the given user without logging an exposure event
func (c *Client) GetConfigWithExposureLoggingDisabled(user User, config string) DynamicConfig {
options := &getConfigOptions{disableLogExposures: true}
context := getConfigImplContext{configOptions: options}
return c.getConfigImpl(user, config, context)
}
// Logs an exposure event for the config
func (c *Client) ManuallyLogConfigExposure(user User, config string) {
c.errorBoundary.captureVoid(func() {
if !c.verifyUser(user) {
return
}
user = normalizeUser(user, *c.options)
res := c.evaluator.getConfig(user, config, nil)
context := &logContext{isManualExposure: true}
c.logger.logConfigExposure(user, config, res.RuleID, res.SecondaryExposures, res.EvaluationDetails, context)
})
}
// Gets the DynamicConfig value of an Experiment for the given user
func (c *Client) GetExperiment(user User, experiment string) DynamicConfig {
if !c.verifyUser(user) {
return *NewConfig(experiment, nil, "", "", nil)
}
options := &GetExperimentOptions{DisableLogExposures: false}
context := getConfigImplContext{experimentOptions: options}
return c.getConfigImpl(user, experiment, context)
}
// 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 {
if !c.verifyUser(user) {
return *NewConfig(experiment, nil, "", "", nil)
}
options := &GetExperimentOptions{DisableLogExposures: true}
context := getConfigImplContext{experimentOptions: options}
return c.getConfigImpl(user, experiment, context)
}
// 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 {
if !c.verifyUser(user) {
return *NewConfig(experiment, nil, "", "", nil)
}
context := getConfigImplContext{experimentOptions: options}
return c.getConfigImpl(user, experiment, context)
}
// 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() UserPersistedValues {
persistedValues := c.evaluator.persistentStorageUtils.getUserPersistedValues(user, idType)
if persistedValues == nil {
return make(UserPersistedValues)
} else {
return persistedValues
}
})
}
// Gets the Layer object for the given user
func (c *Client) GetLayer(user User, layer string) Layer {
options := getLayerOptions{disableLogExposures: false}
return c.getLayerImpl(user, layer, options)
}
// Gets the Layer object for the given user without logging an exposure event
func (c *Client) GetLayerWithExposureLoggingDisabled(user User, layer string) Layer {
options := getLayerOptions{disableLogExposures: true}
return c.getLayerImpl(user, layer, options)
}
// 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() {
if !c.verifyUser(user) {
return
}
user = normalizeUser(user, *c.options)
res := c.evaluator.getLayer(user, layer)
config := NewLayer(layer, res.ConfigValue.Value, res.ConfigValue.RuleID, res.ConfigValue.GroupName, nil).configBase
context := &logContext{isManualExposure: true}
c.logger.logLayerExposure(user, config, parameter, *res, res.EvaluationDetails, context)
})
}
// Logs an event to Statsig for analysis in the Statsig Console
func (c *Client) LogEvent(event Event) {
c.errorBoundary.captureVoid(func() {
event.User = normalizeUser(event.User, *c.options)
if event.EventName == "" {
return
}
c.logger.logCustom(event)
})
}
// Override the value of a Feature Gate for the given user
func (c *Client) OverrideGate(gate string, val bool) {
c.errorBoundary.captureVoid(func() { c.evaluator.OverrideGate(gate, val) })
}
// Override the DynamicConfig value for the given user
func (c *Client) OverrideConfig(config string, val map[string]interface{}) {
c.errorBoundary.captureVoid(func() { c.evaluator.OverrideConfig(config, val) })
}
// Override the Layer value for the given user
func (c *Client) OverrideLayer(layer string, val map[string]interface{}) {
c.errorBoundary.captureVoid(func() { c.evaluator.OverrideLayer(layer, val) })
}
func (c *Client) LogImmediate(events []Event) (*http.Response, error) {
if len(events) > 500 {
err := errors.New(EventBatchSizeError)
return nil, fmt.Errorf(err.Error())
}
events_processed := make([]interface{}, 0)
for _, event := range events {
event.User = normalizeUser(event.User, *c.options)
events_processed = append(events_processed, event)
}
input := logEventInput{
Events: events_processed,
StatsigMetadata: c.transport.metadata,
}
return c.transport.post("/log_event", input, nil, RequestOptions{})
}
func (c *Client) GetClientInitializeResponse(user User, clientKey string) ClientInitializeResponse {
return c.errorBoundary.captureGetClientInitializeResponse(func() ClientInitializeResponse {
if !c.verifyUser(user) {
return *new(ClientInitializeResponse)
}
user = normalizeUser(user, *c.options)
return c.evaluator.getClientInitializeResponse(user, clientKey)
})
}
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() {
c.logger.flush(true)
c.evaluator.shutdown()
})
}
type checkGateOptions struct {
disableLogExposures bool
}
type getConfigOptions struct {
disableLogExposures bool
}
type GetExperimentOptions struct {
DisableLogExposures bool
PersistedValues UserPersistedValues
}
type getLayerOptions struct {
disableLogExposures bool
}
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, gate string, options checkGateOptions) FeatureGate {
return c.errorBoundary.captureCheckGate(func() FeatureGate {
if !c.verifyUser(user) {
return *NewGate(gate, false, "", "")
}
user = normalizeUser(user, *c.options)
res := c.evaluator.checkGate(user, gate)
if res.FetchFromServer {
serverRes := fetchGate(user, gate, c.transport)
res = &evalResult{Pass: serverRes.Value, RuleID: serverRes.RuleID}
} else {
var exposure *ExposureEvent = nil
if !options.disableLogExposures {
context := &logContext{isManualExposure: false}
exposure = c.logger.logGateExposure(user, gate, res.Pass, res.RuleID, res.SecondaryExposures, res.EvaluationDetails, context)
}
if c.options.EvaluationCallbacks.GateEvaluationCallback != nil {
c.options.EvaluationCallbacks.GateEvaluationCallback(gate, res.Pass, exposure)
}
}
return *NewGate(gate, res.Pass, res.RuleID, res.GroupName)
})
}
type getConfigImplContext struct {
configOptions *getConfigOptions
experimentOptions *GetExperimentOptions
}
func (c *Client) getConfigImpl(user User, config string, context getConfigImplContext) DynamicConfig {
return c.errorBoundary.captureGetConfig(func() DynamicConfig {
if !c.verifyUser(user) {
return *NewConfig(config, nil, "", "", nil)
}
isExperiment := context.experimentOptions != nil
var persistedValues UserPersistedValues
if isExperiment {
persistedValues = context.experimentOptions.PersistedValues
}
user = normalizeUser(user, *c.options)
res := c.evaluator.getConfig(user, config, persistedValues)
if res.FetchFromServer {
res = c.fetchConfigFromServer(user, config)
} else {
var exposure *ExposureEvent = nil
var logExposure bool
if isExperiment {
logExposure = !context.experimentOptions.DisableLogExposures
} else {
logExposure = !context.configOptions.disableLogExposures
}
if logExposure {
context := &logContext{isManualExposure: false}
exposure = c.logger.logConfigExposure(user, config, res.RuleID, res.SecondaryExposures, res.EvaluationDetails, context)
}
if isExperiment && c.options.EvaluationCallbacks.ExperimentEvaluationCallback != nil {
c.options.EvaluationCallbacks.ExperimentEvaluationCallback(config, res.ConfigValue, exposure)
} else if c.options.EvaluationCallbacks.ConfigEvaluationCallback != nil {
c.options.EvaluationCallbacks.ConfigEvaluationCallback(config, res.ConfigValue, exposure)
}
}
return res.ConfigValue
})
}
func (c *Client) getLayerImpl(user User, layer string, options getLayerOptions) Layer {
return c.errorBoundary.captureGetLayer(func() Layer {
if !c.verifyUser(user) {
return *NewLayer(layer, nil, "", "", nil)
}
user = normalizeUser(user, *c.options)
res := c.evaluator.getLayer(user, layer)
if res.FetchFromServer {
res = c.fetchConfigFromServer(user, layer)
}
logFunc := func(config configBase, parameterName string) {
var exposure *ExposureEvent = nil
if !options.disableLogExposures {
context := &logContext{isManualExposure: false}
exposure = c.logger.logLayerExposure(user, config, parameterName, *res, res.EvaluationDetails, context)
}
if c.options.EvaluationCallbacks.LayerEvaluationCallback != nil {
c.options.EvaluationCallbacks.LayerEvaluationCallback(layer, parameterName, res.ConfigValue, exposure)
}
}
return *NewLayer(layer, res.ConfigValue.Value, res.ConfigValue.RuleID, res.ConfigValue.GroupName, &logFunc)
})
}
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{})
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{})
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{
ConfigValue: *NewConfig(configName, serverRes.Value, serverRes.RuleID, "", nil),
RuleID: serverRes.RuleID,
}
}