From 80809e9ac7e2b0b1dcbc8cb9fd19279fff5e3a91 Mon Sep 17 00:00:00 2001 From: shmocz <112764837+shmocz@users.noreply.github.com> Date: Tue, 3 Oct 2023 16:05:22 +0300 Subject: [PATCH] fix(pyra2yr): Race condition in WebSocketClient In send_message(), when retrieving result from out_queue, another task could put a message to in_queue, resulting in wrong message to be retrieved from out_queue. Fixed by introducing a lock. Closes #5 --- pyra2yr/pyra2yr/network.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pyra2yr/pyra2yr/network.py b/pyra2yr/pyra2yr/network.py index c4694e83..8f915de5 100644 --- a/pyra2yr/pyra2yr/network.py +++ b/pyra2yr/pyra2yr/network.py @@ -94,6 +94,7 @@ def __init__(self, uri: str, timeout=5.0): self.task = None self._tries = 15 self._connect_delay = 1.0 + self._lock = asyncio.Lock() def open(self): self.task = asyncio.create_task(async_log_exceptions(self.main())) @@ -103,8 +104,9 @@ async def close(self): await self.task async def send_message(self, m: str) -> aiohttp.WSMessage: - await self.in_queue.put(m) - return await self.out_queue.get() + async with self._lock: + await self.in_queue.put(m) + return await self.out_queue.get() async def main(self): # send the initial message