Skip to content

Commit

Permalink
Internalize the max connection retries for now
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
fselmo committed Jul 28, 2023
1 parent ca8985f commit 311b706
Showing 1 changed file with 4 additions and 10 deletions.
14 changes: 4 additions & 10 deletions web3/providers/websocket/websocket_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 "
Expand Down

0 comments on commit 311b706

Please sign in to comment.