-
Notifications
You must be signed in to change notification settings - Fork 530
/
Copy pathmetrics.go
50 lines (40 loc) · 1.15 KB
/
metrics.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
package hedgedmetrics
import (
"time"
"github.com/cristalhq/hedgedhttp"
"github.com/prometheus/client_golang/prometheus"
)
const (
hedgedMetricsPublishDuration = 10 * time.Second
)
type diffCounter struct {
previous uint64
counter prometheus.Counter
}
func (d *diffCounter) addAbsoluteToCounter(value uint64) {
diff := float64(value - d.previous)
if value < d.previous {
diff = float64(value)
}
d.counter.Add(diff)
d.previous = value
}
// statsProvider defines the interface that wraps hedgedhttp.Stats for ease of testing
type statsProvider interface {
Snapshot() hedgedhttp.StatsSnapshot
}
// Publish flushes metrics from hedged requests every tickerDur
func Publish(s *hedgedhttp.Stats, counter prometheus.Counter) {
publishWithDuration(s, counter, hedgedMetricsPublishDuration)
}
func publishWithDuration(s statsProvider, counter prometheus.Counter, duration time.Duration) {
ticker := time.NewTicker(duration)
diff := &diffCounter{previous: 0, counter: counter}
go func() {
for range ticker.C {
snap := s.Snapshot()
hedgedRequests := snap.ActualRoundTrips - snap.RequestedRoundTrips
diff.addAbsoluteToCounter(hedgedRequests)
}
}()
}