Teekeks / pyTwitchAPI

A Python 3.7 compatible implementation of the Twitch API, EventSub, PubSub and Chat
https://pytwitchapi.dev
MIT License
256 stars 38 forks source link

Rewrite session_reconnect handling to follow twitch rules #310

Closed Latent-Logic closed 5 months ago

Latent-Logic commented 5 months ago

https://dev.twitch.tv/docs/eventsub/handling-websocket-events/#reconnect-message When a session_reconnect message is received, the client should create a new connection to the reconnect url while leaving the existing connection open to receive messages until the new connection gets the welcome message. This way no events should be missed during the handoff.

In my testing this fixes #286 where the connection gets broken because of a Websocket closing: 4007 - Invalid reconnect

I'll update this PR with logs from a repro of the issue once twitch sends me another session_reconnect. (It worked for a slightly less cleaned up version of these changes previously, but it had a bunch of debug logging and hooked in slightly different ways)

Latent-Logic commented 5 months ago

Repro of the 4007 issue:

2024-05-30 10:28:46,681 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:28:56,680 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:29:05,753 DEBUG   twitchAPI.eventsub.websocket    got request from websocket to reconnect
2024-05-30 10:29:05,753 DEBUG   twitchAPI.eventsub.websocket    reconnecting using wss://cell-a.eventsub.wss.twitch.tv/ws?challenge=a4749afd-7957-4ad9-bd38-b5027ff50018&id=AgoQ9OavRrveQSiC1PBorLcHDxIGY2VsbC1h...
2024-05-30 10:29:05,792 DEBUG   twitchAPI.eventsub.websocket    websocket is closing
2024-05-30 10:29:05,905 INFO    twitchAPI.eventsub.websocket    Websocket closing: 4007 - Invalid reconnect

2024-05-30 11:21:31,857 DEBUG   twitchAPI.eventsub.websocket    stopping websocket EventSub...

With this MR:

2024-05-30 10:23:38,105 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:23:48,056 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:23:58,057 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:24:03,635 DEBUG   twitchAPI.eventsub.websocket    got request from websocket to reconnect, reconnect url: wss://cell-a.eventsub.wss.twitch.tv/ws?challenge=613f1eb7-396e-4b67-98d5-7360d9197b5b&id=AgoQPnH5Rj6KQC2h53YJGlnHKRIGY2VsbC1h
2024-05-30 10:24:04,102 DEBUG   twitchAPI.eventsub.websocket    websocket session_reconnect completed
2024-05-30 10:24:14,151 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:24:24,096 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:24:34,098 DEBUG   twitchAPI.eventsub.websocket    got session keep alive
2024-05-30 10:24:44,101 DEBUG   twitchAPI.eventsub.websocket    got session keep alive