Skip to content

Commit

Permalink
metricshelper: improve checks for ip and transport (#2849)
Browse files Browse the repository at this point in the history
  • Loading branch information
sukunrt authored Jun 26, 2024
1 parent effa3fc commit d8bb57c
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 5 deletions.
15 changes: 10 additions & 5 deletions p2p/metricshelper/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import ma "github.com/multiformats/go-multiaddr"
var transports = [...]int{ma.P_CIRCUIT, ma.P_WEBRTC, ma.P_WEBRTC_DIRECT, ma.P_WEBTRANSPORT, ma.P_QUIC, ma.P_QUIC_V1, ma.P_WSS, ma.P_WS, ma.P_TCP}

func GetTransport(a ma.Multiaddr) string {
if a == nil {
return "other"
}
for _, t := range transports {
if _, err := a.ValueForProtocol(t); err == nil {
return ma.ProtocolWithCode(t).Name
Expand All @@ -15,15 +18,17 @@ func GetTransport(a ma.Multiaddr) string {

func GetIPVersion(addr ma.Multiaddr) string {
version := "unknown"
if addr == nil {
return version
}
ma.ForEach(addr, func(c ma.Component) bool {
if c.Protocol().Code == ma.P_IP4 {
switch c.Protocol().Code {
case ma.P_IP4, ma.P_DNS4:
version = "ip4"
return false
} else if c.Protocol().Code == ma.P_IP6 {
case ma.P_IP6, ma.P_DNS6:
version = "ip6"
return false
}
return true
return false
})
return version
}
68 changes: 68 additions & 0 deletions p2p/metricshelper/conn_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package metricshelper

import (
"fmt"
"testing"

ma "github.com/multiformats/go-multiaddr"
)

func TestGetTransport(t *testing.T) {
cases := []struct {
addr ma.Multiaddr
result string
}{
{
addr: ma.StringCast("/ip4/1.1.1.1/tcp/1"),
result: "tcp",
},
{
addr: ma.StringCast("/ip4/1.1.1.1/udp/10"),
result: "other",
},
{
addr: nil,
result: "other",
},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
got := GetTransport(tc.addr)
if got != tc.result {
t.Fatalf("invalid transport for %s\ngot:%v\nwant:%v", tc.addr, got, tc.result)
}
})
}
}

func TestIPVersion(t *testing.T) {
cases := []struct {
addr ma.Multiaddr
result string
}{
{
addr: ma.StringCast("/ip4/1.1.1.1/tcp/1"),
result: "ip4",
},
{
addr: ma.StringCast("/ip4/1.1.1.1/udp/10"),
result: "ip4",
},
{
addr: nil,
result: "unknown",
},
{
addr: ma.StringCast("/dns/hello.world/tcp/10"),
result: "unknown",
},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
got := GetIPVersion(tc.addr)
if got != tc.result {
t.Fatalf("invalid ip version for %s\ngot:%v\nwant:%v", tc.addr, got, tc.result)
}
})
}
}

0 comments on commit d8bb57c

Please sign in to comment.