github.com/badrootd/nibiru-cometbft@v0.37.5-0.20240307173500-2a75559eee9b/p2p/base_reactor.go (about) 1 package p2p 2 3 import ( 4 "github.com/badrootd/nibiru-cometbft/libs/service" 5 "github.com/badrootd/nibiru-cometbft/p2p/conn" 6 ) 7 8 // Reactor is responsible for handling incoming messages on one or more 9 // Channel. Switch calls GetChannels when reactor is added to it. When a new 10 // peer joins our node, InitPeer and AddPeer are called. RemovePeer is called 11 // when the peer is stopped. Receive is called when a message is received on a 12 // channel associated with this reactor. 13 // 14 // Peer#Send or Peer#TrySend should be used to send the message to a peer. 15 type Reactor interface { 16 service.Service // Start, Stop 17 18 // SetSwitch allows setting a switch. 19 SetSwitch(*Switch) 20 21 // GetChannels returns the list of MConnection.ChannelDescriptor. Make sure 22 // that each ID is unique across all the reactors added to the switch. 23 GetChannels() []*conn.ChannelDescriptor 24 25 // InitPeer is called by the switch before the peer is started. Use it to 26 // initialize data for the peer (e.g. peer state). 27 // 28 // NOTE: The switch won't call AddPeer nor RemovePeer if it fails to start 29 // the peer. Do not store any data associated with the peer in the reactor 30 // itself unless you don't want to have a state, which is never cleaned up. 31 InitPeer(peer Peer) Peer 32 33 // AddPeer is called by the switch after the peer is added and successfully 34 // started. Use it to start goroutines communicating with the peer. 35 AddPeer(peer Peer) 36 37 // RemovePeer is called by the switch when the peer is stopped (due to error 38 // or other reason). 39 RemovePeer(peer Peer, reason interface{}) 40 41 // ReceiveEnvelope is called by the switch when an envelope is received from any connected 42 // peer on any of the channels registered by the reactor. 43 ReceiveEnvelope(Envelope) 44 } 45 46 //-------------------------------------- 47 48 type BaseReactor struct { 49 service.BaseService // Provides Start, Stop, .Quit 50 Switch *Switch 51 } 52 53 func NewBaseReactor(name string, impl Reactor) *BaseReactor { 54 return &BaseReactor{ 55 BaseService: *service.NewBaseService(nil, name, impl), 56 Switch: nil, 57 } 58 } 59 60 func (br *BaseReactor) SetSwitch(sw *Switch) { 61 br.Switch = sw 62 } 63 64 func (*BaseReactor) GetChannels() []*conn.ChannelDescriptor { return nil } 65 func (*BaseReactor) AddPeer(peer Peer) {} 66 func (*BaseReactor) RemovePeer(peer Peer, reason interface{}) {} 67 func (*BaseReactor) ReceiveEnvelope(e Envelope) {} 68 func (*BaseReactor) InitPeer(peer Peer) Peer { return peer }