forked from gempir/go-twitch-irc
/
ratelimit.go
63 lines (49 loc) · 1.18 KB
/
ratelimit.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
package twitch
import (
"time"
)
type RateLimiter struct {
joinLimit int
window []time.Time
}
const Unlimited = -1
const TwitchRateLimitWindow = 10 * time.Second
func CreateDefaultRateLimiter() *RateLimiter {
return createRateLimiter(20)
}
func CreateVerifiedRateLimiter() *RateLimiter {
return createRateLimiter(2000)
}
func CreateUnlimitedRateLimiter() *RateLimiter {
return createRateLimiter(Unlimited)
}
func createRateLimiter(limit int) *RateLimiter {
var window []time.Time
return &RateLimiter{
joinLimit: limit,
window: window,
}
}
func (r *RateLimiter) Throttle(count int) {
if r.joinLimit == Unlimited {
return
}
newWindow := []time.Time{}
for i := 0; i < len(r.window); i++ {
if r.window[i].Add(TwitchRateLimitWindow).After(time.Now()) {
newWindow = append(newWindow, r.window[i])
}
}
if r.joinLimit-len(newWindow) > count || len(newWindow) == 0 {
for i := 0; i < count; i++ {
newWindow = append(newWindow, time.Now())
}
r.window = newWindow
return
}
time.Sleep(time.Until(r.window[0].Add(TwitchRateLimitWindow).Add(time.Millisecond * 100)))
r.Throttle(count)
}
func (r *RateLimiter) isUnlimited() bool {
return r.joinLimit == Unlimited
}