Skip to content

Commit

Permalink
fix: resubscribe when no session present (#895) (#1650)
Browse files Browse the repository at this point in the history
  • Loading branch information
simonnilsson committed Jul 28, 2023
1 parent 18bdd49 commit 37acda6
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2105,8 +2105,11 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
if (
!this._firstConnection &&
// Only resubscribe in case of clean connection or if the server does not have a stored session.
// The Session Present flag is available since v3.1.1
// https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349254
(this.options.clean ||
(this.options.protocolVersion === 5 &&
(this.options.protocolVersion >= 4 &&
!this.connackPacket.sessionPresent)) &&
_resubscribeTopicsKeys.length > 0
) {
Expand Down
33 changes: 33 additions & 0 deletions test/abstract_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3165,6 +3165,39 @@ export default function abstractTest(server, config) {
})
})

it('should resubscribe when clean=false and sessionPresent=false', function _test(done) {
const client = connect({
clientId: 'test',
reconnectPeriod: 100,
clean: false,
protocolVersion: 4,
})
let tryReconnect = true
let reconnectEvent = false

client.on('reconnect', () => {
reconnectEvent = true
})

client.on('connect', () => {
if (tryReconnect) {
client.subscribe('hello', () => {
client.stream.end()

server.once('client', (serverClient) => {
serverClient.on('subscribe', () => {
client.end(done)
})
})
})

tryReconnect = false
} else {
assert.isTrue(reconnectEvent)
}
})
})

it('should not resubscribe when reconnecting if resubscribe is disabled', function _test(done) {
const client = connect({ reconnectPeriod: 100, resubscribe: false })
let tryReconnect = true
Expand Down
3 changes: 3 additions & 0 deletions test/server_helpers_for_client_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ export default function serverBuilder(
if (!serverClient.writable) return false
let rc = 'returnCode'
const connack = {}
if (serverClient.options.protocolVersion >= 4) {
connack['sessionPresent'] = false
}
if (
serverClient.options &&
serverClient.options.protocolVersion === 5
Expand Down

0 comments on commit 37acda6

Please sign in to comment.