From 311b7068ea9177139831e216e5326556ef5cbcb0 Mon Sep 17 00:00:00 2001 From: fselmo Date: Fri, 28 Jul 2023 16:20:31 -0600 Subject: [PATCH] Internalize the max connection retries for now - Due to the exponential backoff, it is already pretty reasonable to have this number at 5 but more than this might add long wait times. If there is demand, we can open this up to an init arg in the future. --- web3/providers/websocket/websocket_v2.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/web3/providers/websocket/websocket_v2.py b/web3/providers/websocket/websocket_v2.py index 7f6451841d..b9e6c4af3e 100644 --- a/web3/providers/websocket/websocket_v2.py +++ b/web3/providers/websocket/websocket_v2.py @@ -52,20 +52,18 @@ def get_default_endpoint() -> URI: class WebsocketProviderV2(PersistentConnectionProvider): logger = logging.getLogger("web3.providers.WebsocketProviderV2") is_async: bool = True + _max_connection_retries: int = 5 def __init__( self, endpoint_uri: Optional[Union[URI, str]] = None, websocket_kwargs: Optional[Dict[str, Any]] = None, call_timeout: Optional[int] = None, - max_connection_retries: Optional[int] = 5, ) -> None: self.endpoint_uri = URI(endpoint_uri) if self.endpoint_uri is None: self.endpoint_uri = get_default_endpoint() - self.max_connection_retries = max_connection_retries - if not any( self.endpoint_uri.startswith(prefix) for prefix in VALID_WEBSOCKET_URI_PREFIXES @@ -112,19 +110,15 @@ async def connect(self) -> None: _backoff_rate_change = 1.75 _backoff_time = 1.75 - while True: + while _connection_attempts != self._max_connection_retries: try: _connection_attempts += 1 self.ws = await connect(self.endpoint_uri, **self.websocket_kwargs) - break except WebSocketException as e: - if ( - self.max_connection_retries - and _connection_attempts > self.max_connection_retries - ): + if _connection_attempts == self._max_connection_retries: raise ProviderConnectionError( f"Could not connect to endpoint: {self.endpoint_uri}. " - f"Retries exceeded max of {self.max_connection_retries}." + f"Retries exceeded max of {self._max_connection_retries}." ) from e self.logger.info( f"Could not connect to endpoint: {self.endpoint_uri}. Retrying in "