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
  • Loading branch information
aleasto committed Oct 11, 2024
1 parent 006a799 commit 17cbcd6
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/wsdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,7 @@ class ApiServer:
def __init__(self, aio_loop: asyncio.AbstractEventLoop, listen_address: bytes,
address_monitor: 'NetworkAddressMonitor') -> None:
self.server = None
self.clients = set()
self.address_monitor = address_monitor

# defer server creation
Expand All @@ -1146,6 +1147,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.add(write_stream.transport)
while True:
try:
line = await read_stream.readline()
Expand All @@ -1154,12 +1156,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.discard(write_stream.transport)
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.discard(write_stream.transport)
write_stream.close()
return

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


Expand Down

0 comments on commit 17cbcd6

Please sign in to comment.