This repository has been archived by the owner on Aug 1, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
eventprocessor.go
101 lines (88 loc) · 2.09 KB
/
eventprocessor.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
// Copyright (c) 2020 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package appservice
import (
"encoding/json"
"runtime/debug"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
)
type ExecMode uint8
const (
AsyncHandlers ExecMode = iota
AsyncLoop
Sync
)
type EventProcessor struct {
ExecMode ExecMode
as *AppService
log log.Logger
stop chan struct{}
handlers map[event.Type][]mautrix.OnEventListener
}
func NewEventProcessor(as *AppService) *EventProcessor {
return &EventProcessor{
ExecMode: AsyncHandlers,
as: as,
log: as.Log.Sub("Events"),
stop: make(chan struct{}, 1),
handlers: make(map[event.Type][]mautrix.OnEventListener),
}
}
func (ep *EventProcessor) On(evtType event.Type, handler mautrix.OnEventListener) {
handlers, ok := ep.handlers[evtType]
if !ok {
handlers = []mautrix.OnEventListener{handler}
} else {
handlers = append(handlers, handler)
}
ep.handlers[evtType] = handlers
}
func (ep *EventProcessor) callHandler(handler mautrix.OnEventListener, evt *event.Event) {
defer func() {
if err := recover(); err != nil {
d, _ := json.Marshal(evt)
ep.log.Errorfln("Panic in Matrix event handler: %v (event content: %s):\n%s", err, string(d), string(debug.Stack()))
}
}()
handler(evt)
}
func (ep *EventProcessor) Dispatch(evt *event.Event) {
handlers, ok := ep.handlers[evt.Type]
if !ok {
return
}
switch ep.ExecMode {
case AsyncHandlers:
for _, handler := range handlers {
go ep.callHandler(handler, evt)
}
case AsyncLoop:
go func() {
for _, handler := range handlers {
ep.callHandler(handler, evt)
}
}()
case Sync:
for _, handler := range handlers {
ep.callHandler(handler, evt)
}
}
}
func (ep *EventProcessor) Start() {
for {
select {
case evt := <-ep.as.Events:
ep.Dispatch(evt)
case <-ep.stop:
return
}
}
}
func (ep *EventProcessor) Stop() {
ep.stop <- struct{}{}
}