/
limiter.go
103 lines (84 loc) · 2.39 KB
/
limiter.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
package websocket
import (
"bytes"
"math"
"strconv"
"strings"
"github.com/throttled/throttled"
core "github.com/miphilipp/devchat-server/internal"
)
type WebsocketVaryBy struct {
RemoteAddr bool
Method bool
Ressource bool
}
// Key returns the key for this request based on the criteria defined by the VaryBy struct.
func (vb *WebsocketVaryBy) Key(method int, ressource string, remoteAddr string) string {
var buf bytes.Buffer
sep := "\n" // Separator defaults to newline
buf.WriteString("ws__")
if vb.RemoteAddr && len(remoteAddr) > 0 {
index := strings.LastIndex(remoteAddr, ":")
var ip string
if index == -1 {
ip = remoteAddr
} else {
ip = remoteAddr[:index]
}
buf.WriteString(strings.ToLower(ip) + sep)
}
if vb.Method {
buf.WriteString(strconv.Itoa(method) + sep)
}
if vb.Ressource {
buf.WriteString(ressource + sep)
}
return buf.String()
}
type WebsocketRateLimiter struct {
RateLimiter throttled.RateLimiter
VaryBy interface {
Key(method int, ressource string, remoteAddr string) string
}
}
func newWebsocketRateLimiter(store throttled.GCRAStore, vary *WebsocketVaryBy, perMin, burstSize int) (*WebsocketRateLimiter, error) {
quota := throttled.RateQuota{MaxRate: throttled.PerMin(perMin), MaxBurst: burstSize}
rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
if err != nil {
return nil, err
}
return &WebsocketRateLimiter{
RateLimiter: rateLimiter,
VaryBy: vary,
}, nil
}
// RateLimit checks if the rate limit for the given citeria was reached. If yes it returns
// an RequestLimitExceededError error as its first return value. The second returned error is not nil
// if something went wrong.
func (l *WebsocketRateLimiter) RateLimit(method int, ressource string, remoteAddr string) (error, error) {
k := l.VaryBy.Key(method, ressource, remoteAddr)
limited, context, err := l.RateLimiter.RateLimit(k, 1)
if err != nil {
return nil, err
}
if limited {
var limit int
if v := context.Limit; v >= 0 {
limit = v
}
var remaining int
if v := context.Remaining; v >= 0 {
remaining = v
}
var resetAfter int
if v := context.ResetAfter; v >= 0 {
resetAfter = int(math.Ceil(v.Seconds()))
}
var retryAfter int
if v := context.RetryAfter; v >= 0 {
retryAfter = int(math.Ceil(v.Seconds()))
}
return core.NewRequestLimitExceededError(retryAfter, remaining, limit, resetAfter), nil
}
return nil, nil
}