forked from ginuerzh/gost
/
limiter.go
259 lines (233 loc) · 4.75 KB
/
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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package gost
import (
"bufio"
"errors"
"io"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
type Limiter interface {
CheckRate(key string, checkConcurrent bool) (func(), bool)
}
func NewLocalLimiter(user string, cfg string) (*LocalLimiter, error) {
limiter := LocalLimiter{
buckets: map[string]*limiterBucket{},
concurrent: map[string]chan bool{},
stopped: make(chan struct{}),
}
if cfg == "" || user == "" {
return &limiter, nil
}
if err := limiter.AddRule(user, cfg); err != nil {
return nil, err
}
return &limiter, nil
}
// Token Bucket
type limiterBucket struct {
max int64
cur int64
duration int64
batch int64
}
type LocalLimiter struct {
buckets map[string]*limiterBucket
concurrent map[string]chan bool
mux sync.RWMutex
stopped chan struct{}
period time.Duration
}
func (l *LocalLimiter) CheckRate(key string, checkConcurrent bool) (func(), bool) {
if checkConcurrent {
done, ok := l.checkConcurrent(key)
if !ok {
return nil, false
}
if t := l.getToken(key); !t {
done()
return nil, false
}
return done, true
} else {
if t := l.getToken(key); !t {
return nil, false
}
return nil, true
}
}
func (l *LocalLimiter) AddRule(user string, cfg string) error {
if user == "" {
return nil
}
if cfg == "" {
//reload need check old limit exists
if _, ok := l.buckets[user]; ok {
delete(l.buckets, user)
}
if _, ok := l.concurrent[user]; ok {
delete(l.concurrent, user)
}
return nil
}
args := strings.Split(cfg, ",")
if len(args) < 2 || len(args) > 3 {
return errors.New("parse limiter fail:" + cfg)
}
if len(args) == 2 {
args = append(args, "0")
}
duration, e1 := strconv.ParseInt(strings.TrimSpace(args[0]), 10, 64)
count, e2 := strconv.ParseInt(strings.TrimSpace(args[1]), 10, 64)
cur, e3 := strconv.ParseInt(strings.TrimSpace(args[2]), 10, 64)
if e1 != nil || e2 != nil || e3 != nil {
return errors.New("parse limiter fail:" + cfg)
}
// 0 means not limit
if duration > 0 && count > 0 {
bu := &limiterBucket{
cur: count * 10,
max: count * 10,
duration: duration * 100,
batch: count,
}
go func() {
for {
time.Sleep(time.Millisecond * time.Duration(bu.duration))
if bu.cur+bu.batch > bu.max {
bu.cur = bu.max
} else {
atomic.AddInt64(&bu.cur, bu.batch)
}
}
}()
l.buckets[user] = bu
} else {
if _, ok := l.buckets[user]; ok {
delete(l.buckets, user)
}
}
// zero means not limit
if cur > 0 {
l.concurrent[user] = make(chan bool, cur)
} else {
if _, ok := l.concurrent[user]; ok {
delete(l.concurrent, user)
}
}
return nil
}
// Reload parses config from r, then live reloads the LocalLimiter.
func (l *LocalLimiter) Reload(r io.Reader) error {
var period time.Duration
kvs := make(map[string]string)
if r == nil || l.Stopped() {
return nil
}
// splitLine splits a line text by white space.
// A line started with '#' will be ignored, otherwise it is valid.
split := func(line string) []string {
if line == "" {
return nil
}
line = strings.Replace(line, "\t", " ", -1)
line = strings.TrimSpace(line)
if strings.IndexByte(line, '#') == 0 {
return nil
}
var ss []string
for _, s := range strings.Split(line, " ") {
if s = strings.TrimSpace(s); s != "" {
ss = append(ss, s)
}
}
return ss
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
ss := split(line)
if len(ss) == 0 {
continue
}
switch ss[0] {
case "reload": // reload option
if len(ss) > 1 {
period, _ = time.ParseDuration(ss[1])
}
default:
var k, v string
k = ss[0]
if len(ss) > 2 {
v = ss[2]
}
kvs[k] = v
}
}
if err := scanner.Err(); err != nil {
return err
}
l.mux.Lock()
defer l.mux.Unlock()
l.period = period
for user, args := range kvs {
err := l.AddRule(user, args)
if err != nil {
return err
}
}
return nil
}
// Period returns the reload period.
func (l *LocalLimiter) Period() time.Duration {
if l.Stopped() {
return -1
}
l.mux.RLock()
defer l.mux.RUnlock()
return l.period
}
// Stop stops reloading.
func (l *LocalLimiter) Stop() {
select {
case <-l.stopped:
default:
close(l.stopped)
}
}
// Stopped checks whether the reloader is stopped.
func (l *LocalLimiter) Stopped() bool {
select {
case <-l.stopped:
return true
default:
return false
}
}
func (l *LocalLimiter) getToken(key string) bool {
b, ok := l.buckets[key]
if !ok || b == nil {
return true
}
if b.cur <= 0 {
return false
}
atomic.AddInt64(&b.cur, -10)
return true
}
func (l *LocalLimiter) checkConcurrent(key string) (func(), bool) {
c, ok := l.concurrent[key]
if !ok || c == nil {
return func() {}, true
}
select {
case c <- true:
return func() {
<-c
}, true
default:
return nil, false
}
}