From ad638dbcc509bf3827aa038693a3f0c43015fd56 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 24 May 2024 22:28:14 -1000 Subject: [PATCH] Speed up removing MQTT subscriptions (#118088) --- homeassistant/components/mqtt/client.py | 10 +++++----- tests/components/mqtt/test_device_trigger.py | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/mqtt/client.py b/homeassistant/components/mqtt/client.py index 857b073a746..3e2507ade95 100644 --- a/homeassistant/components/mqtt/client.py +++ b/homeassistant/components/mqtt/client.py @@ -429,10 +429,10 @@ class MQTT: self.config_entry = config_entry self.conf = conf - self._simple_subscriptions: defaultdict[str, list[Subscription]] = defaultdict( - list + self._simple_subscriptions: defaultdict[str, set[Subscription]] = defaultdict( + set ) - self._wildcard_subscriptions: list[Subscription] = [] + self._wildcard_subscriptions: set[Subscription] = set() # _retained_topics prevents a Subscription from receiving a # retained message more than once per topic. This prevents flooding # already active subscribers when new subscribers subscribe to a topic @@ -789,9 +789,9 @@ class MQTT: The caller is responsible clearing the cache of _matching_subscriptions. """ if subscription.is_simple_match: - self._simple_subscriptions[subscription.topic].append(subscription) + self._simple_subscriptions[subscription.topic].add(subscription) else: - self._wildcard_subscriptions.append(subscription) + self._wildcard_subscriptions.add(subscription) @callback def _async_untrack_subscription(self, subscription: Subscription) -> None: diff --git a/tests/components/mqtt/test_device_trigger.py b/tests/components/mqtt/test_device_trigger.py index 1ef80c0b81e..b01e40d311e 100644 --- a/tests/components/mqtt/test_device_trigger.py +++ b/tests/components/mqtt/test_device_trigger.py @@ -529,16 +529,16 @@ async def test_non_unique_triggers( async_fire_mqtt_message(hass, "foobar/triggers/button1", "short_press") await hass.async_block_till_done() assert len(calls) == 2 - assert calls[0].data["some"] == "press1" - assert calls[1].data["some"] == "press2" + all_calls = {calls[0].data["some"], calls[1].data["some"]} + assert all_calls == {"press1", "press2"} # Trigger second config references to same trigger # and triggers both attached instances. async_fire_mqtt_message(hass, "foobar/triggers/button2", "long_press") await hass.async_block_till_done() assert len(calls) == 2 - assert calls[0].data["some"] == "press1" - assert calls[1].data["some"] == "press2" + all_calls = {calls[0].data["some"], calls[1].data["some"]} + assert all_calls == {"press1", "press2"} # Removing the first trigger will clean up calls.clear()