Skip to content

Commit

Permalink
remove stored subsCalled when connection is lost
Browse files Browse the repository at this point in the history
  • Loading branch information
ajatprabha committed Feb 7, 2024
1 parent 1692368 commit 80f9957
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
19 changes: 17 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,19 @@ func (c *Client) attemptSingleConnection(addrs []TCPAddress) error {
return c.resumeSubscriptions()
}

func (c *Client) removeStoreSubscriptions(cc mqtt.Client) {
c.clientMu.RLock()
defer c.clientMu.RUnlock()

for _, v := range c.mqttClients {
if v.client == cc {
v.mu.Lock()
v.subsCalled.Delete(v.subsCalled.Values()...)
v.mu.Unlock()
}
}
}

func toClientOptions(c *Client, o *clientOptions, idSuffix string) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()

Expand All @@ -228,7 +241,7 @@ func toClientOptions(c *Client, o *clientOptions, idSuffix string) *mqtt.ClientO
SetConnectTimeout(o.connectTimeout).
SetMaxReconnectInterval(o.maxReconnectInterval).
SetReconnectingHandler(reconnectHandler(c, o)).
SetConnectionLostHandler(connectionLostHandler(o)).
SetConnectionLostHandler(connectionLostHandler(c, o)).
SetOnConnectHandler(onConnectHandler(c, o))

return opts
Expand Down Expand Up @@ -283,7 +296,7 @@ func reconnectHandler(client PubSub, o *clientOptions) mqtt.ReconnectHandler {
}
}

func connectionLostHandler(o *clientOptions) mqtt.ConnectionLostHandler {
func connectionLostHandler(c *Client, o *clientOptions) mqtt.ConnectionLostHandler {
return func(cc mqtt.Client, err error) {
if o.logger != nil {
o.logger.Error(context.Background(), err, map[string]any{
Expand All @@ -292,6 +305,8 @@ func connectionLostHandler(o *clientOptions) mqtt.ConnectionLostHandler {
})
}

c.removeStoreSubscriptions(cc)

if o.onConnectionLostHandler != nil {
o.onConnectionLostHandler(err)
}
Expand Down
2 changes: 1 addition & 1 deletion client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ func Test_connectionLostHandler(t *testing.T) {
"client_id": "clientID",
}).Return()

f := connectionLostHandler(c.options)
f := connectionLostHandler(c, c.options)
f(c.mqttClient, errors.New("disconnected"))
ml.AssertExpectations(t)
}
Expand Down

0 comments on commit 80f9957

Please sign in to comment.