This repository has been archived by the owner on Jul 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
reactor.go
443 lines (368 loc) · 10.2 KB
/
reactor.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
package disgord
import (
"errors"
"fmt"
"sync"
"time"
"github.com/andersfylling/disgord/internal/gateway"
)
//////////////////////////////////////////////////////
//
// Reactor: Consists of a basic demultiplexer, dispatcher and handlerSpecification.
//
// HandlerSpecification can hold one or more handlers, zero or more middlewares, and one controller.
//
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//
// Demultiplexer
//
//////////////////////////////////////////////////////
func (c *Client) demultiplexer(d *dispatcher, read <-chan *gateway.Event) {
for {
var evt *gateway.Event
var alive bool
select {
case evt, alive = <-read:
if !alive {
return
}
case <-d.shutdown:
return
}
// var resource evtResource
// if resource = defineResource(evt.Name); resource == nil {
// fmt.Printf("------\nTODO\nImplement event handler for `%s`, data: \n%+v\n------\n\n", evt.Name, string(evt.Data))
// continue // move on to next event
// }
resourceI, err := cacheDispatcher(c.cache, evt.Name, evt.Data)
if resourceI == nil {
err = fmt.Errorf("cache did not instantiate object. Prev error: %w", err)
}
if err != nil {
// skip unknown events
var knownEvent bool
evts := AllEvents()
for _, e := range evts {
if knownEvent = e == evt.Name; knownEvent {
break
}
}
if !knownEvent {
continue
}
err = fmt.Errorf("demultiplexer{%s}: %w, data '%s'", evt.Name, err, string(evt.Data))
d.session.Logger().Error(err)
continue
}
resource := resourceI.(evtResource)
resource.setShardID(evt.ShardID)
go d.dispatch(evt.Name, resource)
}
}
//////////////////////////////////////////////////////
//
// Dispatcher
//
//////////////////////////////////////////////////////
// dispatcher holds all the Channels and internal state for all registered
// handlers
type dispatcher struct {
sync.RWMutex
// an event can have one or more handlers
handlerSpecs map[string][]*handlerSpec
// use session to allow mocking the Client instance later on
session Session
shutdown chan struct{}
}
func (d *dispatcher) addSessionInstance(s Session) {
d.session = s
}
// register registers handlers.
// Note! While the dispatcher handles registration in form of a method,
// deregistration is done automatically by checking the controller spec after each dispatch.
// See HandlerCtrl.
func (d *dispatcher) register(evt string, inputs ...interface{}) error {
// detect middleware then handlers. Ordering is important.
spec := &handlerSpec{}
if err := spec.populate(inputs...); err != nil { // TODO: improve redundant checking
return err // if the pattern is wrong: (event,[ ...middlewares,] ...handlers[, controller])
// if you want to error check before you use the .On, you can use disgord.ValidateHandlerInputs(...)
}
// tip to Users: Try to remember the handlers won't be added until the
// OnInsert(..) exits.
err := spec.ctrl.OnInsert(d.session)
if err != nil {
d.session.Logger().Error(err)
}
d.Lock()
d.handlerSpecs[evt] = append(d.handlerSpecs[evt], spec)
d.Unlock()
return nil
}
func (d *dispatcher) dispatch(evtName string, evt resource) {
// handlers
d.RLock()
specs := d.handlerSpecs[evtName]
d.RUnlock()
dead := make([]*handlerSpec, 0)
for _, spec := range specs {
// faster. But somewhat weird to check death before running the handler
// this can be used if we find a different way to write the Client.Ready
// logic.
//if alive := spec.next(); !alive {
// dead = append(dead, spec)
// continue
//}
spec.Lock()
if dead := spec.ctrl.IsDead(); !dead {
localEvt := spec.runMdlws(evt)
if localEvt == nil {
spec.Unlock()
continue
}
for _, handler := range spec.handlers {
d.trigger(handler, localEvt)
}
spec.ctrl.Update()
}
if spec.ctrl.IsDead() {
dead = append(dead, spec)
}
spec.Unlock()
}
// time to remove the dead
if len(dead) == 0 {
return
}
d.Lock()
// make sure the dead has not already been removed, after all this is concurrent
specs = d.handlerSpecs[evtName]
for _, deadspec := range dead {
for i, spec := range specs {
if spec == deadspec { // compare pointers
// delete the dead spec, but keep the ordering
copy(specs[i:], specs[i+1:])
//specs[len(specs)-1] = nil // GC, setting entries to nil requires locking
specs = specs[:len(specs)-1]
break
}
}
}
// update the specs
d.handlerSpecs[evtName] = specs
d.Unlock()
// notify specs
go func(dead []*handlerSpec) {
for i := range dead {
if err := dead[i].ctrl.OnRemove(d.session); err != nil {
d.session.Logger().Error(err)
}
}
}(dead)
}
//////////////////////////////////////////////////////
//
// Handler logic
//
//////////////////////////////////////////////////////
// HandlerCtrl used when inserting a handler to dictate whether or not the handler(s) should
// still be kept in the handlers list..
type HandlerCtrl interface {
OnInsert(Session) error
OnRemove(Session) error
// IsDead does not need to be locked as the demultiplexer access it synchronously.
IsDead() bool
// Update For every time Update is called, it's internal trackers must be updated.
// you should assume that .Update() means the handler was used.
Update()
}
// Handler needs to match one of the *Handler signatures
type Handler = interface{}
// Middleware allows you to manipulate data during the "stream"
type Middleware = func(interface{}) interface{}
// handlerSpec (handler specification) holds the details for executing the handler(s)
// think about the code flow as a whole:
// eg. mdlw1 -> midlw2 -> handler1 -> handler2 -> ctrl
//
// If any of the middlewares manipulates the data, the next middlewares or handlers in the
// chain will get said manipulated data.
type handlerSpec struct {
sync.RWMutex
middlewares []Middleware
handlers []Handler
ctrl HandlerCtrl
}
func (hs *handlerSpec) next() bool {
hs.Lock()
defer hs.Unlock()
if hs.ctrl.IsDead() {
return false
}
hs.ctrl.Update()
return true
}
// populate is essentially the constructor for a handlerSpec
func (hs *handlerSpec) populate(inputs ...interface{}) (err error) {
var i int
// middlewares
for ; i < len(inputs); i++ {
if mdlw, ok := inputs[i].(Middleware); ok {
hs.middlewares = append(hs.middlewares, mdlw)
} else {
break
}
}
// handlers
for ; i < len(inputs)-1; i++ {
if handler, ok := inputs[i].(Handler); ok && isHandler(handler) {
hs.handlers = append(hs.handlers, handler)
} else {
break
}
}
// check if last arg is a controller
if i < len(inputs) {
if ctrl, ok := inputs[i].(HandlerCtrl); ok {
hs.ctrl = ctrl
i++
} else if handler, ok := inputs[i].(Handler); ok {
hs.handlers = append(hs.handlers, handler)
hs.ctrl = eternalCtrl
i++
}
}
if len(inputs) != i {
format := "unable to add all handlers/middlewares (%d/%d). Are they in correct order? middlewares, then handlers"
err = errors.New(fmt.Sprintf(format, i, len(inputs)))
}
return err
}
func (hs *handlerSpec) runMdlws(evt interface{}) interface{} {
for i := range hs.middlewares {
evt = hs.middlewares[i](evt) // note how the evt pointer is overwritten
if evt == nil {
break
}
}
return evt
}
//////////////////////////////////////////////////////
//
// Handler Controller
//
//////////////////////////////////////////////////////
// Ctrl is a handler controller that supports lifetime and max number of execution for one or several handlers.
//
// // register only the first 6 votes
// Client.On("MESSAGE_CREATE", filter.NonVotes, registerVoteHandler, &disgord.Ctrl{Runs: 6})
//
// // Allow voting for only 10 minutes
// Client.On("MESSAGE_CREATE", filter.NonVotes, registerVoteHandler, &disgord.Ctrl{Duration: 10*time.Second})
//
// // Allow voting until the month is over
// Client.On("MESSAGE_CREATE", filter.NonVotes, registerVoteHandler, &disgord.Ctrl{Until: time.Now().AddDate(0, 1, 0)})
type Ctrl struct {
Runs int
Until time.Time
Duration time.Duration
Channel interface{}
}
var _ HandlerCtrl = (*Ctrl)(nil)
func (c *Ctrl) OnInsert(Session) error {
if c.Channel != nil && !isHandler(c.Channel) {
panic("Ctrl.Channel is not a valid Disgord event channel")
}
if c.Runs == 0 {
c.Runs = -1
}
if c.Duration.Nanoseconds() > 0 {
if c.Until.IsZero() {
c.Until = time.Now()
}
c.Until = c.Until.Add(c.Duration)
}
if c.Until.IsZero() {
snow := Snowflake(^uint64(0))
c.Until = snow.Date() // until the snowflakes fall
}
return nil
}
func (c *Ctrl) OnRemove(Session) error {
return nil
}
func (c *Ctrl) IsDead() bool {
return c.Runs == 0 || time.Now().After(c.Until)
}
func (c *Ctrl) Update() {
if c.Runs > 0 {
c.Runs--
}
}
// CloseChannel must be called instead of closing an event channel directly.
// This is to make sure Disgord does not go into a deadlock
func (c *Ctrl) CloseChannel() {
c.Runs = 0
closeChannel(c.Channel)
}
//////////////////////////////////////////////////////
//
// Custom Controllers
//
//////////////////////////////////////////////////////
// eternalHandlersCtrl is used for handlers without a defined controller. Letting them live forever.
type eternalHandlersCtrl struct {
Ctrl
}
var _ HandlerCtrl = (*eternalHandlersCtrl)(nil)
func (c *eternalHandlersCtrl) Update() {}
func (c *eternalHandlersCtrl) IsDead() bool { return false }
// reused by handlers that have no ctrl defined
var eternalCtrl = &eternalHandlersCtrl{}
// rdyCtrl is used to trigger notify the user when all the websocket sessions have received their first READY event
type rdyCtrl struct {
sync.Mutex
shardReady []bool
localShardIDs []uint
cb func()
}
var _ HandlerCtrl = (*rdyCtrl)(nil)
func (c *rdyCtrl) OnInsert(s Session) error {
return nil
}
func (c *rdyCtrl) OnRemove(s Session) error {
c.Lock()
defer c.Unlock()
if c.cb != nil {
go c.cb()
c.cb = nil // such that it is only called once. See Client.GuildsReady(...)
}
return nil
}
func (c *rdyCtrl) IsDead() bool {
c.Lock()
defer c.Unlock()
for _, id := range c.localShardIDs {
if !c.shardReady[id] {
return false
}
}
return true
}
func (c *rdyCtrl) Update() {
// handled in the handler
}
type guildsRdyCtrl struct {
rdyCtrl
status map[Snowflake]bool
}
func (c *guildsRdyCtrl) IsDead() bool {
c.Lock()
defer c.Unlock()
for _, ready := range c.status {
if !ready {
return false
}
}
return true
}