diff --git a/api/monitor/scheduler.py b/api/monitor/scheduler.py index 3d256b7..d073854 100644 --- a/api/monitor/scheduler.py +++ b/api/monitor/scheduler.py @@ -144,6 +144,9 @@ class MonitorScheduler: self._warned_no_cookie: set = set() # 超级编导自动追加是网络操作,单独一个后台任务,不占调度循环。 self._superdir_task: Optional[asyncio.Task] = None + # 正在跑的采集(task_id -> asyncio.Task)。**必须留强引用**,否则任务可能被 + # GC 回收;顺带让测试和停机可以等它们结束。 + self._running_tasks: dict[int, asyncio.Task] = {} async def start(self) -> None: if self._loop_task is not None and not self._loop_task.done(): @@ -469,11 +472,47 @@ class MonitorScheduler: task_id = task.id - try: - await execute_task(task_id, trigger="scheduled") - except Exception as exc: + self._start_execution(task_id) + + def _start_execution(self, task_id: int) -> asyncio.Task: + """把采集丢到后台跑,**不让它堵住调度循环**。 + + ``execute_task`` 里的超时用的是 ``asyncio.wait_for``,它到点会取消采集协程、 + 然后**等取消完成**。抖音那条路偶尔卡在不响应取消的浏览器调用上 —— 内联 + ``await`` 会把整个循环一起钉死 65 分钟:其他任务不触发、自动追加不跑、每日 + 推送也错过。实测任务 25 的 8 次运行里有 4 次就是这样。 + + 放到后台之后,``reap_stale_runs`` 仍会把卡死的 run 标记回收,循环照常 tick。 + """ + running = self._running_tasks.get(task_id) + if running is not None and not running.done(): + # 同一个任务已经有采集在跑(比如手动触发的还没结束),不要再起一个。 + return running + + task = asyncio.create_task(execute_task(task_id, trigger="scheduled")) + self._running_tasks[task_id] = task + task.add_done_callback(lambda done: self._execution_done(task_id, done)) + return task + + def _execution_done(self, task_id: int, task: asyncio.Task) -> None: + if self._running_tasks.get(task_id) is task: + self._running_tasks.pop(task_id, None) + if task.cancelled(): + return + exc = task.exception() + if exc is not None: print(f"[monitor.scheduler] task {task_id} failed: {exc}") + async def drain(self) -> None: + """等后台采集结束。测试与优雅停机用。""" + while True: + pending = [ + task for task in self._running_tasks.values() if not task.done() + ] + if not pending: + return + await asyncio.gather(*pending, return_exceptions=True) + # Global singleton, mirroring the crawler_manager pattern. monitor_scheduler = MonitorScheduler() diff --git a/api/monitor/service.py b/api/monitor/service.py index f85e8d6..4448995 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -1578,7 +1578,9 @@ async def daily_tag_matrix( 返回**长表结构**,转置由前端做: {"dates": ["2026-10-21", ...], # 新到旧 - "creators": [{"hash": ..., "name": ...}], # 按昵称排序 + "creators": [{"hash": ..., "name": ..., "fans": 1200, + "total_favorited": 83000, + "first_published_at": 1780000000000}], # 按昵称排序 "cells": {"2026-10-21": {"": { "count": 2, "tags": ["大字报", "养号"], "likes": 120, "comments": 8, "collected": 30, "shares": 4, @@ -1701,6 +1703,7 @@ async def daily_tag_matrix( MonitorCreatorStat.nickname, MonitorCreatorStat.captured_at, MonitorCreatorStat.fans, + MonitorCreatorStat.total_favorited, ).where( MonitorCreatorStat.task_id.in_(task_ids), MonitorCreatorStat.creator_hash != "", @@ -1711,11 +1714,20 @@ async def daily_tag_matrix( # 粉丝数是给博主列显示用的「最近一次已知值」。某一轮没解析出来(None)不让它把 # 之前的好数字盖掉 —— 一个号有几千粉丝,不会因为这一轮没读到就变成不知道。 latest_fans: Dict[str, tuple] = {} + # 主页上的「获赞总数」,和粉丝数一样取最近一次读到的值。 + latest_likes: Dict[str, tuple] = {} for stat in stat_rows: if stat.fans is not None: current_fans = latest_fans.get(stat.creator_hash) if current_fans is None or stat.captured_at > current_fans[1]: latest_fans[stat.creator_hash] = (stat.fans, stat.captured_at) + if stat.total_favorited is not None: + current_likes = latest_likes.get(stat.creator_hash) + if current_likes is None or stat.captured_at > current_likes[1]: + latest_likes[stat.creator_hash] = ( + stat.total_favorited, + stat.captured_at, + ) # **空昵称不算名字。** 资料接口偶尔会回一个空对象(昵称、sec_uid、粉丝、 # 作品数全空),如果把这一轮当最新快照,就会用一个空字符串把之前的好名字 # 盖掉,界面上变成「未知(hash)」。实测线上有两个号就是这么丢的名字。 @@ -1802,6 +1814,23 @@ async def daily_tag_matrix( # 作品是按发布时间倒序取回来的,明细按时间正序更好读(1、2、3…)。 bucket["details"].reverse() + # 博主的**第一条视频**发布时间。查全库,不受上面 days 窗口的限制 —— 一个号最早的 + # 作品很可能在窗口之外,而「这个号做了多久」看的就是它。 + first_rows = ( + await session.execute( + select(MonitorNote.creator_hash, func.min(MonitorNote.published_at)) + .where( + MonitorNote.task_id.in_(task_ids), + MonitorNote.published_at.is_not(None), + MonitorNote.creator_hash != "", + ) + .group_by(MonitorNote.creator_hash) + ) + ).all() + first_published: Dict[str, int] = { + creator_hash: first_at for creator_hash, first_at in first_rows if first_at + } + creators = [ { "hash": hash_, @@ -1809,6 +1838,8 @@ async def daily_tag_matrix( # 没有账号快照的博主(作品模式刚导入、还没跑过一轮)就是 None, # 前端据此不画那个数字,而不是显示 0。 "fans": latest_fans.get(hash_, (None, 0))[0], + "total_favorited": latest_likes.get(hash_, (None, 0))[0], + "first_published_at": first_published.get(hash_), } for hash_, name in known.items() ] diff --git a/api/reports/matrix.html b/api/reports/matrix.html index 64de18a..753b6dc 100644 --- a/api/reports/matrix.html +++ b/api/reports/matrix.html @@ -163,19 +163,27 @@ .untagged { color: var(--muted); font-size: 11px; } .empty { color: #2a3646; } - /* 博主名字左边的粉丝数。压暗一点:它是参照信息,不该和名字抢视线。 */ - .fans { + /* 博主名字左边的参照信息:粉丝 / 总获赞 / 第一条视频日期。 + 都压暗、贴边,不该和名字抢视线。 */ + .fans, .likes, .first { display: inline-block; min-width: 36px; margin-right: 6px; padding: 0 4px; border-radius: 4px; - background: rgba(34, 211, 238, 0.08); color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; text-align: right; } + .fans { background: rgba(34, 211, 238, 0.08); } + .likes { background: rgba(244, 114, 182, 0.08); } + .first { + min-width: 70px; + background: rgba(123, 139, 163, 0.10); + text-align: center; + font-size: 10px; + } /* 条件格式命中的格子。用 inset 描边而不是 box-shadow 扩散:不改变布局, 也不会触发整行重排。 */ @@ -300,7 +308,7 @@
- 名字左边 = 粉丝数 + 名字左边 = 粉丝数 / 主页总获赞 / 第一条视频发布日期 赞 / 评 = 当天这些作品的点赞 / 评论 左下角数字 = 当天作品条数 悬停后点标题 = 在抖音打开这条作品 @@ -349,6 +357,15 @@ return number.toLocaleString('zh-CN'); } + function dateParts(ms) { + const date = new Date(ms); + const pad = (value) => String(value).padStart(2, '0'); + return { + date: date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()), + time: pad(date.getHours()) + ':' + pad(date.getMinutes()), + }; + } + function metricNode(label, kind, value) { const span = document.createElement('span'); span.className = kind; @@ -593,17 +610,41 @@ // 粉丝数放在**名字左边**,一眼能看出这个号多大。没有快照的博主 // (作品模式刚导入还没跑过一轮)就不画 —— 不写 0,那会被读成「没有粉丝」。 const fansKnown = creator.fans !== null && creator.fans !== undefined; + const likesKnown = + creator.total_favorited !== null && creator.total_favorited !== undefined; + const firstAt = creator.first_published_at; + const titleParts = []; if (fansKnown) { const fans = document.createElement('span'); fans.className = 'fans'; - fans.textContent = fmt(creator.fans); + fans.textContent = compact(creator.fans); fans.title = '粉丝数'; th.appendChild(fans); + titleParts.push(fmt(creator.fans) + ' 粉丝'); + } + if (likesKnown) { + // 主页上显示的那个「获赞总数」。 + const likes = document.createElement('span'); + likes.className = 'likes'; + likes.textContent = compact(creator.total_favorited); + likes.title = '主页总获赞'; + th.appendChild(likes); + titleParts.push(fmt(creator.total_favorited) + ' 总获赞'); + } + if (firstAt) { + const parts = dateParts(firstAt); + const first = document.createElement('span'); + first.className = 'first'; + first.textContent = parts.date; + first.title = '第一条视频发布于 ' + parts.date + ' ' + parts.time; + th.appendChild(first); + titleParts.push('第一条视频 ' + parts.date); } const nameSpan = document.createElement('span'); nameSpan.textContent = label; th.appendChild(nameSpan); - th.title = (fansKnown ? fmt(creator.fans) + ' 粉丝 · ' : '') + label; + titleParts.push(label); + th.title = titleParts.join(' · '); tr.appendChild(th); for (const day of data.dates) { const rowCells = data.cells[day] || {}; diff --git a/tests/test_monitor_matrix.py b/tests/test_monitor_matrix.py index cad9625..b306e2f 100644 --- a/tests/test_monitor_matrix.py +++ b/tests/test_monitor_matrix.py @@ -262,6 +262,7 @@ async def _stat( captured_at: int | None = None, run_id: int = 1, fans: int | None = None, + total_favorited: int | None = None, ) -> None: async with monitor_db.get_session() as session: session.add( @@ -273,6 +274,7 @@ async def _stat( creator_id="", works_count=0, fans=fans, + total_favorited=total_favorited, captured_at=captured_at or get_current_timestamp(), ) ) @@ -317,6 +319,52 @@ async def test_the_creator_row_carries_the_latest_fan_count(db): assert data["creators"][0]["fans"] == 1200 +@pytest.mark.asyncio +async def test_the_creator_row_carries_the_total_likes_from_the_profile(db): + """名字左边还要显示主页上的「获赞总数」,同样取最近一次读到的值。""" + task_id = await _task() + now = get_current_timestamp() + await _stat( + task_id, "hash-a", "博主A", + captured_at=now - 60_000, total_favorited=80000, run_id=1, + ) + await _stat( + task_id, "hash-a", "博主A", + captured_at=now, total_favorited=83000, run_id=2, + ) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["creators"][0]["total_favorited"] == 83000 + + +@pytest.mark.asyncio +async def test_the_first_video_date_comes_from_the_whole_table(db): + """第一条视频可能远在日期窗口之外 —— 要查全库,不能只看这 7 天。""" + task_id = await _task() + now = get_current_timestamp() - 1000 + first = now - 400 * DAY_MS + await _note(task_id, "old", "博主A", first) + await _note(task_id, "new", "博主A", now) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["creators"][0]["first_published_at"] == first + + +@pytest.mark.asyncio +async def test_a_creator_without_works_has_no_first_video_date(db): + task_id = await _task() + await _stat(task_id, "hash-a", "博主A", fans=10) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["creators"][0]["first_published_at"] is None + + @pytest.mark.asyncio async def test_a_creator_without_a_snapshot_has_no_fan_count(db): """作品模式刚导入、还没跑过一轮:粉丝数留 None,界面不画那个数字(不是 0)。""" diff --git a/tests/test_monitor_scheduler.py b/tests/test_monitor_scheduler.py index 694e9d0..5e95096 100644 --- a/tests/test_monitor_scheduler.py +++ b/tests/test_monitor_scheduler.py @@ -18,6 +18,8 @@ """Tests for the monitor scheduler's firing, deferral and recovery rules.""" +import asyncio + import pytest import pytest_asyncio from sqlalchemy import select @@ -73,6 +75,16 @@ async def executed(monkeypatch): return calls +async def _tick(scheduler: MonitorScheduler) -> None: + """tick + 等后台采集结束。 + + 采集现在跑在后台任务里(卡死的一轮不能堵住整个调度循环),断言调用记录之前 + 得先把它等回来。 + """ + await scheduler.tick() + await scheduler.drain() + + async def _make_task( next_run_at, enabled: bool = True, interval: int = 60, platform: str = "xhs" ) -> int: @@ -123,7 +135,7 @@ class TestFiring: past = get_current_timestamp() - MS_PER_MINUTE task_id = await _make_task(past) - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [(task_id, "scheduled")] task = await _get_task(task_id) @@ -135,7 +147,7 @@ class TestFiring: monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False)) await _make_task(get_current_timestamp() + 10 * MS_PER_MINUTE) - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [] @@ -144,7 +156,7 @@ class TestFiring: monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False)) await _make_task(get_current_timestamp() - MS_PER_MINUTE, enabled=False) - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [] @@ -163,7 +175,7 @@ class TestFiring: task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy") - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [(task_id, "scheduled")] @@ -182,7 +194,7 @@ class TestFiring: task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy") - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [(task_id, "scheduled")] @@ -195,11 +207,36 @@ class TestFiring: scheduler = MonitorScheduler() await scheduler.tick() + await scheduler.drain() await scheduler.tick() + await scheduler.drain() assert len(executed) == 1 +class TestNonBlocking: + @pytest.mark.asyncio + async def test_a_hanging_run_does_not_block_the_scheduler(self, monkeypatch, db): + """卡死的一轮不能钉住整个循环 —— 其他任务和自动追加都靠这个 tick。 + + 实测:抖音采集协程偶尔不响应取消,内联 await 会让循环停 65 分钟。 + """ + + async def never(task_id, trigger="scheduled"): + await asyncio.Event().wait() + + monkeypatch.setattr(scheduler_module, "execute_task", never) + await _make_task(get_current_timestamp() - MS_PER_MINUTE) + scheduler = MonitorScheduler() + + # 必须在很短时间内返回,而不是等采集结束。 + await asyncio.wait_for(scheduler.tick(), timeout=2) + + assert len(scheduler._running_tasks) == 1 + for task in list(scheduler._running_tasks.values()): + task.cancel() + + class TestDeferral: @pytest.mark.asyncio async def test_busy_crawler_defers_without_advancing(self, monkeypatch, db, executed): @@ -208,7 +245,7 @@ class TestDeferral: due_at = get_current_timestamp() - MS_PER_MINUTE task_id = await _make_task(due_at) - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [] task = await _get_task(task_id) @@ -223,10 +260,12 @@ class TestDeferral: scheduler = MonitorScheduler() await scheduler.tick() + await scheduler.drain() assert executed == [] fake.busy = False await scheduler.tick() + await scheduler.drain() assert executed == [(task_id, "scheduled")] @@ -243,7 +282,7 @@ class TestCookieGuard: due_at = get_current_timestamp() - MS_PER_MINUTE task_id = await _make_task(due_at) - await MonitorScheduler().tick() + await _tick(MonitorScheduler()) assert executed == [] task = await _get_task(task_id)