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

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
+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(