Fix step_sender could deadlock

This commit is contained in:
Lonami Exo 2024-06-29 17:47:01 +02:00
parent 94048d9102
commit 26c32f31d2
2 changed files with 18 additions and 13 deletions

View File

@ -219,6 +219,7 @@ class Client:
self._sender: Optional[Sender] = None
self._sender_lock = asyncio.Lock()
self._sender_lock_flag = False
if isinstance(session, Storage):
self._storage = session
elif session is None:

View File

@ -268,19 +268,23 @@ async def step(client: Client) -> None:
async def step_sender(client: Client, sender: Sender, lock: asyncio.Lock) -> None:
if lock.locked():
async with lock:
pass
else:
async with lock:
try:
updates = await sender.step()
except ConnectionError:
if client.connected:
raise
else:
# disconnect was called, so the socket returning 0 bytes is expected
return
flag = client._sender_lock_flag
async with lock:
if client._sender_lock_flag != flag:
# different task already received an item from the network
return
# current task is responsible for receiving
# toggle the flag so any other task that comes after does not run again
client._sender_lock_flag = not client._sender_lock_flag
try:
updates = await sender.step()
except ConnectionError:
if client.connected:
raise
else:
# disconnect was called, so the socket returning 0 bytes is expected
return
process_socket_updates(client, updates)