-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathrate_limiter.go
More file actions
150 lines (123 loc) · 3.59 KB
/
Copy pathrate_limiter.go
File metadata and controls
150 lines (123 loc) · 3.59 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
package limen
import (
"context"
"maps"
"net/http"
"slices"
"strconv"
"time"
)
type rateLimiter struct {
config *RateLimiterConfig
store RateLimiterStore
httpCore *LimenHTTPCore
rules []*RateLimitRule
}
func newRateLimiter(config *RateLimiterConfig, httpCore *LimenHTTPCore, rules map[string]*RateLimitRule) *rateLimiter {
sortedRules := slices.Collect(maps.Values(rules))
sortRulesBySpecificity(sortedRules)
return &rateLimiter{
config: config,
httpCore: httpCore,
store: determineRateLimiterStore(config, httpCore.core),
rules: sortedRules,
}
}
func determineRateLimiterStore(config *RateLimiterConfig, core *LimenCore) RateLimiterStore {
if config.CustomStore != nil {
return config.CustomStore
}
if config.Store == StoreTypeDatabase {
return newDatabaseRateLimiterStore(core)
}
return newRateLimiterCacheStore(core)
}
func (r *rateLimiter) Check(ctx context.Context, key string, rule *RateLimitRule) (time.Duration, error) {
limit, err := r.store.Get(ctx, key)
if err == ErrRateLimitNotFound {
return r.createNewLimit(ctx, key, rule.window)
}
if err != nil {
return 0, err
}
remainingTime := r.computeRemainingTime(limit, rule.window)
if remainingTime <= 0 {
return r.resetAndIncrement(ctx, limit, rule.window)
}
if limit.Count >= rule.maxRequests {
return remainingTime, ErrRateLimitExceeded
}
if err := r.incrementCounter(ctx, limit, rule.window); err != nil {
return 0, err
}
return remainingTime, nil
}
func (r *rateLimiter) createNewLimit(ctx context.Context, key string, window time.Duration) (time.Duration, error) {
limit := &RateLimit{
Key: key,
Count: 1,
LastRequestAt: time.Now().UnixMilli(),
}
if err := r.store.Set(ctx, limit.Key, limit, window); err != nil {
return 0, err
}
return window, nil
}
func (r *rateLimiter) resetAndIncrement(ctx context.Context, limit *RateLimit, window time.Duration) (time.Duration, error) {
limit.ResetCounter()
limit.Touch()
if err := r.store.Set(ctx, limit.Key, limit, window); err != nil {
return 0, err
}
return window, nil
}
func (r *rateLimiter) incrementCounter(ctx context.Context, limit *RateLimit, window time.Duration) error {
limit.Touch()
return r.store.Set(ctx, limit.Key, limit, window)
}
func (r *rateLimiter) computeRemainingTime(limit *RateLimit, window time.Duration) time.Duration {
remainingTime := window - time.Since(time.UnixMilli(limit.LastRequestAt))
if remainingTime < 0 {
return 0
}
return remainingTime
}
func (r *rateLimiter) findApplicableRule(req *http.Request) *RateLimitRule {
for _, rule := range r.rules {
if pathMatcher(req, rule.pathRegex) {
if rule.limitProvider != nil {
limit, window := rule.limitProvider(req)
if limit == 0 {
break
}
return NewRateLimitRule(rule.path, limit, window)
}
return rule
}
}
return NewRateLimitRule("", r.config.MaxRequests, r.config.Window)
}
func (rl *rateLimiter) handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !rl.config.Enabled {
next.ServeHTTP(w, r)
return
}
rule := rl.findApplicableRule(r)
if !rule.enabled {
next.ServeHTTP(w, r)
return
}
key := rl.config.KeyGenerator(r)
if rule.path != "" && rule.path != "**" {
key = key + "::" + rule.path
}
remainingTime, err := rl.Check(r.Context(), key, rule)
if err != nil {
w.Header().Set("Retry-After", strconv.Itoa(int(remainingTime.Seconds())))
rl.httpCore.Responder.Error(w, r, NewLimenError("Too many requests. Please try again later.", http.StatusTooManyRequests, nil))
return
}
next.ServeHTTP(w, r)
})
}