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:
+184
-2
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user