Fix race on check MQTT subscriptions (#88117)

* Check MQTT subscriptions under paho client lock

* Check simple subscriptions first

* Apply suggestion
This commit is contained in:
Jan Bouwhuis 2023-02-14 21:39:33 +01:00 committed by GitHub
parent 8529bcef2a
commit aaf8196997
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -421,6 +421,12 @@ class MQTT:
retain=will_message.retain,
)
def _is_active_subscription(self, topic: str) -> bool:
"""Check if a topic has an active subscription."""
return topic in self._simple_subscriptions or any(
other.topic == topic for other in self._wildcard_subscriptions
)
async def async_publish(
self, topic: str, payload: PublishPayloadType, qos: int, retain: bool
) -> None:
@ -544,11 +550,11 @@ class MQTT:
_raise_on_error(result)
return mid
if any(other.topic == topic for other in self.subscriptions):
# Other subscriptions on topic remaining - don't unsubscribe.
return
async with self._paho_lock:
if self._is_active_subscription(topic):
# Other subscriptions on topic remaining - don't unsubscribe.
return
mid = await self.hass.async_add_executor_job(_client_unsubscribe, topic)
await self._register_mid(mid)