Skip to content

Commit

Permalink
p2p: move ping handling into pingLoop goroutine (ethereum#27887)
Browse files Browse the repository at this point in the history
Moving the response sending there allows tracking all peer goroutines
in the peer WaitGroup.
  • Loading branch information
fjl authored and libotony committed Mar 8, 2024
1 parent 9d419d1 commit 1b0f485
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions p2p/peer.go
Expand Up @@ -108,6 +108,7 @@ type Peer struct {
wg sync.WaitGroup
protoErr chan error
closed chan struct{}
pingRecv chan struct{}
disc chan DiscReason

// events receives message send / receive events if set
Expand Down Expand Up @@ -178,6 +179,7 @@ func newPeer(conn *conn, protocols []Protocol) *Peer {
protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
closed: make(chan struct{}),
log: log.New("id", conn.id, "conn", conn.flags),
pingRecv: make(chan struct{}, 16),
}
return p
}
Expand Down Expand Up @@ -237,9 +239,11 @@ loop:
}

func (p *Peer) pingLoop() {
ping := time.NewTimer(pingInterval)
defer p.wg.Done()

ping := time.NewTimer(pingInterval)
defer ping.Stop()

for {
select {
case <-ping.C:
Expand All @@ -248,6 +252,10 @@ func (p *Peer) pingLoop() {
return
}
ping.Reset(pingInterval)

case <-p.pingRecv:
SendItems(p.rw, pongMsg)

case <-p.closed:
return
}
Expand All @@ -274,7 +282,10 @@ func (p *Peer) handle(msg Msg) error {
switch {
case msg.Code == pingMsg:
msg.Discard()
go SendItems(p.rw, pongMsg)
select {
case p.pingRecv <- struct{}{}:
case <-p.closed:
}
case msg.Code == discMsg:
var reason [1]DiscReason
// This is the last message. We don't need to discard or
Expand Down

0 comments on commit 1b0f485

Please sign in to comment.