byScore cleanup score sorting

This commit is contained in:
Giovanni Petrantoni 2020-09-11 22:24:46 +09:00
parent af96d6cb10
commit 3b6a26c0bd
1 changed files with 6 additions and 28 deletions

View File

@ -260,6 +260,8 @@ proc validateParameters*(parameters: TopicParams): Result[void, cstring] =
else: else:
ok() ok()
func byScore(x,y: PubSubPeer): int = (x.score - y.score).int
method init*(g: GossipSub) = method init*(g: GossipSub) =
proc handler(conn: Connection, proto: string) {.async.} = proc handler(conn: Connection, proto: string) {.async.} =
## main protocol handler that gets triggered on every ## main protocol handler that gets triggered on every
@ -394,13 +396,7 @@ proc rebalanceMesh(g: GossipSub, topic: string) {.async.} =
x.peerId notin g.backingOff x.peerId notin g.backingOff
# sort peers by score # sort peers by score
grafts.sort do (x, y: PubSubPeer) -> int: grafts.sort(byScore)
let
peerx = x.score
peery = y.score
if peerx < peery: -1
elif peerx == peery: 0
else: 1
# Graft peers so we reach a count of D # Graft peers so we reach a count of D
grafts.setLen(min(grafts.len, GossipSubD - g.mesh.peers(topic))) grafts.setLen(min(grafts.len, GossipSubD - g.mesh.peers(topic)))
@ -431,13 +427,7 @@ proc rebalanceMesh(g: GossipSub, topic: string) {.async.} =
x.peerId notin g.backingOff x.peerId notin g.backingOff
# sort peers by score # sort peers by score
grafts.sort do (x, y: PubSubPeer) -> int: grafts.sort(byScore)
let
peerx = x.score
peery = y.score
if peerx < peery: -1
elif peerx == peery: 0
else: 1
# Graft peers so we reach a count of D # Graft peers so we reach a count of D
grafts.setLen(min(grafts.len, g.parameters.dOut - g.mesh.peers(topic))) grafts.setLen(min(grafts.len, g.parameters.dOut - g.mesh.peers(topic)))
@ -456,13 +446,7 @@ proc rebalanceMesh(g: GossipSub, topic: string) {.async.} =
prunes = toSeq(g.mesh[topic]) prunes = toSeq(g.mesh[topic])
# sort peers by score (inverted) # sort peers by score (inverted)
prunes.sort do (x, y: PubSubPeer) -> int: prunes.sort(byScore)
let
peerx = x.score
peery = y.score
if peerx > peery: -1
elif peerx == peery: 0
else: 1
# keep high score peers # keep high score peers
if prunes.len > g.parameters.dScore: if prunes.len > g.parameters.dScore:
@ -502,13 +486,7 @@ proc rebalanceMesh(g: GossipSub, topic: string) {.async.} =
# opportunistic grafting, by spec mesh should not be empty... # opportunistic grafting, by spec mesh should not be empty...
if g.mesh.peers(topic) > 1: if g.mesh.peers(topic) > 1:
var peers = toSeq(g.mesh[topic]) var peers = toSeq(g.mesh[topic])
peers.sort do (x, y: PubSubPeer) -> int: peers.sort(byScore)
let
peerx = x.score
peery = y.score
if peerx < peery: -1
elif peerx == peery: 0
else: 1
let medianIdx = peers.len div 2 let medianIdx = peers.len div 2
let median = peers[medianIdx] let median = peers[medianIdx]
if median.score < g.parameters.opportunisticGraftThreshold: if median.score < g.parameters.opportunisticGraftThreshold: