feat(monitor): 抖音多身份池 —— 目标按登录态串行分片
把 44 个博主打散给多个抖音号,降低**单个账号**每轮的请求量(约 35 个博主后开始
出现限流是已知现象)。**默认串行,不是并行**:同一个出口 IP 上并发多个 cookie,
平台视角是一台设备在不停换访客,比单账号高频更容易被判异常。并发数做成了设置项,
但要先给每个账号配独立出口 IP 再考虑调大。
新增:
* `monitor_identity` 表:label / source(stored|browser) / cookie / **user_agent** /
client_hints / status / enabled / 冷却字段。cookie 与 UA 必须成套存 —— a_bogus
把 UA 算进签名,空 UA 签出来的请求一定被挡。
* `api/monitor/identities.py`:可用性判定、解析、**Rendezvous Hashing 分片**
(加一个身份只迁移约 1/(n+1) 的目标)、健康状态与指数退避冷却。
* `douyin_api`:四个接口都接受显式 `identity`,走身份池时**不再回读浏览器**(否则
浏览器里的 cookie 会把指定账号顶掉);新增 `shared_fingerprint()` 给粘贴 cookie
的身份兜底 UA。
* `douyin_fetch.collect`:按身份分片执行,分片之间默认串行、可配切换间隔;落盘前
按 note_id 去重(并发时两个分片可能刷到同一件作品)。
* `runner`:池模式下加载身份、不足 `identity_min_available` 就快速失败(不产生请求),
结束后按各自分片结果回写健康。
* 设置项:identity_mode / identity_min_available / identity_switch_delay_sec /
identity_concurrency。
* API:GET/POST/PATCH/DELETE `/api/monitor/identities` + `/{id}/check`(真请求一次,
没有可探测博主时退化成格式检查并在 verified 里标 false)。
* 前端:设置页(仅抖音)新增「多身份(分片采集)」面板。
测试 9 条新增:分片确定性与覆盖、加身份只迁移一小部分、缺 UA/cookie 拒绝、
两次失败进冷却、成功清零、冷却中不可用、采集按身份分片。
This commit is contained in:
@@ -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,
|
||||
}
|
||||
Reference in New Issue
Block a user