修复(斗鱼绑定): 修复工作台换绑识别与轮询并发合入

This commit is contained in:
yml
2026-11-26 09:52:22 +08:00
parent 91e4f5d33a
commit 5a1552915e
3 changed files with 458 additions and 22 deletions
+271
View File
@@ -21,6 +21,7 @@ from web.backend.services import (
douyu_service,
payment_poll_scheduler,
)
from web.backend.services.account_binding import pending_binding_role_from_result
from web.backend.services.douyu_role_audit import record_role_api_candidates
from web.backend.services.douyu_runner import DouyuBatchRunner
from web.backend.services.douyu_runner_bind import bind_poll_interval_seconds
@@ -1403,6 +1404,276 @@ def test_binding_poll_accepts_unchanged_existing_action_alias_pending(
assert task.result["bind_decision"]["reason"] == "existing_actionable_pending"
def test_workbench_rebind_detects_new_cjm_scan_without_expected_role(
db, monkeypatch
):
"""HAR 11.22 用户中心换绑:已绑定账号发码后只有 cjm 变化,工作台轮询也必须识别。"""
_, account, task = _fixtures(db, status="running")
bound_activity = {
"act_alias": "20260120QYOOB",
"role_name": "Dollh",
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
"change_role_wait_time": 0,
"can_change_time": 1_790_006_400,
"can_change_role": 1,
}
stale_legacy = {
"act_alias": "cjm",
"role_name": "历史残留角色",
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": False,
"need_bind_act": False,
"need_bind_role": True,
"change_role_wait_time": 0,
"can_change_time": 0,
"can_change_role": 0,
}
scanned_legacy = {
**stale_legacy,
"role_name": "巫师基尔斯84",
}
stage = {"candidates": [stale_legacy, bound_activity]}
client = type(
"Client",
(),
{"get_bind_qr": lambda self, _alias: {"url": "https://example.test/qr"}},
)()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: client)
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda _client, aliases: [
item
for alias in aliases
for item in stage["candidates"]
if item["act_alias"] == alias
],
)
config = {
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
}
# 1. 发码前已有旧 cjm 残留:必须留在 waiting_scan,不能误认成本次扫码角色
runner._execute_get_bind_qr(db, task, account, "PHPSESSID=x", config)
db.refresh(task)
assert task.status == "running"
assert task.result["bind_phase"] == "waiting_scan"
# 2. 第一轮轮询仍未扫码:继续等待
runner.poll_bind_role_once(db, task, account, config)
db.refresh(task)
assert task.status == "running"
assert task.result["bind_phase"] == "waiting_scan"
# 3. 客户扫码后仅 cjm 变成新角色,20260120QYOOB 仍返回 Dollh
stage["candidates"] = [scanned_legacy, bound_activity]
runner.poll_bind_role_once(db, task, account, config)
db.refresh(task)
assert task.status == "success"
assert task.result["bind_phase"] == "role_ready"
assert task.result["role_name"] == "巫师基尔斯84"
assert task.result["current_role_name"] == "Dollh"
assert task.result["allow_legacy_pending"] is True
assert pending_binding_role_from_result(task.result) == "巫师基尔斯84"
def test_binding_poll_preserves_concurrently_written_expected_role(
db, monkeypatch
):
"""轮询写回 task.result 时,不能覆盖客户并发提交进来的 expected_role_name。"""
_, account, task = _fixtures(db, status="running")
task.queue_lane = "binding_poll"
task.next_run_at = datetime.now(UTC)
task.run_deadline_at = datetime.now(UTC) + timedelta(minutes=10)
bound_activity = {
"act_alias": "20260120QYOOB",
"role_name": "Dollh",
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
"change_role_wait_time": 0,
"can_change_time": 1_790_006_400,
"can_change_role": 1,
}
scanned_legacy = {
"act_alias": "cjm",
"role_name": "吃鸡199706",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": False,
"need_bind_act": False,
"need_bind_role": True,
"change_role_wait_time": 0,
"can_change_time": 0,
"can_change_role": 0,
}
task.result = {
"url": "https://example.test/qr",
"query_act_aliases": ["cjm", "20260120QYOOB"],
"baseline_role_name": "Dollh",
"baseline_is_bound_act": True,
"before_bind_info": bound_activity,
"expected_role_required": True,
"bind_poll_initial_legacy_snapshot": {
"role_name": "",
"area_name": "",
"plat_name": "",
"is_bound_act": False,
"is_bound_role": False,
"need_bind_act": False,
"need_bind_role": True,
},
"bind_poll_legacy_snapshot": {
"role_name": "",
"area_name": "",
"plat_name": "",
"is_bound_act": False,
"is_bound_role": False,
"need_bind_act": False,
"need_bind_role": True,
},
"bind_polling": True,
"qr_generated_at": datetime.now(UTC).isoformat(),
}
db.commit()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: object())
def fetch_and_simulate_concurrent_profile(_client, aliases):
# 模拟客户资料接口在网络查询窗口内并发提交 expected_role_name
with make_test_session() as other_db:
other_task = other_db.get(DouyuTask, task.id)
updated = dict(other_task.result or {})
updated["expected_role_name"] = "吃鸡199706"
updated["expected_role_required"] = True
other_task.result = updated
other_db.commit()
return [
item
for alias in aliases
for item in (scanned_legacy, bound_activity)
if item["act_alias"] == alias
]
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
fetch_and_simulate_concurrent_profile,
)
runner.poll_bind_role_once(
db,
task,
account,
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
assert task.status == "success"
assert task.result["expected_role_name"] == "吃鸡199706"
assert task.result["role_name"] == "吃鸡199706"
assert task.result["bind_phase"] == "role_ready"
def test_confirm_bind_skips_act_bind_when_action_alias_already_bound_to_expected(
db, monkeypatch
):
"""目标角色已在动作 alias 生效(bindAct=1)时,不再重复调 actBind。"""
_, account, task = _fixtures(db, status="running")
target = "狗鼻子弗尼亚bd"
task.task_type = "confirm_bind"
task.result = {
"expected_role_name": target,
"expected_role_required": True,
}
db.commit()
bound_activity = {
"act_alias": "20260120QYOOB",
"role_name": target,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
}
cjm_same = {
**bound_activity,
"act_alias": "cjm",
"is_bound_act": False,
"need_bind_act": False,
}
class Client:
@staticmethod
def confirm_bind(_alias):
raise AssertionError("目标角色已生效时不应重复调用 actBind")
runner = DouyuBatchRunner(
db,
task.batch_id,
"confirm_bind",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: Client())
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda *_args: [cjm_same, bound_activity],
)
runner._execute_confirm_bind(
db,
task,
account,
"PHPSESSID=x",
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
assert task.status == "success"
assert task.result["bind_confirmed"] is True
assert task.result["role_name"] == target
def test_active_task_budget_rejects_new_batch(db, monkeypatch):
user = User(username="budget-user", password_hash="hash", role="operation")
db.add(user)
+17
View File
@@ -617,6 +617,22 @@ def resolve_binding_candidates(
if str(info.get("act_alias") or "").strip() in aliases
and str(info.get("role_name") or "").strip()
}
if effective_baseline is not None:
baseline_alias = str(
effective_baseline.get("act_alias")
or effective_baseline.get("alias")
or ""
).strip()
baseline_role = str(
binding_snapshot(effective_baseline)["role_name"] or ""
).strip()
if baseline_alias in aliases and baseline_role:
action_roles.add(baseline_role)
if effective_baseline_role and (
effective_baseline_bound
or str((effective_baseline or {}).get("act_alias") or "").strip() in aliases
):
action_roles.add(effective_baseline_role)
expected = str(expected_role_name or "").strip().casefold()
if action_roles and not allow_legacy_pending:
for info, decision in zip(ordered, decisions, strict=True):
@@ -733,6 +749,7 @@ def pending_binding_role_from_result(result: dict[str, Any] | None) -> str:
and selected_alias not in action_alias_set
and action_evidence
and not expected_matches
and not bool(result.get("allow_legacy_pending"))
):
# legacy(cjm) 可能返回同一斗鱼账号历史绑过的另一个游戏角色。
# 动作 alias 仍有明确角色时,只有与客户目标一致的 legacy 角色可以进入
+170 -22
View File
@@ -346,6 +346,33 @@ class BindMixin:
f"{pending_text}"
)
@staticmethod
def _decision_for_candidate(
candidate: dict[str, Any] | None,
candidate_decisions: list[dict[str, Any]],
*,
baseline_role_name: str = "",
baseline_is_bound_act: bool = False,
baseline_info: dict | None = None,
actionable_aliases: list[str] | tuple[str, ...] = (),
expected_role_name: str = "",
require_expected_role: bool = False,
) -> dict[str, Any]:
"""从多渠道仲裁明细中取候选判定,避免单候选重判绕过跨 alias 规则。"""
alias = str((candidate or {}).get("act_alias") or "").strip()
for decision in candidate_decisions:
if str(decision.get("alias") or "").strip() == alias:
return dict(decision)
return binding_pending_decision(
candidate,
baseline_role_name=baseline_role_name,
baseline_is_bound_act=baseline_is_bound_act,
baseline_info=baseline_info,
actionable_aliases=actionable_aliases,
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
)
def _binding_candidate_decisions(
self,
candidates: list[dict],
@@ -356,8 +383,14 @@ class BindMixin:
actionable_aliases: list[str] | tuple[str, ...] = (),
expected_role_name: str = "",
require_expected_role: bool = False,
allow_legacy_pending: bool | None = None,
) -> list[dict[str, Any]]:
"""按同一规则解释每个 actAlias 候选,供任务结果和日志复盘。"""
effective_allow_legacy = (
bool(expected_role_name)
if allow_legacy_pending is None
else bool(allow_legacy_pending)
)
return resolve_binding_candidates(
candidates,
baseline_role_name=baseline_role_name,
@@ -367,7 +400,7 @@ class BindMixin:
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
prefer_aliases=actionable_aliases,
allow_legacy_pending=bool(expected_role_name),
allow_legacy_pending=effective_allow_legacy,
)["decisions"]
def _push_binding_decision_log(
@@ -609,6 +642,7 @@ class BindMixin:
actionable_aliases: list[str] | tuple[str, ...] = (),
expected_role_name: str = "",
require_expected_role: bool = False,
allow_legacy_pending: bool | None = None,
) -> dict | None:
"""从多个 alias 结果里挑最有用的绑定信息。
@@ -630,6 +664,7 @@ class BindMixin:
actionable_aliases=actionable_aliases,
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
allow_legacy_pending=allow_legacy_pending,
)
if pending is not None:
return pending
@@ -671,12 +706,18 @@ class BindMixin:
actionable_aliases: list[str] | tuple[str, ...] = (),
expected_role_name: str = "",
require_expected_role: bool = False,
allow_legacy_pending: bool | None = None,
) -> dict | None:
"""唯一的新角色候选选择入口。
“是否 pending”只调用 ``_is_pending_role``;二维码轮询、查询角色和换绑
时间查询都从这里选候选,避免各自用角色名或 bindRole 再写一套判断。
"""
effective_allow_legacy = (
bool(expected_role_name)
if allow_legacy_pending is None
else bool(allow_legacy_pending)
)
return resolve_binding_candidates(
candidates,
baseline_role_name=baseline_role_name,
@@ -686,7 +727,7 @@ class BindMixin:
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
prefer_aliases=prefer_aliases or [],
allow_legacy_pending=bool(expected_role_name),
allow_legacy_pending=effective_allow_legacy,
)["selected"]
def _pick_current_bound_info(
@@ -923,6 +964,52 @@ class BindMixin:
task.next_run_at = now + timedelta(seconds=max(1, interval_seconds))
task.last_run_at = now
@staticmethod
def _merge_latest_expected_role(
db: Session,
task: DouyuTask,
result: dict[str, Any],
) -> tuple[str, bool]:
"""读取数据库最新目标角色,避免轮询写回 task.result 时覆盖并发更新。"""
task_id = getattr(task, "id", None)
latest = (
db.query(DouyuTask.result)
.filter(DouyuTask.id == task_id)
.with_for_update()
.scalar()
if task_id is not None
else None
)
latest_dict = latest if isinstance(latest, dict) else {}
latest_payload = (
latest_dict.get("payload")
if isinstance(latest_dict.get("payload"), dict)
else {}
)
current_payload = (
result.get("payload")
if isinstance(result.get("payload"), dict)
else {}
)
expected_role_name = str(
latest_dict.get("expected_role_name")
or latest_payload.get("expected_role_name")
or result.get("expected_role_name")
or current_payload.get("expected_role_name")
or ""
).strip()
require_expected_role = bool(
result.get("expected_role_required")
or current_payload.get("expected_role_required")
or latest_dict.get("expected_role_required")
or latest_payload.get("expected_role_required")
or task.platform_task_id
)
if expected_role_name:
result["expected_role_name"] = expected_role_name
result["expected_role_required"] = require_expected_role
return expected_role_name, require_expected_role
def poll_bind_role_once(
self,
db: Session,
@@ -932,8 +1019,10 @@ class BindMixin:
) -> None:
"""Run one scheduled binding poll and immediately release the worker."""
now = datetime.now(UTC)
task.last_run_at = now
task.attempt_count = int(task.attempt_count or 0) + 1
# 先只读取出网络轮询所需字段,避免提前脏写 task 触发 autoflush
# 在外部 HTTP 请求期间长持 douyu_tasks 行锁,阻塞客户资料并发写入。
cookie = str(account.cookie or "")
next_attempt_count = int(task.attempt_count or 0) + 1
result = dict(task.result or {})
expected_role_name = str(result.get("expected_role_name") or "").strip()
require_expected_role = bool(
@@ -961,6 +1050,7 @@ class BindMixin:
)
def finish_timeout() -> None:
self._merge_latest_expected_role(db, task, result)
result.update(
{
"bind_polling": False,
@@ -968,6 +1058,8 @@ class BindMixin:
"bind_phase": "role_timeout",
}
)
task.last_run_at = now
task.attempt_count = next_attempt_count
task.queue_lane = ""
task.next_run_at = None
self._mark_task(
@@ -978,7 +1070,7 @@ class BindMixin:
result,
)
client = self._client(str(account.cookie or ""))
client = self._client(cookie)
primary_aliases, action_aliases_to_verify = self._split_bind_poll_aliases(
query_aliases,
config,
@@ -989,6 +1081,28 @@ class BindMixin:
result.get("bind_poll_legacy_snapshot"),
primary_info,
)
initial_legacy_snapshot = (
result.get("bind_poll_initial_legacy_snapshot")
if "bind_poll_initial_legacy_snapshot" in result
else result.get("bind_poll_legacy_snapshot")
)
legacy_changed_since_qr = bool(
result.get("bind_poll_legacy_observed_change")
) or (
primary_info is not None
and "bind_poll_initial_legacy_snapshot" in result
and self._bind_poll_snapshot_changed(
initial_legacy_snapshot,
primary_info,
)
) or (
primary_info is not None
and "bind_poll_initial_legacy_snapshot" not in result
and result.get("bind_poll_legacy_snapshot") is not None
and legacy_changed
)
if legacy_changed_since_qr:
result["bind_poll_legacy_observed_change"] = True
verify_action_alias = bool(
action_aliases_to_verify
and (
@@ -1037,6 +1151,9 @@ class BindMixin:
]
if primary_info is not None:
result["bind_poll_legacy_snapshot"] = self._bind_poll_snapshot(primary_info)
expected_role_name, require_expected_role = self._merge_latest_expected_role(
db, task, result
)
if not candidates:
if deadline is not None and datetime.now(UTC) >= deadline:
finish_timeout()
@@ -1044,6 +1161,8 @@ class BindMixin:
result["bind_poll_error"] = "所有 actAlias 查询绑定信息失败"
result["bind_polling"] = True
result["bind_phase"] = "waiting_scan"
task.last_run_at = now
task.attempt_count = next_attempt_count
self._schedule_next_bind_poll(
task,
now=now,
@@ -1065,6 +1184,9 @@ class BindMixin:
if not isinstance(baseline_info, dict):
baseline_info = None
action_aliases = self._action_act_aliases(config)
allow_legacy_pending = bool(expected_role_name) or (
not require_expected_role and legacy_changed_since_qr
)
bind_info = (
self._pick_bind_info(
candidates,
@@ -1076,6 +1198,7 @@ class BindMixin:
actionable_aliases=action_aliases,
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
allow_legacy_pending=allow_legacy_pending,
)
or candidates[0]
)
@@ -1088,9 +1211,11 @@ class BindMixin:
actionable_aliases=action_aliases,
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
allow_legacy_pending=allow_legacy_pending,
)
selected_decision = binding_pending_decision(
selected_decision = self._decision_for_candidate(
bind_info,
candidate_decisions,
baseline_role_name=baseline_role_name,
baseline_is_bound_act=baseline_is_bound_act,
baseline_info=baseline_info,
@@ -1144,6 +1269,8 @@ class BindMixin:
f"act={query_alias or '-'} "
f"{self._format_bind_summary(bind_info, pending=False)}"
)
task.last_run_at = now
task.attempt_count = next_attempt_count
task.queue_lane = ""
task.next_run_at = None
result.update(
@@ -1177,6 +1304,8 @@ class BindMixin:
return
if is_pending_role:
task.last_run_at = now
task.attempt_count = next_attempt_count
task.queue_lane = ""
task.next_run_at = None
result.update(
@@ -1191,9 +1320,18 @@ class BindMixin:
"pending_role_name": snapshot["role_name"],
"poll_count": poll_number,
"bind_summary": summary,
"bind_candidates": [
{
"act_alias": item.get("act_alias"),
"role_name": item.get("role_name"),
"is_bound_act": self._is_bound_act(item),
}
for item in candidates
],
"action_act_aliases": action_aliases,
"bind_decision": selected_decision,
"bind_candidate_decisions": candidate_decisions,
"allow_legacy_pending": allow_legacy_pending,
}
)
account.updated_at = now
@@ -1239,6 +1377,8 @@ class BindMixin:
if deadline is not None and datetime.now(UTC) >= deadline:
finish_timeout()
return
task.last_run_at = now
task.attempt_count = next_attempt_count
self._schedule_next_bind_poll(
task,
now=now,
@@ -1317,8 +1457,9 @@ class BindMixin:
expected_role_name=expected_role_name,
require_expected_role=require_expected_role,
)
pending_decision = binding_pending_decision(
pending_decision = self._decision_for_candidate(
pending_before,
candidate_decisions,
baseline_role_name=str(before.get("role_name") or ""),
baseline_is_bound_act=self._is_bound_act(before),
baseline_info=before,
@@ -1416,6 +1557,17 @@ class BindMixin:
)
qr_result = client.get_bind_qr(qr_act_alias)
qr_generated_at = datetime.now(UTC)
legacy_snapshot = self._bind_poll_snapshot(
next(
(
item
for item in before_candidates
if str(item.get("act_alias") or "")
== str(config.get("legacy_act_alias") or "")
),
None,
)
)
result = {
**qr_result,
"act_alias": qr_act_alias,
@@ -1443,17 +1595,8 @@ class BindMixin:
"bind_decision": pending_decision,
"bind_candidate_decisions": candidate_decisions,
"poll_count": 0,
"bind_poll_legacy_snapshot": self._bind_poll_snapshot(
next(
(
item
for item in before_candidates
if str(item.get("act_alias") or "")
== str(config.get("legacy_act_alias") or "")
),
None,
)
),
"bind_poll_initial_legacy_snapshot": legacy_snapshot,
"bind_poll_legacy_snapshot": legacy_snapshot,
}
# 2026-11-22 绑定成功 HAR:二维码生成前已经存在的 bindAct=0 角色
# 是官网认可的 pending,可以直接确认,不要求本轮再次出现状态迁移。
@@ -1671,9 +1814,13 @@ class BindMixin:
before_is_current_bound = (
before_bound is not None
and str(before.get("act_alias") or "")
== str(before_bound.get("act_alias") or "")
and role_name == str(before_bound.get("role_name") or "")
and role_name.casefold()
== str(before_bound.get("role_name") or "").strip().casefold()
and (
str(before.get("act_alias") or "")
== str(before_bound.get("act_alias") or "")
or bool(expected_role_name)
)
)
if before_is_current_bound and before_bound is not None:
self._apply_bind_info_to_account(account, before_bound, BIND_BOUND)
@@ -2174,6 +2321,7 @@ class BindMixin:
baseline_is_bound_act=baseline_is_bound_act,
baseline_info=baseline_info,
actionable_aliases=action_aliases,
allow_legacy_pending=True,
)
selected_decision = (
binding_pending_decision(
@@ -2204,7 +2352,7 @@ class BindMixin:
candidates=raw_candidates,
decisions=candidate_decisions,
selected=bind_info,
baseline_info=bind_info if isinstance(bind_info, dict) else None,
baseline_info=baseline_info,
actionable_aliases=action_aliases,
)
persist_probe_result(