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(io): mqtt subscription concurrent map #3475

Merged
merged 2 commits into from
Dec 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
26 changes: 16 additions & 10 deletions internal/io/mqtt/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import (
"crypto/tls"
"fmt"
"sync"
"sync/atomic"
"time"

Expand All @@ -41,7 +42,7 @@
scHandler api.StatusChangeHandler
conf *ConnectionConfig
// key is the topic. Each topic will have only one connector
subscriptions map[string]*subscriptionInfo
subscriptions sync.Map
}

type ConnectionConfig struct {
Expand All @@ -61,7 +62,7 @@

func CreateConnection(_ api.StreamContext) modules.Connection {
return &Connection{
subscriptions: make(map[string]*subscriptionInfo),
subscriptions: sync.Map{},
}
}

Expand Down Expand Up @@ -129,12 +130,17 @@
conn.logger.Warnf("sc handler has not set yet")
}
conn.logger.Infof("The connection to mqtt broker is established")
for topic, info := range conn.subscriptions {
err := conn.Subscribe(topic, info.Qos, info.Handler)
if err != nil { // should never happen. If happens because of connection, it will retry later
conn.logger.Errorf("Failed to subscribe topic %s: %v", topic, err)
conn.subscriptions.Range(func(key, value any) bool {
topic, ok1 := key.(string)
info, ok2 := value.(*subscriptionInfo)
if ok1 && ok2 {
err := conn.Subscribe(topic, info.Qos, info.Handler)
if err != nil { // should never happen. If happens because of connection, it will retry later
conn.logger.Errorf("Failed to subscribe topic %s: %v", topic, err)
}

Check warning on line 140 in internal/io/mqtt/client/client.go

View check run for this annotation

Codecov / codecov/patch

internal/io/mqtt/client/client.go#L139-L140

Added lines #L139 - L140 were not covered by tests
}
}
return true
})
}

func (conn *Connection) onConnectLost(_ pahoMqtt.Client, err error) {
Expand All @@ -159,7 +165,7 @@
if err != nil {
return
}
delete(conn.subscriptions, topic)
conn.subscriptions.Delete(topic)
conn.Client.Unsubscribe(topic)
}

Expand Down Expand Up @@ -190,10 +196,10 @@
}

func (conn *Connection) Subscribe(topic string, qos byte, callback pahoMqtt.MessageHandler) error {
conn.subscriptions[topic] = &subscriptionInfo{
conn.subscriptions.Store(topic, &subscriptionInfo{
Qos: qos,
Handler: callback,
}
})
token := conn.Client.Subscribe(topic, qos, callback)
return handleToken(token)
}
Expand Down
Loading