fix(monitor): 解析视频链接时,网络层抖动重试一次
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

容器刚起来第一发会撞上 DNS 解析失败(实测 [Errno -3]),隔半秒就正常。
批量解析时这种一次性失败只会让某一行莫名其妙地红掉。空 body / 403 仍然不重试
—— 那是风控信号。
This commit is contained in:
2026-10-23 08:58:20 +08:00
parent 1474e5e3eb
commit 213be57055
2 changed files with 57 additions and 1 deletions
+19 -1
View File
@@ -19,6 +19,8 @@ import asyncio
import re import re
from typing import Any, Dict, List from typing import Any, Dict, List
import httpx
from . import adapters, douyin_api, service from . import adapters, douyin_api, service
# 一次最多解析这么多条。限流不是怕算不过来 —— 是怕一不小心粘进来几百条,把详情接口 # 一次最多解析这么多条。限流不是怕算不过来 —— 是怕一不小心粘进来几百条,把详情接口
@@ -26,6 +28,8 @@ from . import adapters, douyin_api, service
MAX_LINKS = 20 MAX_LINKS = 20
# 每两条之间歇一下。同一个登录态连续请求,节律太密比数量更容易被识别。 # 每两条之间歇一下。同一个登录态连续请求,节律太密比数量更容易被识别。
REQUEST_GAP_SECONDS = 0.4 REQUEST_GAP_SECONDS = 0.4
# 网络层失败后隔多久重试那一次。
_DETAIL_RETRY_SLEEP_SECONDS = 1.0
_URL_RE = re.compile(r"https?://[^\s,。;、))\"'<>]+") _URL_RE = re.compile(r"https?://[^\s,。;、))\"'<>]+")
# 19 位作品 id,但放宽到 15–20:平台偶尔给别的位数,只按 19 位写会漏。 # 19 位作品 id,但放宽到 15–20:平台偶尔给别的位数,只按 19 位写会漏。
@@ -69,6 +73,20 @@ def aweme_id_from_url(value: str) -> str:
return "" return ""
async def _detail(aweme_id: str) -> Dict[str, Any]:
"""取一次作品详情,网络层抖动(DNS/连接/超时)重试一次。
实测容器刚起来时第一发会撞上 ``[Errno -3] Temporary failure in name resolution``,
隔半秒就正常 —— 批量解析时这种一次性的失败只会让某一行莫名其妙地红掉,用户还得
整段重贴。**「200 + 空 body」不重试**:那是风控信号,重试只会让它更确定。
"""
try:
return await douyin_api.video_detail(aweme_id)
except httpx.TransportError:
await asyncio.sleep(_DETAIL_RETRY_SLEEP_SECONDS)
return await douyin_api.video_detail(aweme_id)
async def _aweme_id(value: str) -> str: async def _aweme_id(value: str) -> str:
"""短链先展开,再抠 id。""" """短链先展开,再抠 id。"""
expanded = value expanded = value
@@ -125,7 +143,7 @@ async def resolve(text: str) -> Dict[str, Any]:
continue continue
try: try:
record = await douyin_api.video_detail(aweme_id) record = await _detail(aweme_id)
except Exception as exc: except Exception as exc:
item["error"] = str(exc) or "接口没有返回这条作品" item["error"] = str(exc) or "接口没有返回这条作品"
continue continue
+38
View File
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""视频链接 → 博主主页:链接抠取、id 解析、批量解析的容错。""" """视频链接 → 博主主页:链接抠取、id 解析、批量解析的容错。"""
import httpx
import pytest import pytest
from api.monitor import douyin_api, service, video_link from api.monitor import douyin_api, service, video_link
@@ -149,6 +150,43 @@ async def test_a_missing_sec_uid_is_reported_not_faked(monkeypatch):
assert "sec_uid" in item["error"] assert "sec_uid" in item["error"]
@pytest.mark.asyncio
async def test_a_transport_hiccup_is_retried_once(monkeypatch):
"""容器刚起来时第一发可能撞上 DNS 失败;重试一次就过去了,别让它红掉一行。"""
calls = []
async def flaky_detail(aweme_id, **_):
calls.append(aweme_id)
if len(calls) == 1:
raise httpx.ConnectError("[Errno -3] Temporary failure in name resolution")
return {"aweme_id": aweme_id, "nickname": "锋哥", "creator_id": SEC_UID}
monkeypatch.setattr(douyin_api, "video_detail", flaky_detail)
monkeypatch.setattr(video_link, "_DETAIL_RETRY_SLEEP_SECONDS", 0)
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
assert len(calls) == 2
assert result["results"][0]["ok"] is True
@pytest.mark.asyncio
async def test_an_empty_body_is_not_retried(monkeypatch):
"""空 body 是风控信号 —— 重试只会让它更确定。"""
calls = []
async def blocked_detail(aweme_id, **_):
calls.append(aweme_id)
raise douyin_api.DouyinApiError("接口返回了空内容")
monkeypatch.setattr(douyin_api, "video_detail", blocked_detail)
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
assert len(calls) == 1
assert result["results"][0]["ok"] is False
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_more_than_the_limit_is_truncated(monkeypatch): async def test_more_than_the_limit_is_truncated(monkeypatch):
async def fake_detail(aweme_id, **_): async def fake_detail(aweme_id, **_):