Skip to content

Commit

Permalink
Fix re-entrancy issue with MQTTListeners.notify (#131)
Browse files Browse the repository at this point in the history
* Copy listener array when inside lock

process copied listener array outside lock

* Remove commented out code
  • Loading branch information
adam-fowler authored Jan 5, 2023
1 parent b4fab62 commit a0e1126
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
6 changes: 3 additions & 3 deletions Sources/MQTTNIO/MQTTClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -411,9 +411,9 @@ public final class MQTTClient {
}

var connectionParameters = ConnectionParameters()
var publishListeners = MQTTListeners<MQTTPublishInfo>()
var closeListeners = MQTTListeners<Void>()
var shutdownListeners = MQTTListeners<Void>()
let publishListeners = MQTTListeners<MQTTPublishInfo>()
let closeListeners = MQTTListeners<Void>()
let shutdownListeners = MQTTListeners<Void>()
private var _connection: MQTTConnection?
private var lock = NIOLock()
}
Expand Down
15 changes: 9 additions & 6 deletions Sources/MQTTNIO/MQTTListeners.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@
import NIO
import NIOConcurrencyHelpers

class MQTTListeners<ReturnType> {
final class MQTTListeners<ReturnType> {
typealias Listener = (Result<ReturnType, Error>) -> Void

func notify(_ result: Result<ReturnType, Error>) {
self.lock.withLock {
listeners.values.forEach { listener in
listener(result)
}
let listeners = self.lock.withLock {
return self.listeners
}
listeners.values.forEach { listener in
listener(result)
}
}

Expand All @@ -38,7 +39,9 @@ class MQTTListeners<ReturnType> {
}

func removeAll() {
self.listeners = [:]
self.lock.withLock {
self.listeners = [:]
}
}

private let lock = NIOLock()
Expand Down

0 comments on commit a0e1126

Please sign in to comment.