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,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
|
||||
Reference in New Issue
Block a user