From 9302105a2e482dc13f0b08afde2ab511ca2e304f Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Wed, 21 Jan 2015 20:42:27 +0000 Subject: [PATCH] refactor: abstract away connection tie breaking So we don't need to carry that logic in LocalPeer --- router/connection.go | 20 ++++++++++++++++++++ router/local_peer.go | 17 ++++++++--------- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/router/connection.go b/router/connection.go index f4cc3762..173162f2 100644 --- a/router/connection.go +++ b/router/connection.go @@ -20,6 +20,14 @@ type Connection interface { Shutdown(error) } +type ConnectionTieBreak int + +const ( + TieBreakWon ConnectionTieBreak = iota + TieBreakLost + TieBreakTied +) + type RemoteConnection struct { local *Peer remote *Peer @@ -116,6 +124,18 @@ func (conn *LocalConnection) Start(acceptNewPeer bool) { go conn.run(queryChan, acceptNewPeer) } +func (conn *LocalConnection) BreakTie(dupConn *LocalConnection) ConnectionTieBreak { + // conn.UID is used as the tie breaker here, in the knowledge that + // both sides will make the same decision. + if conn.UID < dupConn.UID { + return TieBreakWon + } else if dupConn.UID < conn.UID { + return TieBreakLost + } else { + return TieBreakTied + } +} + func (conn *LocalConnection) Established() bool { conn.RLock() defer conn.RUnlock() diff --git a/router/local_peer.go b/router/local_peer.go index 1b1160f5..33c49de3 100644 --- a/router/local_peer.go +++ b/router/local_peer.go @@ -189,21 +189,20 @@ func (peer *LocalPeer) handleAddConnection(conn *LocalConnection) { if dupConn == conn { return } - // conn.UID is used as the tie breaker here, in the - // knowledge that both sides will make the same decision. dupConnLocal := dupConn.(*LocalConnection) - if conn.UID == dupConnLocal.UID { + switch conn.BreakTie(dupConnLocal) { + case TieBreakWon: + dupConnLocal.CheckFatal(dupErr) + peer.handleDeleteConnection(dupConnLocal) + case TieBreakLost: + conn.CheckFatal(dupErr) + return + case TieBreakTied: // oh good grief. Sod it, just kill both of them. conn.CheckFatal(dupErr) dupConnLocal.CheckFatal(dupErr) peer.handleDeleteConnection(dupConnLocal) return - } else if conn.UID < dupConnLocal.UID { - dupConnLocal.CheckFatal(dupErr) - peer.handleDeleteConnection(dupConnLocal) - } else { - conn.CheckFatal(dupErr) - return } } if err := peer.checkConnectionLimit(); err != nil {