forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqueue.go
306 lines (258 loc) · 7.06 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
package mqueue
import (
"encoding/json"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/common"
"github.com/mediocregopher/radix.v3"
"github.com/sirupsen/logrus"
"gopkg.in/src-d/go-kallax.v1"
"strconv"
"sync"
"time"
)
var (
sources = make(map[string]PluginWithErrorHandler)
stopChan = make(chan *sync.WaitGroup)
currentlyProcessing = make([]int64, 0)
currentlyProcessingLock sync.RWMutex
store *QueuedElementStore
startedLock sync.Mutex
started bool
)
type PluginWithErrorHandler interface {
HandleMQueueError(elem *QueuedElementNoKallax, err error)
}
var (
_ bot.BotInitHandler = (*Plugin)(nil)
_ bot.BotStopperHandler = (*Plugin)(nil)
)
type Plugin struct {
}
func (p *Plugin) Name() string {
return "mqueue"
}
func RegisterPlugin() {
p := &Plugin{}
common.RegisterPlugin(p)
}
func InitStores() {
// Init table
_, err := common.PQ.Exec(`CREATE TABLE IF NOT EXISTS mqueue (
id serial NOT NULL PRIMARY KEY,
source text NOT NULL,
source_id text NOT NULL,
message_str text NOT NULL,
message_embed text NOT NULL,
channel text NOT NULL,
processed boolean NOT NULL
);
CREATE INDEX IF NOT EXISTS mqueue_processed_x ON mqueue(processed);
`)
if err != nil {
panic("mqueue: " + err.Error())
}
store = NewQueuedElementStore(common.PQ)
}
func RegisterSource(name string, source PluginWithErrorHandler) {
sources[name] = source
}
func IncrIDCounter() (next int64) {
err := common.RedisPool.Do(radix.Cmd(&next, "INCR", "mqueue_id_counter"))
if err != nil {
logrus.WithError(err).Error("Failed increasing mqueue id counter")
return -1
}
return next
}
func QueueMessageString(source, sourceID string, channel int64, message string) {
QueueMessage(source, sourceID, channel, message, nil)
}
func QueueMessageEmbed(source, sourceID string, channel int64, embed *discordgo.MessageEmbed) {
QueueMessage(source, sourceID, channel, "", embed)
}
func QueueMessage(source, sourceID string, channel int64, msgStr string, embed *discordgo.MessageEmbed) {
nextID := IncrIDCounter()
if nextID == -1 {
return
}
elem := &QueuedElementNoKallax{
ID: nextID,
Source: source,
SourceID: sourceID,
Channel: channel,
MessageStr: msgStr,
MessageEmbed: embed,
}
serialized, err := json.Marshal(elem)
if err != nil {
logrus.WithError(err).Error("Failed marshaling mqueue element")
return
}
err = common.RedisPool.Do(radix.Cmd(nil, "ZADD", "mqueue", "-1", string(serialized)))
if err != nil {
return
}
}
func (p *Plugin) BotInit() {
go startPolling()
}
func (p *Plugin) StopBot(wg *sync.WaitGroup) {
startedLock.Lock()
if !started {
startedLock.Unlock()
wg.Done()
return
}
startedLock.Unlock()
stopChan <- wg
}
func startPolling() {
startedLock.Lock()
if started {
startedLock.Unlock()
panic("Already started mqueue")
}
started = true
startedLock.Unlock()
ticker := time.NewTicker(time.Second)
tickerClean := time.NewTicker(time.Hour)
for {
select {
case wg := <-stopChan:
shutdown(wg)
return
case <-ticker.C:
pollLegacy()
pollRedis()
case <-tickerClean.C:
go func() {
result, err := common.PQ.Exec("DELETE FROM mqueue WHERE processed=true")
if err != nil {
logrus.WithError(err).Error("Failed cleaning mqueue db")
} else {
rows, err := result.RowsAffected()
if err == nil {
logrus.Println("mqueue cleaned up ", rows, " rows")
}
}
}()
}
}
}
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 pollLegacy() {
// Grab the current processing elements
currentlyProcessingLock.RLock()
processing := make([]int64, len(currentlyProcessing))
copy(processing, currentlyProcessing)
currentlyProcessingLock.RUnlock()
elems, err := store.FindAll(NewQueuedElementQuery().Where(kallax.Eq(Schema.QueuedElement.Processed, false)))
if err != nil {
logrus.WithError(err).Error("MQueue: Failed polling message queue")
return
}
currentlyProcessingLock.Lock()
OUTER:
for _, v := range elems {
for _, current := range processing {
if v.ID == current {
continue OUTER
}
}
currentlyProcessing = append(currentlyProcessing, v.ID)
go process(v, nil, nil, true)
}
currentlyProcessingLock.Unlock()
}
func pollRedis() {
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 := strconv.FormatInt(common.CurrentRunCounter, 10)
err := common.RedisPool.Do(radix.Cmd(&results, "ZRANGEBYSCORE", "mqueue", "-1", "("+max))
if err != nil {
logrus.WithError(err).Error("Failed polling redis mqueue")
return
}
common.RedisPool.Do(radix.WithConn("mqueue", func(rc radix.Conn) error {
for _, elem := range results {
// 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(radix.FlatCmd(nil, "ZADD", "mqueue", common.CurrentRunCounter, string(elem)))
var parsed *QueuedElementNoKallax
err := json.Unmarshal(elem, &parsed)
if err != nil {
logrus.WithError(err).Error("Failed parsing mqueue redis elemtn")
continue
}
go process(nil, parsed, elem, false)
}
return nil
}))
}
func process(elem *QueuedElement, elemSimple *QueuedElementNoKallax, elemSimpleRaw []byte, isLegacy bool) {
id := int64(0)
if elem != nil {
id = elem.ID
} else {
id = elemSimple.ID
}
queueLogger := logrus.WithField("mq_id", id).WithField("legacy", isLegacy)
defer func() {
if !isLegacy {
common.RedisPool.Do(radix.Cmd(nil, "ZREM", "mqueue", string(elemSimpleRaw)))
return
}
elem.Processed = true
_, err := store.Save(elem)
if err != nil {
queueLogger.WithError(err).Error("MQueue: Failed marking elem as processed")
}
currentlyProcessingLock.Lock()
for i, v := range currentlyProcessing {
if v == elem.ID {
currentlyProcessing = append(currentlyProcessing[:i], currentlyProcessing[i+1:]...)
break
}
}
currentlyProcessingLock.Unlock()
}()
if elemSimple == nil {
elemSimple = NewElemFromKallax(elem)
}
parsedChannel := elemSimple.Channel
for {
var err error
if elemSimple.MessageStr != "" {
_, err = common.BotSession.ChannelMessageSend(parsedChannel, elemSimple.MessageStr)
} else if elemSimple.MessageEmbed != nil {
_, err = common.BotSession.ChannelMessageSendEmbed(parsedChannel, elemSimple.MessageEmbed)
} else {
queueLogger.Error("MQueue: Both MessageEmbed and MessageStr empty")
break
}
if err == nil {
break
}
if e, ok := 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[elemSimple.Source]; ok {
source.HandleMQueueError(elemSimple, err)
}
break
}
}
queueLogger.Warn("MQueue: Non-discord related error when sending message, retrying. ", err)
time.Sleep(time.Second)
}
}