From aaf819699724c22dfa980dbbaec0325199320820 Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Tue, 14 Feb 2023 21:39:33 +0100 Subject: [PATCH] Fix race on check MQTT subscriptions (#88117) * Check MQTT subscriptions under paho client lock * Check simple subscriptions first * Apply suggestion --- homeassistant/components/mqtt/client.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/mqtt/client.py b/homeassistant/components/mqtt/client.py index c2891ed1068..8a18c392ca2 100644 --- a/homeassistant/components/mqtt/client.py +++ b/homeassistant/components/mqtt/client.py @@ -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)