Skip to content

Commit acb24fa

Browse files
authored
Merge pull request #477 from blinklabs-io/fix/connection-manager-panic
fix: add locking around connection manager connections
2 parents 54ef0ff + 391e38e commit acb24fa

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

connection_manager.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
package ouroboros
1616

17+
import "sync"
18+
1719
// ConnectionManagerErrorFunc is a function that takes a connection ID and an error
1820
type ConnectionManagerErrorFunc func(int, error)
1921

@@ -53,9 +55,10 @@ func (c ConnectionManagerTag) String() string {
5355
}
5456

5557
type ConnectionManager struct {
56-
config ConnectionManagerConfig
57-
hosts []ConnectionManagerHost
58-
connections map[int]*ConnectionManagerConnection
58+
config ConnectionManagerConfig
59+
hosts []ConnectionManagerHost
60+
connections map[int]*ConnectionManagerConnection
61+
connectionsMutex sync.Mutex
5962
}
6063

6164
type ConnectionManagerConfig struct {
@@ -107,10 +110,12 @@ func (c *ConnectionManager) AddHostsFromTopology(topology *TopologyConfig) {
107110
}
108111

109112
func (c *ConnectionManager) AddConnection(connId int, conn *Connection) {
113+
c.connectionsMutex.Lock()
110114
c.connections[connId] = &ConnectionManagerConnection{
111115
Id: connId,
112116
Conn: conn,
113117
}
118+
c.connectionsMutex.Unlock()
114119
go func() {
115120
err, ok := <-conn.ErrorChan()
116121
if !ok {
@@ -123,15 +128,20 @@ func (c *ConnectionManager) AddConnection(connId int, conn *Connection) {
123128
}
124129

125130
func (c *ConnectionManager) RemoveConnection(connId int) {
131+
c.connectionsMutex.Lock()
126132
delete(c.connections, connId)
133+
c.connectionsMutex.Unlock()
127134
}
128135

129136
func (c *ConnectionManager) GetConnectionById(connId int) *ConnectionManagerConnection {
137+
c.connectionsMutex.Lock()
138+
defer c.connectionsMutex.Unlock()
130139
return c.connections[connId]
131140
}
132141

133142
func (c *ConnectionManager) GetConnectionsByTags(tags ...ConnectionManagerTag) []*ConnectionManagerConnection {
134143
var ret []*ConnectionManagerConnection
144+
c.connectionsMutex.Lock()
135145
for _, conn := range c.connections {
136146
skipConn := false
137147
for _, tag := range tags {
@@ -144,6 +154,7 @@ func (c *ConnectionManager) GetConnectionsByTags(tags ...ConnectionManagerTag) [
144154
ret = append(ret, conn)
145155
}
146156
}
157+
c.connectionsMutex.Unlock()
147158
return ret
148159
}
149160

0 commit comments

Comments
 (0)