From eb58005ec3a93bef70c4bb3bca4c7631cca8b30d Mon Sep 17 00:00:00 2001 From: Richard Ramos Date: Tue, 22 Oct 2024 17:03:44 -0400 Subject: [PATCH] refactor: extract ping interface --- waku/v2/api/common/pinger.go | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 waku/v2/api/common/pinger.go diff --git a/waku/v2/api/common/pinger.go b/waku/v2/api/common/pinger.go new file mode 100644 index 000000000..ba8c26a21 --- /dev/null +++ b/waku/v2/api/common/pinger.go @@ -0,0 +1,37 @@ +package common + +import ( + "context" + "time" + + "github.com/libp2p/go-libp2p/core/host" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/p2p/protocol/ping" +) + +type Pinger interface { + PingPeer(ctx context.Context, peerID peer.ID) (time.Duration, error) +} + +type defaultPingImpl struct { + host host.Host +} + +func NewDefaultPinger(host host.Host) Pinger { + return &defaultPingImpl{ + host: host, + } +} + +func (d *defaultPingImpl) PingPeer(ctx context.Context, peerID peer.ID) (time.Duration, error) { + pingResultCh := ping.Ping(ctx, d.host, peerID) + select { + case <-ctx.Done(): + return 0, ctx.Err() + case r := <-pingResultCh: + if r.Error != nil { + return 0, r.Error + } + return r.RTT, nil + } +}