-
Notifications
You must be signed in to change notification settings - Fork 3
/
throttler.go
85 lines (69 loc) · 1.31 KB
/
throttler.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
package main
import (
"fmt"
"sync"
"time"
)
type Throttler struct {
Concurrency int
Quota int
Clients map[string]int
Requests map[string]int
Whitelist map[string]bool
*sync.Mutex
}
func NewThrottler(concurrency int, quota int) *Throttler {
return &Throttler{
Concurrency: concurrency,
Quota: quota,
Clients: make(map[string]int),
Requests: make(map[string]int),
Whitelist: make(map[string]bool),
Mutex: &sync.Mutex{},
}
}
func (t *Throttler) StartPeriodicFlush() {
go func() {
for {
t.Flush()
time.Sleep(time.Second * 5)
}
}()
}
func (t *Throttler) Add(ip string) error {
t.Lock()
defer t.Unlock()
t.Requests[ip]++
if t.Requests[ip] > t.Quota || t.Clients[ip] >= t.Concurrency {
return fmt.Errorf("Too many requests")
}
t.Clients[ip]++
return nil
}
func (t *Throttler) Remove(ip string) {
t.Lock()
defer t.Unlock()
t.Clients[ip]--
if t.Clients[ip] < 0 {
t.Clients[ip] = 0
}
}
func (t *Throttler) Flush() {
t.Lock()
defer t.Unlock()
for k := range t.Clients {
delete(t.Clients, k)
}
for k := range t.Requests {
delete(t.Requests, k)
}
}
func (t *Throttler) SetWhitelist(ips []string) {
for _, ip := range ips {
t.Whitelist[ip] = true
}
}
func (t *Throttler) Whitelisted(ip string) bool {
_, ok := t.Whitelist[ip]
return ok
}