forked from PostHog/posthog-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
posthog.go
560 lines (475 loc) · 14 KB
/
posthog.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
package posthog
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
"time"
)
const unimplementedError = "not implemented"
const SIZE_DEFAULT = 50_000
// This interface is the main API exposed by the posthog package.
// Values that satsify this interface are returned by the client constructors
// provided by the package and provide a way to send messages via the HTTP API.
type Client interface {
io.Closer
// Queues a message to be sent by the client when the conditions for a batch
// upload are met.
// This is the main method you'll be using, a typical flow would look like
// this:
//
// client := posthog.New(apiKey)
// ...
// client.Enqueue(posthog.Capture{ ... })
// ...
// client.Close()
//
// The method returns an error if the message queue could not be queued, which
// happens if the client was already closed at the time the method was
// called or if the message was malformed.
Enqueue(Message) error
//
// Method returns if a feature flag is on for a given user based on their distinct ID
IsFeatureEnabled(FeatureFlagPayload) (interface{}, error)
//
// Method returns variant value if multivariantflag or otherwise a boolean indicating
// if the given flag is on or off for the user
GetFeatureFlag(FeatureFlagPayload) (interface{}, error)
//
// Method forces a reload of feature flags
ReloadFeatureFlags() error
//
// Get feature flags - for testing only
GetFeatureFlags() ([]FeatureFlag, error)
//
// Get all flags - returns all flags for a user
GetAllFlags(FeatureFlagPayloadNoKey) (map[string]interface{}, error)
}
type client struct {
Config
key string
// This channel is where the `Enqueue` method writes messages so they can be
// picked up and pushed by the backend goroutine taking care of applying the
// batching rules.
msgs chan APIMessage
// These two channels are used to synchronize the client shutting down when
// `Close` is called.
// The first channel is closed to signal the backend goroutine that it has
// to stop, then the second one is closed by the backend goroutine to signal
// that it has finished flushing all queued messages.
quit chan struct{}
shutdown chan struct{}
// This HTTP client is used to send requests to the backend, it uses the
// HTTP transport provided in the configuration.
http http.Client
// A background poller for fetching feature flags
featureFlagsPoller *FeatureFlagsPoller
distinctIdsFeatureFlagsReported *SizeLimitedMap
}
// Instantiate a new client that uses the write key passed as first argument to
// send messages to the backend.
// The client is created with the default configuration.
func New(apiKey string) Client {
// Here we can ignore the error because the default config is always valid.
c, _ := NewWithConfig(apiKey, Config{})
return c
}
// Instantiate a new client that uses the write key and configuration passed as
// arguments to send messages to the backend.
// The function will return an error if the configuration contained impossible
// values (like a negative flush interval for example).
// When the function returns an error the returned client will always be nil.
func NewWithConfig(apiKey string, config Config) (cli Client, err error) {
if err = config.validate(); err != nil {
return
}
c := &client{
Config: makeConfig(config),
key: apiKey,
msgs: make(chan APIMessage, 100),
quit: make(chan struct{}),
shutdown: make(chan struct{}),
http: makeHttpClient(config.Transport),
distinctIdsFeatureFlagsReported: newSizeLimitedMap(SIZE_DEFAULT),
}
if len(c.PersonalApiKey) > 0 {
c.featureFlagsPoller = newFeatureFlagsPoller(
c.key,
c.Config.PersonalApiKey,
c.Errorf,
c.Endpoint,
c.http,
c.DefaultFeatureFlagsPollingInterval,
c.NextFeatureFlagsPollingTick,
c.FeatureFlagRequestTimeout,
)
}
go c.loop()
cli = c
return
}
func makeHttpClient(transport http.RoundTripper) http.Client {
httpClient := http.Client{
Transport: transport,
}
if supportsTimeout(transport) {
httpClient.Timeout = 10 * time.Second
}
return httpClient
}
func dereferenceMessage(msg Message) Message {
switch m := msg.(type) {
case *Alias:
if m == nil {
return nil
}
return *m
case *Identify:
if m == nil {
return nil
}
return *m
case *GroupIdentify:
if m == nil {
return nil
}
return *m
case *Capture:
if m == nil {
return nil
}
return *m
}
return msg
}
func (c *client) Enqueue(msg Message) (err error) {
msg = dereferenceMessage(msg)
if err = msg.Validate(); err != nil {
return
}
var ts = c.now()
switch m := msg.(type) {
case Alias:
m.Type = "alias"
m.Timestamp = makeTimestamp(m.Timestamp, ts)
msg = m
case Identify:
m.Type = "identify"
m.Timestamp = makeTimestamp(m.Timestamp, ts)
msg = m
case GroupIdentify:
m.Timestamp = makeTimestamp(m.Timestamp, ts)
msg = m
case Capture:
m.Type = "capture"
m.Timestamp = makeTimestamp(m.Timestamp, ts)
if m.SendFeatureFlags {
// Add all feature variants to event
featureVariants, err := c.getFeatureVariants(m.DistinctId, m.Groups, NewProperties(), map[string]Properties{})
if err != nil {
c.Errorf("unable to get feature variants - %s", err)
}
if m.Properties == nil {
m.Properties = NewProperties()
}
for feature, variant := range featureVariants {
propKey := fmt.Sprintf("$feature/%s", feature)
m.Properties[propKey] = variant
}
// Add all feature flag keys to $active_feature_flags key
featureKeys := make([]string, len(featureVariants))
i := 0
for k := range featureVariants {
featureKeys[i] = k
i++
}
m.Properties["$active_feature_flags"] = featureKeys
}
msg = m
default:
err = fmt.Errorf("messages with custom types cannot be enqueued: %T", msg)
return
}
defer func() {
// When the `msgs` channel is closed writing to it will trigger a panic.
// To avoid letting the panic propagate to the caller we recover from it
// and instead report that the client has been closed and shouldn't be
// used anymore.
if recover() != nil {
err = ErrClosed
}
}()
c.msgs <- msg.APIfy()
return
}
func (c *client) IsFeatureEnabled(flagConfig FeatureFlagPayload) (interface{}, error) {
if err := flagConfig.validate(); err != nil {
return false, err
}
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
return false, errors.New(errorMessage)
}
result, err := c.GetFeatureFlag(flagConfig)
if err != nil {
return nil, err
}
if result == "false" {
result = false
} else if result == "true" {
result = true
}
return result, nil
}
func (c *client) ReloadFeatureFlags() error {
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
return errors.New(errorMessage)
}
c.featureFlagsPoller.ForceReload()
return nil
}
func (c *client) GetFeatureFlag(flagConfig FeatureFlagPayload) (interface{}, error) {
if err := flagConfig.validate(); err != nil {
return false, err
}
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
return "false", errors.New(errorMessage)
}
flagValue, err := c.featureFlagsPoller.GetFeatureFlag(flagConfig)
if *flagConfig.SendFeatureFlagEvents && !c.distinctIdsFeatureFlagsReported.contains(flagConfig.DistinctId, flagConfig.Key) {
c.Enqueue(Capture{
DistinctId: flagConfig.DistinctId,
Event: "$feature_flag_called",
Properties: NewProperties().
Set("$feature_flag", flagConfig.Key).
Set("$feature_flag_response", flagValue).
Set("$feature_flag_errored", err != nil),
Groups: flagConfig.Groups,
})
c.distinctIdsFeatureFlagsReported.add(flagConfig.DistinctId, flagConfig.Key)
}
return flagValue, err
}
func (c *client) GetFeatureFlags() ([]FeatureFlag, error) {
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
return nil, errors.New(errorMessage)
}
return c.featureFlagsPoller.GetFeatureFlags()
}
func (c *client) GetAllFlags(flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error) {
if err := flagConfig.validate(); err != nil {
return nil, err
}
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
return nil, errors.New(errorMessage)
}
return c.featureFlagsPoller.GetAllFlags(flagConfig)
}
// Close and flush metrics.
func (c *client) Close() (err error) {
defer func() {
// Always recover, a panic could be raised if `c`.quit was closed which
// means the method was called more than once.
if recover() != nil {
err = ErrClosed
}
}()
close(c.quit)
<-c.shutdown
return
}
// Asychronously send a batched requests.
func (c *client) sendAsync(msgs []message, wg *sync.WaitGroup, ex *executor) {
wg.Add(1)
if !ex.do(func() {
defer wg.Done()
defer func() {
// In case a bug is introduced in the send function that triggers
// a panic, we don't want this to ever crash the application so we
// catch it here and log it instead.
if err := recover(); err != nil {
c.Errorf("panic - %s", err)
}
}()
c.send(msgs)
}) {
wg.Done()
c.Errorf("sending messages failed - %s", ErrTooManyRequests)
c.notifyFailure(msgs, ErrTooManyRequests)
}
}
// Send batch request.
func (c *client) send(msgs []message) {
const attempts = 10
b, err := json.Marshal(batch{
ApiKey: c.key,
Messages: msgs,
})
if err != nil {
c.Errorf("marshalling messages - %s", err)
c.notifyFailure(msgs, err)
return
}
for i := 0; i != attempts; i++ {
if err = c.upload(b); err == nil {
c.notifySuccess(msgs)
return
}
// Wait for either a retry timeout or the client to be closed.
select {
case <-time.After(c.RetryAfter(i)):
case <-c.quit:
c.Errorf("%d messages dropped because they failed to be sent and the client was closed", len(msgs))
c.notifyFailure(msgs, err)
return
}
}
c.Errorf("%d messages dropped because they failed to be sent after %d attempts", len(msgs), attempts)
c.notifyFailure(msgs, err)
}
// Upload serialized batch message.
func (c *client) upload(b []byte) error {
url := c.Endpoint + "/batch/"
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
if err != nil {
c.Errorf("creating request - %s", err)
return err
}
version := getVersion()
req.Header.Add("User-Agent", "posthog-go (version: "+version+")")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", fmt.Sprintf("%d", len(b)))
res, err := c.http.Do(req)
if err != nil {
c.Errorf("sending request - %s", err)
return err
}
defer res.Body.Close()
return c.report(res)
}
// Report on response body.
func (c *client) report(res *http.Response) (err error) {
var body []byte
if res.StatusCode < 300 {
c.debugf("response %s", res.Status)
return
}
if body, err = ioutil.ReadAll(res.Body); err != nil {
c.Errorf("response %d %s - %s", res.StatusCode, res.Status, err)
return
}
c.logf("response %d %s – %s", res.StatusCode, res.Status, string(body))
return fmt.Errorf("%d %s", res.StatusCode, res.Status)
}
// Batch loop.
func (c *client) loop() {
defer close(c.shutdown)
if c.featureFlagsPoller != nil {
defer c.featureFlagsPoller.shutdownPoller()
}
wg := &sync.WaitGroup{}
defer wg.Wait()
tick := time.NewTicker(c.Interval)
defer tick.Stop()
ex := newExecutor(c.maxConcurrentRequests)
defer ex.close()
mq := messageQueue{
maxBatchSize: c.BatchSize,
maxBatchBytes: c.maxBatchBytes(),
}
for {
select {
case msg := <-c.msgs:
c.push(&mq, msg, wg, ex)
case <-tick.C:
c.flush(&mq, wg, ex)
case <-c.quit:
c.debugf("exit requested – draining messages")
// Drain the msg channel, we have to close it first so no more
// messages can be pushed and otherwise the loop would never end.
close(c.msgs)
for msg := range c.msgs {
c.push(&mq, msg, wg, ex)
}
c.flush(&mq, wg, ex)
c.debugf("exit")
return
}
}
}
func (c *client) push(q *messageQueue, m APIMessage, wg *sync.WaitGroup, ex *executor) {
var msg message
var err error
if msg, err = makeMessage(m, maxMessageBytes); err != nil {
c.Errorf("%s - %v", err, m)
c.notifyFailure([]message{{m, nil}}, err)
return
}
c.debugf("buffer (%d/%d) %v", len(q.pending), c.BatchSize, m)
if msgs := q.push(msg); msgs != nil {
c.debugf("exceeded messages batch limit with batch of %d messages – flushing", len(msgs))
c.sendAsync(msgs, wg, ex)
}
}
func (c *client) flush(q *messageQueue, wg *sync.WaitGroup, ex *executor) {
if msgs := q.flush(); msgs != nil {
c.debugf("flushing %d messages", len(msgs))
c.sendAsync(msgs, wg, ex)
}
}
func (c *client) debugf(format string, args ...interface{}) {
if c.Verbose {
c.logf(format, args...)
}
}
func (c *client) logf(format string, args ...interface{}) {
c.Logger.Logf(format, args...)
}
func (c *client) Errorf(format string, args ...interface{}) {
c.Logger.Errorf(format, args...)
}
func (c *client) maxBatchBytes() int {
b, _ := json.Marshal(batch{
Messages: []message{},
})
return maxBatchBytes - len(b)
}
func (c *client) notifySuccess(msgs []message) {
if c.Callback != nil {
for _, m := range msgs {
c.Callback.Success(m.msg)
}
}
}
func (c *client) notifyFailure(msgs []message, err error) {
if c.Callback != nil {
for _, m := range msgs {
c.Callback.Failure(m.msg, err)
}
}
}
func (c *client) getFeatureVariants(distinctId string, groups Groups, personProperties Properties, groupProperties map[string]Properties) (map[string]interface{}, error) {
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
return nil, errors.New(errorMessage)
}
featureVariants, err := c.featureFlagsPoller.getFeatureFlagVariants(distinctId, groups, personProperties, groupProperties)
if err != nil {
return nil, err
}
return featureVariants, nil
}