/
events.go
349 lines (293 loc) · 7.83 KB
/
events.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
package ldclient
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"math/rand"
"net/http"
"sync"
"time"
)
type eventProcessor struct {
queue []Event
sdkKey string
config Config
closed bool
mu *sync.Mutex
client *http.Client
closer chan struct{}
}
type Event interface {
GetBase() BaseEvent
GetKind() string
}
type BaseEvent struct {
CreationDate uint64 `json:"creationDate"`
Key string `json:"key"`
Kind string `json:"kind"`
User User `json:"user"`
}
type FeatureRequestEvent struct {
BaseEvent
Value interface{} `json:"value"`
Default interface{} `json:"default"`
Version *int `json:"version,omitempty"`
PrereqOf *string `json:"prereqOf,omitempty"`
}
const (
FEATURE_REQUEST_EVENT = "feature"
CUSTOM_EVENT = "custom"
IDENTIFY_EVENT = "identify"
)
func newEventProcessor(sdkKey string, config Config) *eventProcessor {
res := &eventProcessor{
queue: make([]Event, 0),
sdkKey: sdkKey,
config: config,
client: &http.Client{},
closer: make(chan struct{}),
mu: &sync.Mutex{},
}
go func() {
if err := recover(); err != nil {
res.config.Logger.Printf("Unexpected panic in event processing thread: %+v", err)
}
ticker := time.NewTicker(config.FlushInterval)
for {
select {
case <-ticker.C:
res.flush()
case <-res.closer:
ticker.Stop()
return
}
}
}()
return res
}
func (ep *eventProcessor) close() {
ep.mu.Lock()
closed := ep.closed
ep.closed = true
ep.mu.Unlock()
if !closed {
close(ep.closer)
ep.flush()
}
}
func (ep *eventProcessor) flush() {
uri := ep.config.EventsUri + "/bulk"
ep.mu.Lock()
if len(ep.queue) == 0 || ep.closed {
ep.mu.Unlock()
return
}
events := ep.queue
ep.queue = make([]Event, 0)
ep.mu.Unlock()
payload, marshalErr := json.Marshal(events)
if marshalErr != nil {
ep.config.Logger.Printf("Unexpected error marshalling event json: %+v", marshalErr)
}
req, reqErr := http.NewRequest("POST", uri, bytes.NewReader(payload))
if reqErr != nil {
ep.config.Logger.Printf("Unexpected error while creating event request: %+v", reqErr)
}
req.Header.Add("Authorization", ep.sdkKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", "GoClient/"+Version)
resp, respErr := ep.client.Do(req)
defer func() {
if resp != nil && resp.Body != nil {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
}()
if respErr != nil {
ep.config.Logger.Printf("Unexpected error while sending events: %+v", respErr)
return
}
err := checkStatusCode(resp.StatusCode, uri)
if err != nil {
ep.config.Logger.Printf("Unexpected status code when sending events: %+v", err)
if err != nil && err.Code == 401 {
ep.config.Logger.Printf("Received 401 error, no further events will be posted since SDK key is invalid")
ep.mu.Lock()
ep.closed = true
ep.mu.Unlock()
}
}
}
func (ep *eventProcessor) sendEvent(evt Event) error {
if !ep.config.SendEvents {
return nil
}
if ep.config.SamplingInterval > 0 && rand.Int31n(ep.config.SamplingInterval) != 0 {
return nil
}
scrubbedUser := scrubUser(evt.GetBase().User, ep.config.AllAttributesPrivate, ep.config.PrivateAttributeNames)
var newEvent Event
switch evt := evt.(type) {
case FeatureRequestEvent:
evt.User = scrubbedUser
newEvent = evt
case CustomEvent:
evt.User = scrubbedUser
newEvent = evt
case IdentifyEvent:
evt.User = scrubbedUser
newEvent = evt
default:
return errors.New("unknown event type")
}
ep.mu.Lock()
defer ep.mu.Unlock()
if ep.closed {
return nil
}
if len(ep.queue) >= ep.config.Capacity {
return errors.New("Exceeded event queue capacity. Increase capacity to avoid dropping events.")
}
ep.queue = append(ep.queue, newEvent)
return nil
}
// Used to just create the event. Normally, you don't need to call this;
// the event is created and queued automatically during feature flag evaluation.
func NewFeatureRequestEvent(key string, user User, value, defaultVal interface{}, version *int, prereqOf *string) FeatureRequestEvent {
return FeatureRequestEvent{
BaseEvent: BaseEvent{
CreationDate: now(),
Key: key,
User: user,
Kind: FEATURE_REQUEST_EVENT,
},
Value: value,
Default: defaultVal,
Version: version,
PrereqOf: prereqOf,
}
}
func (evt FeatureRequestEvent) GetBase() BaseEvent {
return evt.BaseEvent
}
func (evt FeatureRequestEvent) GetKind() string {
return evt.Kind
}
type CustomEvent struct {
BaseEvent
Data interface{} `json:"data"`
}
// Constructs a new custom event, but does not send it. Typically, Track should be used to both create the
// event and send it to LaunchDarkly.
func NewCustomEvent(key string, user User, data interface{}) CustomEvent {
return CustomEvent{
BaseEvent: BaseEvent{
CreationDate: now(),
Key: key,
User: user,
Kind: CUSTOM_EVENT,
},
Data: data,
}
}
func (evt CustomEvent) GetBase() BaseEvent {
return evt.BaseEvent
}
func (evt CustomEvent) GetKind() string {
return evt.Kind
}
type IdentifyEvent struct {
BaseEvent
}
// Constructs a new identify event, but does not send it. Typically, Identify should be used to both create the
// event and send it to LaunchDarkly.
func NewIdentifyEvent(user User) IdentifyEvent {
var key string
if user.Key == nil {
key = ""
} else {
key = *user.Key
}
return IdentifyEvent{
BaseEvent: BaseEvent{
CreationDate: now(),
Key: key,
User: user,
Kind: IDENTIFY_EVENT,
},
}
}
func (evt IdentifyEvent) GetBase() BaseEvent {
return evt.BaseEvent
}
func (evt IdentifyEvent) GetKind() string {
return evt.Kind
}
func now() uint64 {
return toUnixMillis(time.Now())
}
func toUnixMillis(t time.Time) uint64 {
ms := time.Duration(t.UnixNano()) / time.Millisecond
return uint64(ms)
}
func scrubUser(user User, allAttributesPrivate bool, globalPrivateAttributes []string) User {
user.PrivateAttributes = nil
if len(user.PrivateAttributeNames) == 0 && len(globalPrivateAttributes) == 0 && !allAttributesPrivate {
return user
}
isPrivate := map[string]bool{}
for _, n := range globalPrivateAttributes {
isPrivate[n] = true
}
for _, n := range user.PrivateAttributeNames {
isPrivate[n] = true
}
if user.Custom != nil {
var custom = map[string]interface{}{}
for k, v := range *user.Custom {
if allAttributesPrivate || isPrivate[k] {
user.PrivateAttributes = append(user.PrivateAttributes, k)
} else {
custom[k] = v
}
}
user.Custom = &custom
}
if !isEmpty(user.Avatar) && (allAttributesPrivate || isPrivate["avatar"]) {
user.Avatar = nil
user.PrivateAttributes = append(user.PrivateAttributes, "avatar")
}
if !isEmpty(user.Country) && (allAttributesPrivate || isPrivate["country"]) {
user.Country = nil
user.PrivateAttributes = append(user.PrivateAttributes, "country")
}
if !isEmpty(user.Ip) && (allAttributesPrivate || isPrivate["ip"]) {
user.Ip = nil
user.PrivateAttributes = append(user.PrivateAttributes, "ip")
}
if !isEmpty(user.FirstName) && (allAttributesPrivate || isPrivate["firstName"]) {
user.FirstName = nil
user.PrivateAttributes = append(user.PrivateAttributes, "firstName")
}
if !isEmpty(user.LastName) && (allAttributesPrivate || isPrivate["lastName"]) {
user.LastName = nil
user.PrivateAttributes = append(user.PrivateAttributes, "lastName")
}
if !isEmpty(user.Name) && (allAttributesPrivate || isPrivate["name"]) {
user.Name = nil
user.PrivateAttributes = append(user.PrivateAttributes, "name")
}
if !isEmpty(user.Secondary) && (allAttributesPrivate || isPrivate["secondary"]) {
user.Secondary = nil
user.PrivateAttributes = append(user.PrivateAttributes, "secondary")
}
if !isEmpty(user.Email) && (allAttributesPrivate || isPrivate["email"]) {
user.Email = nil
user.PrivateAttributes = append(user.PrivateAttributes, "email")
}
return user
}
func isEmpty(s *string) bool {
return s == nil || *s == ""
}