fix: reboot dropped (by server) connections automatically

This commit is contained in:
17ms 2024-07-12 23:05:21 +03:00
parent f4df43f3a1
commit 8462ab866c
Signed by untrusted user who does not match committer: ae
GPG Key ID: 995EFD5C1B532B3E
2 changed files with 12 additions and 4 deletions

View File

@ -2,5 +2,6 @@ import json
WS_ADDR = "wss://ws.blockchain.info/coins" WS_ADDR = "wss://ws.blockchain.info/coins"
SUB_MSG = json.dumps({"coin": "eth", "command": "subscribe", "entity": "confirmed_transaction"}) SUB_MSG = json.dumps({"coin": "eth", "command": "subscribe", "entity": "confirmed_transaction"})
WS_RECONNECT_PAUSE = 2 # Seconds
DEFAULT_EXPORT_PATH = "./data/export.json" DEFAULT_EXPORT_PATH = "./data/export.json"

View File

@ -4,7 +4,7 @@ import threading
import logging import logging
import websockets import websockets
from src.const import WS_ADDR, SUB_MSG from src.const import WS_ADDR, SUB_MSG, WS_RECONNECT_PAUSE
class WebSocketThread(threading.Thread): class WebSocketThread(threading.Thread):
@ -26,6 +26,7 @@ class WebSocketThread(threading.Thread):
# Ignores the confirmation message, as it can't be parsed with the same template # Ignores the confirmation message, as it can't be parsed with the same template
_ = await ws.recv() _ = await ws.recv()
logging.info("Confirmation received, ready to receive the TX data")
while not self.shutdown_event.is_set(): while not self.shutdown_event.is_set():
try: try:
@ -37,8 +38,11 @@ class WebSocketThread(threading.Thread):
await self.q.coro_put(data) await self.q.coro_put(data)
except websockets.exceptions.ConnectionClosed: except websockets.exceptions.ConnectionClosed:
logging.info("WebSocket connection closed") logging.info(
self.shutdown_event.set() "WebSocket connection closed unexpectedly, sleeping for %d seconds before rebooting the connection",
WS_RECONNECT_PAUSE,
)
await asyncio.sleep(WS_RECONNECT_PAUSE)
break break
# pylint: disable=broad-exception-caught # pylint: disable=broad-exception-caught
except Exception as e: except Exception as e:
@ -68,7 +72,10 @@ class WebSocketThread(threading.Thread):
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
try: try:
loop.run_until_complete(self.connect()) while not self.shutdown_event.is_set():
# If the connection drops here, rebooting is attempted (unless error is returned)
logging.info("Connecting to the WebSocket")
loop.run_until_complete(self.connect())
# pylint: disable=broad-exception-caught # pylint: disable=broad-exception-caught
except Exception as e: except Exception as e:
logging.error("WebSocket thread crashed: %s", str(e)) logging.error("WebSocket thread crashed: %s", str(e))