-
Notifications
You must be signed in to change notification settings - Fork 17
/
queue.go
374 lines (324 loc) · 9.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package lib
import (
"context"
"errors"
"github.com/Clever/leakybucket"
"github.com/Clever/leakybucket/memory"
"github.com/sirupsen/logrus"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
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
globalLockedUntil *int64
// bucket path hash as key
queues map[uint64]*QueueChannel
processor func(ctx context.Context, item *QueueItem) (*http.Response, error)
globalBucket leakybucket.Bucket
// bufferSize Defines the size of the request channel buffer for each bucket
bufferSize int
user *BotUserResponse
identifier string
isTokenInvalid *int64
botLimit uint
queueType QueueType
}
func NewRequestQueue(processor func(ctx context.Context, item *QueueItem) (*http.Response, error), token string, bufferSize int) (*RequestQueue, error) {
queueType := NoAuth
var user *BotUserResponse
var err error
if !strings.HasPrefix(token, "Bearer") {
user, err = GetBotUser(token)
if err != nil && token != "" {
return nil, err
}
} else {
queueType = Bearer
}
limit, err := GetBotGlobalLimit(token, user)
memStorage := memory.New()
globalBucket, _ := memStorage.Create("global", limit, 1 * time.Second)
if err != nil {
if strings.HasPrefix(err.Error(), "invalid token") {
// Return a queue that will only return 401s
var invalid = new(int64)
*invalid = 999
return &RequestQueue{
queues: make(map[uint64]*QueueChannel),
processor: processor,
globalBucket: globalBucket,
globalLockedUntil: new(int64),
bufferSize: bufferSize,
user: nil,
identifier: "InvalidTokenQueue",
isTokenInvalid: invalid,
botLimit: limit,
}, nil
}
return nil, err
}
identifier := "NoAuth"
if user != nil {
queueType = Bot
identifier = user.Username + "#" + user.Discrim
}
if queueType == Bearer {
identifier = "Bearer"
}
ret := &RequestQueue{
queues: make(map[uint64]*QueueChannel),
processor: processor,
globalBucket: globalBucket,
globalLockedUntil: new(int64),
bufferSize: bufferSize,
user: user,
identifier: identifier,
isTokenInvalid: new(int64),
botLimit: limit,
queueType: queueType,
}
if queueType != Bearer {
logger.WithFields(logrus.Fields{"globalLimit": limit, "identifier": identifier, "bufferSize": bufferSize}).Info("Created new queue")
// Only sweep bot queues, bearer queues get completely destroyed and hold way less endpoints
go ret.tickSweep()
} else {
logger.WithFields(logrus.Fields{"globalLimit": limit, "identifier": identifier, "bufferSize": bufferSize}).Debug("Created new bearer queue")
}
return ret, nil
}
func (q *RequestQueue) destroy() {
q.Lock()
defer q.Unlock()
logger.Debug("Destroying queue")
for _, val := range q.queues {
close(val.ch)
}
}
func (q *RequestQueue) sweep() {
q.Lock()
defer q.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() {
t := time.NewTicker(5 * time.Minute)
for range t.C {
q.sweep()
}
}
func safeSend(ch chan *QueueItem, value *QueueItem) {
defer func() {
if recover() != nil {
value.errChan <- errors.New("failed to send due to closed channel, sending 429 for client to retry")
Generate429(value.Res)
}
}()
ch <- value
}
func (q *RequestQueue) Queue(req *http.Request, res *http.ResponseWriter, path string, pathHash uint64) error {
logger.WithFields(logrus.Fields{
"bucket": path,
"path": req.URL.Path,
"method": req.Method,
}).Trace("Inbound request")
ch := q.getQueueChannel(path, pathHash)
doneChan := make(chan *http.Response)
errChan := make(chan error)
safeSend(ch.ch, &QueueItem{req, res, doneChan, errChan })
select {
case <-doneChan:
return nil
case err := <-errChan:
return err
}
}
func (q *RequestQueue) getQueueChannel(path string, pathHash uint64) *QueueChannel {
t := time.Now()
q.Lock()
defer q.Unlock()
ch, ok := q.queues[pathHash]
if !ok {
ch = &QueueChannel{ make(chan *QueueItem, q.bufferSize), 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 = 0
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, reset, 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 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 {
item.errChan <- err
return
}
item.doneChan <- nil
}
func return401(item *QueueItem) {
res := *item.Res
res.WriteHeader(401)
body := "{\n\t\"message\": \"401: Unauthorized\",\n\t\"code\": 0\n}"
_, err := res.Write([]byte(body))
if err != nil {
item.errChan <- err
return
}
item.doneChan <- nil
}
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 {
ctx := context.WithValue(item.Req.Context(), "identifier", q.identifier)
if ret404 {
return404webhook(item)
continue
}
if atomic.LoadInt64(q.isTokenInvalid) > 0 {
return401(item)
continue
}
resp, err := q.processor(ctx, item)
if err != nil {
item.errChan <- err
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
scope := resp.Header.Get("x-ratelimit-scope")
if resp.StatusCode == 429 && scope != "shared"{
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 resp.StatusCode == 401 && !isInteraction(item.Req.URL.String()) && q.queueType != NoAuth {
// Permanently lock this queue
logger.WithFields(logrus.Fields{
"bucket": path,
"route": item.Req.URL.String(),
"method": item.Req.Method,
"identifier": q.identifier,
"status": resp.StatusCode,
}).Error("Received 401 during normal operation, assuming token is invalidated, locking bucket permanently")
if EnvGet("DISABLE_401_LOCK", "false") != "true" {
atomic.StoreInt64(q.isTokenInvalid, 999)
}
}
if remaining == 0 || resp.StatusCode == 429 {
time.Sleep(time.Until(time.Now().Add(resetAfter)))
}
prevRem, prevReset = remaining, resetAfter
}
}