fix(monitor): 超级编导查询复用连接池,别再每个请求重解析 DNS
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

实测容器里解析 api.superdir.cn 要 5 秒,而每个请求都新建 httpx.AsyncClient
就要重新解析 + 握手:一次查询几十个请求,58~90 秒都见过,界面上一直转。
一次查询共用一条连接池后同一主机走 keep-alive,实测 0.1 秒级。
This commit is contained in:
2026-10-24 16:43:35 +08:00
parent a46caf59f4
commit 2b19808f6b
2 changed files with 77 additions and 46 deletions
+61 -30
View File
@@ -22,8 +22,9 @@
import asyncio import asyncio
import uuid import uuid
from contextlib import asynccontextmanager
from datetime import date, datetime, time as day_time, timedelta, timezone 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 import httpx
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@@ -120,7 +121,28 @@ async def get_token(session: AsyncSession, platform: str = adapters.PLATFORM_DY)
).strip() ).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。""" """发一个 GET,返回 ``data``。业务错误码抛出 SuperDirError。"""
headers = { headers = {
"Accept": "application/json", "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 last_error: Optional[Exception] = None
for attempt in range(REQUEST_RETRIES + 1): for attempt in range(REQUEST_RETRIES + 1):
try: 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: except httpx.TransportError as exc:
last_error = exc last_error = exc
if attempt >= REQUEST_RETRIES: if attempt >= REQUEST_RETRIES:
@@ -172,6 +193,7 @@ async def _paginate(
path: str, path: str,
params: Dict[str, Any], params: Dict[str, Any],
token: str, token: str,
client: httpx.AsyncClient,
*, *,
page_size: int, page_size: int,
max_pages: int, max_pages: int,
@@ -184,7 +206,7 @@ async def _paginate(
items: List[Dict[str, Any]] = [] items: List[Dict[str, Any]] = []
for page in range(1, max_pages + 1): for page in range(1, max_pages + 1):
data = await _request( 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 [] page_items = data.get("items") or []
items.extend(page_items) items.extend(page_items)
@@ -196,7 +218,9 @@ async def _paginate(
return items 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,剩下的页并发翻**。 """拉全部分发活动,**先问第一页拿到 total,剩下的页并发翻**。
这个接口不支持日期过滤,每次查询都得把整个历史翻一遍(实测 277 个活动 = 3 页), 这个接口不支持日期过滤,每次查询都得把整个历史翻一遍(实测 277 个活动 = 3 页),
@@ -208,7 +232,7 @@ async def _fetch_activities(token: str) -> List[Dict[str, Any]]:
""" """
path = "/member/douyin/share_activity/page" path = "/member/douyin/share_activity/page"
params = {"page_size": ACTIVITY_PAGE_SIZE} 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 []) items = list(first.get("items") or [])
total = first.get("total") total = first.get("total")
@@ -218,7 +242,7 @@ async def _fetch_activities(token: str) -> List[Dict[str, Any]]:
# 接口没给 total:退回逐页翻(实测一直给,只是不做这个假设)。 # 接口没给 total:退回逐页翻(实测一直给,只是不做这个假设)。
page = 2 page = 2
while page <= MAX_ACTIVITY_PAGES: 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 [] page_items = data.get("items") or []
items.extend(page_items) items.extend(page_items)
if len(page_items) < ACTIVITY_PAGE_SIZE: 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 def fetch(page: int) -> List[Dict[str, Any]]:
async with semaphore: 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 [] return data.get("items") or []
results = await asyncio.gather(*(fetch(page) for page in range(2, pages + 1))) 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 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,接口会返回空列表。 # video_status=-1(全部)**必须带**,不传时默认 0,接口会返回空列表。
return await _paginate( return await _paginate(
"/member/douyin/data_center/page", "/member/douyin/data_center/page",
{"video_status": -1, "activity_id": int(activity_id)}, {"video_status": -1, "activity_id": int(activity_id)},
token, token,
client,
page_size=VIDEO_PAGE_SIZE, page_size=VIDEO_PAGE_SIZE,
max_pages=MAX_VIDEO_PAGES, max_pages=MAX_VIDEO_PAGES,
) )
@@ -309,32 +336,36 @@ async def preview(
) )
start_ts, end_ts = _day_start(start_day), _day_end(end_day) start_ts, end_ts = _day_start(start_day), _day_end(end_day)
activities = [
activity # 整次查询共用一条连接池 —— 容器里每次新建连接都要重新做 5 秒的 DNS 解析,
for activity in await _fetch_activities(token) # 逐请求新建 client 会让一次查询从几秒变成几分钟(见 _client_session)。
if start_ts <= _as_int(activity.get("created_at")) <= end_ts async with _client_session() as client:
] activities = [
activities.sort(key=lambda activity: _as_int(activity.get("created_at"))) 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]] = [] rows: List[Dict[str, Any]] = []
seen: set = set() seen: set = set()
skipped = 0 skipped = 0
failed: List[Dict[str, Any]] = [] 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): for activity, videos in zip(usable, results):
if isinstance(videos, BaseException): if isinstance(videos, BaseException):
failed.append( failed.append(
+16 -16
View File
@@ -62,13 +62,13 @@ class TestPreview:
async def test_only_activities_created_in_the_range_are_fetched(self, monkeypatch): async def test_only_activities_created_in_the_range_are_fetched(self, monkeypatch):
fetched: list = [] fetched: list = []
async def fake_activities(token): async def fake_activities(token, client):
return [ return [
_activity(1, date(2026, 10, 19), "区间外"), _activity(1, date(2026, 10, 19), "区间外"),
_activity(2, date(2026, 10, 21), "目标活动"), _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) fetched.append(activity_id)
return [_video(AWEME_A)] return [_video(AWEME_A)]
@@ -88,10 +88,10 @@ class TestPreview:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_unpublished_and_private_videos_are_skipped(self, monkeypatch): 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))] return [_activity(2, date(2026, 10, 21))]
async def fake_videos(token, activity_id): async def fake_videos(token, activity_id, client):
return [ return [
_video(AWEME_A), _video(AWEME_A),
# 还没发布:没有 share_url # 还没发布:没有 share_url
@@ -116,13 +116,13 @@ class TestPreview:
async def test_the_same_video_under_two_activities_is_one_row(self, monkeypatch): 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 [ return [
_activity(2, date(2026, 10, 21)), _activity(2, date(2026, 10, 21)),
_activity(3, 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)] return [_video(AWEME_A)]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY): async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
@@ -138,13 +138,13 @@ class TestPreview:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_one_broken_activity_does_not_sink_the_preview(self, monkeypatch): 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 [ return [
_activity(2, date(2026, 10, 21), "坏的"), _activity(2, date(2026, 10, 21), "坏的"),
_activity(3, 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: if activity_id == 2:
raise superdir.SuperDirError(500, "取作品失败") raise superdir.SuperDirError(500, "取作品失败")
return [_video(AWEME_A)] return [_video(AWEME_A)]
@@ -163,10 +163,10 @@ class TestPreview:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_more_than_the_limit_is_truncated_not_silently_dropped(self, monkeypatch): 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))] 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)] return [_video(str(7000000000000000000 + i)) for i in range(3)]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY): 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): async def test_pages_stop_at_total(self, monkeypatch):
calls: list = [] calls: list = []
async def fake_request(path, params, token): async def fake_request(path, params, token, client):
calls.append(params["page"]) calls.append(params["page"])
if params["page"] == 1: if params["page"] == 1:
return {"items": [{"id": 1}, {"id": 2}], "total": 3} return {"items": [{"id": 1}, {"id": 2}], "total": 3}
@@ -220,7 +220,7 @@ class TestPagination:
monkeypatch.setattr(superdir, "_request", fake_request) monkeypatch.setattr(superdir, "_request", fake_request)
items = await superdir._paginate( 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] assert [item["id"] for item in items] == [1, 2, 3]
@@ -233,7 +233,7 @@ class TestActivityPaging:
"""活动列表没有日期过滤,每次查询都要把整个历史翻完 —— 一页都不能少。""" """活动列表没有日期过滤,每次查询都要把整个历史翻完 —— 一页都不能少。"""
calls: list = [] calls: list = []
async def fake_request(path, params, token): async def fake_request(path, params, token, client):
calls.append(params["page"]) calls.append(params["page"])
pages = { pages = {
1: [{"id": 1}, {"id": 2}], 1: [{"id": 1}, {"id": 2}],
@@ -245,7 +245,7 @@ class TestActivityPaging:
monkeypatch.setattr(superdir, "_request", fake_request) monkeypatch.setattr(superdir, "_request", fake_request)
monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2) 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 sorted(calls) == [1, 2, 3]
assert [item["id"] for item in items] == [1, 2, 3, 4, 5] 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 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: if params["page"] == 2:
raise superdir.SuperDirError(500, "这一页没取到") raise superdir.SuperDirError(500, "这一页没取到")
return {"items": [{"id": 1}, {"id": 2}], "total": 5} return {"items": [{"id": 1}, {"id": 2}], "total": 5}
@@ -263,7 +263,7 @@ class TestActivityPaging:
monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2) monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2)
with pytest.raises(superdir.SuperDirError): with pytest.raises(superdir.SuperDirError):
await superdir._fetch_activities("token") await superdir._fetch_activities("token", None)
class TestErrorHints: class TestErrorHints: