diff --git a/run.py b/run.py index c7ca560..bb60c46 100644 --- a/run.py +++ b/run.py @@ -22,6 +22,7 @@ import aiohttp import aiofiles from websockets.exceptions import ConnectionClosed +from websockets import WebSocketCommonProtocol from sanic import Sanic, response from sanic.exceptions import NotFound @@ -103,6 +104,24 @@ subscriptions = defaultdict(list) jobs_in_memory_state = {} +@asyncio.coroutine +def wait_closed(self): + """ + Wait until the connection is closed. + + This is identical to :attr:`closed`, except it can be awaited. + + This can make it easier to handle connection termination, regardless + of its cause, in tasks that interact with the WebSocket connection. + + """ + yield from asyncio.shield(self.connection_lost_waiter) + + +# this is a backport of websockets 7.0 which sanic doesn't support yet +WebSocketCommonProtocol.wait_closed = wait_closed + + def reset_pending_jobs(): Job.update(state="scheduled", log="").where(Job.state == "running").execute()