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:
+99
-20
@@ -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 的「疑似登录失效」分支 —— 又骗人一次,正是这套东西一直在犯的毛病。
|
||||
|
||||
Reference in New Issue
Block a user