Skip to content

Commit 7ec60d5

Browse files
authored
p2p: move ping handling into pingLoop goroutine (#27887)
Moving the response sending there allows tracking all peer goroutines in the peer WaitGroup.
1 parent e13fa32 commit 7ec60d5

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

p2p/peer.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ type Peer struct {
112112
wg sync.WaitGroup
113113
protoErr chan error
114114
closed chan struct{}
115+
pingRecv chan struct{}
115116
disc chan DiscReason
116117

117118
// events receives message send / receive events if set
@@ -233,6 +234,7 @@ func newPeer(log log.Logger, conn *conn, protocols []Protocol) *Peer {
233234
disc: make(chan DiscReason),
234235
protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
235236
closed: make(chan struct{}),
237+
pingRecv: make(chan struct{}, 16),
236238
log: log.New("id", conn.node.ID(), "conn", conn.flags),
237239
}
238240
return p
@@ -293,9 +295,11 @@ loop:
293295
}
294296

295297
func (p *Peer) pingLoop() {
296-
ping := time.NewTimer(pingInterval)
297298
defer p.wg.Done()
299+
300+
ping := time.NewTimer(pingInterval)
298301
defer ping.Stop()
302+
299303
for {
300304
select {
301305
case <-ping.C:
@@ -304,6 +308,10 @@ func (p *Peer) pingLoop() {
304308
return
305309
}
306310
ping.Reset(pingInterval)
311+
312+
case <-p.pingRecv:
313+
SendItems(p.rw, pongMsg)
314+
307315
case <-p.closed:
308316
return
309317
}
@@ -330,7 +338,10 @@ func (p *Peer) handle(msg Msg) error {
330338
switch {
331339
case msg.Code == pingMsg:
332340
msg.Discard()
333-
go SendItems(p.rw, pongMsg)
341+
select {
342+
case p.pingRecv <- struct{}{}:
343+
case <-p.closed:
344+
}
334345
case msg.Code == discMsg:
335346
// This is the last message. We don't need to discard or
336347
// check errors because, the connection will be closed after it.

0 commit comments

Comments
 (0)