From dcfc9632f361bf3d766bced5c51c8aaadcd58ff4 Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Mon, 17 Jun 2024 02:51:35 +0300 Subject: [PATCH] Add DNS cache ttl setting to aiohttp session. (#1514) * Add DNS cache ttl setting to aiohttp session. Also the limit argument is added to the session initializer. This commit adds a setting for DNS cache ttl (time-to-live) to the aiohttp session configuration. This is implemented as a workaround for a known issue in aiogram as exhibited in aiogram/aiogram#1500. * Added changelog --- CHANGES/1500.bugfix.rst | 1 + aiogram/client/session/aiohttp.py | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 CHANGES/1500.bugfix.rst diff --git a/CHANGES/1500.bugfix.rst b/CHANGES/1500.bugfix.rst new file mode 100644 index 00000000..23b78e8c --- /dev/null +++ b/CHANGES/1500.bugfix.rst @@ -0,0 +1 @@ +Increased DNS cache ttl setting to aiohttp session as a workaround for DNS resolution issues in aiohttp. diff --git a/aiogram/client/session/aiohttp.py b/aiogram/client/session/aiohttp.py index 0878e315..9e1d9e1b 100644 --- a/aiogram/client/session/aiohttp.py +++ b/aiogram/client/session/aiohttp.py @@ -23,11 +23,10 @@ from aiohttp.http import SERVER_SOFTWARE from aiogram.__meta__ import __version__ from aiogram.methods import TelegramMethod - +from .base import BaseSession from ...exceptions import TelegramNetworkError from ...methods.base import TelegramType from ...types import InputFile -from .base import BaseSession if TYPE_CHECKING: from ..bot import Bot @@ -86,13 +85,24 @@ def _prepare_connector(chain_or_plain: _ProxyType) -> Tuple[Type["TCPConnector"] class AiohttpSession(BaseSession): - def __init__(self, proxy: Optional[_ProxyType] = None, **kwargs: Any) -> None: + def __init__( + self, proxy: Optional[_ProxyType] = None, limit: int = 100, **kwargs: Any + ) -> None: + """ + Client session based on aiohttp. + + :param proxy: The proxy to be used for requests. Default is None. + :param limit: The total number of simultaneous connections. Default is 100. + :param kwargs: Additional keyword arguments. + """ super().__init__(**kwargs) self._session: Optional[ClientSession] = None self._connector_type: Type[TCPConnector] = TCPConnector self._connector_init: Dict[str, Any] = { "ssl": ssl.create_default_context(cafile=certifi.where()), + "limit": limit, + "ttl_dns_cache": 3600, # Workaround for https://github.com/aiogram/aiogram/issues/1500 } self._should_reset_connector = True # flag determines connector state self._proxy: Optional[_ProxyType] = None