ratelimit.go93 lines, 2.1 KB
| 1 | // Package ratelimit is a token bucket rate limiter in memory, or shared through Redis. |
| 2 | package ratelimit |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "sync" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | // A Limiter keeps one bucket of tokens per key. |
| 11 | type Limiter struct { |
| 12 | name string |
| 13 | burst int |
| 14 | perMinute int |
| 15 | now func() time.Time |
| 16 | |
| 17 | mu sync.Mutex |
| 18 | buckets map[string]bucket |
| 19 | swept time.Time |
| 20 | } |
| 21 | |
| 22 | // A bucket is all we keep about one key. |
| 23 | type bucket struct { |
| 24 | tokens float64 |
| 25 | seen time.Time |
| 26 | } |
| 27 | |
| 28 | // New returns a Limiter for the policy called name. Its buckets hold burst tokens, |
| 29 | // and they gain perMinute tokens a minute. |
| 30 | func New(name string, burst, perMinute int) *Limiter { |
| 31 | return &Limiter{ |
| 32 | name: name, |
| 33 | burst: burst, |
| 34 | perMinute: perMinute, |
| 35 | now: time.Now, |
| 36 | buckets: make(map[string]bucket), |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // Result is the answer to one request. |
| 41 | type Result struct { |
| 42 | Allowed bool |
| 43 | Remaining int |
| 44 | RetryAfter time.Duration |
| 45 | } |
| 46 | |
| 47 | // Policy is what this limit is called, and how many tokens a bucket gains in a minute. |
| 48 | func (l *Limiter) Policy() (name string, perMinute int) { |
| 49 | return l.name, l.perMinute |
| 50 | } |
| 51 | |
| 52 | // Allow takes one token from key's bucket, if there is one. |
| 53 | func (l *Limiter) Allow(_ context.Context, key string) (Result, error) { |
| 54 | burst, rate := float64(l.burst), float64(l.perMinute)/60 |
| 55 | l.mu.Lock() |
| 56 | defer l.mu.Unlock() |
| 57 | now := l.now() |
| 58 | if now.Sub(l.swept) >= l.full() { |
| 59 | l.sweep(now) |
| 60 | } |
| 61 | b, ok := l.buckets[key] |
| 62 | if !ok { |
| 63 | b = bucket{tokens: burst, seen: now} |
| 64 | } |
| 65 | b.tokens = min(burst, b.tokens+now.Sub(b.seen).Seconds()*rate) |
| 66 | b.seen = now |
| 67 | |
| 68 | var res Result |
| 69 | if b.tokens >= 1 { |
| 70 | b.tokens-- |
| 71 | res.Allowed = true |
| 72 | } else { |
| 73 | res.RetryAfter = time.Duration((1 - b.tokens) / rate * float64(time.Second)) |
| 74 | } |
| 75 | res.Remaining = int(b.tokens) |
| 76 | l.buckets[key] = b |
| 77 | return res, nil |
| 78 | } |
| 79 | |
| 80 | // full is how long an empty bucket takes to fill up. |
| 81 | func (l *Limiter) full() time.Duration { |
| 82 | return time.Duration(l.burst) * time.Minute / time.Duration(l.perMinute) |
| 83 | } |
| 84 | |
| 85 | // sweep forgets every bucket that has been idle for that long. It is full again. |
| 86 | func (l *Limiter) sweep(now time.Time) { |
| 87 | for key, b := range l.buckets { |
| 88 | if now.Sub(b.seen) >= l.full() { |
| 89 | delete(l.buckets, key) |
| 90 | } |
| 91 | } |
| 92 | l.swept = now |
| 93 | } |