Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add locking around connection manager connections #477

Merged
merged 1 commit into from
Jan 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading