From 1d6fd7898adf2b25d697463600183391636aa83d Mon Sep 17 00:00:00 2001 From: yash-dk Date: Sun, 13 Sep 2020 13:13:01 +0530 Subject: [PATCH] Consider all reconnect attempts as retrying (#1557) This means that a value of 0 retries will no longer try to reconnect. --- telethon/client/users.py | 1 + telethon/helpers.py | 12 +++++++++--- telethon/network/mtprotosender.py | 7 +++++-- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/telethon/client/users.py b/telethon/client/users.py index 3c6faa6e..5c806f5c 100644 --- a/telethon/client/users.py +++ b/telethon/client/users.py @@ -51,6 +51,7 @@ class UserMethods: request_index = 0 self._last_request = time.time() + for attempt in retry_range(self._request_retries): try: future = sender.send(request, ordered=ordered) diff --git a/telethon/helpers.py b/telethon/helpers.py index 55eb1b79..fd37487d 100644 --- a/telethon/helpers.py +++ b/telethon/helpers.py @@ -95,17 +95,23 @@ def strip_text(text, entities): return text -def retry_range(retries): +def retry_range(retries, force_retry=True): """ Generates an integer sequence starting from 1. If `retries` is not a zero or a positive integer value, the sequence will be infinite, otherwise it will end at `retries + 1`. """ - yield 1 + + # We need at least one iteration even if the retries are 0 + # when force_retry is True. + if force_retry and not (retries is None or retries < 0): + retries += 1 + attempt = 0 while attempt != retries: attempt += 1 - yield 1 + attempt + yield attempt + async def _maybe_await(value): diff --git a/telethon/network/mtprotosender.py b/telethon/network/mtprotosender.py index 48f6e238..06f60506 100644 --- a/telethon/network/mtprotosender.py +++ b/telethon/network/mtprotosender.py @@ -217,6 +217,7 @@ class MTProtoSender: self._log.info('Connecting to %s...', self._connection) connected = False + for attempt in retry_range(self._retries): if not connected: connected = await self._try_connect(attempt) @@ -357,14 +358,16 @@ class MTProtoSender: self._state.reset() retries = self._retries if self._auto_reconnect else 0 - for attempt in retry_range(retries): + + attempt = 0 + # We're already "retrying" to connect, so we don't want to force retries + for attempt in retry_range(retries, force_retry=False): try: await self._connect() except (IOError, asyncio.TimeoutError) as e: last_error = e self._log.info('Failed reconnection attempt %d with %s', attempt, e.__class__.__name__) - await asyncio.sleep(self._delay) except Exception as e: last_error = e