p2p: add cache for func PacketConn.relayPeer

This commit is contained in:
rkonfj
2025-02-15 20:47:12 +08:00
parent 88a2870174
commit 1476061b60
2 changed files with 24 additions and 20 deletions

2
cache/cache.go vendored
View File

@@ -33,7 +33,7 @@ var (
) )
func init() { func init() {
defaultCache = lru.New[string, *CacheValue[any]](1024) defaultCache = lru.New[string, *CacheValue[any]](2048)
} }
// LoadTTL load value by key from default cache pool // LoadTTL load value by key from default cache pool

View File

@@ -13,6 +13,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/sigcn/pg/cache"
"github.com/sigcn/pg/cache/lru" "github.com/sigcn/pg/cache/lru"
"github.com/sigcn/pg/disco" "github.com/sigcn/pg/disco"
"github.com/sigcn/pg/disco/udp" "github.com/sigcn/pg/disco/udp"
@@ -265,27 +266,30 @@ func (c *PacketConn) PeerMeta(peerID disco.PeerID) url.Values {
// relayPeer find the suitable relay peer // relayPeer find the suitable relay peer
func (c *PacketConn) relayPeer(peerID disco.PeerID) disco.PeerID { func (c *PacketConn) relayPeer(peerID disco.PeerID) disco.PeerID {
peers := c.PeerStore().Peers() selectRelayPeer := func(_ string) disco.PeerID {
for range len(peers) { peers := c.PeerStore().Peers()
index := c.relayPeerIndex.Add(1) % uint64(len(peers)) for range len(peers) {
p := peers[index] index := c.relayPeerIndex.Add(1) % uint64(len(peers))
if p.PeerID == peerID { p := peers[index]
continue if p.PeerID == peerID {
} continue
meta := c.PeerMeta(p.PeerID) }
if meta == nil { meta := c.PeerMeta(p.PeerID)
continue if meta == nil {
} continue
if _, ok := disco.Labels(meta["label"]).Get("node.nr"); ok { }
// can not as relay peer when `node.nr` label is present if _, ok := disco.Labels(meta["label"]).Get("node.nr"); ok {
continue // can not as relay peer when `node.nr` label is present
} continue
peerNAT := disco.NATType(meta.Get("nat")) }
if peerNAT == disco.Easy || peerNAT == disco.IP4 || peerNAT == disco.IP46 { peerNAT := disco.NATType(meta.Get("nat"))
return p.PeerID if peerNAT == disco.Easy || peerNAT == disco.IP4 || peerNAT == disco.IP46 {
return p.PeerID
}
} }
return ""
} }
return "" return cache.LoadTTL(peerID.String(), time.Millisecond, selectRelayPeer)
} }
// networkChangeDetect listen network change and restart udp and websocket listener // networkChangeDetect listen network change and restart udp and websocket listener