-
Notifications
You must be signed in to change notification settings - Fork 672
/
timed_meter.go
81 lines (66 loc) · 1.61 KB
/
timed_meter.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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package timer
import (
"container/list"
"sync"
"time"
)
var _ Meter = &TimedMeter{}
// TimedMeter is a meter that discards old events
type TimedMeter struct {
lock sync.Mutex
// Can be used to fake time in tests
Clock *Clock
// Amount of time to keep a tick
Duration time.Duration
// TODO: Currently this list has an entry for each tick... This isn't really
// sustainable at high tick numbers. We should be batching ticks with
// similar times into the same bucket.
tickList *list.List
}
// Tick implements the Meter interface
func (tm *TimedMeter) Tick() {
tm.lock.Lock()
defer tm.lock.Unlock()
tm.tick()
}
// Ticks implements the Meter interface
func (tm *TimedMeter) Ticks() int {
tm.lock.Lock()
defer tm.lock.Unlock()
return tm.ticks()
}
func (tm *TimedMeter) init() {
if tm.tickList == nil {
tm.tickList = list.New()
}
if tm.Clock == nil {
tm.Clock = &Clock{}
}
}
func (tm *TimedMeter) tick() {
tm.init()
tm.tickList.PushBack(tm.Clock.Time())
}
func (tm *TimedMeter) ticks() int {
tm.init()
timeBound := tm.Clock.Time().Add(-tm.Duration)
// removeExpiredHead returns false once there is nothing left to remove
for tm.removeExpiredHead(timeBound) {
}
return tm.tickList.Len()
}
// Returns true if the head was removed, false otherwise
func (tm *TimedMeter) removeExpiredHead(t time.Time) bool {
if tm.tickList.Len() == 0 {
return false
}
head := tm.tickList.Front()
headTime := head.Value.(time.Time)
if headTime.Before(t) {
tm.tickList.Remove(head)
return true
}
return false
}