shared.go57 lines, 1.9 KB
| 1 | package ratelimit |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "time" |
| 6 | |
| 7 | "github.com/redis/go-redis/v9" |
| 8 | ) |
| 9 | |
| 10 | // take is Allow, as one script inside Redis. |
| 11 | // KEYS[1] is the bucket. ARGV is the burst, the tokens a minute, and the time in milliseconds. |
| 12 | var take = redis.NewScript(` |
| 13 | local burst, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]) / 60, tonumber(ARGV[3]) |
| 14 | local b = redis.call('HMGET', KEYS[1], 'tokens', 'seen') |
| 15 | local tokens, seen = tonumber(b[1]) or burst, tonumber(b[2]) or now |
| 16 | tokens = math.min(burst, tokens + math.max(0, now - seen) / 1000 * rate) |
| 17 | local allowed, wait = 0, 0 |
| 18 | if tokens >= 1 then |
| 19 | tokens = tokens - 1 |
| 20 | allowed = 1 |
| 21 | else |
| 22 | wait = math.ceil((1 - tokens) / rate * 1000) |
| 23 | end |
| 24 | redis.call('HSET', KEYS[1], 'tokens', tokens, 'seen', math.max(now, seen)) |
| 25 | redis.call('PEXPIRE', KEYS[1], math.ceil(burst / rate * 1000)) |
| 26 | return {allowed, math.floor(tokens), wait}`) |
| 27 | |
| 28 | // A Shared limiter keeps its buckets in Redis, where every API server finds the same ones. |
| 29 | type Shared struct { |
| 30 | name string |
| 31 | burst int |
| 32 | perMinute int |
| 33 | now func() time.Time |
| 34 | rdb *redis.Client |
| 35 | } |
| 36 | |
| 37 | // NewShared returns a Shared limiter for the policy called name, with its buckets in rdb. |
| 38 | func NewShared(rdb *redis.Client, name string, burst, perMinute int) *Shared { |
| 39 | return &Shared{name: name, burst: burst, perMinute: perMinute, now: time.Now, rdb: rdb} |
| 40 | } |
| 41 | |
| 42 | // Policy is what this limit is called, and how many tokens a bucket gains in a minute. |
| 43 | func (s *Shared) Policy() (name string, perMinute int) { |
| 44 | return s.name, s.perMinute |
| 45 | } |
| 46 | |
| 47 | // Allow takes one token from key's bucket in Redis, if there is one. |
| 48 | func (s *Shared) Allow(ctx context.Context, key string) (Result, error) { |
| 49 | keys := []string{"ratelimit:" + s.name + ":" + key} |
| 50 | now := s.now().UnixMilli() |
| 51 | v, err := take.Run(ctx, s.rdb, keys, s.burst, s.perMinute, now).Int64Slice() |
| 52 | if err != nil { |
| 53 | return Result{}, err |
| 54 | } |
| 55 | wait := time.Duration(v[2]) * time.Millisecond |
| 56 | return Result{Allowed: v[0] == 1, Remaining: int(v[1]), RetryAfter: wait}, nil |
| 57 | } |