Skip to content

Commit

Permalink
Handle broken aiohttp websocket in chat bot client
Browse files Browse the repository at this point in the history
It turns out that aiohttp WebSocket code does not recognize if the
underlying connection is broken:
aio-libs/aiohttp#2309
As a twitch client we know we'll at minimum receive a PING request every
5 minutes even if no other channel updates are happening:
https://dev.twitch.tv/docs/irc/#keepalive-messages
(I tested this and saw every a ping request always happened between
every 4min 1sec to 4min 51sec)

If we miss a PING and fail to respond twitch considers the connection
closed. Thus we can add a timeout to our websocket receive() call and if
we've heard nothing in over 5 minutes our connection is broken and we
should perform a reconnect. This has been tested running the bot, and
then trying 3 different types of connection breaking:
1) Disabling the network interface on my computer for 5 minutes
2) Suspending laptop and resuming later
3) Dropping related active NAT state on router (similar to rebooting router)
  • Loading branch information
Latent-Logic committed Oct 15, 2023
1 parent 363797d commit 329a8a6
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion twitchAPI/chat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,18 @@ async def __task_receive(self):
'USERSTATE': self._handle_user_state
}
while not self.__connection.closed:
message = await self.__connection.receive()
try: # At minimum we should receive a PING request just under every 5 minutes
message = await self.__connection.receive(timeout=5*60)
except asyncio.TimeoutError:
self.logger.warning(f"Reached timeout for websocket receive, will attempt a reconnect")
if self.__running:
try:
await self._handle_base_reconnect()
except TwitchBackendException:
self.logger.exception('Connection to chat websocket lost and unable to reestablish connection!')
break
else:
break
if message.type == aiohttp.WSMsgType.TEXT:
messages = message.data.split('\r\n')
for m in messages:
Expand Down

0 comments on commit 329a8a6

Please sign in to comment.