Skip to content

Commit 03131e9

Browse files
committed
add option to consider closed connections for connectedness
1 parent 884c093 commit 03131e9

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

p2p/net/swarm/swarm.go

+14-6
Original file line numberDiff line numberDiff line change
@@ -384,11 +384,11 @@ func (s *Swarm) addConn(tc transport.CapableConn, dir network.Direction) (*Conn,
384384
return nil, ErrSwarmClosed
385385
}
386386

387-
oldState := s.connectednessUnlocked(p)
387+
oldState := s.connectednessUnlocked(p, true)
388388

389389
c.streams.m = make(map[*Stream]struct{})
390390
s.conns.m[p] = append(s.conns.m[p], c)
391-
newState := s.connectednessUnlocked(p)
391+
newState := s.connectednessUnlocked(p, true)
392392

393393
// Add two swarm refs:
394394
// * One will be decremented after the close notifications fire in Conn.doClose
@@ -653,12 +653,20 @@ func (s *Swarm) Connectedness(p peer.ID) network.Connectedness {
653653
s.conns.RLock()
654654
defer s.conns.RUnlock()
655655

656-
return s.connectednessUnlocked(p)
656+
return s.connectednessUnlocked(p, false)
657657
}
658658

659-
func (s *Swarm) connectednessUnlocked(p peer.ID) network.Connectedness {
659+
// connectednessUnlocked returns the connectedness of a peer. For sending peer connectedness
660+
// changed notifications consider closed connections. When remote closes a connection
661+
// the underlying transport connection is closed first, so tracking change to the connectedness
662+
// state requires considering this recently closed connections impact on Connectedness.
663+
func (s *Swarm) connectednessUnlocked(p peer.ID, considerClosed bool) network.Connectedness {
660664
var haveTransient bool
661665
for _, c := range s.conns.m[p] {
666+
if !considerClosed && c.IsClosed() {
667+
// These will be garbage collected soon
668+
continue
669+
}
662670
if c.Stat().Transient {
663671
haveTransient = true
664672
} else {
@@ -768,7 +776,7 @@ func (s *Swarm) removeConn(c *Conn) {
768776

769777
cs := s.conns.m[p]
770778

771-
oldState := s.connectednessUnlocked(p)
779+
oldState := s.connectednessUnlocked(p, true)
772780

773781
if len(cs) == 1 {
774782
delete(s.conns.m, p)
@@ -786,7 +794,7 @@ func (s *Swarm) removeConn(c *Conn) {
786794
}
787795
}
788796

789-
newState := s.connectednessUnlocked(p)
797+
newState := s.connectednessUnlocked(p, true)
790798

791799
s.conns.Unlock()
792800

0 commit comments

Comments
 (0)