1818
1919import asyncio
2020import logging
21+ import random
2122from typing import Optional , Type , Union
2223
2324from pyrogram import utils
2930
3031class 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 :
0 commit comments