-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimiter.go
98 lines (80 loc) · 1.98 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package ratelimiter
import (
"context"
"time"
)
type AllowRequest struct {
Key string
DurationPerToken time.Duration
Burst int
Tokens int
}
type ReserveRequest struct {
Key string
DurationPerToken time.Duration
Burst int
Tokens int
MaxFutureReserve time.Duration
}
type Reservation struct {
*ReserveRequest
OK bool
TimeToAct time.Time
Now time.Time
}
func (r *Reservation) DelayFrom(t time.Time) time.Duration {
if !r.OK {
panic("ratelimiter: cannot get delay from non-OK reservation")
}
delay := r.TimeToAct.Sub(t)
if delay < 0 {
return 0
}
return delay
}
func (r *Reservation) Delay() time.Duration {
return r.DelayFrom(time.Now())
}
func (r *Reservation) RetryAfterFrom(t time.Time) time.Duration {
if r.OK {
panic("ratelimiter: cannot get retry after from OK reservation")
}
delay := r.TimeToAct.Sub(t) - r.MaxFutureReserve
if delay < 0 {
return 0
}
return delay
}
func (r *Reservation) RetryAfter() time.Duration {
return r.RetryAfterFrom(time.Now())
}
type Driver interface {
Reserve(ctx context.Context, req *ReserveRequest) (*Reservation, error)
}
type DriverFunc func(ctx context.Context, req *ReserveRequest) (*Reservation, error)
func (f DriverFunc) Reserve(ctx context.Context, req *ReserveRequest) (*Reservation, error) {
return f(ctx, req)
}
type RateLimiter struct {
driver Driver
}
func New(driver Driver) *RateLimiter {
return &RateLimiter{driver: driver}
}
func (lim *RateLimiter) Allow(ctx context.Context, req *AllowRequest) (bool, error) {
reserveReq := &ReserveRequest{
Key: req.Key,
DurationPerToken: req.DurationPerToken,
Burst: req.Burst,
Tokens: req.Tokens,
MaxFutureReserve: 0,
}
r, err := lim.Reserve(ctx, reserveReq)
if err != nil {
return false, err
}
return r.OK, nil
}
func (lim *RateLimiter) Reserve(ctx context.Context, req *ReserveRequest) (*Reservation, error) {
return lim.driver.Reserve(ctx, req)
}