Skip to content

Commit

Permalink
feat: reconnect websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
platonfloria committed May 1, 2024
1 parent 525feb2 commit dd930fa
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions fastlane_bot/events/listener.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import asyncio
import logging
import time
import websockets
from typing import AsyncGenerator, List

from web3 import AsyncWeb3
Expand All @@ -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.
Expand Down Expand Up @@ -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)

0 comments on commit dd930fa

Please sign in to comment.