Skip to content

Commit

Permalink
fix(src): Close connections to API clients when shutting down
Browse files Browse the repository at this point in the history
This effectively re-implements asyncio.Server::close_clients which
is only available in python3.13.

In python3.12 asyncio.Server::wait_closed will hang unless these
sockets are closed: python/cpython#104344

Co-authored-by: Steffen Christgau <[email protected]>
  • Loading branch information
aleasto and christgau committed Dec 26, 2024
1 parent 52c50dd commit 147c903
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/wsdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -1125,10 +1125,12 @@ def do_POST(self) -> None:
class ApiServer:

address_monitor: 'NetworkAddressMonitor'
clients: List[asyncio.StreamWriter]

def __init__(self, aio_loop: asyncio.AbstractEventLoop, listen_address: bytes,
address_monitor: 'NetworkAddressMonitor') -> None:
self.server = None
self.clients = []
self.address_monitor = address_monitor

# defer server creation
Expand All @@ -1148,6 +1150,7 @@ async def create_server(self, aio_loop: asyncio.AbstractEventLoop, listen_addres
self.on_connect, path=listen_address))

async def on_connect(self, read_stream: asyncio.StreamReader, write_stream: asyncio.StreamWriter) -> None:
self.clients.append(write_stream)
while True:
try:
line = await read_stream.readline()
Expand All @@ -1156,12 +1159,14 @@ async def on_connect(self, read_stream: asyncio.StreamReader, write_stream: asyn
if not write_stream.is_closing():
await write_stream.drain()
else:
self.clients.remove(write_stream)
write_stream.close()
return
except UnicodeDecodeError as e:
logger.debug('invalid input utf8', e)
except Exception as e:
logger.warning('exception in API client', e)
self.clients.remove(write_stream)
write_stream.close()
return

Expand Down Expand Up @@ -1221,6 +1226,8 @@ async def cleanup(self) -> None:
await self.create_task
if self.server:
self.server.close()
for client in self.clients:
client.close()
await self.server.wait_closed()


Expand Down

0 comments on commit 147c903

Please sign in to comment.