feat(monitor): 抖音多身份池 —— 目标按登录态串行分片
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

把 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:
butubb
2026-10-22 16:37:12 +08:00
parent 4665dac667
commit d95e5ec8e2
15 changed files with 1402 additions and 65 deletions
+23 -23
View File
@@ -36,7 +36,7 @@ def fake_profile(monkeypatch):
用例再单独覆盖这个 fixture。
"""
async def _profile_call(sec_user_id, *, cookie=""):
async def _profile_call(sec_user_id, *, cookie="", identity=None):
return _profile()
monkeypatch.setattr(douyin_api, "author_profile", _profile_call)
@@ -99,10 +99,10 @@ async def _collect(tmp_path, **overrides):
class TestHappyPath:
@pytest.mark.asyncio
async def test_writes_the_layout_ingest_expects(self, monkeypatch, tmp_path):
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111"), _video("222")]
async def fake_comments(aweme_id, count=20, *, cookie=""):
async def fake_comments(aweme_id, count=20, *, cookie="", identity=None):
return [_comment(aweme_id, 1)]
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -140,7 +140,7 @@ class TestHappyPath:
两种情况的含义完全不同。
"""
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111")]
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -151,7 +151,7 @@ class TestHappyPath:
@pytest.mark.asyncio
async def test_duplicate_works_are_written_once(self, monkeypatch, tmp_path):
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111"), _video("111")]
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -175,7 +175,7 @@ class TestNoteMode:
async def must_not_be_called(*args, **kwargs):
raise AssertionError("作品模式不该去拉博主的作品列表")
async def fake_detail(aweme_id, *, cookie=""):
async def fake_detail(aweme_id, *, cookie="", identity=None):
return _video(aweme_id)
monkeypatch.setattr(douyin_api, "author_videos", must_not_be_called)
@@ -196,7 +196,7 @@ class TestNoteMode:
@pytest.mark.asyncio
async def test_a_broken_work_does_not_lose_the_others(self, monkeypatch, tmp_path):
async def flaky(aweme_id, *, cookie=""):
async def flaky(aweme_id, *, cookie="", identity=None):
if aweme_id == "222":
raise douyin_api.DouyinApiError("作品已被删除")
return _video(aweme_id)
@@ -219,12 +219,12 @@ class TestDegradation:
@pytest.mark.asyncio
async def test_falls_back_to_refreshing_known_works(self, monkeypatch, tmp_path):
async def blocked(sec_user_id, count=20, *, cookie=""):
async def blocked(sec_user_id, count=20, *, cookie="", identity=None):
raise douyin_api.DouyinApiError("接口返回了空内容")
refreshed = []
async def fake_detail(aweme_id, *, cookie=""):
async def fake_detail(aweme_id, *, cookie="", identity=None):
refreshed.append(aweme_id)
return _video(aweme_id, likes="9")
@@ -249,12 +249,12 @@ class TestDegradation:
Duplicate entry for key 'uq_note_metric')。
"""
async def blocked(sec_user_id, count=20, *, cookie=""):
async def blocked(sec_user_id, count=20, *, cookie="", identity=None):
raise douyin_api.DouyinApiError("接口返回了空内容")
calls = []
async def fake_detail(aweme_id, *, cookie=""):
async def fake_detail(aweme_id, *, cookie="", identity=None):
calls.append(aweme_id)
return _video(aweme_id)
@@ -273,7 +273,7 @@ class TestDegradation:
@pytest.mark.asyncio
async def test_nothing_at_all_still_reports_the_reason(self, monkeypatch, tmp_path):
async def blocked(sec_user_id, count=20, *, cookie=""):
async def blocked(sec_user_id, count=20, *, cookie="", identity=None):
raise douyin_api.DouyinApiError("接口返回了空内容")
monkeypatch.setattr(douyin_api, "author_videos", blocked)
@@ -287,10 +287,10 @@ class TestDegradation:
@pytest.mark.asyncio
async def test_a_failing_comment_fetch_does_not_lose_the_work(self, monkeypatch, tmp_path):
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111")]
async def broken_comments(aweme_id, count=20, *, cookie=""):
async def broken_comments(aweme_id, count=20, *, cookie="", identity=None):
raise douyin_api.DouyinApiError("评论接口抽风")
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -318,7 +318,7 @@ class TestCreatorProfile:
@pytest.mark.asyncio
async def test_the_profile_lands_in_the_run_dir(self, monkeypatch, tmp_path):
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111")]
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -336,11 +336,11 @@ class TestCreatorProfile:
而且是静默的:表里有数据,界面上什么都没有。
"""
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111")] # 作品带的哈希是 "hash"
# 资料接口自己算出来的是另一个值(比如它那边 uid 缺字段、只能拿 sec_uid 算)。
async def off_hash_profile(sec_user_id, *, cookie=""):
async def off_hash_profile(sec_user_id, *, cookie="", identity=None):
return _profile(creator_hash="另一个哈希")
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -355,10 +355,10 @@ class TestCreatorProfile:
async def test_a_profile_without_an_identity_is_dropped(self, monkeypatch, tmp_path):
"""哈希都算不出来的快照,落下去只会是一条谁也查不到的垃圾。"""
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return []
async def anonymous_profile(sec_user_id, *, cookie=""):
async def anonymous_profile(sec_user_id, *, cookie="", identity=None):
return _profile(creator_hash="")
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -373,10 +373,10 @@ class TestCreatorProfile:
async def test_a_failing_profile_does_not_lose_the_works(self, monkeypatch, tmp_path):
"""附加信息拿不到,这一轮采到的作品不能跟着判成失败。"""
async def fake_videos(sec_user_id, count=20, *, cookie=""):
async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None):
return [_video("111")]
async def broken_profile(sec_user_id, *, cookie=""):
async def broken_profile(sec_user_id, *, cookie="", identity=None):
raise douyin_api.DouyinApiError("资料接口抽风")
monkeypatch.setattr(douyin_api, "author_videos", fake_videos)
@@ -394,10 +394,10 @@ class TestCreatorProfile:
asked = []
async def fake_detail(aweme_id, *, cookie=""):
async def fake_detail(aweme_id, *, cookie="", identity=None):
return _video(aweme_id)
async def recording_profile(sec_user_id, *, cookie=""):
async def recording_profile(sec_user_id, *, cookie="", identity=None):
asked.append(sec_user_id)
return _profile()
+236
View File
@@ -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