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:
+149
-11
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user