From 0cb2ae7fcd905130ec121c4420f8af677e0f9335 Mon Sep 17 00:00:00 2001 From: DevilXD Date: Thu, 16 Dec 2021 19:09:55 +0100 Subject: [PATCH] Improve WS ping timeout handling --- constants.py | 1 + websocket.py | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/constants.py b/constants.py index 454eada..e193476 100644 --- a/constants.py +++ b/constants.py @@ -26,6 +26,7 @@ SETTINGS_PATH = "settings.json" COOKIES_PATH = "cookies.pickle" # Intervals and Delays PING_INTERVAL = timedelta(minutes=3) +PING_TIMEOUT = timedelta(seconds=10) ONLINE_DELAY = timedelta(seconds=30) # Tags DROPS_ENABLED_TAG = "c2542d6d-cd10-4532-919b-3d19f30a768b" diff --git a/websocket.py b/websocket.py index b3d4820..5aaac5e 100644 --- a/websocket.py +++ b/websocket.py @@ -20,6 +20,7 @@ from constants import ( WebsocketTopic, WEBSOCKET_URL, PING_INTERVAL, + PING_TIMEOUT, MAX_WEBSOCKETS, WS_TOPICS_LIMIT, ) @@ -62,8 +63,8 @@ class Websocket: # set when the topics changed self._topics_changed = asyncio.Event() # ping timestamps - self._next_ping = time() - self._max_pong = time() + self._next_ping: float = time() + self._max_pong: float = self._next_ping + PING_TIMEOUT.total_seconds() # main task, responsible for receiving messages, sending them, and websocket ping self._handle_task: Optional[asyncio.Task[Any]] = None # topics stuff @@ -79,6 +80,8 @@ class Websocket: def request_reconnect(self): ws_logger.warning(f"Websocket[{self._idx}] requested reconnect.") + # reset our ping interval, so we send a PING after reconnect right away + self._next_ping = time() self._reconnect_requested.set() async def start(self): @@ -152,7 +155,7 @@ class Websocket: now = time() if now >= self._next_ping: self._next_ping = now + PING_INTERVAL.total_seconds() - self._max_pong = now + 10 # wait for a PONG for up to 10s + self._max_pong = now + PING_TIMEOUT.total_seconds() # wait for a PONG for up to 10s await self.send({"type": "PING"}) elif now >= self._max_pong: # it's been more than 10s and there was no PONG