|
9 | 9 | from typing import List, Mapping, Callable, Union |
10 | 10 | import trio |
11 | 11 | import logging |
| 12 | +from logging import INFO |
12 | 13 | from trio_websocket import ( |
13 | 14 | open_websocket_url, |
14 | 15 | ConnectionClosed, |
|
24 | 25 | SubscriptionType, |
25 | 26 | to_camel_case, |
26 | 27 | ) |
| 28 | + |
27 | 29 | from blocknative import __version__ as API_VERSION |
28 | 30 |
|
| 31 | +FORMAT = "%(asctime)s [%(levelname)s]: %(message)s" |
| 32 | +logging.basicConfig(format=FORMAT, level=INFO) |
| 33 | + |
29 | 34 | PING_INTERVAL = 15 |
30 | 35 | PING_TIMEOUT = 10 |
31 | 36 | MESSAGE_SEND_INTERVAL = 0.021 # 21ms |
@@ -174,7 +179,11 @@ def subscribe_txn(self, tx_hash: str, callback: Callback, status: str = "sent"): |
174 | 179 | self._send_txn_watch_message(tx_hash, status) |
175 | 180 |
|
176 | 181 | def connect(self, base_url: str = BN_BASE_URL): |
177 | | - """Initializes the connection to the WebSocket server.""" |
| 182 | + """Initializes the connection to the WebSocket server. |
| 183 | +
|
| 184 | + Args: |
| 185 | + base_url: The websocket url to connect to. Useful for when using a proxy. |
| 186 | + """ |
178 | 187 | try: |
179 | 188 | return trio.run(self._connect, base_url) |
180 | 189 | except KeyboardInterrupt: |
@@ -267,6 +276,15 @@ async def _message_handler(self, message: dict): |
267 | 276 | ) |
268 | 277 |
|
269 | 278 | def unsubscribe(self, watched_address): |
| 279 | + """Unsubscribe from the current stream. |
| 280 | +
|
| 281 | + Note: |
| 282 | + This function is passed as a parameter to the to the transaction callback that you provide. |
| 283 | +
|
| 284 | + Args: |
| 285 | + watched_address: The address to unsubscribe from. |
| 286 | + """ |
| 287 | + |
270 | 288 | # remove this subscription from the registry so that we don't execute the callback |
271 | 289 | del self._subscription_registry[watched_address] |
272 | 290 |
|
@@ -330,7 +348,12 @@ async def _handle_connection(self, base_url: str): |
330 | 348 | nursery.start_soon(self._heartbeat) |
331 | 349 | nursery.start_soon(self._poll_messages) |
332 | 350 | nursery.start_soon(self._message_dispatcher) |
333 | | - except (ConnectionClosed, trio.MultiError) as error: |
| 351 | + except (ConnectionClosed, trio.MultiError, trio.TooSlowError) as error: |
| 352 | + if isinstance(error, trio.TooSlowError): |
| 353 | + logging.warn( |
| 354 | + f"Server failed to respond to ping within the given timeout of {PING_TIMEOUT} seconds." |
| 355 | + ) |
| 356 | + logging.info("Attempting to reconnect...") |
334 | 357 | # If server times the connection out or drops, reconnect |
335 | 358 | await trio.sleep(0.5) |
336 | 359 | await self._connect(base_url) |
|
0 commit comments