speechmatics / speechmatics-python

Python library and CLI for Speechmatics
https://speechmatics.github.io/speechmatics-python/
MIT License
59 stars 15 forks source link

Fix unhandled task exception when using run_synchronously with a timeout #51

Closed benjamingorman closed 2 years ago

benjamingorman commented 2 years ago

This could occur due to _consumer_task attempting to receive from an already closed websocket. This is due to the timeout causing the socket to close in the 'finally' block of the context manager we now use to manage the connection, which could occur at the same time as _consumer_task attempted to receive from the websocket.

This would result in the following exception being logged:

Task exception was never retrieved
future: <Task finished name='Task-7' coro=<WebsocketClient._consumer_handler() done, defined at /home/beng/Projects/speechmatics-python/speechmatics/client.py:205> exception=ConnectionClosedOK(Close(code=1000, reason=''), Close(code=1000, reason=''), False)>
Traceback (most recent call last):
  File "/home/beng/Projects/speechmatics-python/speechmatics/client.py", line 210, in _consumer_handler
    message = await self.websocket.recv()
  File "/home/beng/.local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 552, in recv
    await self.ensure_open()
  File "/home/beng/.local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 929, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: sent 1000 (OK); then received 1000 (OK)

This exception being logged was confusing because it was always the last thing output in the logs however it came from a background task and thus was not actually the exception on the main thread (TimeoutError is).