-
Notifications
You must be signed in to change notification settings - Fork 18
/
limiter.go
183 lines (152 loc) · 4.9 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
package httprate
import (
"fmt"
"math"
"net/http"
"sync"
"time"
)
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 {
rl := &RateLimiter{
requestLimit: requestLimit,
windowLength: windowLength,
headers: ResponseHeaders{
Limit: "X-RateLimit-Limit",
Remaining: "X-RateLimit-Remaining",
Increment: "X-RateLimit-Increment",
Reset: "X-RateLimit-Reset",
RetryAfter: "Retry-After",
},
}
for _, opt := range options {
opt(rl)
}
if rl.keyFn == nil {
rl.keyFn = Key("*")
}
if rl.limitCounter == nil {
rl.limitCounter = NewLocalLimitCounter(windowLength)
} else {
rl.limitCounter.Config(requestLimit, windowLength)
}
if rl.onRateLimited == nil {
rl.onRateLimited = onRateLimited
}
if rl.onError == nil {
rl.onError = onError
}
return rl
}
type RateLimiter struct {
requestLimit int
windowLength time.Duration
keyFn KeyFunc
limitCounter LimitCounter
onRateLimited http.HandlerFunc
onError func(http.ResponseWriter, *http.Request, error)
headers ResponseHeaders
mu sync.Mutex
}
// OnLimit checks the rate limit for the given key and updates the response headers accordingly.
// If the limit is reached, it returns true, indicating that the request should be halted. Otherwise,
// it increments the request count and returns false. This method does not send an HTTP response,
// so the caller must handle the response themselves or use the RespondOnLimit() method instead.
func (l *RateLimiter) OnLimit(w http.ResponseWriter, r *http.Request, key string) bool {
currentWindow := time.Now().UTC().Truncate(l.windowLength)
ctx := r.Context()
limit := l.requestLimit
if val := getRequestLimit(ctx); val > 0 {
limit = val
}
setHeader(w, l.headers.Limit, fmt.Sprintf("%d", limit))
setHeader(w, l.headers.Reset, fmt.Sprintf("%d", currentWindow.Add(l.windowLength).Unix()))
l.mu.Lock()
_, rateFloat, err := l.calculateRate(key, limit)
if err != nil {
l.mu.Unlock()
l.onError(w, r, err)
return true
}
rate := int(math.Round(rateFloat))
increment := getIncrement(r.Context())
if increment > 1 {
setHeader(w, l.headers.Increment, fmt.Sprintf("%d", increment))
}
if rate+increment > limit {
setHeader(w, l.headers.Remaining, fmt.Sprintf("%d", limit-rate))
l.mu.Unlock()
setHeader(w, l.headers.RetryAfter, fmt.Sprintf("%d", int(l.windowLength.Seconds()))) // RFC 6585
return true
}
err = l.limitCounter.IncrementBy(key, currentWindow, increment)
if err != nil {
l.mu.Unlock()
l.onError(w, r, err)
return true
}
l.mu.Unlock()
setHeader(w, l.headers.Remaining, fmt.Sprintf("%d", limit-rate-increment))
return false
}
// RespondOnLimit checks the rate limit for the given key and updates the response headers accordingly.
// If the limit is reached, it automatically sends an HTTP response and returns true, signaling the
// caller to halt further request processing. If the limit is not reached, it increments the request
// count and returns false, allowing the request to proceed.
func (l *RateLimiter) RespondOnLimit(w http.ResponseWriter, r *http.Request, key string) bool {
onLimit := l.OnLimit(w, r, key)
if onLimit {
l.onRateLimited(w, r)
}
return onLimit
}
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 {
l.onError(w, r, err)
return
}
if l.RespondOnLimit(w, r, key) {
return
}
next.ServeHTTP(w, r)
})
}
func (l *RateLimiter) calculateRate(key string, requestLimit int) (bool, float64, error) {
now := time.Now().UTC()
currentWindow := now.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 := now.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
}
func setHeader(w http.ResponseWriter, key string, value string) {
if key != "" {
w.Header().Set(key, value)
}
}
func onRateLimited(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
}
func onError(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusPreconditionRequired)
}