Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

metricshelper: improve checks for ip and transport #2849

Merged
merged 1 commit into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
})
}
}
Loading