-
Notifications
You must be signed in to change notification settings - Fork 20
/
callratelimiter.go
108 lines (91 loc) · 2.09 KB
/
callratelimiter.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
99
100
101
102
103
104
105
106
107
108
package services
import (
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
)
type CallRateLimiter struct {
proxyCount uint
rateLimit uint
burstLimit uint
mutex sync.Mutex
visitors map[string]*callRateVisitor
}
type callRateVisitor struct {
limiter *rate.Limiter
lastSeen time.Time
}
var GlobalCallRateLimiter *CallRateLimiter
// StartFrontendCache is used to start the global frontend cache service
func StartCallRateLimiter(proxyCount uint, rateLimit uint, burstLimit uint) error {
if GlobalCallRateLimiter != nil {
return nil
}
GlobalCallRateLimiter = &CallRateLimiter{
proxyCount: proxyCount,
rateLimit: rateLimit,
burstLimit: burstLimit,
visitors: map[string]*callRateVisitor{},
}
go GlobalCallRateLimiter.cleanupVisitors()
return nil
}
func (crl *CallRateLimiter) CheckCallLimit(r *http.Request, callCost uint) error {
if crl == nil {
return nil
}
visitor := crl.getVisitor(r)
if visitor == nil {
return fmt.Errorf("could not get visitor")
}
if !visitor.limiter.AllowN(time.Now(), int(callCost)) {
return fmt.Errorf("call rate limit exceeded")
}
return nil
}
func (crl *CallRateLimiter) getVisitor(r *http.Request) *callRateVisitor {
var ip string
if crl.proxyCount > 0 {
forwardIps := strings.Split(r.Header.Get("X-Forwarded-For"), ", ")
forwardIdx := len(forwardIps) - int(crl.proxyCount)
if forwardIdx >= 0 {
ip = forwardIps[forwardIdx]
}
}
if ip == "" {
var err error
ip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
return nil
}
}
crl.mutex.Lock()
defer crl.mutex.Unlock()
visitor := crl.visitors[ip]
if visitor == nil {
visitor = &callRateVisitor{
limiter: rate.NewLimiter(rate.Limit(crl.rateLimit), int(crl.burstLimit)),
lastSeen: time.Now(),
}
crl.visitors[ip] = visitor
} else {
visitor.lastSeen = time.Now()
}
return visitor
}
func (crl *CallRateLimiter) cleanupVisitors() {
for {
time.Sleep(time.Minute)
crl.mutex.Lock()
for ip, v := range crl.visitors {
if time.Since(v.lastSeen) > 3*time.Minute {
delete(crl.visitors, ip)
}
}
crl.mutex.Unlock()
}
}