要的是这个博主**最早发的**那条(可能根本不在监控目标里),不是主页第一屏。 按游标翻到底才知道,所以: - 新增 monitor_creator_first_video 缓存表,按 sec_uid 存最早发布时间, 30 天内不再扫; - 调度器后台任务慢慢扫(每页 20 条、页间 0.5 秒、单次最多 50 页 / 3 分钟), 不占调度循环; - 矩阵只读缓存,读不到退回库里最早的一条作品; - 失败只锁 6 小时再试,不会把没扫到的号锁 30 天。 同时撤掉上一版「每轮采集多问一次主页最新视频」的实现(方向反了)。
202 lines
7.0 KiB
Python
202 lines
7.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""扫博主主页,找出**最早一条视频**的发布时间。
|
||
|
||
抖音的作品列表按时间倒序、按游标翻页:要知道「这个号第一条视频是什么时候发的」,
|
||
只能一页页翻到最后一页。一个号几十上百条作品就是十几次请求,接口还时不时超时 ——
|
||
所以这件事不能放在采集主流程里,更不能放在矩阵页的请求里。做法是:
|
||
|
||
* 扫一次存进 ``monitor_creator_first_video``,30 天内不再扫(老作品不会变);
|
||
* 由调度器在**后台任务**里慢慢扫,不占调度循环;
|
||
* 矩阵只读缓存,读不到就退回库里最早的一条作品。
|
||
|
||
翻到 ``MAX_PAGES`` 页还没到底(作品上千条)就带着已有结果收工,标记为不完整 ——
|
||
为了一个日期打几十次请求不划算,翻到的部分里最早那条已经足够接近。
|
||
"""
|
||
|
||
import asyncio
|
||
import time
|
||
from typing import Dict, List, Optional, Tuple
|
||
|
||
from sqlalchemy import func, select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from tools.time_util import get_current_timestamp
|
||
|
||
from . import adapters, douyin_api
|
||
from .db import get_session
|
||
from .models import (
|
||
MonitorCreatorFirstVideo,
|
||
MonitorCreatorStat,
|
||
MonitorNote,
|
||
MonitorTask,
|
||
)
|
||
|
||
PAGE_SIZE = 20
|
||
# 最多翻 50 页 = 1000 条作品。
|
||
MAX_PAGES = 50
|
||
# 单个博主最多扫这么久;到点带着已有结果收工,标记不完整。
|
||
MAX_SECONDS_PER_CREATOR = 180
|
||
# 两次请求之间歇一下:主页接口不是我们的,连着打更容易被限流。
|
||
REQUEST_GAP_SECONDS = 0.5
|
||
# 扫到的值 30 天内复用。
|
||
TTL_MS = 30 * 24 * 60 * 60_000
|
||
# 失败之后多久重试(用把 checked_at 往前拨的方式表达)。
|
||
RETRY_MS = 6 * 60 * 60_000
|
||
# 一批最多处理多少个博主。调度器每个 tick 都来问一次,扫完了自然不再有 due。
|
||
BATCH_SIZE = 20
|
||
|
||
|
||
async def due_creators(
|
||
session: AsyncSession,
|
||
platform: str,
|
||
now: int,
|
||
limit: int = BATCH_SIZE,
|
||
) -> List[Tuple[str, str]]:
|
||
"""需要(重新)扫的 ``(creator_hash, creator_id)``,最近活跃的优先。"""
|
||
task_ids = select(MonitorTask.id).where(MonitorTask.platform == platform)
|
||
|
||
candidates: Dict[Tuple[str, str], int] = {}
|
||
note_rows = await session.execute(
|
||
select(
|
||
MonitorNote.creator_hash,
|
||
MonitorNote.creator_id,
|
||
func.max(MonitorNote.last_seen_at),
|
||
)
|
||
.where(MonitorNote.task_id.in_(task_ids), MonitorNote.creator_id != "")
|
||
.group_by(MonitorNote.creator_hash, MonitorNote.creator_id)
|
||
)
|
||
for creator_hash, creator_id, seen_at in note_rows.all():
|
||
candidates[(creator_hash, creator_id)] = seen_at or 0
|
||
|
||
# 作品模式早期入库的笔记没有 creator_id,但快照里可能有 —— 两边都收进来。
|
||
stat_rows = await session.execute(
|
||
select(MonitorCreatorStat.creator_hash, MonitorCreatorStat.creator_id)
|
||
.where(
|
||
MonitorCreatorStat.task_id.in_(task_ids),
|
||
MonitorCreatorStat.creator_id != "",
|
||
)
|
||
.group_by(MonitorCreatorStat.creator_hash, MonitorCreatorStat.creator_id)
|
||
)
|
||
for creator_hash, creator_id in stat_rows.all():
|
||
candidates.setdefault((creator_hash, creator_id), 0)
|
||
|
||
cached = {
|
||
row.creator_id: row
|
||
for row in await session.scalars(
|
||
select(MonitorCreatorFirstVideo).where(
|
||
MonitorCreatorFirstVideo.platform == platform
|
||
)
|
||
)
|
||
}
|
||
due = [
|
||
key
|
||
for key in candidates
|
||
if key[1] not in cached
|
||
or now - (cached[key[1]].checked_at or 0) >= TTL_MS
|
||
]
|
||
due.sort(key=lambda key: candidates[key], reverse=True)
|
||
return due[:limit]
|
||
|
||
|
||
async def _scan(creator_id: str) -> Tuple[Optional[int], int, bool]:
|
||
"""从最新一页翻到最后一页,返回 ``(最早时间毫秒, 页数, 是否翻到底)``。"""
|
||
identity = await douyin_api.browser_identity()
|
||
cursor = 0
|
||
oldest: Optional[int] = None
|
||
pages = 0
|
||
complete = False
|
||
started = time.monotonic()
|
||
|
||
while pages < MAX_PAGES:
|
||
videos, next_cursor, has_more = await douyin_api.author_videos_page(
|
||
creator_id, cursor, PAGE_SIZE, identity=identity
|
||
)
|
||
pages += 1
|
||
|
||
stamps = [
|
||
adapters.DY.to_ms(video.get("create_time")) for video in videos
|
||
]
|
||
stamps = [stamp for stamp in stamps if stamp]
|
||
if stamps:
|
||
page_oldest = min(stamps)
|
||
oldest = page_oldest if oldest is None else min(oldest, page_oldest)
|
||
|
||
if not has_more or not videos:
|
||
complete = True
|
||
break
|
||
# 游标不动就是到了尽头(接口偶尔 has_more 和游标对不上),别死循环。
|
||
if not next_cursor or next_cursor == cursor:
|
||
break
|
||
cursor = next_cursor
|
||
|
||
if time.monotonic() - started >= MAX_SECONDS_PER_CREATOR:
|
||
break
|
||
await asyncio.sleep(REQUEST_GAP_SECONDS)
|
||
|
||
return oldest, pages, complete
|
||
|
||
|
||
async def scan_one(
|
||
session: AsyncSession,
|
||
platform: str,
|
||
creator_hash: str,
|
||
creator_id: str,
|
||
now: Optional[int] = None,
|
||
) -> bool:
|
||
"""扫一个博主并写缓存。返回是否成功(失败也落一行,记录原因和下次重试时间)。"""
|
||
now = now or get_current_timestamp()
|
||
row = await session.scalar(
|
||
select(MonitorCreatorFirstVideo).where(
|
||
MonitorCreatorFirstVideo.platform == platform,
|
||
MonitorCreatorFirstVideo.creator_id == creator_id,
|
||
)
|
||
)
|
||
if row is None:
|
||
row = MonitorCreatorFirstVideo(
|
||
platform=platform,
|
||
creator_id=creator_id,
|
||
creator_hash=creator_hash,
|
||
checked_at=0,
|
||
)
|
||
session.add(row)
|
||
|
||
try:
|
||
oldest, pages, complete = await _scan(creator_id)
|
||
except Exception as exc: # noqa: BLE001 - 接口抖动不该炸掉整批
|
||
row.creator_hash = creator_hash
|
||
row.error = str(exc)[:500]
|
||
# checked_at 往前拨,让这一行在 RETRY_MS 之后重新进入待扫队列;
|
||
# 不拨到 now 是因为那会把它锁 30 天。
|
||
row.checked_at = now - TTL_MS + RETRY_MS
|
||
return False
|
||
|
||
row.creator_hash = creator_hash
|
||
row.first_published_at = oldest
|
||
row.scanned_pages = pages
|
||
row.complete = complete
|
||
row.checked_at = now
|
||
row.error = ""
|
||
return True
|
||
|
||
|
||
async def refresh_batch(
|
||
platform: str = adapters.PLATFORM_DY, limit: int = BATCH_SIZE
|
||
) -> Dict[str, int]:
|
||
"""扫一批到期的博主。由调度器的后台任务调用。"""
|
||
now = get_current_timestamp()
|
||
async with get_session() as session:
|
||
due = await due_creators(session, platform, now, limit)
|
||
|
||
scanned = failed = 0
|
||
for creator_hash, creator_id in due:
|
||
async with get_session() as session:
|
||
ok = await scan_one(
|
||
session, platform, creator_hash, creator_id,
|
||
now=get_current_timestamp(),
|
||
)
|
||
if ok:
|
||
scanned += 1
|
||
else:
|
||
failed += 1
|
||
return {"due": len(due), "scanned": scanned, "failed": failed}
|