-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrate_limiter.go
59 lines (53 loc) · 1.09 KB
/
rate_limiter.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
package kitty
import (
"time"
)
// Token Bucket rate limiter
type rateLimiter struct {
messageLimit int
interval time.Duration
tokens chan struct{}
tokenInterval time.Duration
killchan chan struct{}
}
func newRateLimiter(messageLimit int, interval time.Duration) *rateLimiter {
return &rateLimiter{
messageLimit: messageLimit,
interval: interval,
tokens: make(chan struct{}, messageLimit),
tokenInterval: interval / time.Duration(messageLimit),
killchan: make(chan struct{}),
}
}
func (rl *rateLimiter) start() {
go func() {
timer := time.NewTimer(rl.tokenInterval)
for {
select {
case <-rl.killchan:
timer.Stop()
close(rl.tokens)
return
case <-timer.C:
select {
case rl.tokens <- struct{}{}:
default:
}
timer = time.NewTimer(rl.tokenInterval)
}
}
}()
}
func (rl *rateLimiter) kill() {
close(rl.killchan)
}
// Drop drains the token bucket rate limiter
// returns true when the bucket is empty
func (rl *rateLimiter) drop() bool {
select {
case <-rl.tokens:
return false
default:
return true
}
}