tendermint/p2p/base_reactor.go

72 lines
2.5 KiB
Go
Raw Normal View History

2018-01-13 17:25:51 -05:00
package p2p
2018-01-20 21:12:04 -05:00
import (
2018-07-01 22:36:49 -04:00
cmn "github.com/tendermint/tendermint/libs/common"
"github.com/tendermint/tendermint/p2p/conn"
2018-01-20 21:12:04 -05:00
)
2018-01-13 17:25:51 -05:00
// Reactor is responsible for handling incoming messages on one or more
// Channel. Switch calls GetChannels when reactor is added to it. When a new
// peer joins our node, InitPeer and AddPeer are called. RemovePeer is called
// when the peer is stopped. Receive is called when a message is received on a
// channel associated with this reactor.
//
// Peer#Send or Peer#TrySend should be used to send the message to a peer.
2018-01-13 17:25:51 -05:00
type Reactor interface {
cmn.Service // Start, Stop
2018-02-08 13:07:40 +04:00
// SetSwitch allows setting a switch.
2018-01-13 17:25:51 -05:00
SetSwitch(*Switch)
2018-02-08 13:07:40 +04:00
// GetChannels returns the list of MConnection.ChannelDescriptor. Make sure
// that each ID is unique across all the reactors added to the switch.
2018-01-21 00:33:53 -05:00
GetChannels() []*conn.ChannelDescriptor
2018-02-08 13:07:40 +04:00
// InitPeer is called by the switch before the peer is started. Use it to
// initialize data for the peer (e.g. peer state).
//
// NOTE: The switch won't call AddPeer nor RemovePeer if it fails to start
// the peer. Do not store any data associated with the peer in the reactor
// itself unless you don't want to have a state, which is never cleaned up.
InitPeer(peer Peer) Peer
// AddPeer is called by the switch after the peer is added and successfully
// started. Use it to start goroutines communicating with the peer.
2018-01-13 17:25:51 -05:00
AddPeer(peer Peer)
2018-02-08 13:07:40 +04:00
// RemovePeer is called by the switch when the peer is stopped (due to error
// or other reason).
2018-01-13 17:25:51 -05:00
RemovePeer(peer Peer, reason interface{})
2018-02-08 13:07:40 +04:00
// Receive is called by the switch when msgBytes is received from the peer.
2018-02-08 13:07:40 +04:00
//
// NOTE reactor can not keep msgBytes around after Receive completes without
// copying.
//
// CONTRACT: msgBytes are not nil.
2018-02-08 13:07:40 +04:00
Receive(chID byte, peer Peer, msgBytes []byte)
2018-01-13 17:25:51 -05:00
}
//--------------------------------------
type BaseReactor struct {
cmn.BaseService // Provides Start, Stop, .Quit
Switch *Switch
}
func NewBaseReactor(name string, impl Reactor) *BaseReactor {
return &BaseReactor{
BaseService: *cmn.NewBaseService(nil, name, impl),
Switch: nil,
}
}
func (br *BaseReactor) SetSwitch(sw *Switch) {
br.Switch = sw
}
func (*BaseReactor) GetChannels() []*conn.ChannelDescriptor { return nil }
func (*BaseReactor) AddPeer(peer Peer) {}
func (*BaseReactor) RemovePeer(peer Peer, reason interface{}) {}
func (*BaseReactor) Receive(chID byte, peer Peer, msgBytes []byte) {}
func (*BaseReactor) InitPeer(peer Peer) Peer { return peer }