-
Notifications
You must be signed in to change notification settings - Fork 18
/
queue.go
284 lines (252 loc) · 7.1 KB
/
queue.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
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package lib
import (
"errors"
"github.com/Clever/leakybucket"
"github.com/Clever/leakybucket/memory"
"github.com/sirupsen/logrus"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
// QueueChannelBufferSize Defines the size of the request channel buffer for each bucket
// Realistically, this should be as high as possible to prevent blocking sends
// While blocking sends aren't a problem in itself, they are unordered, meaning
// in a high load situation, if this number is too low, it would cause requests to
// fight to send, which messes up the ordering of requests.
const QueueChannelBufferSize = 200
type QueueItem struct {
Req *http.Request
Res *http.ResponseWriter
doneChan chan *http.Response
errChan chan error
}
type QueueChannel struct {
ch chan *QueueItem
lastUsed *time.Time
}
type RequestQueue struct {
sync.RWMutex
channelMu sync.Mutex
globalLockedUntil *int64
sweepTicker *time.Ticker
// bucket path hash as key
queues map[uint64]*QueueChannel
processor func(item *QueueItem) *http.Response
globalBucket leakybucket.Bucket
}
func NewRequestQueue(processor func(item *QueueItem) *http.Response, globalLimit uint) *RequestQueue {
memStorage := memory.New()
globalBucket, err := memStorage.Create("global", globalLimit, 1 * time.Second)
if err != nil {
panic(err)
}
ret := &RequestQueue{
queues: make(map[uint64]*QueueChannel),
processor: processor,
globalBucket: globalBucket,
globalLockedUntil: new(int64),
}
go ret.tickSweep()
return ret
}
func (q *RequestQueue) sweep() {
q.Lock()
q.channelMu.Lock()
defer q.Unlock()
defer q.channelMu.Unlock()
logger.Info("Sweep start")
sweptEntries := 0
for key, val := range q.queues {
if time.Since(*val.lastUsed) > 10 * time.Minute {
close(val.ch)
delete(q.queues, key)
sweptEntries++
}
}
logger.WithFields(logrus.Fields{"sweptEntries": sweptEntries}).Info("Finished sweep")
}
func (q *RequestQueue) tickSweep() {
q.sweepTicker = time.NewTicker(5 * time.Minute)
for range q.sweepTicker.C {
q.sweep()
}
}
func (q *RequestQueue) Queue(req *http.Request, res *http.ResponseWriter) (string, *http.Response, error) {
path := GetOptimisticBucketPath(req.URL.Path, req.Method)
q.RLock()
ch := q.getQueueChannel(path)
doneChan := make(chan *http.Response)
errChan := make(chan error)
ch.ch <- &QueueItem{req, res, doneChan, errChan }
q.RUnlock()
select {
case resp := <-doneChan:
return path, resp, nil
case err := <-errChan:
return path, nil, err
}
}
func (q *RequestQueue) getQueueChannel(path string) *QueueChannel {
pathHash := HashCRC64(path)
q.channelMu.Lock()
defer q.channelMu.Unlock()
t := time.Now()
ch, ok := q.queues[pathHash]
if !ok {
// Check again to see if the queue channel wasn't created
// While we didn't hold the exclusive lock
ch, ok = q.queues[pathHash]
if !ok {
ch = &QueueChannel{ make(chan *QueueItem, QueueChannelBufferSize), &t }
q.queues[pathHash] = ch
// It's important that we only have 1 goroutine per channel
go q.subscribe(ch, path, pathHash)
}
} else {
ch.lastUsed = &t
}
return ch
}
func parseHeaders(headers *http.Header) (int64, int64, time.Duration, bool, error) {
if headers == nil {
return 0, 0, 0, false, errors.New("null headers")
}
limit := headers.Get("x-ratelimit-limit")
remaining := headers.Get("x-ratelimit-remaining")
resetAfter := headers.Get("x-ratelimit-reset-after")
if resetAfter == "" {
// Globals return no x-ratelimit-reset-after headers, this is the best option without parsing the body
resetAfter = headers.Get("retry-after")
}
isGlobal := headers.Get("x-ratelimit-global") == "true"
var resetParsed float64
var reset time.Duration
var err error
if resetAfter != "" {
resetParsed, err = strconv.ParseFloat(resetAfter, 64)
if err != nil {
return 0, 0, 0, false, err
}
// Convert to MS instead of seconds to preserve decimal precision
reset = time.Duration(int(resetParsed * 1000)) * time.Millisecond
}
if isGlobal {
return 0, 0, reset, isGlobal, nil
}
if limit == "" {
return 0, 0, 0, false, nil
}
limitParsed, err := strconv.ParseInt(limit, 10, 32)
if err != nil {
return 0, 0, 0, false, err
}
remainingParsed, err := strconv.ParseInt(remaining, 10, 32)
if err != nil {
return 0, 0, 0, false, err
}
return limitParsed, remainingParsed, reset, isGlobal, nil
}
func (q *RequestQueue) takeGlobal() {
takeGlobal:
waitTime := atomic.LoadInt64(q.globalLockedUntil)
if waitTime > 0 {
time.Sleep(time.Until(time.Unix(0, waitTime)))
sw := atomic.CompareAndSwapInt64(q.globalLockedUntil, waitTime, 0)
if sw {
logger.Info("Unlocked global bucket")
}
}
_, err := q.globalBucket.Add(1)
if err != nil {
reset := q.globalBucket.Reset()
time.Sleep(time.Until(reset))
goto takeGlobal
}
}
func return404webhook(item *QueueItem) {
res := *item.Res
res.WriteHeader(404)
body := "{\n \"message\": \"Unknown Webhook\",\n \"code\": 10015\n}"
_, err := res.Write([]byte(body))
if err != nil {
return
}
}
func isInteraction(url string) bool {
parts := strings.Split(strings.SplitN(url, "?", 1)[0], "/")
for _, p := range parts {
if len(p) > 128 {
return true
}
}
return false
}
func (q *RequestQueue) subscribe(ch *QueueChannel, path string, pathHash uint64) {
// This function has 1 goroutine for each bucket path
// Locking here is not needed
//Only used for logging
var prevRem int64 = 0
var prevReset time.Duration = 0
// Fail fast path for webhook 404s
var ret404 = false
for item := range ch.ch {
q.takeGlobal()
if ret404 {
return404webhook(item)
item.doneChan <- nil
continue
}
resp := q.processor(item)
if resp == nil {
item.errChan <- errors.New("invalid HTTP response from process()")
continue
}
_, remaining, resetAfter, isGlobal, err := parseHeaders(&resp.Header)
if isGlobal {
//Lock global
sw := atomic.CompareAndSwapInt64(q.globalLockedUntil, 0, time.Now().Add(resetAfter).UnixNano())
if sw {
logger.WithFields(logrus.Fields{
"until": time.Now().Add(resetAfter),
"resetAfter": resetAfter,
}).Warn("Global reached, locking")
}
}
if err != nil {
item.errChan <- err
continue
}
item.doneChan <- resp
if resp.StatusCode == 429 {
logger.WithFields(logrus.Fields{
"prevRemaining": prevRem,
"prevResetAfter": prevReset,
"remaining": remaining,
"resetAfter": resetAfter,
"bucket": path,
"route": item.Req.URL.String(),
"method": item.Req.Method,
"isGlobal": isGlobal,
"pathHash": pathHash,
// TODO: Remove this when 429s are not a problem anymore
"discordBucket": resp.Header.Get("x-ratelimit-bucket"),
"ratelimitScope": resp.Header.Get("x-ratelimit-scope"),
}).Warn("Unexpected 429")
}
if resp.StatusCode == 404 && strings.HasPrefix(path, "/webhooks/") && !isInteraction(item.Req.URL.String()) {
logger.WithFields(logrus.Fields{
"bucket": path,
"route": item.Req.URL.String(),
"method": item.Req.Method,
}).Info("Setting fail fast 404 for webhook")
ret404 = true
}
if remaining == 0 || resp.StatusCode == 429 {
time.Sleep(time.Until(time.Now().Add(resetAfter)))
}
prevRem, prevReset = remaining, resetAfter
}
}