Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Fixed race condition in mqtt container for extra subscriptions #159

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions mango/container/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
# dict mapping additionally subscribed topics to a set of aids
self.additional_subscriptions: dict[str, set[str]] = {}
# Future for pending sub requests
self.pending_sub_request: None | asyncio.Future = None
self.pending_sub_request: dict[int, asyncio.Future] = {}

async def start(self):
self._loop = asyncio.get_event_loop()
Expand Down Expand Up @@ -264,8 +264,11 @@

self.mqtt_client.on_disconnect = on_discon

def process_sub_request(mid):
self.pending_sub_request[mid].set_result(0)

def on_sub(client, userdata, mid, reason_code_list, properties):
self._loop.call_soon_threadsafe(self.pending_sub_request.set_result, 0)
self._loop.call_soon_threadsafe(process_sub_request, mid)

self.mqtt_client.on_subscribe = on_sub

Expand Down Expand Up @@ -433,14 +436,17 @@
return True

self.additional_subscriptions[topic] = {aid}
self.pending_sub_request = asyncio.Future()
result, _ = self.mqtt_client.subscribe(topic, qos=qos)
future = asyncio.Future()
result, mid = self.mqtt_client.subscribe(topic, qos=qos)

if result != paho.MQTT_ERR_SUCCESS:
self.pending_sub_request.set_result(False)
future.set_result(False)

Check warning on line 443 in mango/container/mqtt.py

View check run for this annotation

Codecov / codecov/patch

mango/container/mqtt.py#L443

Added line #L443 was not covered by tests
return False

await self.pending_sub_request
self.pending_sub_request[mid] = future

await self.pending_sub_request[mid]
del self.pending_sub_request[mid]
return True

def deregister(self, aid):
Expand Down