feat(bot): add flood-control retry session middleware
This commit is contained in:
1 parent
056fc2c90a
commit
6bf62bc331
1 file changed
+83
@@ -0,0 +1,83 @@
|
|||||||
|
"""Retry Telegram requests that hit flood control (HTTP 429 / TelegramRetryAfter)."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING, Any, Iterable
|
||||||
|
|
||||||
|
from aiogram.client.session.middlewares.base import BaseRequestMiddleware, NextRequestMiddlewareType
|
||||||
|
from aiogram.exceptions import TelegramRetryAfter
|
||||||
|
from aiogram.methods import TelegramMethod
|
||||||
|
from aiogram.methods.base import Response, TelegramType
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from aiogram import Bot
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Methods used to deliver the final answer to the user.
|
||||||
|
# Progress edits (editMessageText) and deletes are intentionally excluded:
|
||||||
|
# they are cosmetic and must not stall the agent while it waits out a flood limit.
|
||||||
|
DEFAULT_RETRY_METHODS: frozenset[str] = frozenset(
|
||||||
|
{
|
||||||
|
"sendRichMessage",
|
||||||
|
"sendMessage",
|
||||||
|
"answerGuestQuery",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FloodRetryMiddleware(BaseRequestMiddleware):
|
||||||
|
"""Session middleware that waits `retry_after` seconds and retries on flood control.
|
||||||
|
|
||||||
|
Only TelegramRetryAfter is retried: Telegram guarantees the request was rejected,
|
||||||
|
so a retry cannot produce a duplicate message. Network/5xx errors are not retried
|
||||||
|
because the message might already have been delivered.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
max_retries: int = 3,
|
||||||
|
max_wait: float = 60.0,
|
||||||
|
extra_delay: float = 0.5,
|
||||||
|
methods: Iterable[str] = DEFAULT_RETRY_METHODS,
|
||||||
|
) -> None:
|
||||||
|
self.max_retries = max_retries
|
||||||
|
self.max_wait = max_wait
|
||||||
|
self.extra_delay = extra_delay
|
||||||
|
self.methods = frozenset(methods)
|
||||||
|
|
||||||
|
def _should_retry(self, method: TelegramMethod[Any]) -> bool:
|
||||||
|
return getattr(method, "__api_method__", None) in self.methods
|
||||||
|
|
||||||
|
async def __call__(
|
||||||
|
self,
|
||||||
|
make_request: NextRequestMiddlewareType[TelegramType],
|
||||||
|
bot: "Bot",
|
||||||
|
method: TelegramMethod[TelegramType],
|
||||||
|
) -> Response[TelegramType]:
|
||||||
|
if not self._should_retry(method):
|
||||||
|
return await make_request(bot, method)
|
||||||
|
|
||||||
|
attempt = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
return await make_request(bot, method)
|
||||||
|
except TelegramRetryAfter as e:
|
||||||
|
attempt += 1
|
||||||
|
wait = float(e.retry_after) + self.extra_delay
|
||||||
|
if attempt > self.max_retries or wait > self.max_wait:
|
||||||
|
logger.error(
|
||||||
|
"Flood control on %s: giving up after %d attempt(s) (retry_after=%ss)",
|
||||||
|
method.__api_method__,
|
||||||
|
attempt,
|
||||||
|
e.retry_after,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
logger.warning(
|
||||||
|
"Flood control on %s: retry %d/%d in %.1fs",
|
||||||
|
method.__api_method__,
|
||||||
|
attempt,
|
||||||
|
self.max_retries,
|
||||||
|
wait,
|
||||||
|
)
|
||||||
|
await asyncio.sleep(wait)
|
||||||
Reference in new issue
Block a user