github.com/annchain/OG@v0.0.9/eventbus/event.go (about) 1 package eventbus 2 3 import ( 4 "github.com/annchain/OG/debug/debuglog" 5 "github.com/sirupsen/logrus" 6 "strconv" 7 "sync" 8 ) 9 10 type EventType uint8 11 12 type Event interface { 13 GetEventType() EventType 14 } 15 type EventHandler interface { 16 HandlerDescription(EventType) string 17 HandleEvent(Event) 18 Name() string 19 } 20 21 type EventHandlerRegisterInfo struct { 22 Type EventType 23 Name string 24 Handler EventHandler 25 } 26 27 type DefaultEventBus struct { 28 debuglog.NodeLogger 29 ID int 30 knownNames map[EventType]string 31 listeners map[EventType][]EventHandler 32 inited bool // do not use Mutex after initialization. It will downgrade performance 33 mu sync.Mutex // use only during initialization 34 } 35 36 func (e *DefaultEventBus) InitDefault() { 37 e.listeners = make(map[EventType][]EventHandler) 38 e.knownNames = make(map[EventType]string) 39 } 40 41 func (e *DefaultEventBus) ListenTo(regInfo EventHandlerRegisterInfo) { 42 e.mu.Lock() 43 defer e.mu.Unlock() 44 l, ok := e.listeners[regInfo.Type] 45 if !ok { 46 l = []EventHandler{regInfo.Handler} 47 } else { 48 l = append(l, regInfo.Handler) 49 } 50 e.listeners[regInfo.Type] = l 51 e.knownNames[regInfo.Type] = regInfo.Name 52 } 53 54 // Eventbus must be built before events are to be received. 55 // This is an commit from programmer, showing that all modules are inited and well-prepared to receive events. 56 func (e *DefaultEventBus) Build() { 57 if e.knownNames == nil { 58 panic("not initialized.") 59 } 60 e.inited = true 61 } 62 63 func (e *DefaultEventBus) Route(ev Event) { 64 if !e.inited { 65 panic("bad code. build eventbus before routing") 66 } 67 name, ok := e.knownNames[ev.GetEventType()] 68 if !ok { 69 name = strconv.Itoa(int(ev.GetEventType())) 70 } 71 e.Logger.WithField("type", name).WithField("v", ev).Debug("router received event") 72 handlers, ok := e.listeners[ev.GetEventType()] 73 if !ok { 74 e.Logger.WithField("type", name).WithField("typecode", ev.GetEventType()).Warn("no event handler to handle event type") 75 return 76 } 77 for _, handler := range handlers { 78 e.Logger.WithFields(logrus.Fields{ 79 "handler": handler.Name(), 80 "desc": handler.HandlerDescription(ev.GetEventType()), 81 }).Debug("handling") 82 handler.HandleEvent(ev) 83 } 84 85 e.Logger.WithField("type", name).WithField("v", ev).Debug("router handled event") 86 }