From a46caf59f459b41d85583fe0785266ebb3eaea88 Mon Sep 17 00:00:00 2001 From: butubb <1422726308@qq.com> Date: Sat, 24 Oct 2026 16:37:21 +0800 Subject: [PATCH] =?UTF-8?q?perf(monitor):=20=E8=B6=85=E7=BA=A7=E7=BC=96?= =?UTF-8?q?=E5=AF=BC=E6=9F=A5=E8=AF=A2=E5=B9=B6=E5=8F=91=E7=BF=BB=E9=A1=B5?= =?UTF-8?q?=EF=BC=8C20=20=E7=A7=92=E5=8E=8B=E5=88=B0=205=20=E7=A7=92?= =?UTF-8?q?=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实测单个请求 1–4 秒,活动列表三页串行就 12 秒,界面上就是一个一直转的 「查询中」。活动页之间、活动之间的作品集本来互不依赖,改成有界并发: 翻页 4 路、取作品 6 路。活动页任何一页失败仍让整次查询报错 —— 少一页 就是少一批活动和作品,看上去却像「这段时间就这些」。 --- api/monitor/superdir.py | 85 ++++++++++++++++++++++++++++------ tests/test_monitor_superdir.py | 39 ++++++++++++++++ 2 files changed, 109 insertions(+), 15 deletions(-) diff --git a/api/monitor/superdir.py b/api/monitor/superdir.py index 80a21e4..e94e758 100644 --- a/api/monitor/superdir.py +++ b/api/monitor/superdir.py @@ -50,6 +50,13 @@ MAX_ACTIVITY_PAGES = 100 # 作品的 page_size 放到 200:一个活动通常几十条,一页就够。 VIDEO_PAGE_SIZE = 200 MAX_VIDEO_PAGES = 50 + +# 并发数。**实测单个请求就要 1–4 秒**(活动列表那三页各约 4 秒),串行做一轮 +# 5 天区间的查询要 20 秒 —— 界面上就是一个一直转的「查询中」。 +# 翻页和按活动取作品彼此独立,并起来做能压到 5–6 秒;再高的并发对人家接口不礼貌, +# 收益也看不出来(瓶颈在服务端响应,不在我们发请求的速度)。 +ACTIVITY_CONCURRENCY = 4 +VIDEO_CONCURRENCY = 6 # 一次预览/建任务最多这么多条作品。不是接口限制,是监控任务的现实:作品模式每轮要 # 逐条请求详情接口,几百条就是几百次请求,抖音那边很容易当异常流量。 MAX_TARGETS = 1000 @@ -190,13 +197,52 @@ async def _paginate( async def _fetch_activities(token: str) -> List[Dict[str, Any]]: - return await _paginate( - "/member/douyin/share_activity/page", - {}, - token, - page_size=ACTIVITY_PAGE_SIZE, - max_pages=MAX_ACTIVITY_PAGES, + """拉全部分发活动,**先问第一页拿到 total,剩下的页并发翻**。 + + 这个接口不支持日期过滤,每次查询都得把整个历史翻一遍(实测 277 个活动 = 3 页), + 而它恰恰是最慢的:每页约 4 秒,串行就是 12 秒起步。所以这里不用通用的 + ``_paginate``,而是自己控制并发。 + + 任何一页失败都让整次查询失败,**不返回半份活动列表** —— 少一页就是少一批活动和 + 作品,看上去却像「这段时间就这些」,比报错难查得多。 + """ + path = "/member/douyin/share_activity/page" + params = {"page_size": ACTIVITY_PAGE_SIZE} + first = await _request(path, {**params, "page": 1}, token) + items = list(first.get("items") or []) + total = first.get("total") + + if not items or len(items) < ACTIVITY_PAGE_SIZE: + return items + if not isinstance(total, int): + # 接口没给 total:退回逐页翻(实测一直给,只是不做这个假设)。 + page = 2 + while page <= MAX_ACTIVITY_PAGES: + data = await _request(path, {**params, "page": page}, token) + page_items = data.get("items") or [] + items.extend(page_items) + if len(page_items) < ACTIVITY_PAGE_SIZE: + break + page += 1 + return items + + pages = min( + (total + ACTIVITY_PAGE_SIZE - 1) // ACTIVITY_PAGE_SIZE, MAX_ACTIVITY_PAGES ) + if pages <= 1: + return items + + semaphore = asyncio.Semaphore(ACTIVITY_CONCURRENCY) + + async def fetch(page: int) -> List[Dict[str, Any]]: + async with semaphore: + data = await _request(path, {**params, "page": page}, token) + return data.get("items") or [] + + results = await asyncio.gather(*(fetch(page) for page in range(2, pages + 1))) + for page_items in results: + items.extend(page_items) + return items async def _fetch_videos(token: str, activity_id: Any) -> List[Dict[str, Any]]: @@ -275,18 +321,27 @@ async def preview( skipped = 0 failed: List[Dict[str, Any]] = [] - for activity in activities: - activity_id = activity.get("id") - if activity_id in (None, ""): - continue - try: - videos = await _fetch_videos(token, activity_id) - except SuperDirError as exc: + 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( { - "activity_id": _as_int(activity_id), + "activity_id": _as_int(activity.get("id")), "title": str(activity.get("title") or ""), - "error": str(exc), + "error": str(videos), } ) continue diff --git a/tests/test_monitor_superdir.py b/tests/test_monitor_superdir.py index 81f9f72..fea1190 100644 --- a/tests/test_monitor_superdir.py +++ b/tests/test_monitor_superdir.py @@ -227,6 +227,45 @@ class TestPagination: assert calls == [1, 2] +class TestActivityPaging: + @pytest.mark.asyncio + async def test_every_activity_page_is_fetched(self, monkeypatch): + """活动列表没有日期过滤,每次查询都要把整个历史翻完 —— 一页都不能少。""" + calls: list = [] + + async def fake_request(path, params, token): + calls.append(params["page"]) + pages = { + 1: [{"id": 1}, {"id": 2}], + 2: [{"id": 3}, {"id": 4}], + 3: [{"id": 5}], + } + return {"items": pages[params["page"]], "total": 5} + + monkeypatch.setattr(superdir, "_request", fake_request) + monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2) + + items = await superdir._fetch_activities("token") + + assert sorted(calls) == [1, 2, 3] + assert [item["id"] for item in items] == [1, 2, 3, 4, 5] + + @pytest.mark.asyncio + async def test_a_failed_page_fails_the_whole_list_not_a_partial_one(self, monkeypatch): + """少一页 = 少一批活动,看上去却像「这段时间就这些」—— 必须报错。""" + + async def fake_request(path, params, token): + if params["page"] == 2: + raise superdir.SuperDirError(500, "这一页没取到") + return {"items": [{"id": 1}, {"id": 2}], "total": 5} + + monkeypatch.setattr(superdir, "_request", fake_request) + monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2) + + with pytest.raises(superdir.SuperDirError): + await superdir._fetch_activities("token") + + class TestErrorHints: def test_a_relogin_error_explains_itself(self): error = superdir._error({"code": 4017, "message": "账号已在别处登录"})