From dd930fafc6785d6eb7b71ace499999331aa8dbf4 Mon Sep 17 00:00:00 2001 From: Platon Floria Date: Wed, 1 May 2024 10:46:14 +0300 Subject: [PATCH] feat: reconnect websocket --- fastlane_bot/events/listener.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/fastlane_bot/events/listener.py b/fastlane_bot/events/listener.py index 17d929d66..f51928039 100644 --- a/fastlane_bot/events/listener.py +++ b/fastlane_bot/events/listener.py @@ -1,5 +1,7 @@ import asyncio +import logging import time +import websockets from typing import AsyncGenerator, List from web3 import AsyncWeb3 @@ -9,6 +11,9 @@ from .interfaces.event import Event +logger = logging.getLogger(__name__) + + class EventListener: """ The EventListener is the entry point to create & manage websocket event subscriptions. @@ -63,10 +68,15 @@ async def _get_batched_events(self): await asyncio.sleep(min(self.NEW_EVENT_TIMEOUT, self._last_event_ts + self.NEW_EVENT_TIMEOUT - ts)) async def _listen(self): - async for response in self._w3.ws.process_subscriptions(): - self._last_event_ts = time.time() - subscription_id = response["subscription"] - log = response["result"] - event = self._subscription_by_id[subscription_id].process_log(log) - if event is not None: - self._event_buffer.append(complex_handler(event)) + while True: + try: + async for response in self._w3.ws.process_subscriptions(): + self._last_event_ts = time.time() + subscription_id = response["subscription"] + log = response["result"] + event = self._subscription_by_id[subscription_id].process_log(log) + if event is not None: + self._event_buffer.append(complex_handler(event)) + except websockets.exceptions.ConnectionClosed: + logger.info("Websocket connection lost. Reconnecting ...") + await asyncio.sleep(1)