-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
197 lines (158 loc) · 3.2 KB
/
client.go
File metadata and controls
197 lines (158 loc) · 3.2 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
package main
import (
"bufio"
"errors"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"golang.org/x/time/rate"
)
type Client struct {
http *http.Client
localLimit *rate.Limiter
remoteRL *RemoteRL
maxLimit int
inflight chan struct{}
}
func NewLimitedClient(rps int) *Client {
initProxies()
cli := &Client{
http: &http.Client{
Timeout: 15 * time.Second,
},
localLimit: rate.NewLimiter(rate.Limit(rps), rps),
remoteRL: NewRemoteRL(),
inflight: make(chan struct{}, 20),
}
if os.Getenv("ENABLE_PROXY") == "true" && len(proxy.proxies) != 0 {
cli.http.Transport = &http.Transport{
Proxy: proxy.NextProxy,
DisableKeepAlives: true,
}
}
return cli
}
func (c *Client) Do(req *http.Request) (*http.Response, error) {
c.inflight <- struct{}{}
defer func() { <-c.inflight }()
c.remoteRL.Check()
if err := c.localLimit.Wait(req.Context()); err != nil {
return nil, err
}
resp, err := c.http.Do(req)
if err != nil {
f, _ := os.OpenFile("error.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
w := bufio.NewWriter(f)
w.WriteString(err.Error() + "\n")
w.Flush()
f.Close()
return nil, err
}
c.UpdateLimit(resp)
if resp.StatusCode == 429 {
c.remoteRL.TriggerFixed(time.Hour)
log.Printf("Received 429, waiting for 1 hour")
return nil, errors.New("remote rate limit reached (429)")
}
return resp, nil
}
type RemoteRL struct {
mu sync.Mutex
waitUntil time.Time
waiting bool
cond *sync.Cond
timer *time.Timer
remaining int
}
func NewRemoteRL() *RemoteRL {
rl := &RemoteRL{}
rl.cond = sync.NewCond(&rl.mu)
return rl
}
func (rl *RemoteRL) Check() {
rl.mu.Lock()
defer rl.mu.Unlock()
if !rl.waiting {
return
}
rl.cond.Wait()
}
func (rl *RemoteRL) TriggerFixed(d time.Duration) {
rl.mu.Lock()
if rl.waiting {
rl.mu.Unlock()
return
}
// Cancel any previous timer
if rl.timer != nil {
rl.timer.Stop()
}
rl.waiting = true
rl.waitUntil = time.Now().Add(d)
rl.timer = time.NewTimer(d)
// Dedicated wait goroutine
go func() {
<-rl.timer.C
rl.mu.Lock()
rl.waiting = false
rl.mu.Unlock()
rl.cond.Broadcast()
}()
rl.mu.Unlock()
}
func (c *Client) UpdateLimit(resp *http.Response) {
limitStr := resp.Header.Get("X-RateLimit-Limit")
remainStr := resp.Header.Get("X-RateLimit-Remaining")
// resetStr := resp.Header.Get("X-Ratelimit-Reset")
if limitStr == "" || remainStr == "" {
return
}
limit, err := strconv.Atoi(limitStr)
if err != nil {
return
}
remain, err := strconv.Atoi(remainStr)
if err != nil {
return
}
if c.maxLimit == 0 {
c.maxLimit = limit
}
if remain > c.maxLimit {
c.maxLimit = remain
}
rl := c.remoteRL
rl.mu.Lock()
defer rl.mu.Unlock()
if remain > rl.remaining {
if remain > (c.maxLimit / 2) {
rl.remaining = remain
rl.waiting = false
if rl.timer != nil {
rl.timer.Stop()
rl.cond.Broadcast()
}
}
return
}
rl.remaining = remain
if remain < 100 {
resetDur := 60 * time.Second
rl.waiting = true
rl.waitUntil = time.Now().Add(resetDur)
if rl.timer != nil {
rl.timer.Stop()
}
rl.timer = time.NewTimer(resetDur)
go func() {
<-rl.timer.C
rl.mu.Lock()
rl.waiting = false
rl.mu.Unlock()
rl.cond.Broadcast()
}()
}
}