Skip to content

Commit

Permalink
Merge pull request #477 from blinklabs-io/fix/connection-manager-panic
Browse files Browse the repository at this point in the history
fix: add locking around connection manager connections
  • Loading branch information
agaffney authored Jan 25, 2024
2 parents 54ef0ff + 391e38e commit acb24fa
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions connection_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

package ouroboros

import "sync"

// ConnectionManagerErrorFunc is a function that takes a connection ID and an error
type ConnectionManagerErrorFunc func(int, error)

Expand Down Expand Up @@ -53,9 +55,10 @@ func (c ConnectionManagerTag) String() string {
}

type ConnectionManager struct {
config ConnectionManagerConfig
hosts []ConnectionManagerHost
connections map[int]*ConnectionManagerConnection
config ConnectionManagerConfig
hosts []ConnectionManagerHost
connections map[int]*ConnectionManagerConnection
connectionsMutex sync.Mutex
}

type ConnectionManagerConfig struct {
Expand Down Expand Up @@ -107,10 +110,12 @@ func (c *ConnectionManager) AddHostsFromTopology(topology *TopologyConfig) {
}

func (c *ConnectionManager) AddConnection(connId int, conn *Connection) {
c.connectionsMutex.Lock()
c.connections[connId] = &ConnectionManagerConnection{
Id: connId,
Conn: conn,
}
c.connectionsMutex.Unlock()
go func() {
err, ok := <-conn.ErrorChan()
if !ok {
Expand All @@ -123,15 +128,20 @@ func (c *ConnectionManager) AddConnection(connId int, conn *Connection) {
}

func (c *ConnectionManager) RemoveConnection(connId int) {
c.connectionsMutex.Lock()
delete(c.connections, connId)
c.connectionsMutex.Unlock()
}

func (c *ConnectionManager) GetConnectionById(connId int) *ConnectionManagerConnection {
c.connectionsMutex.Lock()
defer c.connectionsMutex.Unlock()
return c.connections[connId]
}

func (c *ConnectionManager) GetConnectionsByTags(tags ...ConnectionManagerTag) []*ConnectionManagerConnection {
var ret []*ConnectionManagerConnection
c.connectionsMutex.Lock()
for _, conn := range c.connections {
skipConn := false
for _, tag := range tags {
Expand All @@ -144,6 +154,7 @@ func (c *ConnectionManager) GetConnectionsByTags(tags ...ConnectionManagerTag) [
ret = append(ret, conn)
}
}
c.connectionsMutex.Unlock()
return ret
}

Expand Down

0 comments on commit acb24fa

Please sign in to comment.