@cryptotaxi247 / kubo / commits / c7fd1d9dd

swarm: refactored multiconn creation

Juan Batiz-Benet committed Nov 20, 2014 at 08:49 UTC c7fd1d9ddb896afd1e9310fdc660b7bf81fd2df6
1 file changed +37 -27
net/swarm/conn.go
+37 -27
@@ -6,6 +6,7 @@ import (
6
7 conn "github.com/jbenet/go-ipfs/net/conn"
8 msg "github.com/jbenet/go-ipfs/net/message"
9 + peer "github.com/jbenet/go-ipfs/peer"
10
11 context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
12 ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
@@ -95,6 +96,36 @@ func (s *Swarm) handleIncomingConn(nconn conn.Conn) {
96 }
97 }
98
99 +// peerMultiConn returns the MultiConn responsible for handling this peer.
100 +// if there is none, it creates one and returns it. Note that timeouts
101 +// and connection teardowns will remove it.
102 +func (s *Swarm) peerMultiConn(p peer.Peer) (*conn.MultiConn, error) {
103 +
104 + s.connsLock.Lock()
105 + mc, found := s.conns[p.Key()]
106 + if found {
107 + s.connsLock.Unlock()
108 + return mc, nil
109 + }
110 +
111 + // multiconn doesn't exist, make a new one.
112 + mc, err := conn.NewMultiConn(s.Context(), s.local, p, nil)
113 + if err != nil {
114 + s.connsLock.Unlock()
115 + log.Errorf("error creating multiconn: %s", err)
116 + return nil, err
117 + }
118 + s.conns[p.Key()] = mc
119 + s.connsLock.Unlock()
120 +
121 + // kick off reader goroutine
122 + s.Children().Add(1)
123 + mc.Children().Add(1) // child of Conn as well.
124 + go s.fanInSingle(mc)
125 + log.Debugf("added new multiconn: %s", mc)
126 + return mc, nil
127 +}
128 +
129 // connSetup adds the passed in connection to its peerMap and starts
130 // the fanInSingle routine for that connection
131 func (s *Swarm) connSetup(c conn.Conn) (conn.Conn, error) {
@@ -126,35 +157,14 @@ func (s *Swarm) connSetup(c conn.Conn) (conn.Conn, error) {
157 }
158
159 // add to conns
129 - s.connsLock.Lock()
130 -
131 - mc, found := s.conns[c.RemotePeer().Key()]
132 - if !found {
133 - // multiconn doesn't exist, make a new one.
134 - conns := []conn.Conn{c}
135 - mc, err := conn.NewMultiConn(s.Context(), s.local, c.RemotePeer(), conns)
136 - if err != nil {
137 - log.Errorf("error creating multiconn: %s", err)
138 - c.Close()
139 - return nil, err
140 - }
141 -
142 - s.conns[c.RemotePeer().Key()] = mc
143 - s.connsLock.Unlock()
144 -
145 - // kick off reader goroutine
146 - s.Children().Add(1)
147 - mc.Children().Add(1) // child of Conn as well.
148 - go s.fanInSingle(mc)
149 - log.Debugf("added new multiconn: %s", mc)
150 - } else {
151 - s.connsLock.Unlock() // unlock before adding new conn
152 -
153 - mc.Add(c)
154 - log.Debugf("multiconn found: %s", mc)
160 + mc, err := s.peerMultiConn(c.RemotePeer())
161 + if err != nil {
162 + c.Close()
163 + return nil, err
164 }
156 -
165 + mc.Add(c)
166 log.Debugf("multiconn added new conn %s", c)
167 +
168 return c, nil
169 }
170