-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimiter.go
74 lines (67 loc) · 1.82 KB
/
ratelimiter.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
package golimit
import (
"time"
)
// the Lua script that implements the Token Bucket Algorithm.
// bucket.tc represents the token count.
// bucket.ts represents the timestamp of the last time the bucket was refilled.
const luaRateLimiter = `
local key = KEYS[1]
local interval = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local amount = tonumber(ARGV[4])
local bucket = {tc=capacity, ts=now}
local value = redis.call("get", key)
if value then
bucket = cjson.decode(value)
end
local added = math.floor((now - bucket.ts) / interval)
if added > 0 then
bucket.tc = math.min(bucket.tc + added, capacity)
bucket.ts = bucket.ts + added * interval
end
if bucket.tc >= amount then
bucket.tc = bucket.tc - amount
bucket.ts = string.format("%.f", bucket.ts)
if redis.call("set", key, cjson.encode(bucket)) then
return 1
end
end
return 0
`
// RateLimiter implements the Token Bucket Algorithm.
// See https://en.wikipedia.org/wiki/Token_bucket.
type RateLimiter struct {
baseBucket
script *Script
key string
}
// NewRateLimiter returns a new token-bucket rate limiter special for key in redis
// with the specified bucket configuration.
func NewRateLimiter(redis Redis, key string, config *Config) *RateLimiter {
return &RateLimiter{
baseBucket: baseBucket{config: config},
script: NewScript(redis, luaRateLimiter),
key: key,
}
}
// Take takes amount tokens from the bucket.
func (b *RateLimiter) Take(amount int64) (bool, error) {
config := b.Config()
if amount > config.Capacity {
return false, nil
}
now := time.Now().UnixNano()
result, err := b.script.Run(
[]string{b.key},
int64(config.Interval/time.Microsecond),
config.Capacity,
int64(time.Duration(now)/time.Microsecond),
amount,
)
if err != nil {
return false, err
}
return result == int64(1), nil
}