fix(monitor): 超级编导查询复用连接池,别再每个请求重解析 DNS
实测容器里解析 api.superdir.cn 要 5 秒,而每个请求都新建 httpx.AsyncClient 就要重新解析 + 握手:一次查询几十个请求,58~90 秒都见过,界面上一直转。 一次查询共用一条连接池后同一主机走 keep-alive,实测 0.1 秒级。
This commit is contained in:
+61
-30
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user