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

feat: add connection selection logic #2726

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 38 additions & 5 deletions p2p/net/swarm/swarm.go
Expand Up @@ -22,6 +22,7 @@ import (
logging "github.com/ipfs/go-log/v2"
ma "github.com/multiformats/go-multiaddr"
madns "github.com/multiformats/go-multiaddr-dns"
manet "github.com/multiformats/go-multiaddr/net"
)

const (
Expand Down Expand Up @@ -578,11 +579,11 @@ func isBetterConn(a, b *Conn) bool {
return !aTransient
}

// If one is direct and not the other, prefer the direct connection.
aDirect := isDirectConn(a)
bDirect := isDirectConn(b)
if aDirect != bDirect {
return aDirect
// Compare connection priorities and choose the better connection
aPriority := connPriority(a)
bPriority := connPriority(b)
if aPriority >= bPriority {
return true
}

// Otherwise, prefer the connection with more open streams.
Expand All @@ -602,6 +603,38 @@ func isBetterConn(a, b *Conn) bool {
return true
}

func connPriority(c *Conn) int {
if c == nil {
return 0
}

var priority int
// LAN > WAN > PROXY
switch {
case c.conn.Transport().Proxy():
priority += 10
case manet.IsPrivateAddr(c.RemoteMultiaddr()):
priority += 20
case manet.IsPublicAddr(c.RemoteMultiaddr()):
priority += 15
}

// We prefer udp protocols
switch c.ConnState().Transport {
case "quic", "quic-v1", "webtransport", "webrtc":
priority += 5
case "tcp", "websocket":
priority += 3
}
wlynxg marked this conversation as resolved.
Show resolved Hide resolved

// If one is transient and not the other, prefer the non-transient connection.
if !c.Stat().Transient {
priority += 2
wlynxg marked this conversation as resolved.
Show resolved Hide resolved
}

wlynxg marked this conversation as resolved.
Show resolved Hide resolved
return priority
}

// bestConnToPeer returns the best connection to peer.
func (s *Swarm) bestConnToPeer(p peer.ID) *Conn {

Expand Down