vppn/node/peer-supervisor.go
2024-12-20 21:06:16 +01:00

75 lines
1.4 KiB
Go

package node
import (
"time"
"vppn/m"
)
const (
connectTimeout = 6 * time.Second
pingInterval = 6 * time.Second
timeoutInterval = 20 * time.Second
)
func (rp *remotePeer) supervise(
conf m.PeerConfig,
remoteIP byte,
conn *connWriter,
peers *remotePeers,
) {
defer panicHandler()
base := &stateBase{
published: rp.published,
peers: rp.peers,
localIP: rp.localIP,
remoteIP: rp.remoteIP,
privKey: conf.EncPrivKey,
localPub: addrIsValid(conf.PublicIP),
conn: rp.conn,
counter: &rp.counter,
pingTimer: time.NewTimer(time.Second),
timeoutTimer: time.NewTimer(time.Second),
buf: make([]byte, bufferSize),
encBuf: make([]byte, bufferSize),
}
base.pingTimer.Stop()
base.timeoutTimer.Stop()
var (
curState peerState = base
nextState peerState
)
for {
nextState = nil
select {
case peer := <-rp.peerUpdates:
nextState = curState.OnPeerUpdate(peer)
case pkt := <-rp.controlPackets:
switch p := pkt.Payload.(type) {
case pingPacket:
nextState = curState.OnPing(pkt.RemoteAddr, p)
case pongPacket:
nextState = curState.OnPong(pkt.RemoteAddr, p)
default:
// Unknown packet type.
}
case <-base.pingTimer.C:
nextState = curState.OnPingTimer()
case <-base.timeoutTimer.C:
nextState = curState.OnTimeoutTimer()
}
if nextState != nil {
rp.logf("%s --> %s", curState.Name(), nextState.Name())
curState = nextState
}
}
}