mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-25 05:12:42 +08:00
fix(telegram): retry poster uploads before text fallback (#7330)
This commit is contained in:
@@ -33,6 +33,7 @@ from app.modules.telegram.botapi import (
|
||||
JsonDict,
|
||||
TelegramApiError,
|
||||
TelegramBotApi,
|
||||
TelegramNetworkError,
|
||||
)
|
||||
from app.runtime.execution import retry
|
||||
from app.runtime.log import logger
|
||||
@@ -2177,15 +2178,37 @@ class Telegram:
|
||||
) from err
|
||||
raise RetryException(f"发送{'图片' if image else '文本'}消息失败:{err}") from err
|
||||
|
||||
@retry(TelegramNetworkError, logger=logger)
|
||||
def __send_photo(self, *, photo: Any, caption: Optional[str], **kwargs: Any) -> JsonDict:
|
||||
"""
|
||||
海报上传遇到网络异常时最多尝试三次,沿用 3 秒、6 秒的退避间隔。
|
||||
|
||||
仅重试当前图片,成功后不补发文本;API 明确拒绝或限流时直接交给调用方处理。
|
||||
|
||||
:param photo: 已获取的图片字节或文件名与字节组成的二元组,重试时复用
|
||||
:param caption: 已按目标格式处理的图片说明,可为空
|
||||
:param kwargs: 目标会话、解析格式、话题、回复和键盘参数
|
||||
:return: Telegram 确认发送的消息
|
||||
:raises TelegramNetworkError: 三次上传均未获得响应
|
||||
:raises TelegramApiError: Telegram 拒绝上传,不在此处重试
|
||||
"""
|
||||
return self._api.send_photo(photo=photo, caption=caption, **kwargs)
|
||||
|
||||
def __send_photo_or_text(
|
||||
self, *, photo: Any, caption: Optional[str],
|
||||
disable_web_page_preview: Optional[bool] = None, **kwargs: Any,
|
||||
) -> Optional[JsonDict]:
|
||||
"""
|
||||
海报上传失败立即降级为同一正文,保留会话、话题和按钮;429 不追加请求。
|
||||
海报网络重试耗尽或被拒绝时降级为同一正文;429 不追加请求。
|
||||
|
||||
:param photo: 可复用的图片字节或文件名与字节组成的二元组
|
||||
:param caption: 图片说明,降级时作为正文;为空时上传失败直接向上抛出
|
||||
:param disable_web_page_preview: 文本兜底时是否禁用链接预览
|
||||
:param kwargs: 原样保留的目标会话、解析格式、话题、回复和键盘参数
|
||||
:return: 成功上传图片或文本兜底的消息
|
||||
"""
|
||||
try:
|
||||
return self._api.send_photo(photo=photo, caption=caption, **kwargs)
|
||||
return self.__send_photo(photo=photo, caption=caption, **kwargs)
|
||||
except Exception as error:
|
||||
if self._is_rate_limit_error(error) or not caption:
|
||||
raise
|
||||
|
||||
@@ -61,6 +61,9 @@ focused 测试验证,不要求启动产品全套测试。
|
||||
整理事件阻塞时下载通知仍能完成、同类事件不会并行重复认领、在途租约续期、崩溃租约接管、
|
||||
提交失败与取消后的重试,以及关闭超时保留资源。`tests/test_telegram.py` 覆盖海报失败后的文本
|
||||
兜底、会话/话题/按钮保留、429 不追加请求,以及发送失败不能被 outbox 当作成功确认。
|
||||
海报上传网络失败时最多尝试三次,退避为 3、6 秒;短通知及 plain、HTML、MarkdownV2
|
||||
长通知覆盖重试成功、耗尽后文本兜底、重试中被拒绝或遇到 429,验证顺序与正文完整性。
|
||||
等待与 Bot API 均使用替身,不代表真实 Telegram 网络和 Docker 实例验收。
|
||||
|
||||
`tests/test_outbox_event_isolation.py` 使用临时 SQLite、真实恢复线程和可释放屏障验证逐处理器
|
||||
持久投递:慢处理器尚未返回时,其他处理器已经收到同批十二集;失败只重试对应投递,父消息
|
||||
|
||||
@@ -44,6 +44,19 @@ def telegram():
|
||||
telegram.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def telegram_retry_sleep(monkeypatch) -> Mock:
|
||||
"""
|
||||
记录发送重试的退避秒数,避免网络故障用例真实等待。
|
||||
|
||||
:param monkeypatch: 用例结束后恢复真实等待函数的隔离夹具
|
||||
:return: 可断言等待次数与顺序的替身
|
||||
"""
|
||||
sleep = Mock()
|
||||
monkeypatch.setattr("app.runtime.execution.time.sleep", sleep)
|
||||
return sleep
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("partial_answer, trailing_tool", [(False, False), (True, False), (True, True)])
|
||||
async def test_agent_final_edit_waits_during_telegram_edit_interval(
|
||||
@@ -509,13 +522,15 @@ def test_send_msg_markdown_escaping(telegram):
|
||||
assert send_kwargs["text"].startswith("*测试标题*\n")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [
|
||||
TelegramApiError("sendPhoto", "invalid photo", 400),
|
||||
TelegramNetworkError("sendPhoto", "timeout"),
|
||||
@pytest.mark.parametrize("error, attempts", [
|
||||
(TelegramApiError("sendPhoto", "invalid photo", 400), 1),
|
||||
(TelegramNetworkError("sendPhoto", "timeout"), 3),
|
||||
])
|
||||
def test_photo_failure_falls_back_without_losing_notification_context(telegram, error):
|
||||
def test_photo_failure_falls_back_without_losing_notification_context(
|
||||
telegram, telegram_retry_sleep, error, attempts,
|
||||
):
|
||||
"""
|
||||
图片被拒绝或网络失败时立即发正文,保留格式、链接、话题与按钮。
|
||||
图片被拒绝或网络重试耗尽时发正文,保留格式、链接、话题与按钮。
|
||||
"""
|
||||
telegram.bot.send_photo.side_effect = error
|
||||
telegram.bot.send_message.return_value = {"message_id": 18, "chat": {"id": "fake_chat_id"}}
|
||||
@@ -526,7 +541,8 @@ def test_photo_failure_falls_back_without_losing_notification_context(telegram,
|
||||
buttons=[[{"text": "查看", "url": "https://example.com"}]],
|
||||
)
|
||||
assert result == {"success": True, "message_id": 18, "chat_id": "fake_chat_id"}
|
||||
telegram.bot.send_photo.assert_called_once()
|
||||
assert telegram.bot.send_photo.call_count == attempts
|
||||
assert [call.args[0] for call in telegram_retry_sleep.call_args_list] == [3, 6][:attempts - 1]
|
||||
telegram.bot.send_message.assert_called_once()
|
||||
photo = telegram.bot.send_photo.call_args.kwargs
|
||||
text = telegram.bot.send_message.call_args.kwargs
|
||||
@@ -537,21 +553,83 @@ def test_photo_failure_falls_back_without_losing_notification_context(telegram,
|
||||
assert text["message_thread_id"] == 101 and text["disable_web_page_preview"] is True
|
||||
|
||||
|
||||
def test_photo_rate_limit_does_not_send_fallback_or_retry(telegram):
|
||||
@pytest.mark.parametrize("failures", [1, 2])
|
||||
@pytest.mark.parametrize("parse_mode", ["", "HTML", "MarkdownV2"])
|
||||
@pytest.mark.parametrize("long_message", [False, True])
|
||||
def test_photo_network_retry_recovers_before_sending_text(
|
||||
telegram, telegram_retry_sleep, failures, parse_mode, long_message,
|
||||
):
|
||||
"""
|
||||
短通知和三种格式的长通知只重试失败图片,成功后继续发送尚未发送的正文。
|
||||
"""
|
||||
message = {"message_id": 18, "chat": {"id": "fake_chat_id"}}
|
||||
telegram.bot.send_photo.side_effect = [
|
||||
TelegramNetworkError("sendPhoto", "Connection reset by peer")
|
||||
] * failures + [message]
|
||||
telegram.bot.send_message.return_value = message
|
||||
telegram._telegram_topic_id = 101
|
||||
timeline = Mock()
|
||||
timeline.attach_mock(telegram.bot.send_photo, "photo")
|
||||
timeline.attach_mock(telegram_retry_sleep, "wait")
|
||||
timeline.attach_mock(telegram.bot.send_message, "text")
|
||||
body = "完整通知内容" * (800 if long_message else 1)
|
||||
|
||||
result = telegram.send_msg(
|
||||
title="", text=body, parse_mode=parse_mode, image="https://example.com/poster.jpg",
|
||||
buttons=[[{"text": "查看", "url": "https://example.com"}]],
|
||||
)
|
||||
|
||||
assert result == {"success": True, "message_id": 18, "chat_id": "fake_chat_id"}
|
||||
assert telegram.bot.send_photo.call_count == failures + 1
|
||||
assert [call.args[0] for call in telegram_retry_sleep.call_args_list] == [3, 6][:failures]
|
||||
assert [call[0] for call in timeline.mock_calls] == (
|
||||
["photo", "wait"] * failures + ["photo"] + ["text"] * telegram.bot.send_message.call_count
|
||||
)
|
||||
photo_calls = telegram.bot.send_photo.call_args_list
|
||||
assert all(call == photo_calls[0] for call in photo_calls)
|
||||
photo = photo_calls[0].kwargs
|
||||
assert photo["chat_id"] == "fake_chat_id" and photo["message_thread_id"] == 101
|
||||
assert photo["reply_markup"]["inline_keyboard"][0][0]["text"] == "查看"
|
||||
chunks = [call.kwargs for call in telegram.bot.send_message.call_args_list]
|
||||
assert "".join([photo["caption"]] + [chunk["text"] for chunk in chunks]).replace("\n", "") == body
|
||||
assert bool(chunks) is long_message
|
||||
assert all(chunk["reply_markup"] is None for chunk in chunks)
|
||||
|
||||
|
||||
def test_photo_retry_stops_when_telegram_rejects_image(telegram, telegram_retry_sleep):
|
||||
"""
|
||||
网络重试中遇到明确图片拒绝时立即改发正文,不继续上传同一坏图片。
|
||||
"""
|
||||
telegram.bot.send_photo.side_effect = [
|
||||
TelegramNetworkError("sendPhoto", "timeout"),
|
||||
TelegramApiError("sendPhoto", "invalid photo", 400),
|
||||
]
|
||||
result = telegram.send_msg(title="通知", image="https://example.com/poster.jpg")
|
||||
assert result["success"] is True
|
||||
assert telegram.bot.send_photo.call_count == 2
|
||||
telegram_retry_sleep.assert_called_once_with(3)
|
||||
telegram.bot.send_message.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failures", [0, 1, 2])
|
||||
def test_photo_rate_limit_does_not_send_fallback_or_retry(telegram, telegram_retry_sleep, failures):
|
||||
"""
|
||||
429 必须尊重冷却期,不再用文本请求加重限流。
|
||||
"""
|
||||
telegram.bot.send_photo.side_effect = TelegramApiError(
|
||||
rate_limit = TelegramApiError(
|
||||
"sendPhoto", "Too Many Requests", 429, {"retry_after": 17},
|
||||
)
|
||||
telegram.bot.send_photo.side_effect = [TelegramNetworkError("sendPhoto", "timeout")] * failures + [rate_limit]
|
||||
result = telegram.send_msg(title="通知", image="https://example.com/poster.jpg")
|
||||
assert result["success"] is False
|
||||
telegram.bot.send_photo.assert_called_once()
|
||||
assert telegram.send_msg(title="冷却期间通知")["success"] is False
|
||||
assert telegram.bot.send_photo.call_count == failures + 1
|
||||
assert [call.args[0] for call in telegram_retry_sleep.call_args_list] == [3, 6][:failures]
|
||||
telegram.bot.send_message.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("parse_mode", ["", "MarkdownV2"])
|
||||
def test_long_photo_notification_preserves_all_text_after_fallback(telegram, parse_mode):
|
||||
@pytest.mark.parametrize("parse_mode", ["", "HTML", "MarkdownV2"])
|
||||
def test_long_photo_notification_preserves_all_text_after_fallback(telegram, telegram_retry_sleep, parse_mode):
|
||||
"""
|
||||
长正文首段图片失败时改发文本,其余分段与首段按钮保持完整。
|
||||
"""
|
||||
@@ -562,7 +640,8 @@ def test_long_photo_notification_preserves_all_text_after_fallback(telegram, par
|
||||
buttons=[[{"text": "查看", "url": "https://example.com"}]],
|
||||
)
|
||||
assert result["success"] is True
|
||||
telegram.bot.send_photo.assert_called_once()
|
||||
assert telegram.bot.send_photo.call_count == 3
|
||||
assert [call.args[0] for call in telegram_retry_sleep.call_args_list] == [3, 6]
|
||||
chunks = [call.kwargs for call in telegram.bot.send_message.call_args_list]
|
||||
assert len(chunks) > 1
|
||||
assert "".join(chunk["text"] for chunk in chunks).replace("\n", "") == body
|
||||
|
||||
Reference in New Issue
Block a user