-
Notifications
You must be signed in to change notification settings - Fork 921
/
eventsystem.go
420 lines (343 loc) · 10.7 KB
/
eventsystem.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
package eventsystem
//go:generate go run gen/events_gen.go -o events.go
import (
"context"
"errors"
"fmt"
"runtime/debug"
"sync/atomic"
"time"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/common/featureflags"
"github.com/botlabs-gg/yagpdb/v2/lib/discordgo"
"github.com/botlabs-gg/yagpdb/v2/lib/dstate"
"github.com/sirupsen/logrus"
)
var DiscordState dstate.StateTracker
func init() {
for i := range handlers {
handlers[i] = make([][]*Handler, 3)
}
}
type HandlerFunc func(evtData *EventData) (retry bool, err error)
type HandlerFuncLegacy func(evtData *EventData)
type Handler struct {
Plugin common.Plugin
F HandlerFunc
FLegacy HandlerFuncLegacy
}
type EventData struct {
EvtInterface interface{}
Type Event
ctx context.Context
Session *discordgo.Session
GuildFeatureFlags []string
GS *dstate.GuildSet // Guaranteed to be available for guild events, except creates and deletes
cancelled *int32
}
func (e *EventData) Clone() *EventData {
return &EventData{
EvtInterface: e.EvtInterface,
Type: e.Type,
ctx: e.ctx,
Session: e.Session,
GuildFeatureFlags: e.GuildFeatureFlags,
GS: e.GS,
cancelled: e.cancelled,
}
}
func NewEventData(session *discordgo.Session, t Event, evtInterface interface{}) *EventData {
return &EventData{
EvtInterface: evtInterface,
Type: t,
Session: session,
cancelled: new(int32),
}
}
func (e *EventData) Cancel() {
atomic.StoreInt32(e.cancelled, 1)
}
func (e *EventData) Context() context.Context {
if e.ctx == nil {
return context.Background()
}
return e.ctx
}
func (e *EventData) WithContext(ctx context.Context) *EventData {
cop := e.Clone()
cop.ctx = ctx
return cop
}
// HasFeatureFlag returns true if the guild the event came from has the provided feature flag
func (e *EventData) HasFeatureFlag(flag string) bool {
return common.ContainsStringSlice(e.GuildFeatureFlags, flag)
}
// EmitEvent emits an event
func EmitEvent(data *EventData, evt Event) {
h := handlers[evt]
runEvents(h[0], data)
runEvents(h[1], data)
data = data.Clone()
// re-fetch state info after state had been updated
if guildEvt, ok := data.EvtInterface.(discordgo.GuildEvent); ok {
id := guildEvt.GetGuildID()
if id != 0 {
newGS := DiscordState.GetGuild(id)
// If guild state is not available for any guild related events, except creates and deletes, do not run the handlers
if newGS == nil && data.Type != EventGuildDelete {
logrus.Debugf("Skipped event as guild state info is not available: %v, %d", data.Type, guildEvt.GetGuildID())
return
}
if newGS != nil {
data.GS = newGS
}
}
}
if len(h[2]) > 0 {
go func() {
defer func() {
if errI := recover(); errI != nil {
stack := string(debug.Stack())
var err error
switch t := errI.(type) {
case error:
err = t
case string:
err = errors.New(t)
default:
err = fmt.Errorf("unknown error: %v", t)
}
logrus.WithError(err).WithField("evt", data.Type.String()).Error("Recovered from panic in event handler\n" + stack)
}
}()
runEvents(h[2], data)
}()
}
}
func runEvents(h []*Handler, data *EventData) {
retryCount := 0
for _, v := range h {
retry := true
sleepTime := 500 * time.Millisecond
first := true
for retry && retryCount < 5 {
if atomic.LoadInt32(data.cancelled) != 0 {
return
}
// Sleep a bit between retries
// will retry up to 5 times (rc = 4)
// total time would be 8 seconds
if retry && !first {
retryCount++
time.Sleep(sleepTime)
sleepTime *= 2
}
first = false
if v.F != nil {
var err error
retry, err = v.F(data)
guildID := int64(0)
if guildIDProvider, ok := data.EvtInterface.(discordgo.GuildEvent); ok {
guildID = guildIDProvider.GetGuildID()
}
if err != nil {
logrus.WithField("guild", guildID).WithField("evt", data.Type.String()).Errorf("%s: An error occured in a discord event handler: %+v", v.Plugin.PluginInfo().SysName, err)
}
if retry {
logrus.WithField("guild", guildID).WithField("evt", data.Type.String()).Errorf("%s: Retrying event handler... %dc", v.Plugin.PluginInfo().SysName, retryCount)
}
} else {
retry = false
v.FLegacy(data)
}
}
}
}
type Order int
const (
// Ran first, syncrounously, before changes from the event is applied to state
OrderSyncPreState Order = 0
// Ran second, syncrounsly, after state changes have been applied
OrderSyncPostState Order = 1
// Ran last, asyncrounously, most handlers should use this unless you need something else in special circumstances
OrderAsyncPostState Order = 2
)
// AddHandler adds a event handler
func AddHandlerLegacy(p common.Plugin, handler HandlerFuncLegacy, order Order, evts ...Event) {
h := &Handler{
FLegacy: handler,
Plugin: p,
}
// check if one of them is EventAll
for _, evt := range evts {
if evt == EventAll {
for _, e := range AllDiscordEvents {
handlers[e][int(order)] = append(handlers[e][int(order)], h)
}
// If one of the events is all, then there's not point in passing more
return
}
}
for _, evt := range evts {
handlers[evt][int(order)] = append(handlers[evt][int(order)], h)
}
}
// AddHandlerFirst adds handlers using the OrderSyncPreState order
func AddHandlerFirstLegacy(p common.Plugin, handler HandlerFuncLegacy, evts ...Event) {
AddHandlerLegacy(p, handler, OrderSyncPreState, evts...)
}
// AddHandlerSecond adds handlers using the OrderSyncPostState order
func AddHandlerSecondLegacy(p common.Plugin, handler HandlerFuncLegacy, evts ...Event) {
AddHandlerLegacy(p, handler, OrderSyncPostState, evts...)
}
// AddHandlerAsyncLast adds handlers using the OrderAsyncPostState order
func AddHandlerAsyncLastLegacy(p common.Plugin, handler HandlerFuncLegacy, evts ...Event) {
AddHandlerLegacy(p, handler, OrderAsyncPostState, evts...)
}
// AddHandler adds a event handler
func AddHandler(p common.Plugin, handler HandlerFunc, order Order, evts ...Event) {
h := &Handler{
F: handler,
Plugin: p,
}
// check if one of them is EventAll
for _, evt := range evts {
if evt == EventAll {
for _, e := range AllDiscordEvents {
handlers[e][int(order)] = append(handlers[e][int(order)], h)
}
// If one of the events is all, then there's not point in passing more
return
}
}
for _, evt := range evts {
handlers[evt][int(order)] = append(handlers[evt][int(order)], h)
}
}
// AddHandlerFirst adds handlers using the OrderSyncPreState order
func AddHandlerFirst(p common.Plugin, handler HandlerFunc, evts ...Event) {
AddHandler(p, handler, OrderSyncPreState, evts...)
}
// AddHandlerSecond adds handlers using the OrderSyncPostState order
func AddHandlerSecond(p common.Plugin, handler HandlerFunc, evts ...Event) {
AddHandler(p, handler, OrderSyncPostState, evts...)
}
// AddHandlerAsyncLast adds handlers using the OrderAsyncPostState order
func AddHandlerAsyncLast(p common.Plugin, handler HandlerFunc, evts ...Event) {
AddHandler(p, handler, OrderAsyncPostState, evts...)
}
func HandleEvent(s *discordgo.Session, evt interface{}) {
var evtData = &EventData{
Session: s,
EvtInterface: evt,
cancelled: new(int32),
}
ctx := context.WithValue(context.Background(), common.ContextKeyDiscordSession, s)
evtData.ctx = ctx
fillEvent(evtData)
if s == nil {
handleEvent(evtData)
return
}
if s.ShardID >= len(workers) || workers[s.ShardID] == nil {
logrus.Errorf("bad shard event: sid: %d, len: %d", s.ShardID, len(workers))
return
}
select {
case workers[s.ShardID] <- evtData:
return
default:
logrus.Errorf("Max events in queue: %d, %d", len(workers[s.ShardID]), s.ShardID)
logrus.Warningf("excess Discord event in queue for %d, %d with data %#v", len(workers[s.ShardID]), s.ShardID, evtData)
workers[s.ShardID] <- evtData // attempt to send it anyways for now
}
}
func QueueEventNonDiscord(evtData *EventData) {
if evtData.Session != nil {
ctx := context.WithValue(evtData.Context(), common.ContextKeyDiscordSession, evtData.Session)
evtData.ctx = ctx
} else {
handleEvent(evtData)
return
}
s := evtData.Session
if s.ShardID >= len(workers) || workers[s.ShardID] == nil {
logrus.Errorf("bad shard event: sid: %d, len: %d", s.ShardID, len(workers))
return
}
select {
case workers[s.ShardID] <- evtData:
return
default:
logrus.Errorf("Max events in queue: %d, %d", len(workers[s.ShardID]), s.ShardID)
logrus.Warningf("excess Discord event in queue for %d, %d with data %#v", len(workers[s.ShardID]), s.ShardID, evtData)
workers[s.ShardID] <- evtData // attempt to send it anyways for now
}
}
// CS is the same as calling d.GS.GetChannel
func (d *EventData) CS() *dstate.ChannelState {
if channelEvt, ok := d.EvtInterface.(discordgo.ChannelEvent); ok {
if d.GS != nil {
return d.GS.GetChannel(channelEvt.GetChannelID())
}
}
return nil
}
// CS is the same as calling d.GS.GetChannelOrThread
func (d *EventData) CSOrThread() *dstate.ChannelState {
if channelEvt, ok := d.EvtInterface.(discordgo.ChannelEvent); ok {
if d.GS != nil {
return d.GS.GetChannelOrThread(channelEvt.GetChannelID())
}
}
return nil
}
// RequireCSMW will only call the inner handler if a channel state is available
func RequireCSMW(inner HandlerFunc) HandlerFunc {
return func(evt *EventData) (retry bool, err error) {
if evt.CS() == nil {
return false, nil
}
return inner(evt)
}
}
var workers []chan *EventData
func InitWorkers(totalShards int) {
workers = make([]chan *EventData, totalShards)
for i := range workers {
workers[i] = make(chan *EventData, 1000)
go eventWorker(workers[i])
}
}
func eventWorker(ch chan *EventData) {
for evt := range ch {
handleEvent(evt)
}
}
func handleEvent(evtData *EventData) {
// fill in guild state if applicable
if guildEvt, ok := evtData.EvtInterface.(discordgo.GuildEvent); ok {
id := guildEvt.GetGuildID()
if id != 0 {
evtData.GS = DiscordState.GetGuild(id)
// If guild state is not available for any guild related events, except creates and deletes, do not run the handlers
if evtData.GS == nil && evtData.Type != EventGuildCreate && evtData.Type != EventGuildDelete {
logrus.Debugf("Skipped event as guild state info is not available: %v, %d", evtData.Type, guildEvt.GetGuildID())
return
}
flags, err := featureflags.RetryGetGuildFlags(id)
if err == nil {
evtData.GuildFeatureFlags = flags
}
}
}
defer func() {
if err := recover(); err != nil {
stack := string(debug.Stack())
logrus.WithField(logrus.ErrorKey, err).WithField("evt", evtData.Type.String()).Error("Recovered from panic in event handler\n" + stack)
}
}()
EmitEvent(evtData, EventAllPre)
EmitEvent(evtData, evtData.Type)
EmitEvent(evtData, EventAllPost)
}