-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathmetrics.go
More file actions
499 lines (422 loc) · 13.1 KB
/
Copy pathmetrics.go
File metadata and controls
499 lines (422 loc) · 13.1 KB
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
package unleash
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"net/url"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/Unleash/unleash-go-sdk/v6/internal/api"
"github.com/Unleash/unleash-go-sdk/v6/internal/impactmetrics"
)
// MetricsData represents the data sent to the unleash server.
type MetricsData struct {
// AppName is the name of the application.
AppName string `json:"appName"`
// InstanceID is the instance identifier.
InstanceID string `json:"instanceId"`
// ConnectionId is the connection id for instance.
ConnectionId string `json:"connectionId"`
// Bucket is the payload data sent to the server.
Bucket api.Bucket `json:"bucket"`
// The runtime version of our Platform
PlatformVersion string `json:"platformVersion"`
// The runtime name of our Platform
PlatformName string `json:"platformName"`
// Which version of Yggdrasil is being used
YggdrasilVersion *string `json:"yggdrasilVersion"`
// Optional field that describes the sdk version (name:version)
SDKVersion string `json:"sdkVersion"`
// Which version of the Unleash-Client-Spec is this SDK validated against
SpecVersion string `json:"specVersion"`
// ImpactMetrics are optional custom application-level metrics
ImpactMetrics []impactmetrics.CollectedMetric `json:"impactMetrics,omitempty"`
}
// ClientData represents the data sent to the unleash during registration.
type ClientData struct {
// AppName is the name of the application.
AppName string `json:"appName"`
// InstanceID is the instance identifier.
InstanceID string `json:"instanceId"`
// ConnectionId is the connection id for instance.
ConnectionId string `json:"connectionId"`
// Optional field that describes the sdk version (name:version)
SDKVersion string `json:"sdkVersion"`
// Strategies is a list of names of the strategies supported by the client.
Strategies []string `json:"strategies"`
// Started indicates the time at which the client was created.
Started time.Time `json:"started"`
// Interval specifies the time interval (in ms) that the client is using for refreshing
// feature toggles.
Interval int64 `json:"interval"`
PlatformVersion string `json:"platformVersion"`
PlatformName string `json:"platformName"`
YggdrasilVersion *string `json:"yggdrasilVersion"`
// Which version of the Unleash-Client-Spec is this SDK validated against
SpecVersion string `json:"specVersion"`
}
// metricsShutdownTimeout bounds the best-effort final flush performed by
// Close so an unreachable server cannot hang shutdown indefinitely.
const metricsShutdownTimeout = 5 * time.Second
type metric struct {
// Name is the name of the feature toggle.
Name string
// Enabled indicates whether the feature was enabled or not.
Enabled bool
}
type toggleCounters struct {
yes int64
no int64
mu sync.Mutex
variants map[string]int64
}
type metrics struct {
metricsChannels
options metricsOptions
started time.Time
lastCloseTime time.Time
counters sync.Map // map[string]*toggleCounters
ticker *time.Ticker
close chan struct{}
closed chan struct{}
ctx context.Context
cancel func()
maxSkips float64
errors float64
skips float64
metricRegistry impactmetrics.ImpactMetricsDataSource
}
func newMetrics(options metricsOptions, channels metricsChannels) *metrics {
m := &metrics{
metricsChannels: channels,
options: options,
started: time.Now(),
close: make(chan struct{}),
closed: make(chan struct{}),
maxSkips: 10,
errors: 0,
skips: 0,
lastCloseTime: time.Now(),
metricRegistry: options.metricRegistry,
}
ctx, cancel := context.WithCancel(context.Background())
m.ctx = ctx
m.cancel = cancel
if m.options.httpClient == nil {
m.options.httpClient = http.DefaultClient
}
if m.options.metricsInterval <= 0 {
m.options.disableMetrics = true
}
if !m.options.disableMetrics {
m.ticker = time.NewTicker(m.options.metricsInterval)
m.registerInstance()
go m.sync()
}
return m
}
func (m *metrics) Close() error {
if m.options.disableMetrics {
return nil
}
m.ticker.Stop()
m.cancel()
close(m.close)
<-m.closed
// Best-effort final flush of anything buffered since the last tick.
// Bounded so an unreachable server cannot hang Close indefinitely.
ctx, cancel := context.WithTimeout(context.Background(), metricsShutdownTimeout)
defer cancel()
m.flushOnShutdown(ctx)
return nil
}
func (m *metrics) sync() {
for {
select {
case <-m.ticker.C:
if m.skips == 0 {
m.sendMetrics(m.ctx)
} else {
m.decrementSkip()
}
case <-m.close:
close(m.closed)
return
}
}
}
func (m *metrics) registerInstance() {
u, _ := m.options.url.Parse("./client/register")
payload := m.getClientData()
resp, err := m.doPost(m.ctx, u, payload)
if err != nil {
m.err(err)
return
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusMultipleChoices {
m.warn(fmt.Errorf("%s return %d", u.String(), resp.StatusCode))
}
m.registered <- payload
}
func (m *metrics) backoff() {
m.errors = math.Min(m.maxSkips, m.errors+1)
m.skips = m.errors
}
func (m *metrics) configurationError() {
m.errors = m.maxSkips
m.skips = m.errors
}
func (m *metrics) successfulPost() {
m.errors = math.Max(0, m.errors-1)
m.skips = m.errors
}
func (m *metrics) decrementSkip() {
m.skips = math.Max(0, m.skips-1)
}
// This does not remove stale toggle names from the map. I don't think there's a safe, lock free way to do that
// The consequence is that if the user archives a lot of toggles this internal representation will not lose those
// toggles until the process is terminated. In practice, I don't believe this is a big problem, just means a
// little bit more memory is held than necessary
func (m *metrics) buildBucketAndReset(lastCloseTime time.Time) (api.Bucket, bool) {
bucket := api.Bucket{
Start: lastCloseTime,
Toggles: make(map[string]api.ToggleCount),
}
m.counters.Range(func(key, value any) bool {
name := key.(string)
counter := value.(*toggleCounters)
yes := atomic.SwapInt64(&counter.yes, 0)
no := atomic.SwapInt64(&counter.no, 0)
if yes == 0 && no == 0 {
counter.mu.Lock()
emptyVariants := len(counter.variants) == 0
counter.mu.Unlock()
if emptyVariants {
return true
}
}
toggleCounters := api.ToggleCount{
Yes: int32(yes),
No: int32(no),
Variants: map[string]int32{},
}
// we can have a little locking, as a treat. Variants are likely a luke warm path at best
// until we have evidence that this is a hot path API, I'd like to keep this simple
// simple here means a local lock per toggle counter while we swap out the variants map
counter.mu.Lock()
if len(counter.variants) > 0 {
vars := make(map[string]int32, len(counter.variants))
for vName, cnt := range counter.variants {
vars[vName] = int32(cnt)
}
toggleCounters.Variants = vars
counter.variants = make(map[string]int64)
}
counter.mu.Unlock()
bucket.Toggles[name] = toggleCounters
return true
})
if len(bucket.Toggles) == 0 {
return api.Bucket{}, false
}
return bucket, true
}
// flushOnShutdown makes a best-effort attempt to POST any buffered toggle
// counts and impact metrics before Close returns. It intentionally emits
// no events: OnSent, OnError, and the backoff counter are all skipped
// because the caller has committed to teardown and cannot react to them.
// The bounded ctx keeps an unreachable server from hanging shutdown.
func (m *metrics) flushOnShutdown(ctx context.Context) {
bucket, ok := m.buildBucketAndReset(m.lastCloseTime)
collectedMetrics := impactmetrics.CollectedMetrics(m.metricRegistry.Collect())
if !ok && collectedMetrics.IsEmpty() {
return
}
bucket.Stop = time.Now()
payload := MetricsData{
AppName: m.options.appName,
InstanceID: m.options.instanceId,
ConnectionId: m.options.connectionId,
Bucket: bucket,
SDKVersion: fmt.Sprintf("%s:%s", clientName, clientVersion),
PlatformName: "go",
PlatformVersion: runtime.Version(),
YggdrasilVersion: nil,
SpecVersion: specVersion,
ImpactMetrics: collectedMetrics,
}
u, _ := m.options.url.Parse("./client/metrics")
resp, err := m.doPost(ctx, u, payload)
if err != nil {
return
}
_ = resp.Body.Close()
}
func (m *metrics) sendMetrics(ctx context.Context) {
bucket, ok := m.buildBucketAndReset(m.lastCloseTime)
collectedMetrics := impactmetrics.CollectedMetrics(m.metricRegistry.Collect())
if !ok && collectedMetrics.IsEmpty() {
return
}
m.lastCloseTime = time.Now()
bucket.Stop = time.Now()
payload := MetricsData{
AppName: m.options.appName,
InstanceID: m.options.instanceId,
ConnectionId: m.options.connectionId,
Bucket: bucket,
SDKVersion: fmt.Sprintf("%s:%s", clientName, clientVersion),
PlatformName: "go",
PlatformVersion: runtime.Version(),
YggdrasilVersion: nil,
SpecVersion: specVersion,
ImpactMetrics: collectedMetrics,
}
u, _ := m.options.url.Parse("./client/metrics")
resp, err := m.doPost(ctx, u, payload)
if err != nil {
m.err(err)
return
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusMultipleChoices {
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusNotFound {
m.configurationError()
} else if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= http.StatusInternalServerError {
m.backoff()
}
m.warn(fmt.Errorf("%s return %d", u.String(), resp.StatusCode))
// The post failed, re-add the metrics we attempted to send so
// they are included in the next post.
m.reinsertBucket(bucket)
if !collectedMetrics.IsEmpty() {
m.metricRegistry.Restore(collectedMetrics)
}
// Set the start time of the current bucket to the one we
// attempted to send.
m.lastCloseTime = bucket.Start
} else {
m.successfulPost()
m.sent <- payload
}
}
func (m *metrics) doPost(ctx context.Context, url *url.URL, payload interface{}) (*http.Response, error) {
var body bytes.Buffer
enc := json.NewEncoder(&body)
if err := enc.Encode(payload); err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url.String(), &body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("UNLEASH-APPNAME", m.options.appName)
req.Header.Add("UNLEASH-INSTANCEID", m.options.instanceId)
req.Header.Add("User-Agent", m.options.appName)
req.Header.Add("Unleash-Interval", fmt.Sprintf("%d", m.options.metricsInterval.Milliseconds()))
for k, v := range m.options.headers {
req.Header[k] = v
}
return m.options.httpClient.Do(req)
}
func (m *metrics) getOrCreateCounter(name string) *toggleCounters {
c, ok := m.counters.Load(name)
if ok {
return c.(*toggleCounters)
}
nc := &toggleCounters{
variants: make(map[string]int64),
}
actual, _ := m.counters.LoadOrStore(name, nc)
return actual.(*toggleCounters)
}
func (m *metrics) reinsertBucket(bucket api.Bucket) {
for name, bucketToggle := range bucket.Toggles {
counter := m.getOrCreateCounter(name)
if bucketToggle.Yes != 0 {
atomic.AddInt64(&counter.yes, int64(bucketToggle.Yes))
}
if bucketToggle.No != 0 {
atomic.AddInt64(&counter.no, int64(bucketToggle.No))
}
if len(bucketToggle.Variants) > 0 {
counter.mu.Lock()
if counter.variants == nil {
counter.variants = make(map[string]int64, len(bucketToggle.Variants))
}
for vName, cnt := range bucketToggle.Variants {
if cnt == 0 {
continue
}
counter.variants[vName] += int64(cnt)
}
counter.mu.Unlock()
}
}
}
func (m *metrics) add(name string, enabled bool, num int32) {
if m.options.disableMetrics || num == 0 {
return
}
c := m.getOrCreateCounter(name)
if enabled {
atomic.AddInt64(&c.yes, int64(num))
} else {
atomic.AddInt64(&c.no, int64(num))
}
}
func (m *metrics) count(name string, enabled bool) {
if m.options.disableMetrics {
return
}
m.add(name, enabled, 1)
// best effort delivery, if the channel is full, we skip notifying
// means under high load we lose some fidelity here, but we avoid blocking
// the main path. That's probably the correct trade-off. Impression data
// is the correct insight into this behaviour anyway
select {
case m.metricsChannels.count <- metric{Name: name, Enabled: enabled}:
default:
}
}
func (m *metrics) countVariants(name string, enabled bool, variantName string) {
if m.options.disableMetrics {
return
}
m.add(name, enabled, 1)
// again best effort delivery
select {
case m.metricsChannels.count <- metric{Name: name, Enabled: enabled}:
default:
}
c := m.getOrCreateCounter(name)
c.mu.Lock()
if c.variants == nil {
c.variants = make(map[string]int64)
}
c.variants[variantName]++
c.mu.Unlock()
}
func (m *metrics) getClientData() ClientData {
return ClientData{
m.options.appName,
m.options.instanceId,
m.options.connectionId,
fmt.Sprintf("%s:%s", clientName, clientVersion),
m.options.strategies,
m.started,
int64(m.options.metricsInterval.Seconds()),
runtime.Version(),
"go",
nil,
specVersion,
}
}