diff --git a/api/monitor/app_settings.py b/api/monitor/app_settings.py index 539cf91..8ff457b 100644 --- a/api/monitor/app_settings.py +++ b/api/monitor/app_settings.py @@ -144,6 +144,51 @@ SETTING_SPECS: List[SettingSpec] = [ minimum=0, maximum=600, ), + SettingSpec( + name="identity_mode", + scope=SCOPE_PLATFORM, + type=TYPE_STR, + label="多身份采集", + help=( + "single=只用一份登录态(默认);pool=把目标分给身份池里的多个账号。" + "池模式是**串行分片**,不是并行 —— 同一个出口 IP 上并发多个 cookie 更容易被风控。" + ), + default="single", + choices=["single", "pool"], + ), + SettingSpec( + name="identity_min_available", + scope=SCOPE_PLATFORM, + type=TYPE_INT, + label="最少可用身份数", + help="池模式下可用身份少于这个数就不跑这一轮 —— 别拿一个号硬扛全部目标。", + default=1, + minimum=1, + maximum=20, + ), + SettingSpec( + name="identity_switch_delay_sec", + scope=SCOPE_PLATFORM, + type=TYPE_INT, + label="身份切换间隔(秒)", + help="换下一个账号之前等多久。同一出口上连续切换登录态更像异常流量。", + default=30, + minimum=0, + maximum=600, + ), + SettingSpec( + name="identity_concurrency", + scope=SCOPE_PLATFORM, + type=TYPE_INT, + label="身份并发数", + help=( + "默认 1(串行)。**只有给每个账号配了独立出口 IP 才建议调大** —— " + "同一 IP 上并发多个身份,平台视角是一台设备在不停换访客。" + ), + default=1, + minimum=1, + maximum=8, + ), SettingSpec( name="enable_ip_proxy", scope=SCOPE_PLATFORM, diff --git a/api/monitor/douyin_api.py b/api/monitor/douyin_api.py index 1e9bb91..bbbcce5 100644 --- a/api/monitor/douyin_api.py +++ b/api/monitor/douyin_api.py @@ -101,6 +101,9 @@ class BrowserIdentity: cookie: str user_agent: str client_hints: Dict[str, str] + # 身份池里的标识:``"browser"`` / ``"id:"`` / ``"legacy"``。只用于日志与分片, + # 不参与请求。放在最后且有默认值,现有构造点不用改。 + identity_key: str = "legacy" def headers(self) -> Dict[str, str]: headers = { @@ -299,6 +302,19 @@ def forget_identity() -> None: _identity_cache = None +async def shared_fingerprint() -> Tuple[str, Dict[str, str]]: + """只从浏览器读 UA + client hints,**不要它的 cookie**。 + + 给「粘贴 cookie」的身份兜底:cookie 来自哪个浏览器我们不知道,至少让 UA 和 + ``sec-ch-ua`` 成套。读不到返回空 —— 调用方应当拒绝创建没有 UA 的身份,因为 + 评论接口的 ``a_bogus`` 要拿 UA 去签名,空 UA 签出来的请求一定被挡。 + """ + identity = await _read_browser() + if identity is None: + return "", {} + return identity.user_agent, identity.client_hints + + def _cookie_header(cookie: str) -> str: """把 ``a=1; b=2`` 形式的 cookie 串规整成请求头用的形状。""" pairs = [] @@ -427,14 +443,19 @@ def normalize_aweme(aweme: Dict[str, Any]) -> Dict[str, Any]: async def author_videos( - sec_user_id: str, count: int = MAX_PAGE_SIZE, *, cookie: str = "" + sec_user_id: str, + count: int = MAX_PAGE_SIZE, + *, + cookie: str = "", + identity: Optional[BrowserIdentity] = None, ) -> List[Dict[str, Any]]: """某个博主最新发布的作品(按发布时间倒序),已翻译成 store 的键名。 用 ``sec_user_id`` 而不是数字 uid:监控任务里存的就是主页链接里的那段 sec_uid, 而且这个接口两种都收(爬虫那边用的也是 sec_user_id)。 """ - identity = await browser_identity(cookie) + # 身份池传进来的身份直接用 —— 不要再去读浏览器,那会把别的账号的 cookie 顶进来。 + identity = identity or await browser_identity(cookie) if not _has_session(identity.cookie): raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有") @@ -458,13 +479,18 @@ async def author_videos( return [normalize_aweme(aweme) for aweme in awemes] -async def video_detail(aweme_id: str, *, cookie: str = "") -> Dict[str, Any]: +async def video_detail( + aweme_id: str, + *, + cookie: str = "", + identity: Optional[BrowserIdentity] = None, +) -> Dict[str, Any]: """单条作品的详情,已翻译成 store 的键名。 这个接口**没有**被那道真校验挡着(实测 200 / 45425 字节),所以在拿不到作品列表时, 它是「刷新已知作品指标」的唯一途径。 """ - identity = await browser_identity(cookie) + identity = identity or await browser_identity(cookie) if not _has_session(identity.cookie): raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有") @@ -481,9 +507,14 @@ async def video_detail(aweme_id: str, *, cookie: str = "") -> Dict[str, Any]: return normalize_aweme(aweme) -async def author_profile(sec_user_id: str, *, cookie: str = "") -> Dict[str, Any]: +async def author_profile( + sec_user_id: str, + *, + cookie: str = "", + identity: Optional[BrowserIdentity] = None, +) -> Dict[str, Any]: """博主主页指标:昵称 / 粉丝数 / 总获赞 / 作品数。""" - identity = await browser_identity(cookie) + identity = identity or await browser_identity(cookie) if not _has_session(identity.cookie): raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有") @@ -541,14 +572,18 @@ def normalize_comment(comment: Dict[str, Any], aweme_id: str) -> Dict[str, Any]: async def video_comments( - aweme_id: str, count: int = 20, *, cookie: str = "" + aweme_id: str, + count: int = 20, + *, + cookie: str = "", + identity: Optional[BrowserIdentity] = None, ) -> List[Dict[str, Any]]: """一条作品的评论,翻译成 store 的评论键名。 刻意不带 ``sub_comment_count`` / ``parent_comment_id`` 的猜测值 —— 接口给了就用, 没给就留空,不编。 """ - identity = await browser_identity(cookie) + identity = identity or await browser_identity(cookie) if not _has_session(identity.cookie): raise DouyinApiError("抖音登录态不可用") diff --git a/api/monitor/douyin_fetch.py b/api/monitor/douyin_fetch.py index 5344678..ee48576 100644 --- a/api/monitor/douyin_fetch.py +++ b/api/monitor/douyin_fetch.py @@ -29,6 +29,7 @@ —— 重采样、差分、事件、通知、报表全都照旧。 """ +import asyncio import json from datetime import datetime from pathlib import Path @@ -54,12 +55,19 @@ async def collect( targets: Sequence[Any], known_aweme_ids: Iterable[str] = (), cookie: str = "", + identities: Sequence[Any] = (), + concurrency: int = 1, + switch_delay_seconds: float = 0.0, ) -> Dict[str, Any]: """跑一轮抖音采集,把产物写进 ``out_dir`` 下 store 那个目录里。 参数是散的、不收 ORM 对象:调用方那边 ``task`` 在会话关掉之后就 detached 了, 传对象进来迟早会踩到「属性已过期」。 + ``identities`` 非空时进入**身份池模式**:目标按 Rendezvous Hashing 分给各个身份, + 逐个分片执行。默认串行 —— 同一个出口 IP 上并发多个 cookie 比单账号高频更可疑; + ``concurrency`` 只是留了个口子,有独立出口 IP 之前别调大。 + **不抛异常**:失败也把(可能为空的)产物落下去,并把原因放进 ``errors`` 交给调用方。 让调用方去决定这是「一轮正常但没数据」还是「一轮失败」—— 这个判断不该藏在这里。 """ @@ -69,12 +77,117 @@ async def collect( # 只有博主模式才有 —— 作品模式的目标是一件作品,没有"这个博主是谁"可问。 profiles: List[Dict[str, Any]] = [] errors: List[str] = [] + shards: List[Dict[str, Any]] = [] # **整个 collect 只去重一次的、跨目标的集合**:退化路径会把「库里已知的全部作品」 # 在每个目标下都刷一遍,多个目标就会出现同一件作品好几条记录 —— 而一对一快照的 # 唯一键是 (task_id, note_id, run_id),同一条作品在一轮里出现两次会直接撞键。 seen_aweme: set = set() + if identities: + from . import identities as identity_pool + + plan = identity_pool.assign(targets, [item.identity_key for item in identities]) + batches = [ + (item, plan[item.identity_key]) + for item in identities + if plan[item.identity_key] + ] + + async def run_batch(identity, shard): + return await _collect_batch( + shard, + identity=identity, + mode=mode, + limit=limit, + want_comments=want_comments, + comment_limit=comment_limit, + cookie=cookie, + known_aweme_ids=known_aweme_ids, + seen_aweme=seen_aweme, + ) + + if concurrency > 1 and len(batches) > 1: + results = await asyncio.gather(*(run_batch(i, s) for i, s in batches)) + else: + results = [] + for index, (identity, shard) in enumerate(batches): + results.append(await run_batch(identity, shard)) + # 换账号之间留一点空档:连续在同一个 IP 上换登录态更像异常流量。 + if index < len(batches) - 1 and switch_delay_seconds > 0: + await asyncio.sleep(switch_delay_seconds) + + for (identity, shard), result in zip(batches, results): + notes.extend(result["notes"]) + comments.extend(result["comments"]) + profiles.extend(result["profiles"]) + errors.extend(result["errors"]) + shards.append( + { + "key": identity.identity_key, + "targets": result["targets"], + "notes": len(result["notes"]), + "comments": len(result["comments"]), + "errors": list(result["errors"]), + } + ) + else: + result = await _collect_batch( + targets, + identity=None, + mode=mode, + limit=limit, + want_comments=want_comments, + comment_limit=comment_limit, + cookie=cookie, + known_aweme_ids=known_aweme_ids, + seen_aweme=seen_aweme, + ) + notes.extend(result["notes"]) + comments.extend(result["comments"]) + profiles.extend(result["profiles"]) + errors.extend(result["errors"]) + + # 并发跑分片时,两个分片可能各自刷新到同一件已知作品 —— 落盘前去一次重, + # 否则唯一键 (task_id, note_id, run_id) 会撞。 + deduped: List[Dict[str, Any]] = [] + seen_note_ids: set = set() + for note in notes: + note_id = note.get("aweme_id") + if note_id and note_id in seen_note_ids: + continue + if note_id: + seen_note_ids.add(note_id) + deduped.append(note) + + jsonl_dir = _write_artifacts(out_dir, platform, mode, deduped, comments, profiles) + return { + "notes": len(deduped), + "comments": len(comments), + "errors": errors, + "jsonl_dir": str(jsonl_dir), + "shards": shards, + } + + +async def _collect_batch( + targets: Sequence[Any], + *, + identity: Any, + mode: str, + limit: int, + want_comments: bool, + comment_limit: int, + cookie: str, + known_aweme_ids: Iterable[str], + seen_aweme: set, +) -> Dict[str, Any]: + """一个身份负责的那一片目标。错误只往自己的列表里记,由调用方合并。""" + notes: List[Dict[str, Any]] = [] + comments: List[Dict[str, Any]] = [] + profiles: List[Dict[str, Any]] = [] + errors: List[str] = [] + for target in targets: external_id = target.external_id @@ -84,15 +197,27 @@ async def collect( # 刷新库里已知的作品(新作品发现不了)。 if mode == MODE_NOTE: try: - videos = [await douyin_api.video_detail(external_id, cookie=cookie)] + videos = [ + await douyin_api.video_detail( + external_id, cookie=cookie, identity=identity + ) + ] except douyin_api.DouyinApiError as exc: errors.append(f"拉取作品 {external_id} 失败:{exc}") videos = [] else: videos = await _creator_works( - external_id, limit, known_aweme_ids, seen_aweme, cookie, errors + external_id, + limit, + known_aweme_ids, + seen_aweme, + cookie, + errors, + identity, + ) + profile = await _creator_profile( + external_id, videos, cookie, errors, identity ) - profile = await _creator_profile(external_id, videos, cookie, errors) if profile is not None: profiles.append(profile) @@ -107,18 +232,21 @@ async def collect( try: comments.extend( await douyin_api.video_comments( - aweme_id, count=comment_limit, cookie=cookie + aweme_id, + count=comment_limit, + cookie=cookie, + identity=identity, ) ) except douyin_api.DouyinApiError as exc: errors.append(f"拉取作品 {aweme_id} 的评论失败:{exc}") - jsonl_dir = _write_artifacts(out_dir, platform, mode, notes, comments, profiles) return { - "notes": len(notes), - "comments": len(comments), + "notes": notes, + "comments": comments, + "profiles": profiles, "errors": errors, - "jsonl_dir": str(jsonl_dir), + "targets": len(targets), } @@ -127,6 +255,7 @@ async def _creator_profile( videos: Sequence[Dict[str, Any]], cookie: str, errors: List[str], + identity: Any = None, ) -> Optional[Dict[str, Any]]: """问一次博主的账号级指标。拿不到就算了 —— **不能因为顺手的附加信息失败, 就把这一轮本来采到的作品也判成失败。** @@ -137,7 +266,9 @@ async def _creator_profile( 那种情况下也只剩它了。 """ try: - profile = await douyin_api.author_profile(sec_user_id, cookie=cookie) + profile = await douyin_api.author_profile( + sec_user_id, cookie=cookie, identity=identity + ) except douyin_api.DouyinApiError as exc: errors.append(f"拉取博主 {sec_user_id} 的资料失败:{exc}") return None @@ -158,6 +289,7 @@ async def _creator_works( seen_aweme: set, cookie: str, errors: List[str], + identity: Any = None, ) -> List[Dict[str, Any]]: """一个博主的作品:先要列表,列表被挡时退化成刷新已知作品。 @@ -165,7 +297,9 @@ async def _creator_works( 带上 dummy 值回 200 + 空 body。所以这里拿不到**新**作品,只能保住已知的。 """ try: - return await douyin_api.author_videos(sec_user_id, count=limit, cookie=cookie) + return await douyin_api.author_videos( + sec_user_id, count=limit, cookie=cookie, identity=identity + ) except douyin_api.DouyinApiError as exc: errors.append(f"拉取博主 {sec_user_id} 的作品列表失败:{exc}") @@ -174,7 +308,11 @@ async def _creator_works( if aweme_id in seen_aweme: continue try: - refreshed.append(await douyin_api.video_detail(aweme_id, cookie=cookie)) + refreshed.append( + await douyin_api.video_detail( + aweme_id, cookie=cookie, identity=identity + ) + ) except douyin_api.DouyinApiError as detail_exc: errors.append(f"刷新作品 {aweme_id} 失败:{detail_exc}") return refreshed diff --git a/api/monitor/identities.py b/api/monitor/identities.py new file mode 100644 index 0000000..c6c4c44 --- /dev/null +++ b/api/monitor/identities.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +"""身份池:多个登录态之间的选取、分片与健康状态。 + +**为什么是「串行分片」而不是「并行抓取」。** 抖音按 *账号 + IP + 设备指纹* 联合判定, +在同一个出口 IP 上并发跑多个 cookie,比单账号高频请求更容易被判成异常 —— 平台视角是 +一台设备在不停换访客。所以默认一次只跑一个身份,靠**把目标分给不同账号**来降低每个 +账号的请求量;并发数由调用方决定(默认 1),有独立出口 IP 之前别调大。 +""" + +import hashlib +import json +from typing import Any, Dict, List, Optional, Sequence + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from tools.time_util import get_current_timestamp + +from . import douyin_api +from .models import ( + IDENTITY_SOURCE_BROWSER, + IDENTITY_STATUS_COOLDOWN, + IDENTITY_STATUS_EXPIRED, + IDENTITY_STATUS_OK, + MonitorIdentity, +) + +IDENTITY_KEY_BROWSER = "browser" +# 连续失败几次才进冷却。一次失败可能只是网络抖动,不值得把账号停半小时。 +COOLDOWN_AFTER_FAILURES = 2 +COOLDOWN_BASE_MS = 30 * 60_000 +COOLDOWN_MAX_MS = 180 * 60_000 + + +def key_for(row: MonitorIdentity) -> str: + """身份在本轮里的稳定标识。``browser`` 只有一个,其它按行 id。""" + if row.source == IDENTITY_SOURCE_BROWSER: + return IDENTITY_KEY_BROWSER + return f"id:{row.id}" + + +def is_available(row: MonitorIdentity, now: Optional[int] = None) -> bool: + if not row.enabled or row.status == IDENTITY_STATUS_EXPIRED: + return False + now = now or get_current_timestamp() + return not row.cooldown_until or row.cooldown_until <= now + + +async def load_available( + session: AsyncSession, platform: str, now: Optional[int] = None +) -> List[MonitorIdentity]: + now = now or get_current_timestamp() + rows = ( + await session.scalars( + select(MonitorIdentity) + .where(MonitorIdentity.platform == platform) + .order_by(MonitorIdentity.id) + ) + ).all() + return [row for row in rows if is_available(row, now)] + + +async def resolve(row: MonitorIdentity) -> douyin_api.BrowserIdentity: + """把一行身份变成请求真正要用的那份。 + + 失败抛 ``ValueError``(消息直接给人看),由调用方决定是跳过这个身份还是整轮失败。 + """ + if row.source == IDENTITY_SOURCE_BROWSER: + identity = await douyin_api.browser_identity(force=True) + if "sessionid=" not in (identity.cookie or ""): + raise ValueError("浏览器里没有可用的抖音登录态") + return douyin_api.BrowserIdentity( + cookie=identity.cookie, + user_agent=identity.user_agent, + client_hints=identity.client_hints, + identity_key=key_for(row), + ) + + try: + hints = json.loads(row.client_hints or "{}") + except ValueError: + hints = {} + if not row.cookie.strip(): + raise ValueError("这份身份没有 cookie") + if not row.user_agent.strip(): + # 评论接口的 a_bogus 把 UA 算进去,空 UA 签出来的请求一定被挡。 + raise ValueError("这份身份没有 UA —— 评论签名要用它") + return douyin_api.BrowserIdentity( + cookie=row.cookie, + user_agent=row.user_agent, + client_hints=hints if isinstance(hints, dict) else {}, + identity_key=key_for(row), + ) + + +def _score(identity_key: str, external_id: str) -> int: + digest = hashlib.blake2b( + f"{identity_key}:{external_id}".encode("utf-8"), digest_size=8 + ).digest() + return int.from_bytes(digest, "big") + + +def assign(targets: Sequence[Any], keys: Sequence[str]) -> Dict[str, List[Any]]: + """用 Rendezvous Hashing 把目标分给身份。 + + 比取模好在:加一个身份时只有约 1/(n+1) 的目标会迁移,而不是全部重排;同一组 + 身份和目标的分配结果是确定的,便于排查和 A/B。 + + 身份列表为空时返回空 —— 调用方应当先确保至少有一个可用身份。 + """ + buckets: Dict[str, List[Any]] = {key: [] for key in keys} + if not keys: + return buckets + for target in targets: + external = getattr(target, "external_id", None) or str(target) + best = max(keys, key=lambda key: _score(key, external)) + buckets[best].append(target) + return buckets + + +async def record_result( + session: AsyncSession, + row: MonitorIdentity, + *, + ok: bool, + error: str = "", + now: Optional[int] = None, +) -> None: + """一轮分片跑完之后更新健康状态。 + + **空 body / 403 只算限流,不算 cookie 失效** —— 前者冷却后还能用,后者才需要 + 人工重新粘贴。这一层区分放在调用方:``ok=False`` 走冷却,``expired=True`` 才置 + ``expired``。 + """ + now = now or get_current_timestamp() + row.last_checked_at = now + + if ok: + row.status = IDENTITY_STATUS_OK + row.consecutive_failures = 0 + row.cooldown_until = None + row.last_ok_at = now + row.last_error = None + row.updated_at = now + return + + row.consecutive_failures = (row.consecutive_failures or 0) + 1 + row.last_error = (error or "")[:500] + row.updated_at = now + if row.consecutive_failures >= COOLDOWN_AFTER_FAILURES: + delay = min( + COOLDOWN_BASE_MS * (2 ** (row.consecutive_failures - COOLDOWN_AFTER_FAILURES)), + COOLDOWN_MAX_MS, + ) + row.status = IDENTITY_STATUS_COOLDOWN + row.cooldown_until = now + delay + + +def mark_expired(row: MonitorIdentity, error: str, now: Optional[int] = None) -> None: + """明确的登录态失效:需要人工重新粘贴,冷却没用。""" + now = now or get_current_timestamp() + row.status = IDENTITY_STATUS_EXPIRED + row.last_checked_at = now + row.last_error = (error or "")[:500] + row.updated_at = now + + +def to_dict(row: MonitorIdentity) -> Dict[str, Any]: + """对外形状。**绝不含 cookie 原文**,只给 has_cookie。""" + return { + "id": row.id, + "platform": row.platform, + "label": row.label, + "source": row.source, + "has_cookie": bool(row.cookie), + "user_agent": row.user_agent, + "status": row.status, + "enabled": row.enabled, + "consecutive_failures": row.consecutive_failures, + "cooldown_until": row.cooldown_until, + "last_checked_at": row.last_checked_at, + "last_ok_at": row.last_ok_at, + "last_error": row.last_error, + } diff --git a/api/monitor/models.py b/api/monitor/models.py index 463b1de..c244071 100644 --- a/api/monitor/models.py +++ b/api/monitor/models.py @@ -503,6 +503,61 @@ SETTING_UPSTREAM_STATE = "system.upstream_check_state" # 更新推一遍,直到有人去合并为止;而上游真又动了的时候应该再推一次。 SETTING_UPSTREAM_NOTIFIED_TIP = "system.upstream_notified_tip" +# --- 身份池 ----------------------------------------------------------------- + +IDENTITY_STATUS_OK = "ok" +IDENTITY_STATUS_COOLDOWN = "cooldown" +IDENTITY_STATUS_EXPIRED = "expired" +IDENTITY_STATUS_DISABLED = "disabled" + +IDENTITY_SOURCE_STORED = "stored" +IDENTITY_SOURCE_BROWSER = "browser" + + +class MonitorIdentity(MonitorBase): + """一个可用于采集的登录态。 + + **为什么 cookie 必须和 UA 一起存**:抖音的 ``a_bogus`` 签名把 UA 算进去 + (``libs/douyin.js``),而网关又把 cookie / UA / sec-ch-ua 当成同一台设备的 + 指纹。只存 cookie、套用另一套 UA,签名和指纹都对不上,接口只会回 200 + 空 body。 + + ``source="browser"`` 表示用 CDP 浏览器**当前**登录态,此时 ``cookie`` 留空、每次 + 运行时现读;``source="stored"`` 才是粘贴进来的那一份。 + """ + + __tablename__ = "monitor_identity" + __table_args__ = ( + UniqueConstraint("platform", "label", name="uq_monitor_identity_label"), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + platform: Mapped[str] = mapped_column( + String(16), nullable=False, default="dy", index=True + ) + label: Mapped[str] = mapped_column(String(128), nullable=False) + source: Mapped[str] = mapped_column( + String(16), nullable=False, default=IDENTITY_SOURCE_STORED + ) + # **永不回显**:接口只返回 has_cookie。 + cookie: Mapped[str] = mapped_column(Text, nullable=False, default="") + user_agent: Mapped[str] = mapped_column(String(512), nullable=False, default="") + client_hints: Mapped[str] = mapped_column(Text, nullable=False, default="{}") + + status: Mapped[str] = mapped_column( + String(16), nullable=False, default=IDENTITY_STATUS_OK + ) + enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True) + # 冷却退避用:连续失败 N 次后冷却,成功后清零。 + consecutive_failures: Mapped[int] = mapped_column(Integer, nullable=False, default=0) + cooldown_until: Mapped[Optional[int]] = mapped_column(BigInteger) + last_checked_at: Mapped[Optional[int]] = mapped_column(BigInteger) + last_ok_at: Mapped[Optional[int]] = mapped_column(BigInteger) + last_error: Mapped[Optional[str]] = mapped_column(Text) + + created_at: Mapped[int] = mapped_column(BigInteger, nullable=False) + updated_at: Mapped[int] = mapped_column(BigInteger, nullable=False) + + # Pre-namespacing keys, kept only so the startup migration can find and move # them. Nothing should read these directly. LEGACY_SETTING_KEY_RENAMES = { diff --git a/api/monitor/runner.py b/api/monitor/runner.py index cd51dae..238e9ba 100644 --- a/api/monitor/runner.py +++ b/api/monitor/runner.py @@ -41,6 +41,7 @@ from ..schemas import ( ) from ..services import crawler_manager from . import adapters, app_settings, covers, douyin_fetch, notify +from . import identities as identity_pool from .db import get_session from .ingest import IngestResult, diagnose_failure, ingest_run from .models import ( @@ -49,6 +50,7 @@ from .models import ( RUN_PENDING, RUN_RUNNING, RUN_TIMEOUT, + MonitorIdentity, MonitorNote, MonitorRun, MonitorTarget, @@ -205,6 +207,34 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult: ) ) + # 身份池只在抖音上有意义(小红书走子进程)。池模式是**串行分片**:把目标分给 + # 多个账号,降低每个账号的请求量,不是并行提速。 + identity_rows = [] + identity_min_available = 1 + identity_switch_delay = 0 + identity_concurrency = 1 + if platform == adapters.PLATFORM_DY: + identity_mode = await app_settings.get_value( + session, "identity_mode", platform, "single" + ) + if identity_mode == "pool": + identity_rows = await identity_pool.load_available(session, platform) + identity_min_available = int( + await app_settings.get_value( + session, "identity_min_available", platform, 1 + ) + ) + identity_switch_delay = int( + await app_settings.get_value( + session, "identity_switch_delay_sec", platform, 30 + ) + ) + identity_concurrency = int( + await app_settings.get_value( + session, "identity_concurrency", platform, 1 + ) + ) + # --- Phase 2: run the collection outside any transaction ------------------ # 抖音走**进程内 HTTP 客户端**,不起 Playwright 子进程:那边会构造一大串自相矛盾的 # 浏览器指纹参数(参数说 Mac + Chrome 125、UA 说 Linux + Chrome 155),网关回一个 @@ -219,33 +249,82 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult: run.status = RUN_RUNNING run.started_at = get_current_timestamp() + # 身份行在会话关掉之后是 detached 的,但 expire_on_commit=False,字段还能读。 + # 解析放到这里(会话之外)—— source="browser" 要连 CDP,可能慢。 + resolved_identities = [] + resolved_ids = [] + for row in identity_rows: + try: + resolved_identities.append(await identity_pool.resolve(row)) + resolved_ids.append(row.id) + except ValueError as exc: + print(f"[monitor.runner] 身份「{row.label}」本轮不可用:{exc}", flush=True) + in_process_tail: List[str] = [] if platform == adapters.PLATFORM_DY: - try: - # 也要有超时。爬虫那条路靠 run_and_wait(timeout=...) 兜底,这条路没有子进程、 - # 没人管 —— 里面**任何一次卡住都会让 run 永远停在「运行中」**(真踩过: - # page.evaluate 打在一个卡死的标签页上不返回)。 - fetched = await asyncio.wait_for( - douyin_fetch.collect( - out_dir, - platform=platform, - mode=mode, - limit=max_notes_count, - want_comments=enable_comments, - comment_limit=max_comments_count, - targets=targets, - known_aweme_ids=known_aweme_ids, - cookie=cookie, - ), - timeout=timeout_seconds, - ) - except asyncio.TimeoutError: + if identity_rows and len(resolved_identities) < identity_min_available: + # 快速失败:宁可这一轮不跑,也别拿一个号硬扛全部目标。 fetched = { "notes": 0, "comments": 0, - "errors": [f"抖音采集超过 {timeout_seconds} 秒仍未完成,已放弃这一轮"], + "errors": [ + f"可用抖音身份不足:{len(resolved_identities)}/{identity_min_available}" + "(其余的已失效或在冷却中)" + ], "jsonl_dir": "", + "shards": [], } + else: + try: + # 也要有超时。爬虫那条路靠 run_and_wait(timeout=...) 兜底,这条路没有子进程、 + # 没人管 —— 里面**任何一次卡住都会让 run 永远停在「运行中」**(真踩过: + # page.evaluate 打在一个卡死的标签页上不返回)。 + fetched = await asyncio.wait_for( + douyin_fetch.collect( + out_dir, + platform=platform, + mode=mode, + limit=max_notes_count, + want_comments=enable_comments, + comment_limit=max_comments_count, + targets=targets, + known_aweme_ids=known_aweme_ids, + cookie=cookie, + identities=resolved_identities, + concurrency=identity_concurrency, + switch_delay_seconds=identity_switch_delay, + ), + timeout=timeout_seconds, + ) + except asyncio.TimeoutError: + fetched = { + "notes": 0, + "comments": 0, + "errors": [f"抖音采集超过 {timeout_seconds} 秒仍未完成,已放弃这一轮"], + "jsonl_dir": "", + "shards": [], + } + + # 每个身份的健康按它自己那一片的结果算:有产物就算成功(哪怕带着退化错误), + # 一条没采到且全是错误才算失败。 + if resolved_ids: + shards_by_key = { + shard.get("key"): shard for shard in (fetched.get("shards") or []) + } + async with get_session() as session: + for row_id in resolved_ids: + row = await session.get(MonitorIdentity, row_id) + if row is None: + continue + shard = shards_by_key.get(identity_pool.key_for(row)) + if shard is None: + continue + await identity_pool.record_result( + session, + row, + ok=bool(shard["notes"]) or not shard["errors"], + error=";".join(shard["errors"]), + ) in_process_tail = list(fetched["errors"]) # 一条都没采到 = 这一轮失败,并把**真因**当作退出诊断传下去。否则它会掉进 # ingest 的「疑似登录失效」分支 —— 又骗人一次,正是这套东西一直在犯的毛病。 diff --git a/api/routers/monitor.py b/api/routers/monitor.py index b1d947c..46a34bd 100644 --- a/api/routers/monitor.py +++ b/api/routers/monitor.py @@ -18,13 +18,19 @@ """HTTP API for scheduled monitoring tasks.""" +import json from datetime import date, datetime, timedelta from typing import Any, Dict, List, Optional from fastapi import APIRouter, HTTPException, Query, Response from fastapi.responses import FileResponse -from ..monitor import covers, notify, qrlogin, report, service, tagrules, upstream +from tools.time_util import get_current_timestamp + +from sqlalchemy import select + +from ..monitor import covers, douyin_api, notify, qrlogin, report, service, tagrules, upstream +from ..monitor import identities as identity_pool from ..monitor.db import get_session from ..monitor.platforms import PLATFORM_XHS from ..monitor.settings import ( @@ -35,10 +41,19 @@ from ..monitor.settings import ( set_cookie, set_setting, ) -from ..monitor.models import SETTING_WECOM_WEBHOOK, MonitorTask +from ..monitor.models import ( + IDENTITY_SOURCE_STORED, + IDENTITY_STATUS_OK, + SETTING_WECOM_WEBHOOK, + MonitorIdentity, + MonitorTarget, + MonitorTask, +) from ..schemas.monitor import ( CookiePayload, CreatorAliasPayload, + IdentityCreate, + IdentityUpdate, NoteAliasPayload, NoteTagsPayload, TagPayload, @@ -879,3 +894,170 @@ async def run_upstream_check(): 没有推过的那批提交会留给下一次「定时检查」推 —— 推送状态记的是 tip,不是「推过没」。 """ return await upstream.run_check(notify_when_new=False) + + +# --------------------------------------------------------------------------- +# 身份池 +# --------------------------------------------------------------------------- +# +# 多个登录态分片采集用。**接口永远不返回 cookie 原文**,只给 has_cookie —— 这是 +# 从运营模块那边沿用下来的约定。 + + +@router.get("/identities") +async def list_identities(platform: str = Query(default=PLATFORM_XHS)): + async with get_session() as session: + rows = ( + await session.scalars( + select(MonitorIdentity) + .where(MonitorIdentity.platform == platform) + .order_by(MonitorIdentity.id) + ) + ).all() + return {"identities": [identity_pool.to_dict(row) for row in rows]} + + +@router.post("/identities", status_code=201) +async def create_identity(payload: IdentityCreate): + """新增一份登录态。 + + UA 留空时会尝试从 CDP 浏览器借一份指纹 —— cookie 仍用用户贴的这一份。再读不到 + 就拒绝:评论签名要拿 UA,空 UA 的请求一定被挡。 + """ + if payload.platform != "dy": + raise HTTPException(status_code=400, detail="目前只有抖音支持多身份") + + user_agent = payload.user_agent.strip() + hints = dict(payload.client_hints) + if not user_agent: + user_agent, shared_hints = await douyin_api.shared_fingerprint() + hints = hints or dict(shared_hints) + if not user_agent: + raise HTTPException( + status_code=400, + detail=( + "拿不到 UA。请手动填写 user_agent(要和 cookie 来自同一个浏览器)," + "或先让 CDP 浏览器登录抖音。" + ), + ) + + label = payload.label.strip() + now = get_current_timestamp() + async with get_session() as session: + exists = await session.scalar( + select(MonitorIdentity.id).where( + MonitorIdentity.platform == payload.platform, + MonitorIdentity.label == label, + ) + ) + if exists: + raise HTTPException(status_code=409, detail="同名身份已存在") + + row = MonitorIdentity( + platform=payload.platform, + label=label, + source=IDENTITY_SOURCE_STORED, + cookie=payload.cookie.strip(), + user_agent=user_agent, + client_hints=json.dumps(hints, ensure_ascii=False), + status=IDENTITY_STATUS_OK, + enabled=True, + created_at=now, + updated_at=now, + ) + session.add(row) + await session.flush() + return identity_pool.to_dict(row) + + +@router.patch("/identities/{identity_id}") +async def update_identity(identity_id: int, payload: IdentityUpdate): + async with get_session() as session: + row = await session.get(MonitorIdentity, identity_id) + if row is None: + raise HTTPException(status_code=404, detail="身份不存在") + + if payload.label is not None: + row.label = payload.label.strip() + if payload.user_agent is not None: + row.user_agent = payload.user_agent.strip() + if payload.cookie is not None: + row.cookie = payload.cookie.strip() + # 换了 cookie,旧状态作废 —— 之前冷却/失效的原因可能已经不存在了。 + row.status = IDENTITY_STATUS_OK + row.consecutive_failures = 0 + row.cooldown_until = None + row.last_error = None + if payload.enabled is not None: + row.enabled = payload.enabled + row.updated_at = get_current_timestamp() + await session.flush() + return identity_pool.to_dict(row) + + +@router.delete("/identities/{identity_id}") +async def delete_identity(identity_id: int): + async with get_session() as session: + row = await session.get(MonitorIdentity, identity_id) + if row is None: + raise HTTPException(status_code=404, detail="身份不存在") + await session.delete(row) + return {"deleted": identity_id} + + +@router.post("/identities/{identity_id}/check") +async def check_identity(identity_id: int): + """真去用这份身份请求一次。 + + 优先拿该平台一个启用中的博主目标做探针(``author_profile``,1 个请求);没有目标 + 时退化成「cookie 里有没有 sessionid」,并在 ``verified`` 里标 False —— 别把格式 + 检查说成验证通过。 + """ + async with get_session() as session: + row = await session.get(MonitorIdentity, identity_id) + if row is None: + raise HTTPException(status_code=404, detail="身份不存在") + platform = row.platform + probe = await session.scalar( + select(MonitorTarget.external_id) + .join(MonitorTask, MonitorTask.id == MonitorTarget.task_id) + .where( + MonitorTask.platform == platform, + MonitorTask.enabled.is_(True), + MonitorTarget.kind == "creator", + ) + .limit(1) + ) + + error = "" + verified = bool(probe) + ok = False + try: + identity = await identity_pool.resolve(row) + except ValueError as exc: + identity = None + error = str(exc) + + if identity is not None: + if probe: + try: + await douyin_api.author_profile(probe, identity=identity) + ok = True + except Exception as exc: # noqa: BLE001 - 任何失败都只是「这份身份不可用」 + error = f"{type(exc).__name__}: {exc}"[:300] + else: + ok = "sessionid=" in identity.cookie + if not ok: + error = "cookie 里没有 sessionid" + + async with get_session() as session: + live = await session.get(MonitorIdentity, identity_id) + if live is not None: + await identity_pool.record_result(session, live, ok=ok, error=error) + return { + "ok": ok, + "verified": verified, + "error": error, + "identity": identity_pool.to_dict(live), + } + return {"ok": ok, "verified": verified, "error": error, "identity": None} diff --git a/api/schemas/monitor.py b/api/schemas/monitor.py index 80a4fc5..bb380d7 100644 --- a/api/schemas/monitor.py +++ b/api/schemas/monitor.py @@ -18,7 +18,7 @@ """Request models for the monitoring API.""" -from typing import List, Literal, Optional +from typing import Dict, List, Literal, Optional from pydantic import BaseModel, Field, model_validator @@ -144,3 +144,24 @@ class WebhookPayload(BaseModel): class WebhookTestPayload(BaseModel): url: Optional[str] = Field(default=None, description="不传则使用已保存的地址") + + +class IdentityCreate(BaseModel): + """新增一个采集身份(一份登录态)。 + + ``user_agent`` 最好和 cookie 来自同一个浏览器。留空时后端会尝试从 CDP 浏览器 + 读一份指纹兜底;再读不到就拒绝 —— 评论接口的 a_bogus 要拿 UA 去签名。 + """ + + platform: str = Field(default="dy", max_length=16) + label: str = Field(min_length=1, max_length=128) + cookie: str = Field(min_length=1) + user_agent: str = Field(default="", max_length=512) + client_hints: Dict[str, str] = Field(default_factory=dict) + + +class IdentityUpdate(BaseModel): + label: Optional[str] = Field(default=None, min_length=1, max_length=128) + cookie: Optional[str] = Field(default=None) + user_agent: Optional[str] = Field(default=None, max_length=512) + enabled: Optional[bool] = None diff --git a/tests/test_douyin_fetch.py b/tests/test_douyin_fetch.py index 8774871..6fdfe1d 100644 --- a/tests/test_douyin_fetch.py +++ b/tests/test_douyin_fetch.py @@ -36,7 +36,7 @@ def fake_profile(monkeypatch): 用例再单独覆盖这个 fixture。 """ - async def _profile_call(sec_user_id, *, cookie=""): + async def _profile_call(sec_user_id, *, cookie="", identity=None): return _profile() monkeypatch.setattr(douyin_api, "author_profile", _profile_call) @@ -99,10 +99,10 @@ async def _collect(tmp_path, **overrides): class TestHappyPath: @pytest.mark.asyncio async def test_writes_the_layout_ingest_expects(self, monkeypatch, tmp_path): - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111"), _video("222")] - async def fake_comments(aweme_id, count=20, *, cookie=""): + async def fake_comments(aweme_id, count=20, *, cookie="", identity=None): return [_comment(aweme_id, 1)] monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -140,7 +140,7 @@ class TestHappyPath: 两种情况的含义完全不同。 """ - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111")] monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -151,7 +151,7 @@ class TestHappyPath: @pytest.mark.asyncio async def test_duplicate_works_are_written_once(self, monkeypatch, tmp_path): - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111"), _video("111")] monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -175,7 +175,7 @@ class TestNoteMode: async def must_not_be_called(*args, **kwargs): raise AssertionError("作品模式不该去拉博主的作品列表") - async def fake_detail(aweme_id, *, cookie=""): + async def fake_detail(aweme_id, *, cookie="", identity=None): return _video(aweme_id) monkeypatch.setattr(douyin_api, "author_videos", must_not_be_called) @@ -196,7 +196,7 @@ class TestNoteMode: @pytest.mark.asyncio async def test_a_broken_work_does_not_lose_the_others(self, monkeypatch, tmp_path): - async def flaky(aweme_id, *, cookie=""): + async def flaky(aweme_id, *, cookie="", identity=None): if aweme_id == "222": raise douyin_api.DouyinApiError("作品已被删除") return _video(aweme_id) @@ -219,12 +219,12 @@ class TestDegradation: @pytest.mark.asyncio async def test_falls_back_to_refreshing_known_works(self, monkeypatch, tmp_path): - async def blocked(sec_user_id, count=20, *, cookie=""): + async def blocked(sec_user_id, count=20, *, cookie="", identity=None): raise douyin_api.DouyinApiError("接口返回了空内容") refreshed = [] - async def fake_detail(aweme_id, *, cookie=""): + async def fake_detail(aweme_id, *, cookie="", identity=None): refreshed.append(aweme_id) return _video(aweme_id, likes="9") @@ -249,12 +249,12 @@ class TestDegradation: Duplicate entry for key 'uq_note_metric')。 """ - async def blocked(sec_user_id, count=20, *, cookie=""): + async def blocked(sec_user_id, count=20, *, cookie="", identity=None): raise douyin_api.DouyinApiError("接口返回了空内容") calls = [] - async def fake_detail(aweme_id, *, cookie=""): + async def fake_detail(aweme_id, *, cookie="", identity=None): calls.append(aweme_id) return _video(aweme_id) @@ -273,7 +273,7 @@ class TestDegradation: @pytest.mark.asyncio async def test_nothing_at_all_still_reports_the_reason(self, monkeypatch, tmp_path): - async def blocked(sec_user_id, count=20, *, cookie=""): + async def blocked(sec_user_id, count=20, *, cookie="", identity=None): raise douyin_api.DouyinApiError("接口返回了空内容") monkeypatch.setattr(douyin_api, "author_videos", blocked) @@ -287,10 +287,10 @@ class TestDegradation: @pytest.mark.asyncio async def test_a_failing_comment_fetch_does_not_lose_the_work(self, monkeypatch, tmp_path): - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111")] - async def broken_comments(aweme_id, count=20, *, cookie=""): + async def broken_comments(aweme_id, count=20, *, cookie="", identity=None): raise douyin_api.DouyinApiError("评论接口抽风") monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -318,7 +318,7 @@ class TestCreatorProfile: @pytest.mark.asyncio async def test_the_profile_lands_in_the_run_dir(self, monkeypatch, tmp_path): - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111")] monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -336,11 +336,11 @@ class TestCreatorProfile: 而且是静默的:表里有数据,界面上什么都没有。 """ - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111")] # 作品带的哈希是 "hash" # 资料接口自己算出来的是另一个值(比如它那边 uid 缺字段、只能拿 sec_uid 算)。 - async def off_hash_profile(sec_user_id, *, cookie=""): + async def off_hash_profile(sec_user_id, *, cookie="", identity=None): return _profile(creator_hash="另一个哈希") monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -355,10 +355,10 @@ class TestCreatorProfile: async def test_a_profile_without_an_identity_is_dropped(self, monkeypatch, tmp_path): """哈希都算不出来的快照,落下去只会是一条谁也查不到的垃圾。""" - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [] - async def anonymous_profile(sec_user_id, *, cookie=""): + async def anonymous_profile(sec_user_id, *, cookie="", identity=None): return _profile(creator_hash="") monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -373,10 +373,10 @@ class TestCreatorProfile: async def test_a_failing_profile_does_not_lose_the_works(self, monkeypatch, tmp_path): """附加信息拿不到,这一轮采到的作品不能跟着判成失败。""" - async def fake_videos(sec_user_id, count=20, *, cookie=""): + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): return [_video("111")] - async def broken_profile(sec_user_id, *, cookie=""): + async def broken_profile(sec_user_id, *, cookie="", identity=None): raise douyin_api.DouyinApiError("资料接口抽风") monkeypatch.setattr(douyin_api, "author_videos", fake_videos) @@ -394,10 +394,10 @@ class TestCreatorProfile: asked = [] - async def fake_detail(aweme_id, *, cookie=""): + async def fake_detail(aweme_id, *, cookie="", identity=None): return _video(aweme_id) - async def recording_profile(sec_user_id, *, cookie=""): + async def recording_profile(sec_user_id, *, cookie="", identity=None): asked.append(sec_user_id) return _profile() diff --git a/tests/test_monitor_identities.py b/tests/test_monitor_identities.py new file mode 100644 index 0000000..8161215 --- /dev/null +++ b/tests/test_monitor_identities.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +"""身份池:分片、解析、健康状态。 + +这里钉住的是「多个账号怎么分活」和「一个号什么时候该被停用」。真去请求抖音的那层 +另有测试(test_douyin_api / test_douyin_fetch),这里全部用假函数。 +""" + +from types import SimpleNamespace + +import pytest +import pytest_asyncio + +from api.monitor import db as monitor_db +from api.monitor import douyin_api, douyin_fetch, identities +from api.monitor.models import ( + IDENTITY_SOURCE_STORED, + IDENTITY_STATUS_COOLDOWN, + IDENTITY_STATUS_OK, + MODE_CREATOR, + MonitorIdentity, +) +from tools.time_util import get_current_timestamp + + +@pytest_asyncio.fixture +async def db(tmp_path): + monitor_db.set_sqlite_path(tmp_path / "identities.db") + await monitor_db.init_db() + yield monitor_db + await monitor_db.dispose_engine() + + +async def _identity( + label: str = "主号", + cookie: str = "sessionid=abc", + user_agent: str = "UA/1.0", +) -> MonitorIdentity: + now = get_current_timestamp() + async with monitor_db.get_session() as session: + row = MonitorIdentity( + platform="dy", + label=label, + source=IDENTITY_SOURCE_STORED, + cookie=cookie, + user_agent=user_agent, + client_hints="{}", + created_at=now, + updated_at=now, + ) + session.add(row) + await session.flush() + return row + + +# --- 分片 ------------------------------------------------------------------- + + +def test_assignment_is_deterministic_and_covers_every_target(): + targets = [SimpleNamespace(external_id=f"t{index}") for index in range(30)] + first = identities.assign(targets, ["id:1", "id:2"]) + second = identities.assign(targets, ["id:1", "id:2"]) + + assert [t.external_id for t in first["id:1"]] == [t.external_id for t in second["id:1"]] + assert sum(len(bucket) for bucket in first.values()) == 30 + # 两个身份都应该分到活,否则分片没意义 + assert first["id:1"] and first["id:2"] + + +def test_adding_an_identity_moves_only_a_fraction_of_targets(): + """Rendezvous Hashing 的意义:加一个身份,只迁移约 1/(n+1) 的目标。""" + targets = [SimpleNamespace(external_id=f"t{index}") for index in range(300)] + before = { + target.external_id: key + for key, bucket in identities.assign(targets, ["id:1", "id:2"]).items() + for target in bucket + } + after = { + target.external_id: key + for key, bucket in identities.assign(targets, ["id:1", "id:2", "id:3"]).items() + for target in bucket + } + moved = sum(1 for external, key in before.items() if after[external] != key) + + assert 0 < moved < len(targets) * 0.6 + + +# --- 解析 ------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_resolve_builds_the_identity_from_the_row(db): + row = await _identity() + + identity = await identities.resolve(row) + + assert identity.cookie == "sessionid=abc" + assert identity.user_agent == "UA/1.0" + assert identity.identity_key == f"id:{row.id}" + + +@pytest.mark.asyncio +async def test_resolve_rejects_a_stored_identity_without_user_agent(db): + """没有 UA 就不能用 —— a_bogus 签名要拿它,空 UA 签出来的请求一定被挡。""" + row = await _identity(user_agent="") + + with pytest.raises(ValueError): + await identities.resolve(row) + + +@pytest.mark.asyncio +async def test_resolve_rejects_a_stored_identity_without_cookie(db): + row = await _identity(cookie="") + + with pytest.raises(ValueError): + await identities.resolve(row) + + +# --- 健康状态 --------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_two_failures_trigger_a_cooldown(db): + row = await _identity() + + async with monitor_db.get_session() as session: + live = await session.get(MonitorIdentity, row.id) + await identities.record_result(session, live, ok=False, error="空 body") + # 一次失败可能只是抖动,不停用 + assert live.status == IDENTITY_STATUS_OK + + await identities.record_result(session, live, ok=False, error="空 body") + assert live.status == IDENTITY_STATUS_COOLDOWN + assert live.cooldown_until > get_current_timestamp() + + +@pytest.mark.asyncio +async def test_success_clears_the_cooldown(db): + row = await _identity() + + async with monitor_db.get_session() as session: + live = await session.get(MonitorIdentity, row.id) + await identities.record_result(session, live, ok=False, error="x") + await identities.record_result(session, live, ok=False, error="x") + assert live.status == IDENTITY_STATUS_COOLDOWN + + await identities.record_result(session, live, ok=True) + assert live.status == IDENTITY_STATUS_OK + assert live.cooldown_until is None + assert live.consecutive_failures == 0 + assert live.last_ok_at is not None + + +def test_a_cooling_identity_is_not_available(): + row = MonitorIdentity( + platform="dy", + label="x", + source=IDENTITY_SOURCE_STORED, + cookie="sessionid=a", + user_agent="UA", + client_hints="{}", + status=IDENTITY_STATUS_OK, + enabled=True, + consecutive_failures=2, + cooldown_until=get_current_timestamp() + 60_000, + created_at=0, + updated_at=0, + ) + assert identities.is_available(row) is False + + row.cooldown_until = get_current_timestamp() - 1 + assert identities.is_available(row) is True + + +# --- 采集分片 --------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_collect_shards_targets_across_identities(tmp_path, monkeypatch): + used = [] + + async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): + used.append((identity.identity_key, sec_user_id)) + return [ + { + "aweme_id": f"a-{sec_user_id}", + "creator_hash": "hash-a", + "creator_name": "博主", + "title": "", + "aweme_url": "", + "cover_url": "", + "aweme_type": "video", + "create_time": 0, + } + ] + + async def fake_profile(sec_user_id, *, cookie="", identity=None): + return { + "creator_hash": "hash-a", + "nickname": "博主", + "creator_id": sec_user_id, + "unique_id": "", + "fans": 0, + "total_favorited": 0, + "works": 0, + "following": 0, + } + + monkeypatch.setattr(douyin_api, "author_videos", fake_videos) + monkeypatch.setattr(douyin_api, "author_profile", fake_profile) + + targets = [SimpleNamespace(external_id=f"t{index}") for index in range(20)] + pool = [ + douyin_api.BrowserIdentity( + cookie="sessionid=a", user_agent="UA", client_hints={}, identity_key="id:1" + ), + douyin_api.BrowserIdentity( + cookie="sessionid=b", user_agent="UA", client_hints={}, identity_key="id:2" + ), + ] + + result = await douyin_fetch.collect( + tmp_path, + platform="dy", + mode=MODE_CREATOR, + limit=20, + want_comments=False, + comment_limit=0, + targets=targets, + identities=pool, + ) + + assert len(used) == 20 + assert {key for key, _ in used} == {"id:1", "id:2"} + assert result["notes"] == 20 + assert len(result["shards"]) == 2 + assert sum(shard["targets"] for shard in result["shards"]) == 20 diff --git a/webui/src/components/monitor/IdentityPanel.tsx b/webui/src/components/monitor/IdentityPanel.tsx new file mode 100644 index 0000000..2f894bd --- /dev/null +++ b/webui/src/components/monitor/IdentityPanel.tsx @@ -0,0 +1,236 @@ +import { useState } from 'react' +import { CheckCircle2, KeyRound, Plus, Power, Trash2 } from 'lucide-react' + +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { + useCheckIdentity, + useCreateIdentity, + useDeleteIdentity, + useMonitorIdentities, + useUpdateIdentity, +} from '@/hooks/useMonitor' +import { formatRelative } from '@/lib/monitorFormat' +import { cn } from '@/lib/utils' +import type { MonitorIdentity } from '@/types/monitor' + +/** + * 多身份(登录态)管理。 + * + * **这里做的是串行分片,不是并行提速。** 抖音按「账号 + IP + 指纹」联合判定,同一个 + * 出口 IP 上并发多个 cookie,比单账号高频请求更容易被判成异常 —— 平台视角是一台设备 + * 在不停换访客。所以默认一次只跑一个身份,把目标分给不同账号,降低单个账号的请求量。 + * + * 卡片上那句提醒是刻意留在界面上的:这个功能的收益和风险都很容易被误解。 + */ +const STATUS: Record< + MonitorIdentity['status'], + { label: string; className: string } +> = { + ok: { + label: '可用', + className: 'border-cyber-neon-green/40 bg-cyber-neon-green/10 text-cyber-neon-green', + }, + cooldown: { + label: '冷却中', + className: + 'border-cyber-neon-orange/40 bg-cyber-neon-orange/10 text-cyber-neon-orange', + }, + expired: { + label: '已失效', + className: 'border-cyber-neon-pink/40 bg-cyber-neon-pink/10 text-cyber-neon-pink', + }, + disabled: { + label: '已停用', + className: 'border-cyber-border-DEFAULT text-cyber-text-muted', + }, +} + +function clockText(ms: number): string { + return new Date(ms).toLocaleTimeString('zh-CN', { + hour: '2-digit', + minute: '2-digit', + }) +} + +export function IdentityPanel() { + const { data: identities, isLoading } = useMonitorIdentities() + const create = useCreateIdentity() + const update = useUpdateIdentity() + const remove = useDeleteIdentity() + const check = useCheckIdentity() + + const [adding, setAdding] = useState(false) + const [label, setLabel] = useState('') + const [cookie, setCookie] = useState('') + const [userAgent, setUserAgent] = useState('') + + const submit = () => { + const name = label.trim() + const value = cookie.trim() + if (!name || !value) return + create.mutate( + { label: name, cookie: value, user_agent: userAgent.trim() }, + { + onSuccess: () => { + setLabel('') + setCookie('') + setUserAgent('') + setAdding(false) + }, + }, + ) + } + + return ( +
+
+ + + 多身份(分片采集) + +
+ +

+ 多个登录态 + 串行分片 + :把博主打散给不同账号,降低单个账号每轮的请求量 —— 这不是并行提速。 + 同一个出口 IP 上并发多个账号,比单账号高频更容易被风控,所以默认一次只跑一个身份。 + 采集策略里的「多身份采集」要选 pool + 才会生效。 +

+ +
+ {isLoading && ( +

加载中…

+ )} + {identities?.length === 0 && ( +

+ 还没有身份。在下面加一条:名称 + 该账号的完整 Cookie。 +

+ )} + + {identities?.map((identity) => { + const status = STATUS[identity.status] + const cooling = + identity.cooldown_until !== null && identity.cooldown_until > Date.now() + return ( +
+ + {identity.label} + + + {status.label} + + + {identity.last_ok_at + ? `最近成功 ${formatRelative(identity.last_ok_at)}` + : '还没成功过'} + + {cooling && identity.cooldown_until !== null && ( + + 冷却到 {clockText(identity.cooldown_until)} + + )} + {identity.last_error && ( + + {identity.last_error} + + )} +
+ + + +
+
+ ) + })} +
+ + {adding ? ( +
+ setLabel(event.target.value)} + placeholder="名称,比如「小号A」" + className="w-full rounded border border-cyber-border-DEFAULT bg-cyber-bg-tertiary px-1.5 py-0.5 text-[11px] font-mono text-cyber-text-primary outline-none focus:border-cyber-neon-cyan/40" + /> +