-
Notifications
You must be signed in to change notification settings - Fork 0
/
tempo_limit.go
79 lines (71 loc) · 1.2 KB
/
tempo_limit.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
package guard_pool
import (
"sync/atomic"
"time"
)
type TempoLimiter struct {
Limit int32
SecondSpan int32
startTime time.Time
count *int32
BaseLimiter
}
func NewTempoLimit(limit, second int32) *TempoLimiter {
tl := &TempoLimiter{
Limit: limit,
SecondSpan: second,
}
var t int32
t = 0
tl.count = &t
go func() {
tl.start()
}()
return tl
}
func (t *TempoLimiter) start() {
t.mu.Lock()
defer t.mu.Unlock()
if t.running {
return
}
t.running = true
ticker := time.NewTicker(time.Duration(t.SecondSpan) * time.Second)
go func() {
for {
select {
case <-ticker.C:
atomic.SwapInt32(t.count, 0)
t.mu.Lock()
t.restrict = false
go func() {
t.callSubscribeForResetFunc()
}()
t.mu.Unlock()
}
}
}()
}
func (t *TempoLimiter) subscribeForReset(f func()) {
t.subscribeForResetFunc = f
}
func (t *TempoLimiter) subscribeForRestrict(f func()) {
t.subscribeForRestrictFunc = f
}
func (t *TempoLimiter) Hit() bool {
if t.restrict {
return false
}
n := atomic.AddInt32(t.count, 1)
if n > t.Limit {
t.mu.Lock()
t.restrict = true
go func() {
t.callSubscribeForRestrictFunc()
}()
t.mu.Unlock()
return false
} else {
return true
}
}