-
Notifications
You must be signed in to change notification settings - Fork 921
/
mqueue.go
497 lines (403 loc) · 11.7 KB
/
mqueue.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package mqueue
import (
"container/list"
"encoding/json"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/jonas747/discordgo"
"github.com/jonas747/retryableredis"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/common"
"github.com/mediocregopher/radix"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var (
sources = make(map[string]PluginWithErrorHandler)
stopChan = make(chan *sync.WaitGroup)
currentlyProcessing = make([]int64, 0)
currentlyProcessingLock sync.RWMutex
startedLock sync.Mutex
started bool
numWorkers = new(int32)
webhookSession *discordgo.Session
logger = common.GetPluginLogger(&Plugin{})
)
type PluginWithErrorHandler interface {
DisableFeed(elem *QueuedElement, err error)
}
type PluginWithWebhookAvatar interface {
WebhookAvatar() string
}
var (
_ bot.LateBotInitHandler = (*Plugin)(nil)
_ bot.BotStopperHandler = (*Plugin)(nil)
)
type Plugin struct {
}
func (p *Plugin) PluginInfo() *common.PluginInfo {
return &common.PluginInfo{
Name: "mqueue",
SysName: "mqueue",
Category: common.PluginCategoryCore,
}
}
func RegisterPlugin() {
var err error
webhookSession, err = discordgo.New()
if err != nil {
logger.WithError(err).Error("failed initiializing webhook session")
}
p := &Plugin{}
common.RegisterPlugin(p)
}
func RegisterSource(name string, source PluginWithErrorHandler) {
sources[name] = source
}
func IncrIDCounter() (next int64) {
err := common.RedisPool.Do(retryableredis.Cmd(&next, "INCR", "mqueue_id_counter"))
if err != nil {
logger.WithError(err).Error("Failed increasing mqueue id counter")
return -1
}
return next
}
func QueueMessageString(source, sourceID string, guildID, channel int64, message string) {
QueueMessage(source, sourceID, guildID, channel, message, nil)
}
func QueueMessageEmbed(source, sourceID string, guildID, channel int64, embed *discordgo.MessageEmbed) {
QueueMessage(source, sourceID, guildID, channel, "", embed)
}
func QueueMessage(source, sourceID string, guildID, channel int64, msgStr string, embed *discordgo.MessageEmbed) {
QueueMessageWebhook(source, sourceID, guildID, channel, msgStr, embed, false, "")
}
func QueueMessageWebhook(source, sourceID string, guildID, channel int64, msgStr string, embed *discordgo.MessageEmbed, webhook bool, webhookUsername string) {
nextID := IncrIDCounter()
if nextID == -1 {
return
}
elem := &QueuedElement{
ID: nextID,
Source: source,
SourceID: sourceID,
Channel: channel,
MessageStr: msgStr,
MessageEmbed: embed,
Guild: guildID,
UseWebhook: webhook,
WebhookUsername: webhookUsername,
}
serialized, err := json.Marshal(elem)
if err != nil {
logger.WithError(err).Error("Failed marshaling mqueue element")
return
}
err = common.RedisPool.Do(retryableredis.Cmd(nil, "ZADD", "mqueue", "-1", string(serialized)))
if err != nil {
return
}
}
func (p *Plugin) LateBotInit() {
go startPolling()
go processWorker()
go workerScaler()
}
func (p *Plugin) StopBot(wg *sync.WaitGroup) {
startedLock.Lock()
if !started {
startedLock.Unlock()
wg.Done()
return
}
startedLock.Unlock()
stopChan <- wg
}
func workerScaler() {
lastWorkerSpawnedAt := time.Now()
t := time.NewTicker(time.Second * 10)
deltaHistory := list.New()
sizeHistory := list.New()
lastSize := 0
for {
<-t.C
workmu.Lock()
current := len(workSlice)
workmu.Unlock()
delta := current - lastSize
lastSize = current
deltaHistory.PushBack(delta)
sizeHistory.PushBack(current)
if deltaHistory.Len() > 6*5 { // keep 5 minute average
deltaHistory.Remove(deltaHistory.Front())
sizeHistory.Remove(sizeHistory.Front())
}
// see if we should launch a worker
if current < 100 || time.Since(lastWorkerSpawnedAt) < time.Minute*10 || deltaHistory.Len() < 6 {
// don't bother launching workers when below 100, and atleast have a minute of averages
continue
}
// calculate average to see if it increased or decreased
deltaAverage := calcListAverage(deltaHistory)
sizeAverage := calcListAverage(sizeHistory)
if deltaAverage > 1 && sizeAverage > 1000 {
logger.Info("Launched new mqueue worker, total workers: ", atomic.LoadInt32(numWorkers)+1)
go processWorker()
lastWorkerSpawnedAt = time.Now()
}
}
}
func calcListAverage(in *list.List) int {
total := 0
for elem := in.Front(); elem != nil; elem = elem.Next() {
total += elem.Value.(int)
}
average := total / in.Len()
return average
}
func startPolling() {
startedLock.Lock()
if started {
startedLock.Unlock()
panic("Already started mqueue")
}
started = true
startedLock.Unlock()
first := true
ticker := time.NewTicker(time.Second * 5)
for {
select {
case wg := <-stopChan:
shutdown(wg)
return
case <-ticker.C:
pollRedis(first)
first = false
if common.Statsd != nil {
workmu.Lock()
l := len(workSlice)
workmu.Unlock()
common.Statsd.Gauge("yagpdb.mqueue.size", float64(l), nil, 1)
common.Statsd.Gauge("yagpdb.mqueue.numworkers", float64(atomic.LoadInt32(numWorkers)), nil, 1)
}
}
}
}
func shutdown(wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
currentlyProcessingLock.RLock()
num := len(currentlyProcessing)
currentlyProcessingLock.RUnlock()
if num < 1 {
break
}
time.Sleep(time.Second)
}
wg.Done()
}
func pollRedis(first bool) {
var results [][]byte
// Get all elements that are currently not being processed, we set thhem to processing by setting their score to our run counter, which increases every time the bot starts
max := "0"
if first {
max = strconv.FormatInt(common.CurrentRunCounter, 10)
}
err := common.RedisPool.Do(retryableredis.Cmd(&results, "ZRANGEBYSCORE", "mqueue", "-1", "("+max))
if err != nil {
logger.WithError(err).Error("Failed polling redis mqueue")
return
}
if len(results) < 1 {
return
}
common.RedisPool.Do(radix.WithConn("mqueue", func(rc radix.Conn) error {
workmu.Lock()
defer workmu.Unlock()
for _, elem := range results {
var parsed *QueuedElement
err := json.Unmarshal(elem, &parsed)
if err != nil {
logger.WithError(err).Error("Failed parsing mqueue redis elemtn")
continue
}
if !bot.IsGuildOnCurrentProcess(parsed.Guild) {
continue
}
// Mark it as being processed so it wont get caught in further polling, unless its a new process in which case it wasnt completed
rc.Do(retryableredis.FlatCmd(nil, "ZADD", "mqueue", common.CurrentRunCounter, string(elem)))
workSlice = append(workSlice, &WorkItem{
elem: parsed,
raw: elem,
})
}
return nil
}))
}
type WorkItem struct {
elem *QueuedElement
raw []byte
}
var (
workSlice []*WorkItem
activeWork []*WorkItem
workmu sync.Mutex
)
func findWork() int {
// find a work item that does not share a channel with any other item being processed (so ratelimits only take up max 1 worker)
OUTER:
for i, v := range workSlice {
for _, active := range activeWork {
if active.elem.Channel == v.elem.Channel {
continue OUTER
}
}
b := common.BotSession.Ratelimiter.GetBucket(discordgo.EndpointChannelMessages(v.elem.Channel))
b.Lock()
waitTime := common.BotSession.Ratelimiter.GetWaitTime(b, 1)
b.Unlock()
if waitTime > time.Millisecond*250 {
continue
}
return i
}
return -1
}
func processWorker() {
atomic.AddInt32(numWorkers, 1)
defer atomic.AddInt32(numWorkers, -1)
var currentItem *WorkItem
for {
workmu.Lock()
// find a work item that does not share a channel with any other item being processed (so ratelimits only take up max 1 worker)
workItemIndex := findWork()
// did not find any
if workItemIndex == -1 {
workmu.Unlock()
time.Sleep(time.Second * 1)
continue
}
currentItem = workSlice[workItemIndex]
activeWork = append(activeWork, currentItem)
workSlice = append(workSlice[:workItemIndex], workSlice[workItemIndex+1:]...)
workmu.Unlock()
process(currentItem.elem, currentItem.raw)
workmu.Lock()
// if were done processing a item previously then remove it from the active processing slice
for i, v := range activeWork {
if v == currentItem {
activeWork = append(activeWork[:i], activeWork[i+1:]...)
break
}
}
currentItem = nil
l := len(workSlice)
workmu.Unlock()
// we sleep between each element as to avoid global ratelimits
// this amount will atuomatically scale with how many elements are in the queue, the max sleep is 1 second
var msSleep int
if l > 5 {
msSleep = 5000 / l
} else {
msSleep = 1000
}
time.Sleep(time.Millisecond * time.Duration(msSleep))
}
}
func process(elem *QueuedElement, raw []byte) {
id := elem.ID
queueLogger := logger.WithField("mq_id", id)
defer func() {
common.RedisPool.Do(retryableredis.Cmd(nil, "ZREM", "mqueue", string(raw)))
}()
for {
var err error
if elem.UseWebhook {
err = trySendWebhook(queueLogger, elem)
} else {
err = trySendNormal(queueLogger, elem)
}
if err == nil {
break
}
if e, ok := errors.Cause(err).(*discordgo.RESTError); ok {
if (e.Response != nil && e.Response.StatusCode >= 400 && e.Response.StatusCode < 500) || (e.Message != nil && e.Message.Code != 0) {
if source, ok := sources[elem.Source]; ok {
maybeDisableFeed(source, elem, e)
}
break
}
}
if c, _ := common.DiscordError(err); c != 0 {
break
}
queueLogger.Warn("Non-discord related error when sending message, retrying. ", err)
time.Sleep(time.Second)
}
}
var disableOnError = []int{
discordgo.ErrCodeUnknownChannel,
discordgo.ErrCodeMissingAccess,
discordgo.ErrCodeMissingPermissions,
30007, // max number of webhooks
}
func maybeDisableFeed(source PluginWithErrorHandler, elem *QueuedElement, err *discordgo.RESTError) {
// source.HandleMQueueError(elem, errors.Cause(err))
if err.Message == nil || !common.ContainsIntSlice(disableOnError, err.Message.Code) {
// don't disable
l := logger.WithError(err).WithField("source", elem.Source).WithField("sourceid", elem.SourceID)
if elem.MessageEmbed != nil {
serializedEmbed, _ := json.Marshal(elem.MessageEmbed)
l = l.WithField("embed", serializedEmbed)
}
l.Error("error sending mqueue message")
return
}
logger.WithError(err).Warnf("disabling feed item %s from %s", elem.SourceID, elem.Source)
source.DisableFeed(elem, err)
}
func trySendNormal(l *logrus.Entry, elem *QueuedElement) (err error) {
if elem.MessageStr != "" {
_, err = common.BotSession.ChannelMessageSend(elem.Channel, elem.MessageStr)
} else if elem.MessageEmbed != nil {
_, err = common.BotSession.ChannelMessageSendEmbed(elem.Channel, elem.MessageEmbed)
} else {
l.Error("Both MessageEmbed and MessageStr empty")
}
return
}
func trySendWebhook(l *logrus.Entry, elem *QueuedElement) (err error) {
if elem.MessageStr == "" && elem.MessageEmbed == nil {
l.Error("Both MessageEmbed and MessageStr empty")
return
}
// find the avatar, this is slightly expensive, do i need to rethink this?
avatar := ""
if source, ok := sources[elem.Source]; ok {
if avatarProvider, ok := source.(PluginWithWebhookAvatar); ok {
avatar = avatarProvider.WebhookAvatar()
}
}
webhook, err := FindCreateWebhook(elem.Guild, elem.Channel, elem.Source, avatar)
if err != nil {
return err
}
webhookParams := &discordgo.WebhookParams{
Username: elem.WebhookUsername,
Content: elem.MessageStr,
}
if elem.MessageEmbed != nil {
webhookParams.Embeds = []*discordgo.MessageEmbed{elem.MessageEmbed}
}
err = webhookSession.WebhookExecute(webhook.ID, webhook.Token, true, webhookParams)
if code, _ := common.DiscordError(err); code == discordgo.ErrCodeUnknownWebhook {
// if the webhook was deleted, then delete the bad boi from the databse and retry
const query = `DELETE FROM mqueue_webhooks WHERE id=$1`
_, err := common.PQ.Exec(query, webhook.ID)
if err != nil {
return errors.Wrap(err, "sql.delete")
}
return errors.New("deleted webhook")
}
return
}