-
Notifications
You must be signed in to change notification settings - Fork 0
/
leaky_bucket.go
59 lines (47 loc) · 1.13 KB
/
leaky_bucket.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
package ratelimit
import (
"context"
"time"
)
// todo: add support for concurrent access
type LeakyBucketLimiter struct {
s Store[leakyBucketRecord]
}
type leakyBucketRecord struct {
Last int64 `redis:"last"`
}
func NewLeakyBucketLimiter(s Store[leakyBucketRecord]) Limiter {
return &LeakyBucketLimiter{s: s}
}
func (l *LeakyBucketLimiter) Allow(ctx context.Context, key string, limit *Limit) (*Result, error) {
if limit.Rate <= 0 {
return &Result{
Allowed: true,
}, nil
}
bucket, err := l.s.Get(ctx, key)
if err != nil || bucket.Last == 0 {
l.s.Set(ctx, key, &leakyBucketRecord{
Last: time.Now().UnixNano(),
})
return &Result{
Allowed: true,
}, nil
}
elapsedTime := time.Now().UnixNano() - bucket.Last
rate := limit.Period.Nanoseconds() / int64(limit.Rate)
if elapsedTime < rate {
return &Result{
Allowed: false,
RetryAfter: time.Duration(l.retryAfter(elapsedTime, rate)),
}, nil
}
bucket.Last = time.Now().UnixNano()
l.s.Set(ctx, key, bucket)
return &Result{
Allowed: true,
}, nil
}
func (l *LeakyBucketLimiter) retryAfter(elapsedTime, rate int64) int64 {
return rate - elapsedTime
}