/
ratelimiter.go
94 lines (85 loc) · 1.76 KB
/
ratelimiter.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
82
83
84
85
86
87
88
89
90
91
92
93
94
package ratelimiter
import (
"sync"
"time"
)
const defaultRefreshPeriod = 10
// Limiter used to limit the rate at which work is done
type Limiter struct {
tpp float64
tokens float64
m sync.Mutex
c *sync.Cond
t *time.Ticker
done chan bool
started bool
}
// New creates a rate limiter that can be used to throttle work to target rate per second. The returned ratelimiter is started and ready to throttle.
func New(rate uint) *Limiter {
if rate == 0 {
panic("rate must be greater than 0")
}
l := &Limiter{}
l.done = make(chan bool)
l.c = sync.NewCond(&l.m)
l.t = time.NewTicker(defaultRefreshPeriod * time.Millisecond)
l.SetRate(rate)
l.Start()
return l
}
// Start a stopped ratelimiter if the rate limiter is already started the operation does nothing.
func (l *Limiter) Start() {
l.m.Lock()
defer l.m.Unlock()
if !l.started {
l.tokens = l.tpp
l.started = true
go l.tokenReplenisher()
}
}
// Stop the rate limiter and releases the internal resources.
func (l *Limiter) Stop() {
l.m.Lock()
defer l.m.Unlock()
if l.started {
l.done <- true
l.t.Stop()
l.started = false
}
}
// SetRate updates the rate of the ratelimiter on the fly.
func (l *Limiter) SetRate(rate uint) {
l.m.Lock()
defer l.m.Unlock()
l.tpp = float64(rate) / 1000 * defaultRefreshPeriod
}
// Throttle blocks if the current rate of work exceeds the limiter.
func (l *Limiter) Throttle() {
l.m.Lock()
if l.started {
for l.tokens <= 0 {
l.c.Wait()
}
l.tokens--
}
l.m.Unlock()
}
func (l *Limiter) tokenReplenisher() {
for {
select {
case <-l.done:
return
case <-l.t.C:
l.m.Lock()
notify := l.tokens <= 0
l.tokens += l.tpp
if l.tokens > l.tpp {
l.tokens = l.tpp
}
l.m.Unlock()
if notify {
l.c.Broadcast()
}
}
}
}