-
Notifications
You must be signed in to change notification settings - Fork 0
/
rolling_counter.go
68 lines (55 loc) · 1.51 KB
/
rolling_counter.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
package rolling
import (
"fmt"
"time"
)
var _ Metric = &rollingCounter{}
var _ Aggregation = &rollingCounter{}
// RollingCounter represents a ring window based on time duration.
// e.g. [[1], [3], [5]]
type RollingCounter interface {
Metric
Aggregation
// Reduce applies the reduction function to all buckets within the window.
Reduce(func(Iterator) float64) float64
}
// RollingCounterOpts contains the arguments for creating RollingCounter.
type RollingCounterOpts struct {
Size int
BucketDuration time.Duration
}
type rollingCounter struct {
policy *RollingPolicy
}
// NewRollingCounter creates a new RollingCounter bases on RollingCounterOpts.
func NewRollingCounter(opts RollingCounterOpts) RollingCounter {
window := NewWindow(WindowOpts{Size: opts.Size})
policy := NewRollingPolicy(window, RollingPolicyOpts{BucketDuration: opts.BucketDuration})
return &rollingCounter{
policy: policy,
}
}
func (r *rollingCounter) Add(val int64) {
if val < 0 {
panic(fmt.Errorf("rolling: cannot decrease in value. val: %d", val))
}
r.policy.Add(float64(val))
}
func (r *rollingCounter) Reduce(f func(Iterator) float64) float64 {
return r.policy.Reduce(f)
}
func (r *rollingCounter) Avg() float64 {
return r.policy.Reduce(Avg)
}
func (r *rollingCounter) Min() float64 {
return r.policy.Reduce(Min)
}
func (r *rollingCounter) Max() float64 {
return r.policy.Reduce(Max)
}
func (r *rollingCounter) Sum() float64 {
return r.policy.Reduce(Sum)
}
func (r *rollingCounter) Value() int64 {
return int64(r.Sum())
}