Skip to content

Commit c6c6479

Browse files
committed
refactor: extract ping interface
1 parent 38be0dc commit c6c6479

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

waku/v2/api/common/pinger.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package common
2+
3+
import (
4+
"context"
5+
"time"
6+
7+
"github.com/libp2p/go-libp2p/core/host"
8+
"github.com/libp2p/go-libp2p/core/peer"
9+
"github.com/libp2p/go-libp2p/p2p/protocol/ping"
10+
)
11+
12+
type Pinger interface {
13+
PingPeer(ctx context.Context, peerID peer.ID) (time.Duration, error)
14+
}
15+
16+
type defaultPingImpl struct {
17+
host host.Host
18+
}
19+
20+
func NewDefaultPinger(host host.Host) Pinger {
21+
return &defaultPingImpl{
22+
host: host,
23+
}
24+
}
25+
26+
func (d *defaultPingImpl) PingPeer(ctx context.Context, peerID peer.ID) (time.Duration, error) {
27+
pingResultCh := ping.Ping(ctx, d.host, peerID)
28+
select {
29+
case <-ctx.Done():
30+
return 0, ctx.Err()
31+
case r := <-pingResultCh:
32+
if r.Error != nil {
33+
return 0, r.Error
34+
}
35+
return r.RTT, nil
36+
}
37+
}

0 commit comments

Comments
 (0)