Skip to content

Commit 4745dcc

Browse files
committed
refactor(connection, session): enhance connection retry logic and improve logging
1 parent 38e58d4 commit 4745dcc

3 files changed

Lines changed: 136 additions & 104 deletions

File tree

pyrogram/connection/connection.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import asyncio
2020
import logging
21+
import random
2122
from typing import Optional, Type, Union
2223

2324
from pyrogram import utils
@@ -29,6 +30,8 @@
2930

3031
class Connection:
3132
MAX_CONNECTION_ATTEMPTS = -1
33+
INITIAL_BACKOFF = 1
34+
MAX_BACKOFF = 30
3235

3336
def __init__(
3437
self,
@@ -62,6 +65,7 @@ def __init__(
6265
async def connect(self) -> None:
6366
attempts = Connection.MAX_CONNECTION_ATTEMPTS
6467
attempt_index = 0
68+
backoff = Connection.INITIAL_BACKOFF
6569

6670
while True:
6771
self.protocol = self.protocol_factory(ipv6=self.ipv6, proxy=self.proxy, crypto_executor_workers=self.crypto_executor_workers, loop=self.loop)
@@ -72,7 +76,11 @@ async def connect(self) -> None:
7276
except OSError as e:
7377
log.warning("Unable to connect due to network issues: %s", e)
7478
await self.protocol.close()
75-
await asyncio.sleep(1)
79+
80+
jittered = backoff * (0.5 + random.random())
81+
log.info("Retrying connection in %.1fs (attempt #%d)", jittered, attempt_index + 1)
82+
await asyncio.sleep(jittered)
83+
backoff = min(backoff * 2, Connection.MAX_BACKOFF)
7684
else:
7785
log.info("Connected! %s DC%s%s - IPv%s",
7886
"Test" if self.test_mode else "Production",
@@ -83,7 +91,7 @@ async def connect(self) -> None:
8391

8492
attempt_index += 1
8593
if attempts > 0 and attempt_index >= attempts:
86-
log.warning("Connection failed! Trying again...")
94+
log.warning("Connection failed after %d attempts", attempt_index)
8795
raise ConnectionError
8896

8997
async def close(self) -> None:

pyrogram/connection/transport/tcp/tcp.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,9 @@ async def send(self, data: bytes, wait_for_marker: bool = True) -> None:
187187
log.debug("Sending %d bytes", len(data))
188188
try:
189189
self.writer.write(data)
190-
await self.writer.drain()
190+
await asyncio.wait_for(self.writer.drain(), timeout=TCP.TIMEOUT)
191+
except asyncio.TimeoutError:
192+
raise OSError("Send drain timed out")
191193
except OSError:
192194
raise
193195
except Exception as e:

0 commit comments

Comments
 (0)