Skip to content

Commit ecae5a0

Browse files
wgr523fjl
andauthored
p2p: move ping handling into pingLoop goroutine (#27887) (#115)
Moving the response sending there allows tracking all peer goroutines in the peer WaitGroup. Co-authored-by: Felix Lange <[email protected]>
1 parent 53db21b commit ecae5a0

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
@@ -105,6 +105,7 @@ type Peer struct {
105105
wg sync.WaitGroup
106106
protoErr chan error
107107
closed chan struct{}
108+
pingRecv chan struct{}
108109
disc chan DiscReason
109110

110111
// events receives message send / receive events if set
@@ -175,6 +176,7 @@ func newPeer(conn *conn, protocols []Protocol) *Peer {
175176
disc: make(chan DiscReason),
176177
protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
177178
closed: make(chan struct{}),
179+
pingRecv: make(chan struct{}, 16),
178180
log: log.New("id", conn.id, "conn", conn.flags),
179181
}
180182
return p
@@ -236,9 +238,11 @@ loop:
236238
}
237239

238240
func (p *Peer) pingLoop() {
239-
ping := time.NewTimer(pingInterval)
240241
defer p.wg.Done()
242+
243+
ping := time.NewTimer(pingInterval)
241244
defer ping.Stop()
245+
242246
for {
243247
select {
244248
case <-ping.C:
@@ -247,6 +251,10 @@ func (p *Peer) pingLoop() {
247251
return
248252
}
249253
ping.Reset(pingInterval)
254+
255+
case <-p.pingRecv:
256+
SendItems(p.rw, pongMsg)
257+
250258
case <-p.closed:
251259
return
252260
}
@@ -273,7 +281,10 @@ func (p *Peer) handle(msg Msg) error {
273281
switch {
274282
case msg.Code == pingMsg:
275283
msg.Discard()
276-
go SendItems(p.rw, pongMsg)
284+
select {
285+
case p.pingRecv <- struct{}{}:
286+
case <-p.closed:
287+
}
277288
case msg.Code == discMsg:
278289
var reason [1]DiscReason
279290
// This is the last message. We don't need to discard or

0 commit comments

Comments
 (0)