forked from mailgun/gubernator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithms.go
352 lines (306 loc) · 8.49 KB
/
algorithms.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
Copyright 2018-2019 Mailgun Technologies Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gubernator
import (
"github.com/mailgun/holster/v4/clock"
)
// Implements token bucket algorithm for rate limiting. https://en.wikipedia.org/wiki/Token_bucket
func tokenBucket(s Store, c Cache, r *RateLimitReq) (resp *RateLimitResp, err error) {
item, ok := c.GetItem(r.HashKey())
if s != nil {
if !ok {
// Check our store for the item
if item, ok = s.Get(r); ok {
c.Add(item)
}
}
}
if ok {
if HasBehavior(r.Behavior, Behavior_RESET_REMAINING) {
c.Remove(r.HashKey())
if s != nil {
s.Remove(r.HashKey())
}
return &RateLimitResp{
Status: Status_UNDER_LIMIT,
Limit: r.Limit,
Remaining: r.Limit,
ResetTime: 0,
}, nil
}
// The following semantic allows for requests of more than the limit to be rejected, but subsequent
// requests within the same duration that are under the limit to succeed. IE: client attempts to
// send 1000 emails but 100 is their limit. The request is rejected as over the limit, but since we
// don't store OVER_LIMIT in the cache the client can retry within the same rate limit duration with
// 100 emails and the request will succeed.
t, ok := item.Value.(*TokenBucketItem)
if !ok {
// Client switched algorithms; perhaps due to a migration?
c.Remove(r.HashKey())
if s != nil {
s.Remove(r.HashKey())
}
return tokenBucket(s, c, r)
}
if s != nil {
defer func() {
s.OnChange(r, item)
}()
}
// Update the limit if it changed
if t.Limit != r.Limit {
// Add difference to remaining
t.Remaining += r.Limit - t.Limit
if t.Remaining < 0 {
t.Remaining = 0
}
t.Limit = r.Limit
}
rl := &RateLimitResp{
Status: t.Status,
Limit: r.Limit,
Remaining: t.Remaining,
ResetTime: item.ExpireAt,
}
// If the duration config changed, update the new ExpireAt
if t.Duration != r.Duration {
expire := t.CreatedAt + r.Duration
if HasBehavior(r.Behavior, Behavior_DURATION_IS_GREGORIAN) {
expire, err = GregorianExpiration(clock.Now(), r.Duration)
if err != nil {
return nil, err
}
}
// If our new duration means we are currently expired
if expire < MillisecondNow() {
// Update this so s.OnChange() will get the new expire change
item.ExpireAt = expire
c.Remove(item.Key)
return tokenBucket(s, c, r)
}
item.ExpireAt = expire
rl.ResetTime = expire
}
// Client is only interested in retrieving the current status or updating the rate limit config
if r.Hits == 0 {
return rl, nil
}
// If we are already at the limit
if rl.Remaining == 0 {
rl.Status = Status_OVER_LIMIT
t.Status = rl.Status
return rl, nil
}
// If requested hits takes the remainder
if t.Remaining == r.Hits {
t.Remaining = 0
rl.Remaining = 0
return rl, nil
}
// If requested is more than available, then return over the limit without updating the cache.
if r.Hits > t.Remaining {
rl.Status = Status_OVER_LIMIT
return rl, nil
}
t.Remaining -= r.Hits
rl.Remaining = t.Remaining
return rl, nil
}
// Add a new rate limit to the cache
now := MillisecondNow()
expire := now + r.Duration
if HasBehavior(r.Behavior, Behavior_DURATION_IS_GREGORIAN) {
expire, err = GregorianExpiration(clock.Now(), r.Duration)
if err != nil {
return nil, err
}
}
t := &TokenBucketItem{
Limit: r.Limit,
Duration: r.Duration,
Remaining: r.Limit - r.Hits,
CreatedAt: now,
}
rl := &RateLimitResp{
Status: Status_UNDER_LIMIT,
Limit: r.Limit,
Remaining: t.Remaining,
ResetTime: expire,
}
// Client could be requesting that we always return OVER_LIMIT
if r.Hits > r.Limit {
rl.Status = Status_OVER_LIMIT
rl.Remaining = r.Limit
t.Remaining = r.Limit
}
item = &CacheItem{
Algorithm: r.Algorithm,
Key: r.HashKey(),
Value: t,
ExpireAt: expire,
}
c.Add(item)
if s != nil {
s.OnChange(r, item)
}
return rl, nil
}
// Implements leaky bucket algorithm for rate limiting https://en.wikipedia.org/wiki/Leaky_bucket
func leakyBucket(s Store, c Cache, r *RateLimitReq) (resp *RateLimitResp, err error) {
if r.Burst == 0 {
r.Burst = r.Limit
}
now := MillisecondNow()
item, ok := c.GetItem(r.HashKey())
if s != nil {
if !ok {
// Check our store for the item
if item, ok = s.Get(r); ok {
c.Add(item)
}
}
}
if ok {
b, ok := item.Value.(*LeakyBucketItem)
if !ok {
// Client switched algorithms; perhaps due to a migration?
c.Remove(r.HashKey())
if s != nil {
s.Remove(r.HashKey())
}
return leakyBucket(s, c, r)
}
if HasBehavior(r.Behavior, Behavior_RESET_REMAINING) {
b.Remaining = float64(r.Burst)
}
// Update burst, limit and duration if they changed
if b.Burst != r.Burst {
if r.Burst > int64(b.Remaining) {
b.Remaining = float64(r.Burst)
}
b.Burst = r.Burst
}
b.Limit = r.Limit
b.Duration = r.Duration
duration := r.Duration
rate := float64(duration) / float64(r.Limit)
if HasBehavior(r.Behavior, Behavior_DURATION_IS_GREGORIAN) {
d, err := GregorianDuration(clock.Now(), r.Duration)
if err != nil {
return nil, err
}
n := clock.Now()
expire, err := GregorianExpiration(n, r.Duration)
if err != nil {
return nil, err
}
// Calculate the rate using the entire duration of the gregorian interval
// IE: Minute = 60,000 milliseconds, etc.. etc..
rate = float64(d) / float64(r.Limit)
// Update the duration to be the end of the gregorian interval
duration = expire - (n.UnixNano() / 1000000)
}
// Calculate how much leaked out of the bucket since the last time we leaked a hit
elapsed := now - b.UpdatedAt
leak := float64(elapsed) / rate
if int64(leak) > 0 {
b.Remaining += leak
b.UpdatedAt = now
}
if int64(b.Remaining) > b.Burst {
b.Remaining = float64(b.Burst)
}
rl := &RateLimitResp{
Limit: b.Limit,
Remaining: int64(b.Remaining),
Status: Status_UNDER_LIMIT,
ResetTime: now + (b.Limit - int64(b.Remaining)) * int64(rate),
}
if s != nil {
defer func() {
s.OnChange(r, item)
}()
}
// If we are already at the limit
if int64(b.Remaining) == 0 {
rl.Status = Status_OVER_LIMIT
return rl, nil
}
// If requested hits takes the remainder
if int64(b.Remaining) == r.Hits {
b.Remaining -= float64(r.Hits)
rl.Remaining = 0
rl.ResetTime = now + (rl.Limit - rl.Remaining) * int64(rate)
return rl, nil
}
// If requested is more than available, then return over the limit
// without updating the bucket.
if r.Hits > int64(b.Remaining) {
rl.Status = Status_OVER_LIMIT
return rl, nil
}
// Client is only interested in retrieving the current status
if r.Hits == 0 {
return rl, nil
}
b.Remaining -= float64(r.Hits)
rl.Remaining = int64(b.Remaining)
rl.ResetTime = now + (rl.Limit - rl.Remaining) * int64(rate)
c.UpdateExpiration(r.HashKey(), now + duration)
return rl, nil
}
duration := r.Duration
rate := float64(duration) / float64(r.Limit)
if HasBehavior(r.Behavior, Behavior_DURATION_IS_GREGORIAN) {
n := clock.Now()
expire, err := GregorianExpiration(n, r.Duration)
if err != nil {
return nil, err
}
// Set the initial duration as the remainder of time until
// the end of the gregorian interval.
duration = expire - (n.UnixNano() / 1000000)
}
// Create a new leaky bucket
b := LeakyBucketItem{
Remaining: float64(r.Burst - r.Hits),
Limit: r.Limit,
Duration: duration,
UpdatedAt: now,
Burst: r.Burst,
}
rl := RateLimitResp{
Status: Status_UNDER_LIMIT,
Limit: b.Limit,
Remaining: r.Burst - r.Hits,
ResetTime: now + (b.Limit - (r.Burst - r.Hits)) * int64(rate),
}
// Client could be requesting that we start with the bucket OVER_LIMIT
if r.Hits > r.Burst {
rl.Status = Status_OVER_LIMIT
rl.Remaining = 0
rl.ResetTime = now + (rl.Limit - rl.Remaining) * int64(rate)
b.Remaining = 0
}
item = &CacheItem{
ExpireAt: now + duration,
Algorithm: r.Algorithm,
Key: r.HashKey(),
Value: &b,
}
c.Add(item)
if s != nil {
s.OnChange(r, item)
}
return &rl, nil
}