-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimit.go
127 lines (98 loc) · 2.26 KB
/
ratelimit.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package proxy
import (
"context"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"golang.org/x/time/rate"
)
const rateLimitBurst = 32 << 10
func init() {
proxy_RegisterDialerType("ratelimit", rateLimitFromURL)
}
func rateLimitFromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) {
values := u.Query()
r := rateLimitParseRate(values, "r", "read", "rw", "readwrite")
w := rateLimitParseRate(values, "w", "write", "rw", "readwrite")
return &rateLimitDialer{r, w, forward}, nil
}
func rateLimitParseRate(values url.Values, keys ...string) int {
for _, key := range keys {
s := values.Get(key)
if s == "" {
continue
}
n := 0
switch s[len(s)-1] {
case 'k', 'K':
n = 10
case 'm', 'M':
n = 20
case 'g', 'G':
n = 30
}
s = strings.TrimRight(s, "kKmMgG")
i, err := strconv.Atoi(s)
if err != nil {
return 0
}
return i << n
}
return 0
}
type rateLimitDialer struct {
ReadRate int
WriteRate int
Forward proxy_Dialer
}
func (d *rateLimitDialer) Dial(network, addr string) (net.Conn, error) {
return d.DialContext(context.Background(), network, addr)
}
func (d *rateLimitDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
switch network {
case "tcp", "tcp4", "tcp6":
default:
return nil, fmt.Errorf("proxy/ratelimit: network not implemented: %v", network)
}
c, err := Dial(ctx, d.Forward, network, addr)
if err != nil {
err = fmt.Errorf("proxy/ratelimit: dial %v: %w", addr, err)
}
if err == nil && (d.ReadRate > 0 || d.WriteRate > 0) {
l := &rateLimiter{Conn: c}
if d.ReadRate > 0 {
l.r = rate.NewLimiter(rate.Limit(d.ReadRate), rateLimitBurst)
}
if d.WriteRate > 0 {
l.w = rate.NewLimiter(rate.Limit(d.WriteRate), rateLimitBurst)
}
c = l
}
return c, err
}
type rateLimiter struct {
net.Conn
r, w *rate.Limiter
}
func (l *rateLimiter) Read(b []byte) (n int, err error) {
n, err = l.Conn.Read(b)
if l.r != nil && err == nil {
if l.r.Burst() < len(b) {
l.r.SetBurst(len(b))
}
err = l.r.WaitN(context.Background(), n)
}
return
}
func (l *rateLimiter) Write(b []byte) (n int, err error) {
n, err = l.Conn.Write(b)
if l.w != nil && err == nil {
if l.w.Burst() < len(b) {
l.w.SetBurst(len(b))
}
err = l.w.WaitN(context.Background(), n)
}
return
}