-
Notifications
You must be signed in to change notification settings - Fork 18
/
limiter.go
226 lines (183 loc) · 5.2 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
package httprate
import (
"fmt"
"math"
"net/http"
"sync"
"time"
"github.com/cespare/xxhash/v2"
)
type LimitCounter interface {
Config(requestLimit int, windowLength time.Duration)
Increment(key string, currentWindow time.Time) error
IncrementBy(key string, currentWindow time.Time, amount int) error
Get(key string, currentWindow, previousWindow time.Time) (int, int, error)
}
func NewRateLimiter(requestLimit int, windowLength time.Duration, options ...Option) *rateLimiter {
return newRateLimiter(requestLimit, windowLength, options...)
}
func newRateLimiter(requestLimit int, windowLength time.Duration, options ...Option) *rateLimiter {
rl := &rateLimiter{
requestLimit: requestLimit,
windowLength: windowLength,
}
for _, opt := range options {
opt(rl)
}
if rl.keyFn == nil {
rl.keyFn = func(r *http.Request) (string, error) {
return "*", nil
}
}
if rl.limitCounter == nil {
rl.limitCounter = &localCounter{
counters: make(map[uint64]*count),
windowLength: windowLength,
}
}
rl.limitCounter.Config(requestLimit, windowLength)
if rl.onRequestLimit == nil {
rl.onRequestLimit = func(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
}
}
return rl
}
type rateLimiter struct {
requestLimit int
windowLength time.Duration
keyFn KeyFunc
limitCounter LimitCounter
onRequestLimit http.HandlerFunc
mu sync.Mutex
}
func (l *rateLimiter) Counter() LimitCounter {
return l.limitCounter
}
func (l *rateLimiter) Status(key string) (bool, float64, error) {
return l.calculateRate(key, l.requestLimit)
}
func (l *rateLimiter) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key, err := l.keyFn(r)
if err != nil {
http.Error(w, err.Error(), http.StatusPreconditionRequired)
return
}
currentWindow := time.Now().UTC().Truncate(l.windowLength)
ctx := r.Context()
limit := l.requestLimit
if val := getRequestLimit(ctx); val > 0 {
limit = val
}
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", limit))
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", 0))
w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", currentWindow.Add(l.windowLength).Unix()))
l.mu.Lock()
_, rate, err := l.calculateRate(key, limit)
if err != nil {
l.mu.Unlock()
http.Error(w, err.Error(), http.StatusPreconditionRequired)
return
}
nrate := int(math.Round(rate))
if limit > nrate {
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", limit-nrate))
}
if nrate >= limit {
l.mu.Unlock()
w.Header().Set("Retry-After", fmt.Sprintf("%d", int(l.windowLength.Seconds()))) // RFC 6585
l.onRequestLimit(w, r)
return
}
err = l.limitCounter.IncrementBy(key, currentWindow, getIncrement(r.Context()))
if err != nil {
l.mu.Unlock()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
l.mu.Unlock()
next.ServeHTTP(w, r)
})
}
func (l *rateLimiter) calculateRate(key string, requestLimit int) (bool, float64, error) {
t := time.Now().UTC()
currentWindow := t.Truncate(l.windowLength)
previousWindow := currentWindow.Add(-l.windowLength)
currCount, prevCount, err := l.limitCounter.Get(key, currentWindow, previousWindow)
if err != nil {
return false, 0, err
}
diff := t.Sub(currentWindow)
rate := float64(prevCount)*(float64(l.windowLength)-float64(diff))/float64(l.windowLength) + float64(currCount)
if rate > float64(requestLimit) {
return false, rate, nil
}
return true, rate, nil
}
type localCounter struct {
counters map[uint64]*count
windowLength time.Duration
lastEvict time.Time
mu sync.Mutex
}
var _ LimitCounter = &localCounter{}
type count struct {
value int
updatedAt time.Time
}
func (c *localCounter) Config(requestLimit int, windowLength time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.windowLength = windowLength
}
func (c *localCounter) Increment(key string, currentWindow time.Time) error {
return c.IncrementBy(key, currentWindow, 1)
}
func (c *localCounter) IncrementBy(key string, currentWindow time.Time, amount int) error {
c.evict()
c.mu.Lock()
defer c.mu.Unlock()
hkey := LimitCounterKey(key, currentWindow)
v, ok := c.counters[hkey]
if !ok {
v = &count{}
c.counters[hkey] = v
}
v.value += amount
v.updatedAt = time.Now()
return nil
}
func (c *localCounter) Get(key string, currentWindow, previousWindow time.Time) (int, int, error) {
c.mu.Lock()
defer c.mu.Unlock()
curr, ok := c.counters[LimitCounterKey(key, currentWindow)]
if !ok {
curr = &count{value: 0, updatedAt: time.Now()}
}
prev, ok := c.counters[LimitCounterKey(key, previousWindow)]
if !ok {
prev = &count{value: 0, updatedAt: time.Now()}
}
return curr.value, prev.value, nil
}
func (c *localCounter) evict() {
c.mu.Lock()
defer c.mu.Unlock()
d := c.windowLength * 3
if time.Since(c.lastEvict) < d {
return
}
c.lastEvict = time.Now()
for k, v := range c.counters {
if time.Since(v.updatedAt) >= d {
delete(c.counters, k)
}
}
}
func LimitCounterKey(key string, window time.Time) uint64 {
h := xxhash.New()
h.WriteString(key)
h.WriteString(fmt.Sprintf("%d", window.Unix()))
return h.Sum64()
}