github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/network/p2p/simulations/events.go (about) 1 package simulations 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 type EventType string 9 10 const ( 11 EventTypeNode EventType = "node" 12 13 EventTypeConn EventType = "conn" 14 15 EventTypeMsg EventType = "msg" 16 ) 17 18 type Event struct { 19 Type EventType `json:"type"` 20 21 Time time.Time `json:"time"` 22 23 Control bool `json:"control"` 24 25 Node *Node `json:"node,omitempty"` 26 27 Conn *Conn `json:"conn,omitempty"` 28 29 Msg *Msg `json:"msg,omitempty"` 30 } 31 32 func NewEvent(v interface{}) *Event { 33 event := &Event{Time: time.Now()} 34 switch v := v.(type) { 35 case *Node: 36 event.Type = EventTypeNode 37 node := *v 38 event.Node = &node 39 case *Conn: 40 event.Type = EventTypeConn 41 conn := *v 42 event.Conn = &conn 43 case *Msg: 44 event.Type = EventTypeMsg 45 msg := *v 46 event.Msg = &msg 47 default: 48 panic(fmt.Sprintf("invalid event type: %T", v)) 49 } 50 return event 51 } 52 53 func ControlEvent(v interface{}) *Event { 54 event := NewEvent(v) 55 event.Control = true 56 return event 57 } 58 59 func (e *Event) String() string { 60 switch e.Type { 61 case EventTypeNode: 62 return fmt.Sprintf("<node-event> id: %s up: %t", e.Node.ID().TerminalString(), e.Node.Up) 63 case EventTypeConn: 64 return fmt.Sprintf("<conn-event> nodes: %s->%s up: %t", e.Conn.One.TerminalString(), e.Conn.Other.TerminalString(), e.Conn.Up) 65 case EventTypeMsg: 66 return fmt.Sprintf("<msg-event> nodes: %s->%s proto: %s, code: %d, received: %t", e.Msg.One.TerminalString(), e.Msg.Other.TerminalString(), e.Msg.Protocol, e.Msg.Code, e.Msg.Received) 67 default: 68 return "" 69 } 70 }