mirror of
https://github.com/libp2p/go-libp2p-peerstore.git
synced 2025-03-22 12:50:07 +08:00
do sorting on addresses before sending them to stream
This commit is contained in:
parent
825dac628c
commit
ffd762afc8
62
addr/sorting.go
Normal file
62
addr/sorting.go
Normal file
@ -0,0 +1,62 @@
|
||||
package addr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
ma "github.com/jbenet/go-multiaddr"
|
||||
manet "github.com/jbenet/go-multiaddr-net"
|
||||
mafmt "github.com/whyrusleeping/mafmt"
|
||||
)
|
||||
|
||||
func isFDCostlyTransport(a ma.Multiaddr) bool {
|
||||
return mafmt.TCP.Matches(a)
|
||||
}
|
||||
|
||||
type AddrList []ma.Multiaddr
|
||||
|
||||
func (al AddrList) Len() int {
|
||||
return len(al)
|
||||
}
|
||||
|
||||
func (al AddrList) Swap(i, j int) {
|
||||
al[i], al[j] = al[j], al[i]
|
||||
}
|
||||
|
||||
func (al AddrList) Less(i, j int) bool {
|
||||
a := al[i]
|
||||
b := al[j]
|
||||
|
||||
// dial localhost addresses next, they should fail immediately
|
||||
lba := manet.IsIPLoopback(a)
|
||||
lbb := manet.IsIPLoopback(b)
|
||||
if lba {
|
||||
if !lbb {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// dial utp and similar 'non-fd-consuming' addresses first
|
||||
fda := isFDCostlyTransport(a)
|
||||
fdb := isFDCostlyTransport(b)
|
||||
if !fda {
|
||||
if fdb {
|
||||
return true
|
||||
}
|
||||
|
||||
// if neither consume fd's, assume equal ordering
|
||||
return false
|
||||
}
|
||||
|
||||
// if 'b' doesnt take a file descriptor
|
||||
if !fdb {
|
||||
return false
|
||||
}
|
||||
|
||||
// if 'b' is loopback and both take file descriptors
|
||||
if lbb {
|
||||
return false
|
||||
}
|
||||
|
||||
// for the rest, just sort by bytes
|
||||
return bytes.Compare(a.Bytes(), b.Bytes()) > 0
|
||||
}
|
@ -1,9 +1,11 @@
|
||||
package peer
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
addr "github.com/ipfs/go-libp2p-peer/addr"
|
||||
ma "github.com/jbenet/go-multiaddr"
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
@ -258,7 +260,7 @@ func (mgr *AddrManager) AddrStream(ctx context.Context, p ID) <-chan ma.Multiadd
|
||||
initial = append(initial, a.Addr)
|
||||
}
|
||||
|
||||
// TODO: sort these?
|
||||
sort.Sort(addr.AddrList(initial))
|
||||
|
||||
go func(buffer []ma.Multiaddr) {
|
||||
defer close(out)
|
||||
|
Loading…
Reference in New Issue
Block a user