3 changed files with 160 additions and 0 deletions

No files matched your search

+83
View File
@@ -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)
+3
View File
@@ -13,6 +13,7 @@ from homeagent.agent.base import BaseAgent
from homeagent.agent.factory import create_agent
from homeagent.bot.handlers import create_bot_router
from homeagent.bot.middlewares import WhitelistMiddleware
from homeagent.bot.retry import FloodRetryMiddleware
from homeagent.config import Settings, get_settings
from homeagent.skills.manager import SkillManager
from homeagent.tools.loader import load_extensions_from_directory
@@ -50,6 +51,8 @@ class TelegramAgentApp:
token=token,
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
)
# Retry final-answer sends (sendRichMessage/sendMessage/answerGuestQuery) on flood control
self.bot.session.middleware(FloodRetryMiddleware())
except Exception as e:
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
+74
View File
@@ -0,0 +1,74 @@
"""Unit tests for FloodRetryMiddleware (Telegram flood control retries)."""
from unittest.mock import AsyncMock, MagicMock
import pytest
from aiogram.exceptions import TelegramBadRequest, TelegramRetryAfter
from aiogram.methods import EditMessageText, SendMessage
import homeagent.bot.retry as retry_mod
from homeagent.bot.retry import FloodRetryMiddleware
@pytest.fixture
def no_sleep(monkeypatch):
sleep = AsyncMock()
monkeypatch.setattr(retry_mod.asyncio, "sleep", sleep)
return sleep
def _flood(method, seconds: int = 3) -> TelegramRetryAfter:
return TelegramRetryAfter(method=method, message="Too Many Requests", retry_after=seconds)
async def test_retries_then_succeeds(no_sleep):
method = SendMessage(chat_id=1, text="final answer")
make_request = AsyncMock(side_effect=[_flood(method, 3), _flood(method, 5), "ok"])
result = await FloodRetryMiddleware(extra_delay=0.5)(make_request, MagicMock(), method)
assert result == "ok"
assert make_request.await_count == 3
assert [c.args[0] for c in no_sleep.await_args_list] == [3.5, 5.5]
async def test_gives_up_after_max_retries(no_sleep):
method = SendMessage(chat_id=1, text="final answer")
make_request = AsyncMock(side_effect=_flood(method, 1))
with pytest.raises(TelegramRetryAfter):
await FloodRetryMiddleware(max_retries=2)(make_request, MagicMock(), method)
assert make_request.await_count == 3 # 1 initial + 2 retries
async def test_gives_up_when_wait_too_long(no_sleep):
method = SendMessage(chat_id=1, text="final answer")
make_request = AsyncMock(side_effect=_flood(method, 600))
with pytest.raises(TelegramRetryAfter):
await FloodRetryMiddleware(max_wait=60)(make_request, MagicMock(), method)
assert make_request.await_count == 1
no_sleep.assert_not_awaited()
async def test_does_not_retry_progress_edits(no_sleep):
method = EditMessageText(chat_id=1, message_id=1, text="⏳")
make_request = AsyncMock(side_effect=_flood(method, 1))
with pytest.raises(TelegramRetryAfter):
await FloodRetryMiddleware()(make_request, MagicMock(), method)
assert make_request.await_count == 1
no_sleep.assert_not_awaited()
async def test_does_not_retry_other_errors(no_sleep):
method = SendMessage(chat_id=1, text="bad *markdown")
make_request = AsyncMock(side_effect=TelegramBadRequest(method=method, message="can't parse entities"))
with pytest.raises(TelegramBadRequest):
await FloodRetryMiddleware()(make_request, MagicMock(), method)
assert make_request.await_count == 1