-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathratelimit.go
80 lines (64 loc) · 1.61 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package twitch
import (
"sync"
"time"
)
type RateLimiter interface {
// This will impact how go-twitch-irc groups joins together per IRC message
GetLimit() int
Throttle(count int)
IsUnlimited() bool
}
type WindowRateLimiter struct {
joinLimit int
window []time.Time
mutex sync.Mutex
}
const Unlimited = -1
const TwitchRateLimitWindow = 10 * time.Second
const windowRateLimiterSleepDuration = 100 * time.Millisecond
func CreateDefaultRateLimiter() *WindowRateLimiter {
return createRateLimiter(20)
}
func CreateVerifiedRateLimiter() *WindowRateLimiter {
return createRateLimiter(2000)
}
func CreateUnlimitedRateLimiter() *WindowRateLimiter {
return createRateLimiter(Unlimited)
}
func createRateLimiter(limit int) *WindowRateLimiter {
var window []time.Time
return &WindowRateLimiter{
joinLimit: limit,
window: window,
}
}
func (r *WindowRateLimiter) GetLimit() int {
return r.joinLimit
}
func (r *WindowRateLimiter) Throttle(count int) {
if r.joinLimit == Unlimited {
return
}
r.mutex.Lock()
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
r.mutex.Unlock()
return
}
time.Sleep(time.Until(r.window[0].Add(TwitchRateLimitWindow).Add(windowRateLimiterSleepDuration)))
r.mutex.Unlock()
r.Throttle(count)
}
func (r *WindowRateLimiter) IsUnlimited() bool {
return r.joinLimit == Unlimited
}