From 29f8bb309d4e82bcccfca6b467321846160b56fb Mon Sep 17 00:00:00 2001 From: Adin Schmahmann Date: Tue, 4 Feb 2020 11:50:16 -0500 Subject: [PATCH] try another peer sorting metric. fix bug in when findproviders returns --- kpeerset/metrics.go | 38 ++++++++++++++++++++++++++++++++++++-- routing.go | 2 +- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/kpeerset/metrics.go b/kpeerset/metrics.go index 3ad50ea6a..dd0ca8c65 100644 --- a/kpeerset/metrics.go +++ b/kpeerset/metrics.go @@ -1,6 +1,7 @@ package kpeerset import ( + "math/big" "sort" "time" @@ -20,7 +21,12 @@ type peerLatencyMetricList []peerLatencyMetric func (p peerLatencyMetricList) Len() int { return len(p) } func (p peerLatencyMetricList) Less(i, j int) bool { pm1, pm2 := p[i], p[j] + return calculationLess(pm1, pm2) +} +func (p peerLatencyMetricList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p peerLatencyMetricList) GetPeerID(i int) peer.ID { return p[i].peer } +func less(pm1, pm2 *peerLatencyMetric) bool { p1Connectedness, p2Connectedness := pm1.connectedness, pm2.connectedness p1Latency, p2Latency := pm1.latency, pm2.latency @@ -58,8 +64,36 @@ func (p peerLatencyMetricList) Less(i, j int) bool { return pm1.metric.Cmp(pm2.metric) == -1 } -func (p peerLatencyMetricList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p peerLatencyMetricList) GetPeerID(i int) peer.ID { return p[i].peer } + +func calculationLess(pm1, pm2 peerLatencyMetric) bool { + return calc(pm1).Cmp(calc(pm2)) == -1 +} + +func calc(pm peerLatencyMetric) *big.Int { + var c int64 + switch pm.connectedness { + case network.Connected: + c = 1 + case network.CanConnect: + c = 5 + case network.CannotConnect: + c = 10000 + default: + c = 20 + } + + l := int64(pm.latency) + if l <= 0 { + l = int64(time.Second) * 10 + } + + res := big.NewInt(c) + tmp := big.NewInt(l) + res.Mul(res, tmp) + res.Mul(res, pm.metric) + + return res +} var _ SortablePeers = (*peerLatencyMetricList)(nil) diff --git a/routing.go b/routing.go index e98ad6af0..03aabb40c 100644 --- a/routing.go +++ b/routing.go @@ -608,7 +608,7 @@ func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key multihash return peers, nil }, func(peerset *kpeerset.SortedPeerset) bool { - return ps.Size() > count + return ps.Size() >= count }, )