feat(matrix): 「第一条视频」改成主页最早一条,后台翻页扫描 + 缓存
要的是这个博主**最早发的**那条(可能根本不在监控目标里),不是主页第一屏。 按游标翻到底才知道,所以: - 新增 monitor_creator_first_video 缓存表,按 sec_uid 存最早发布时间, 30 天内不再扫; - 调度器后台任务慢慢扫(每页 20 条、页间 0.5 秒、单次最多 50 页 / 3 分钟), 不占调度循环; - 矩阵只读缓存,读不到退回库里最早的一条作品; - 失败只锁 6 小时再试,不会把没扫到的号锁 30 天。 同时撤掉上一版「每轮采集多问一次主页最新视频」的实现(方向反了)。
This commit is contained in:
@@ -178,18 +178,13 @@ class TestNoteMode:
|
||||
「粘贴作品链接的监控」今天本来是能用的,别让它因为这一处走错而废掉。
|
||||
"""
|
||||
|
||||
async def only_by_creator_id(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
# 可以为了「主页最新视频」问一次作品列表,但**只能用详情里的 sec_uid 问**,
|
||||
# 不能拿作品目标 id 去当 sec_uid —— 那必然失败,而且报错很难看懂。
|
||||
assert sec_user_id == "MS4wLjABAAAAtestsecuid"
|
||||
return []
|
||||
async def must_not_be_called(*args, **kwargs):
|
||||
raise AssertionError("作品模式不该去拉博主的作品列表")
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
record = _video(aweme_id)
|
||||
record["creator_id"] = "MS4wLjABAAAAtestsecuid"
|
||||
return record
|
||||
return _video(aweme_id)
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos", only_by_creator_id)
|
||||
monkeypatch.setattr(douyin_api, "author_videos", must_not_be_called)
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await _collect(
|
||||
@@ -263,33 +258,6 @@ class TestNoteMode:
|
||||
# 详情里没有作品总数,留 None 而不是 0。
|
||||
assert profiles[0]["works"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_latest_video_time_comes_from_the_profile(self, monkeypatch, tmp_path):
|
||||
"""主页第一条视频可能不在监控目标里 —— 单独问一次,用它的发布时间。"""
|
||||
|
||||
async def fake_detail(aweme_id, *, cookie="", identity=None):
|
||||
record = _video(aweme_id)
|
||||
record.update(
|
||||
{"creator_id": "MS4wLjABAAAAtestsecuid", "creator_fans": 10}
|
||||
)
|
||||
return record
|
||||
|
||||
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
|
||||
assert sec_user_id == "MS4wLjABAAAAtestsecuid"
|
||||
return [{"create_time": 1793000000}]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
|
||||
|
||||
await _collect(
|
||||
tmp_path, mode="note", want_comments=False, targets=[_Target("111")]
|
||||
)
|
||||
|
||||
profiles = _read(
|
||||
list((tmp_path / "douyin" / "jsonl").glob("*_profile_*.jsonl"))[0]
|
||||
)
|
||||
assert profiles[0]["latest_published_at"] == 1793000000 * 1000
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_stats_means_no_profile_row(self, monkeypatch, tmp_path):
|
||||
"""精简版 author(字段全缺)不该写一条全 NULL 的快照。"""
|
||||
@@ -420,10 +388,7 @@ class TestCreatorProfile:
|
||||
|
||||
await _collect(tmp_path, want_comments=False)
|
||||
|
||||
profile = self._profiles(tmp_path)[0]
|
||||
# 作品列表里的最新一条也带出来了(秒 -> 毫秒)。
|
||||
assert profile.pop("latest_published_at") == 1790574515 * 1000
|
||||
assert profile == _profile()
|
||||
assert self._profiles(tmp_path) == [_profile()]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_profile_is_keyed_by_the_same_hash_as_the_works(
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""主页「最早一条视频」的扫描:翻页、取最小值、缓存与失败重试。"""
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import select
|
||||
|
||||
from api.monitor import creator_scan, db as monitor_db, douyin_api
|
||||
from api.monitor.models import MonitorCreatorFirstVideo
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def session(tmp_path):
|
||||
monitor_db.set_sqlite_path(tmp_path / "scan.db")
|
||||
await monitor_db.init_db()
|
||||
async with monitor_db.get_session() as db_session:
|
||||
yield db_session
|
||||
await monitor_db.dispose_engine()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fast(monkeypatch):
|
||||
monkeypatch.setattr(creator_scan, "REQUEST_GAP_SECONDS", 0)
|
||||
|
||||
async def fake_identity(cookie="", force=False):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(douyin_api, "browser_identity", fake_identity)
|
||||
|
||||
|
||||
class TestScan:
|
||||
@pytest.mark.asyncio
|
||||
async def test_pages_to_the_end_and_takes_the_oldest(self, monkeypatch):
|
||||
pages = {
|
||||
0: ([{"create_time": 1793000000}, {"create_time": 1792000000}], 100, True),
|
||||
100: ([{"create_time": 1700000000}], 50, True),
|
||||
50: ([{"create_time": 1600000000}], 0, False),
|
||||
}
|
||||
|
||||
async def fake_page(sec_user_id, max_cursor=0, count=20, *, cookie="", identity=None):
|
||||
return pages[max_cursor]
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos_page", fake_page)
|
||||
|
||||
oldest, page_count, complete = await creator_scan._scan("MS4w-sec")
|
||||
|
||||
assert oldest == 1600000000 * 1000
|
||||
assert page_count == 3
|
||||
assert complete is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_unchanging_cursor_does_not_loop_forever(self, monkeypatch):
|
||||
async def fake_page(sec_user_id, max_cursor=0, count=20, *, cookie="", identity=None):
|
||||
return [{"create_time": 1600000000}], 7, True
|
||||
|
||||
monkeypatch.setattr(douyin_api, "author_videos_page", fake_page)
|
||||
|
||||
_oldest, page_count, complete = await creator_scan._scan("MS4w-sec")
|
||||
|
||||
assert page_count == 2
|
||||
assert complete is False
|
||||
|
||||
|
||||
class TestCache:
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_successful_scan_is_written_to_the_cache(self, session, monkeypatch):
|
||||
async def fake_scan(creator_id):
|
||||
return 1700000000000, 4, True
|
||||
|
||||
monkeypatch.setattr(creator_scan, "_scan", fake_scan)
|
||||
|
||||
ok = await creator_scan.scan_one(session, "dy", "hash-a", "MS4w-sec")
|
||||
|
||||
assert ok is True
|
||||
row = await session.scalar(
|
||||
select(MonitorCreatorFirstVideo).where(
|
||||
MonitorCreatorFirstVideo.creator_id == "MS4w-sec"
|
||||
)
|
||||
)
|
||||
assert row.first_published_at == 1700000000000
|
||||
assert row.scanned_pages == 4
|
||||
assert row.complete is True
|
||||
assert row.error == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_failure_is_recorded_and_retried_after_a_while(
|
||||
self, session, monkeypatch
|
||||
):
|
||||
async def boom(creator_id):
|
||||
raise douyin_api.DouyinApiError("接口超时")
|
||||
|
||||
monkeypatch.setattr(creator_scan, "_scan", boom)
|
||||
now = get_current_timestamp()
|
||||
|
||||
ok = await creator_scan.scan_one(
|
||||
session, "dy", "hash-a", "MS4w-sec", now=now
|
||||
)
|
||||
|
||||
assert ok is False
|
||||
row = await session.scalar(
|
||||
select(MonitorCreatorFirstVideo).where(
|
||||
MonitorCreatorFirstVideo.creator_id == "MS4w-sec"
|
||||
)
|
||||
)
|
||||
assert "接口超时" in row.error
|
||||
assert row.first_published_at is None
|
||||
# checked_at 往前拨:大约 6 小时后就重新到期,而不是锁 30 天。
|
||||
assert row.checked_at == now - creator_scan.TTL_MS + creator_scan.RETRY_MS
|
||||
@@ -21,6 +21,7 @@ from api.monitor import db as monitor_db
|
||||
from api.monitor import service
|
||||
from api.monitor.models import (
|
||||
MODE_CREATOR,
|
||||
MonitorCreatorFirstVideo,
|
||||
MonitorCreatorStat,
|
||||
MonitorNote,
|
||||
MonitorNoteMetric,
|
||||
@@ -263,7 +264,7 @@ async def _stat(
|
||||
run_id: int = 1,
|
||||
fans: int | None = None,
|
||||
total_favorited: int | None = None,
|
||||
latest_published_at: int | None = None,
|
||||
creator_id: str = "",
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
@@ -272,16 +273,36 @@ async def _stat(
|
||||
run_id=run_id,
|
||||
creator_hash=creator_hash,
|
||||
nickname=nickname,
|
||||
creator_id="",
|
||||
creator_id=creator_id,
|
||||
works_count=0,
|
||||
fans=fans,
|
||||
total_favorited=total_favorited,
|
||||
latest_published_at=latest_published_at,
|
||||
captured_at=captured_at or get_current_timestamp(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _first_video(
|
||||
platform: str,
|
||||
creator_id: str,
|
||||
first_at: int | None,
|
||||
creator_hash: str = "hash-a",
|
||||
) -> None:
|
||||
async with monitor_db.get_session() as session:
|
||||
session.add(
|
||||
MonitorCreatorFirstVideo(
|
||||
platform=platform,
|
||||
creator_id=creator_id,
|
||||
creator_hash=creator_hash,
|
||||
first_published_at=first_at,
|
||||
scanned_pages=3,
|
||||
complete=True,
|
||||
checked_at=get_current_timestamp(),
|
||||
error="",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_creators_without_notes_still_get_a_row(db):
|
||||
"""只在账号快照里出现的号不能消失。
|
||||
@@ -342,46 +363,44 @@ async def test_the_creator_row_carries_the_total_likes_from_the_profile(db):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_latest_video_date_comes_from_the_profile(db):
|
||||
"""主页第一条视频可能根本不在监控目标里 —— 采集时单独问过,就用它。"""
|
||||
async def test_the_first_video_date_comes_from_the_scan_cache(db):
|
||||
"""后台扫过主页就把最早那条的日期存下来 —— 它可能根本不在监控目标里。"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
tracked = now - 3 * DAY_MS
|
||||
profile_latest = now - 60_000
|
||||
await _note(task_id, "n1", "博主A", tracked)
|
||||
await _stat(
|
||||
task_id, "hash-a", "博主A", latest_published_at=profile_latest
|
||||
)
|
||||
sec = "MS4wLjABAAAAsecuid"
|
||||
scanned_first = get_current_timestamp() - 300 * DAY_MS
|
||||
await _stat(task_id, "hash-a", "博主A", creator_id=sec)
|
||||
await _first_video("dy", sec, scanned_first)
|
||||
|
||||
async with monitor_db.get_session() as session:
|
||||
data = await service.daily_tag_matrix(session, "dy", days=7)
|
||||
|
||||
assert data["creators"][0]["latest_published_at"] == profile_latest
|
||||
assert data["creators"][0]["first_published_at"] == scanned_first
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_it_falls_back_to_the_newest_tracked_note(db):
|
||||
"""主页那次没问到(接口挡了/超时)时,退到库里最新的一条作品。"""
|
||||
async def test_it_falls_back_to_the_earliest_tracked_note(db):
|
||||
"""还没扫到主页时,退到库里**最早**的一条作品。"""
|
||||
task_id = await _task()
|
||||
now = get_current_timestamp() - 1000
|
||||
await _note(task_id, "old", "博主A", now - 400 * DAY_MS)
|
||||
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]["latest_published_at"] == now
|
||||
assert data["creators"][0]["first_published_at"] == first
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_creator_without_works_has_no_latest_video_date(db):
|
||||
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]["latest_published_at"] is None
|
||||
assert data["creators"][0]["first_published_at"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
Reference in New Issue
Block a user