From 2b19808f6bd3d8db051ee6bb9fdb9b1ff3026fa1 Mon Sep 17 00:00:00 2001 From: butubb <1422726308@qq.com> Date: Sat, 24 Oct 2026 16:43:35 +0800 Subject: [PATCH] =?UTF-8?q?fix(monitor):=20=E8=B6=85=E7=BA=A7=E7=BC=96?= =?UTF-8?q?=E5=AF=BC=E6=9F=A5=E8=AF=A2=E5=A4=8D=E7=94=A8=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E6=B1=A0=EF=BC=8C=E5=88=AB=E5=86=8D=E6=AF=8F=E4=B8=AA=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E9=87=8D=E8=A7=A3=E6=9E=90=20DNS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实测容器里解析 api.superdir.cn 要 5 秒,而每个请求都新建 httpx.AsyncClient 就要重新解析 + 握手:一次查询几十个请求,58~90 秒都见过,界面上一直转。 一次查询共用一条连接池后同一主机走 keep-alive,实测 0.1 秒级。 --- api/monitor/superdir.py | 91 +++++++++++++++++++++++----------- tests/test_monitor_superdir.py | 32 ++++++------ 2 files changed, 77 insertions(+), 46 deletions(-) diff --git a/api/monitor/superdir.py b/api/monitor/superdir.py index e94e758..1e02db8 100644 --- a/api/monitor/superdir.py +++ b/api/monitor/superdir.py @@ -22,8 +22,9 @@ import asyncio import uuid +from contextlib import asynccontextmanager from datetime import date, datetime, time as day_time, timedelta, timezone -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, AsyncIterator, Dict, List, Optional, Sequence, Tuple import httpx from sqlalchemy.ext.asyncio import AsyncSession @@ -120,7 +121,28 @@ async def get_token(session: AsyncSession, platform: str = adapters.PLATFORM_DY) ).strip() -async def _request(path: str, params: Dict[str, Any], token: str) -> Dict[str, Any]: +@asynccontextmanager +async def _client_session() -> AsyncIterator[httpx.AsyncClient]: + """一次查询共用一条连接池。 + + **这不是可选的优化,是能不能用的区别。** 容器里解析 ``api.superdir.cn`` 实测要 + 5 秒(宿主机的 DNS 根本解析不了这个域名,容器走的是转发),而每个请求都新建 + client 的话,每个请求都要重新解析 + 重新握手:一次查询几十个请求就是几分钟, + 界面上一直转「查询中」。复用一个 client 之后走 keep-alive,实测 0.1 秒级。 + + 连接数按并发上限给:翻页 4 路 + 取作品 6 路,再留两个余量。 + """ + limits = httpx.Limits( + max_connections=ACTIVITY_CONCURRENCY + VIDEO_CONCURRENCY + 2, + max_keepalive_connections=ACTIVITY_CONCURRENCY + VIDEO_CONCURRENCY, + ) + async with httpx.AsyncClient(timeout=TIMEOUT_SECONDS, limits=limits) as client: + yield client + + +async def _request( + path: str, params: Dict[str, Any], token: str, client: httpx.AsyncClient +) -> Dict[str, Any]: """发一个 GET,返回 ``data``。业务错误码抛出 SuperDirError。""" headers = { "Accept": "application/json", @@ -135,8 +157,7 @@ async def _request(path: str, params: Dict[str, Any], token: str) -> Dict[str, A last_error: Optional[Exception] = None for attempt in range(REQUEST_RETRIES + 1): try: - async with httpx.AsyncClient(timeout=TIMEOUT_SECONDS) as client: - response = await client.get(BASE_URL + path, params=params, headers=headers) + response = await client.get(BASE_URL + path, params=params, headers=headers) except httpx.TransportError as exc: last_error = exc if attempt >= REQUEST_RETRIES: @@ -172,6 +193,7 @@ async def _paginate( path: str, params: Dict[str, Any], token: str, + client: httpx.AsyncClient, *, page_size: int, max_pages: int, @@ -184,7 +206,7 @@ async def _paginate( items: List[Dict[str, Any]] = [] for page in range(1, max_pages + 1): data = await _request( - path, {**params, "page": page, "page_size": page_size}, token + path, {**params, "page": page, "page_size": page_size}, token, client ) page_items = data.get("items") or [] items.extend(page_items) @@ -196,7 +218,9 @@ async def _paginate( return items -async def _fetch_activities(token: str) -> List[Dict[str, Any]]: +async def _fetch_activities( + token: str, client: httpx.AsyncClient +) -> List[Dict[str, Any]]: """拉全部分发活动,**先问第一页拿到 total,剩下的页并发翻**。 这个接口不支持日期过滤,每次查询都得把整个历史翻一遍(实测 277 个活动 = 3 页), @@ -208,7 +232,7 @@ async def _fetch_activities(token: str) -> List[Dict[str, Any]]: """ path = "/member/douyin/share_activity/page" params = {"page_size": ACTIVITY_PAGE_SIZE} - first = await _request(path, {**params, "page": 1}, token) + first = await _request(path, {**params, "page": 1}, token, client) items = list(first.get("items") or []) total = first.get("total") @@ -218,7 +242,7 @@ async def _fetch_activities(token: str) -> List[Dict[str, Any]]: # 接口没给 total:退回逐页翻(实测一直给,只是不做这个假设)。 page = 2 while page <= MAX_ACTIVITY_PAGES: - data = await _request(path, {**params, "page": page}, token) + data = await _request(path, {**params, "page": page}, token, client) page_items = data.get("items") or [] items.extend(page_items) if len(page_items) < ACTIVITY_PAGE_SIZE: @@ -236,7 +260,7 @@ async def _fetch_activities(token: str) -> List[Dict[str, Any]]: async def fetch(page: int) -> List[Dict[str, Any]]: async with semaphore: - data = await _request(path, {**params, "page": page}, token) + data = await _request(path, {**params, "page": page}, token, client) return data.get("items") or [] results = await asyncio.gather(*(fetch(page) for page in range(2, pages + 1))) @@ -245,12 +269,15 @@ async def _fetch_activities(token: str) -> List[Dict[str, Any]]: return items -async def _fetch_videos(token: str, activity_id: Any) -> List[Dict[str, Any]]: +async def _fetch_videos( + token: str, activity_id: Any, client: httpx.AsyncClient +) -> List[Dict[str, Any]]: # video_status=-1(全部)**必须带**,不传时默认 0,接口会返回空列表。 return await _paginate( "/member/douyin/data_center/page", {"video_status": -1, "activity_id": int(activity_id)}, token, + client, page_size=VIDEO_PAGE_SIZE, max_pages=MAX_VIDEO_PAGES, ) @@ -309,32 +336,36 @@ async def preview( ) start_ts, end_ts = _day_start(start_day), _day_end(end_day) - activities = [ - activity - for activity in await _fetch_activities(token) - if start_ts <= _as_int(activity.get("created_at")) <= end_ts - ] - activities.sort(key=lambda activity: _as_int(activity.get("created_at"))) + + # 整次查询共用一条连接池 —— 容器里每次新建连接都要重新做 5 秒的 DNS 解析, + # 逐请求新建 client 会让一次查询从几秒变成几分钟(见 _client_session)。 + async with _client_session() as client: + activities = [ + activity + for activity in await _fetch_activities(token, client) + if start_ts <= _as_int(activity.get("created_at")) <= end_ts + ] + activities.sort(key=lambda activity: _as_int(activity.get("created_at"))) + + usable = [ + activity for activity in activities if activity.get("id") not in (None, "") + ] + semaphore = asyncio.Semaphore(VIDEO_CONCURRENCY) + + async def fetch(activity: Dict[str, Any]) -> List[Dict[str, Any]]: + async with semaphore: + return await _fetch_videos(token, activity.get("id"), client) + + # 活动之间的作品集互不依赖,并发取;单个失败只记在那一个活动上。 + results = await asyncio.gather( + *(fetch(activity) for activity in usable), return_exceptions=True + ) rows: List[Dict[str, Any]] = [] seen: set = set() skipped = 0 failed: List[Dict[str, Any]] = [] - usable = [ - activity for activity in activities if activity.get("id") not in (None, "") - ] - semaphore = asyncio.Semaphore(VIDEO_CONCURRENCY) - - async def fetch(activity: Dict[str, Any]) -> List[Dict[str, Any]]: - async with semaphore: - return await _fetch_videos(token, activity.get("id")) - - # 活动之间的作品集互不依赖,并发取;单个失败只记在那一个活动上。 - results = await asyncio.gather( - *(fetch(activity) for activity in usable), return_exceptions=True - ) - for activity, videos in zip(usable, results): if isinstance(videos, BaseException): failed.append( diff --git a/tests/test_monitor_superdir.py b/tests/test_monitor_superdir.py index fea1190..b458de1 100644 --- a/tests/test_monitor_superdir.py +++ b/tests/test_monitor_superdir.py @@ -62,13 +62,13 @@ class TestPreview: async def test_only_activities_created_in_the_range_are_fetched(self, monkeypatch): fetched: list = [] - async def fake_activities(token): + async def fake_activities(token, client): return [ _activity(1, date(2026, 10, 19), "区间外"), _activity(2, date(2026, 10, 21), "目标活动"), ] - async def fake_videos(token, activity_id): + async def fake_videos(token, activity_id, client): fetched.append(activity_id) return [_video(AWEME_A)] @@ -88,10 +88,10 @@ class TestPreview: @pytest.mark.asyncio async def test_unpublished_and_private_videos_are_skipped(self, monkeypatch): - async def fake_activities(token): + async def fake_activities(token, client): return [_activity(2, date(2026, 10, 21))] - async def fake_videos(token, activity_id): + async def fake_videos(token, activity_id, client): return [ _video(AWEME_A), # 还没发布:没有 share_url @@ -116,13 +116,13 @@ class TestPreview: async def test_the_same_video_under_two_activities_is_one_row(self, monkeypatch): """分发活动被复制过,同一件作品会挂在两个活动下面 —— 建任务时不能重复。""" - async def fake_activities(token): + async def fake_activities(token, client): return [ _activity(2, date(2026, 10, 21)), _activity(3, date(2026, 10, 21)), ] - async def fake_videos(token, activity_id): + async def fake_videos(token, activity_id, client): return [_video(AWEME_A)] async def fake_token(session, platform=superdir.adapters.PLATFORM_DY): @@ -138,13 +138,13 @@ class TestPreview: @pytest.mark.asyncio async def test_one_broken_activity_does_not_sink_the_preview(self, monkeypatch): - async def fake_activities(token): + async def fake_activities(token, client): return [ _activity(2, date(2026, 10, 21), "坏的"), _activity(3, date(2026, 10, 21), "好的"), ] - async def fake_videos(token, activity_id): + async def fake_videos(token, activity_id, client): if activity_id == 2: raise superdir.SuperDirError(500, "取作品失败") return [_video(AWEME_A)] @@ -163,10 +163,10 @@ class TestPreview: @pytest.mark.asyncio async def test_more_than_the_limit_is_truncated_not_silently_dropped(self, monkeypatch): - async def fake_activities(token): + async def fake_activities(token, client): return [_activity(2, date(2026, 10, 21))] - async def fake_videos(token, activity_id): + async def fake_videos(token, activity_id, client): return [_video(str(7000000000000000000 + i)) for i in range(3)] async def fake_token(session, platform=superdir.adapters.PLATFORM_DY): @@ -211,7 +211,7 @@ class TestPagination: async def test_pages_stop_at_total(self, monkeypatch): calls: list = [] - async def fake_request(path, params, token): + async def fake_request(path, params, token, client): calls.append(params["page"]) if params["page"] == 1: return {"items": [{"id": 1}, {"id": 2}], "total": 3} @@ -220,7 +220,7 @@ class TestPagination: monkeypatch.setattr(superdir, "_request", fake_request) items = await superdir._paginate( - "/x", {}, "token", page_size=2, max_pages=10 + "/x", {}, "token", None, page_size=2, max_pages=10 ) assert [item["id"] for item in items] == [1, 2, 3] @@ -233,7 +233,7 @@ class TestActivityPaging: """活动列表没有日期过滤,每次查询都要把整个历史翻完 —— 一页都不能少。""" calls: list = [] - async def fake_request(path, params, token): + async def fake_request(path, params, token, client): calls.append(params["page"]) pages = { 1: [{"id": 1}, {"id": 2}], @@ -245,7 +245,7 @@ class TestActivityPaging: monkeypatch.setattr(superdir, "_request", fake_request) monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2) - items = await superdir._fetch_activities("token") + items = await superdir._fetch_activities("token", None) assert sorted(calls) == [1, 2, 3] assert [item["id"] for item in items] == [1, 2, 3, 4, 5] @@ -254,7 +254,7 @@ class TestActivityPaging: async def test_a_failed_page_fails_the_whole_list_not_a_partial_one(self, monkeypatch): """少一页 = 少一批活动,看上去却像「这段时间就这些」—— 必须报错。""" - async def fake_request(path, params, token): + async def fake_request(path, params, token, client): if params["page"] == 2: raise superdir.SuperDirError(500, "这一页没取到") return {"items": [{"id": 1}, {"id": 2}], "total": 5} @@ -263,7 +263,7 @@ class TestActivityPaging: monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2) with pytest.raises(superdir.SuperDirError): - await superdir._fetch_activities("token") + await superdir._fetch_activities("token", None) class TestErrorHints: