Repository navigation
Expand file tree
/
Copy pathratelimit.go
More file actions
220 lines (182 loc) · 5.24 KB
/
Copy pathratelimit.go
File metadata and controls
220 lines (182 loc) · 5.24 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package gserv
import (
"context"
"fmt"
"net/http"
"strconv"
"sync"
"time"
"go.oneofone.dev/genh"
)
// LimitKeyFn is a function that generates a rate limit key from the request context.
type LimitKeyFn = func(ctx *Context) string
// RateLimiter returns a middleware that enforces rate limits per key derived from the context.
// If limitKey is nil, it defaults to using the client IP address.
// If setHeaders is true, it sets X-Rate-Limit-Limit, X-Rate-Limit-Remaining, and Retry-After headers on responses.
func RateLimiter(ctx context.Context, limitKey LimitKeyFn, maxPerSecond, maxPerMinute, maxPerHour int, setHeaders bool) Handler {
ls := NewLimiters(ctx, maxPerSecond, maxPerMinute, maxPerHour)
limitsHeader := fmt.Sprintf(`%ds, %dm, %dh`, maxPerSecond, maxPerMinute, maxPerHour)
if limitKey == nil {
limitKey = func(ctx *Context) string {
return ctx.ClientIP()
}
}
return func(ctx *Context) Response {
var (
key = limitKey(ctx)
l = ls.Get(key)
h = ctx.Header()
d, err = l.Allowed()
sec, min, hr = l.RequestsLeft()
)
if setHeaders {
h.Set("X-Rate-Limit-Limit", limitsHeader)
h.Set("X-Rate-Limit-Remaining", fmt.Sprintf("%ds, %dm, %dh", sec, min, hr))
}
if err == nil {
return nil
}
if setHeaders {
ds := strconv.Itoa(int(d.Seconds() + 1))
h.Set("X-Rate-Limit-Reset", ds)
h.Set("Retry-After", ds)
}
return NewJSONErrorResponse(http.StatusTooManyRequests, err)
}
}
// Limiter enforces rate limits per second, minute, and hour.
type Limiter struct {
mux sync.RWMutex
// max per
maxPerSecond int64
maxPerMinute int64
maxPerHour int64
// requests per
reqPerSecond int64
reqPerMinute int64
reqPerHour int64
lastSec int64
lastMin int64
lastHour int64
totalAllowed int64
totalBlocked int64
}
// NewLimiter creates a new rate limiter with the given limits per second, minute, and hour.
func NewLimiter(maxPerSecond, maxPerMinute, maxPerHour int) *Limiter {
ts := time.Now().Unix()
return &Limiter{
maxPerSecond: int64(maxPerSecond),
maxPerMinute: int64(maxPerMinute),
maxPerHour: int64(maxPerHour),
lastSec: ts,
lastMin: ts,
lastHour: ts,
}
}
// Allowed checks if a request is allowed under the current rate limits.
// It returns the duration until the next request can be made and an error if the limit is exceeded.
func (l *Limiter) Allowed() (d time.Duration, err error) {
now := time.Now().Unix()
l.mux.Lock()
defer func() {
if err == nil {
l.totalAllowed++
} else {
l.totalBlocked++
}
l.mux.Unlock()
}()
if now-l.lastHour > 3599 {
l.reqPerHour = 0
l.lastHour = now
}
if l.reqPerHour++; l.reqPerHour > l.maxPerHour {
d = time.Hour - (time.Second * time.Duration(now-l.lastHour))
return d, fmt.Errorf("%d exceeds %d/req per hour, wait %v", l.reqPerHour, l.maxPerHour, d.String())
}
if now-l.lastMin > 59 {
l.reqPerMinute = 0
l.lastMin = now
}
if l.reqPerMinute++; l.reqPerMinute > l.maxPerMinute {
d = time.Minute - (time.Second * time.Duration(now-l.lastMin))
return d, fmt.Errorf("%d exceeds %d/req per minute, wait %v", l.reqPerMinute, l.maxPerMinute, d.String())
}
if now-l.lastSec > 0 {
l.lastSec = now
l.reqPerSecond = 0
}
if l.reqPerSecond++; l.reqPerSecond > l.maxPerSecond {
d = time.Second - (time.Second * time.Duration(now-l.lastSec))
return d, fmt.Errorf("%d exceeds %d/req per second, wait %v", l.reqPerSecond, l.maxPerSecond, d.String())
}
return 0, nil
}
// LastAction returns the time of the last allowed or blocked action.
func (l *Limiter) LastAction() (t time.Time) {
l.mux.RLock()
t = time.Unix(max(l.lastSec, l.lastMin, l.lastHour), 0)
l.mux.RUnlock()
return
}
func max(vs ...int64) int64 {
m := vs[0]
for _, v := range vs[1:] {
if v > m {
m = v
}
}
return m
}
// RequestsLeft returns the remaining allowed requests per second, minute, and hour.
func (l *Limiter) RequestsLeft() (perSecond, perMinute, perHour int64) {
l.mux.RLock()
perHour, perMinute, perSecond = max(0, l.maxPerHour-l.reqPerHour), max(0, l.maxPerMinute-l.reqPerMinute), max(0, l.maxPerSecond-l.reqPerSecond)
l.mux.RUnlock()
return
}
// NewLimiters creates a new pool of rate limiters with the given limits per second, minute, and hour.
func NewLimiters(ctx context.Context, maxPerSecond, maxPerMinute, maxPerHour int) *Limiters {
if ctx == nil {
ctx = context.Background()
}
ls := &Limiters{
ctx: ctx,
maxPerSecond: maxPerSecond,
maxPerMinute: maxPerMinute,
maxPerHour: maxPerHour,
}
go ls.clean()
return ls
}
// Limiters is a pool of rate limiters keyed by an arbitrary string.
type Limiters struct {
ctx context.Context
m genh.LMap[string, *Limiter]
maxPerSecond int
maxPerMinute int
maxPerHour int
}
func (ls *Limiters) clean() {
const checkDuration = time.Hour + (time.Minute * 30)
tk := time.NewTicker(time.Minute * 25)
for {
select {
case <-ls.ctx.Done():
return
case t := <-tk.C:
for _, key := range ls.m.Keys() {
l := ls.m.Get(key)
if t.Sub(l.LastAction()) > checkDuration {
ls.m.Delete(key)
}
}
}
}
}
// Get returns the rate limiter for the given key, creating a new one if it doesn't exist.
func (ls *Limiters) Get(key string) *Limiter {
return ls.m.MustGet(key, func() *Limiter {
return NewLimiter(ls.maxPerSecond, ls.maxPerMinute, ls.maxPerHour)
})
}