"""游戏角色绑定启动、确认与刷新。""" from __future__ import annotations import uuid from typing import Any from fastapi import HTTPException from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from starlette.concurrency import run_in_threadpool from ...models import ( Account, AccountLease, DouyuTask, PlatformFulfillmentEvent, PlatformFulfillmentTask, User, ) from ..account_binding import pending_binding_role_from_result from ..binding_ownership import ( BINDING_TASK_TYPES, fulfillment_lease_for_task, lease_is_active, role_names_match, source_created_within_lease, ) from ..business_events import record_douyu_task_started from ..douyu_binding import ( BINDING_OBSERVATION_TASK_TYPES, BINDING_VIEW_CONFIRMED, BINDING_VIEW_PENDING, resolve_douyu_binding, resolve_fulfillment_binding, ) from ..execution_jobs import ( JOB_DOUYU_BINDING, LANE_FULFILLMENT, enqueue_execution_job, ) from .binding_status import ( _binding_failure_issue, _binding_failure_raw_message, _customer_task_message, ) from .common import _now from .outbox import _emit_order_site_binding_state from .repository import ( _binding_qr_expired, _load_task, _load_task_for_update, ) from .role_lock import ( ACCOUNT_LOCK_ISSUE, ROLE_LOCK_ISSUE, AccountLock, RoleLock, find_account_lock, find_role_lock, ) from .runtime import ( _append_event, _apply_task_lease_policy, ) from .views import get_task_detail BINDING_SYNC_TASK_TYPES = frozenset( { "get_bind_qr", "query_game_name", "confirm_bind", "prepare_esports_bind", "query_esports_game_name", "confirm_esports_bind", "prepare_xpd_bind", "query_xpd_game_name", "confirm_xpd_bind", } ) PENDING_BINDING_TASK_TYPES = frozenset({"get_bind_qr"}) #: 订单仍可接收绑定证据的阶段。bound / completed / cancelled 一律冻结。 ACTIVE_BINDING_STATUSES = frozenset( { "not_started", "allocated", "preparing", "qr_pending", "waiting_bind", "role_ready", } ) #: 可以接受确认任务结算的阶段。 CONFIRMABLE_BINDING_STATUSES = frozenset({"role_ready", "confirming"}) #: 订单的权威绑定任务类型。查询任务只能展示,不能结算。 BINDING_EVIDENCE_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"}) assert BINDING_EVIDENCE_TASK_TYPES <= BINDING_TASK_TYPES def start_binding_sync( db: Session, *, task_id: int, current: User, force_refresh: bool = False, ) -> dict[str, Any]: task = _load_task_for_update(db, task_id) if not task.account_id or not task.lease_id: raise HTTPException(status_code=409, detail="请先分配账号") lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease is None or lease.status != "active": raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配") if task.bind_task_id: existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if existing is not None and existing.platform_task_id not in (None, int(task.id)): # 当前指针指向了别的订单的任务:当作没有绑定任务,重新出码。 existing = None if existing: binding = resolve_fulfillment_binding( existing, account=db.get(Account, int(task.account_id)), binding_status=task.binding_status, ) stale_pending = ( binding.reported_ready_for_confirm and not binding.bind_ready_for_confirm ) if binding.status in { BINDING_VIEW_CONFIRMED, BINDING_VIEW_PENDING, }: return get_task_detail(db, task.id) if existing.status in {"planned", "pending", "running"}: return get_task_detail(db, task.id) if ( existing.status == "success" and not _binding_qr_expired(existing) and not stale_pending ): return get_task_detail(db, task.id) if not force_refresh and existing.status not in { "success", "failed", "error", "stopped", }: return get_task_detail(db, task.id) batch_id = f"pfbind-{task.id}-{uuid.uuid4().hex[:8]}" bind_task = DouyuTask( batch_id=batch_id, account_id=task.account_id, account_assigned_to=current.id, task_type="get_bind_qr", handbook_scope="elite", status="planned", message="等待生成绑定二维码", result={"payload": {}}, created_by=current.id, platform_task_id=task.id, ) db.add(bind_task) try: db.flush() except IntegrityError: # The database uniqueness gate wins a race that started before either # request could acquire the fulfillment row lock. db.rollback() return get_task_detail(db, task_id) account = db.query(Account).filter(Account.id == task.account_id).first() if account is not None: record_douyu_task_started( db, account, task_id=int(bind_task.id), task_type="get_bind_qr", task_label="获取绑定二维码", scope="elite", actor_id=current.id, ) task.bind_task_id = bind_task.id task.binding_status = "preparing" task.execution_status = "waiting_bind" task.issue_code = "" task.last_error = "" task.operator_id = current.id task.updated_at = _now() _apply_task_lease_policy(db, task, lease=lease) _append_event( db, task.id, "binding_started", actor_type="user", actor_id=current.id, detail={"bindTaskId": bind_task.id}, ) _emit_order_site_binding_state(db, task.id) enqueue_execution_job( db, job_type=JOB_DOUYU_BINDING, lane_scope=LANE_FULFILLMENT, batch_id=batch_id, payload={ "task_type": "get_bind_qr", "payload": {}, "concurrency": 1, }, created_by=int(current.id), priority=10, max_attempts=2, ) db.commit() return get_task_detail(db, task.id) async def start_binding( db: Session, *, task_id: int, current: User, force_refresh: bool = False, ) -> dict[str, Any]: """Run the blocking DB/network dispatch path outside the ASGI event loop.""" return await run_in_threadpool( start_binding_sync, db, task_id=task_id, current=current, force_refresh=force_refresh, ) def _frozen(task: PlatformFulfillmentTask) -> bool: """已结束或已绑定的订单不再接受绑定证据回写。""" return ( task.execution_status in {"completed", "cancelled"} or task.binding_status == "bound" ) def _lease_for_task( db: Session, task: PlatformFulfillmentTask, ) -> AccountLease | None: return fulfillment_lease_for_task(db, task) def _actionable_pending_role( result: dict[str, Any] | None, role_name: str, ) -> str: """只有动作 alias 上的 pending 才能作为订单目标。 cjm/legacy 上先出现的角色只能提示,不能直接确认;否则 actBind 会对 QYOOB 调一个未生效的 pending(11.22 抓包 -200001 的根因)。 """ role = str(role_name or "").strip() if not role or not isinstance(result, dict): return "" raw_aliases = result.get("action_act_aliases") action_aliases = ( [str(value).strip() for value in raw_aliases if str(value).strip()] if isinstance(raw_aliases, (list, tuple)) else [] ) selected_alias = str(result.get("act_alias") or "").strip() if action_aliases and selected_alias and selected_alias not in action_aliases: return "" return role def _pending_role_of(task: DouyuTask | None) -> str: if task is None or not isinstance(task.result, dict): return "" return _actionable_pending_role( task.result, pending_binding_role_from_result(task.result), ) def _owned_binding_tasks( db: Session, task: PlatformFulfillmentTask, *, newer_than: int = 0, ) -> list[DouyuTask]: if not task.account_id: return [] return ( db.query(DouyuTask) .filter( DouyuTask.platform_task_id == int(task.id), DouyuTask.account_id == int(task.account_id), DouyuTask.handbook_scope == "elite", DouyuTask.task_type.in_(BINDING_EVIDENCE_TASK_TYPES), DouyuTask.id > int(newer_than), ) .order_by(DouyuTask.id.desc()) .limit(8) .all() ) def _order_target_role( db: Session, task: PlatformFulfillmentTask, *, before_task_id: int | None = None, ) -> str: """订单本次要绑定的目标角色。 优先取当前绑定任务;当前任务已经是确认任务时,从订单自己更新的绑码任务里回看。 只用带订单归属的任务,不看账号历史。 """ current = ( db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None ) role = _pending_role_of(current) if role: return role for row in _owned_binding_tasks(db, task): if before_task_id is not None and int(row.id) >= int(before_task_id): continue if row.status != "success": continue role = _pending_role_of(row) if role: return role return "" def _record_binding_rejection( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, reason: str, confirmed_role: str = "", target_role: str = "", ) -> None: """记录一条不采纳的绑定证据;不改变订单状态,供时间线排查。""" exists = ( db.query(PlatformFulfillmentEvent.id) .filter( PlatformFulfillmentEvent.task_id == int(task.id), PlatformFulfillmentEvent.event_type == "binding_sync_rejected", PlatformFulfillmentEvent.detail_json["sourceTaskId"].as_integer() == int(source.id), ) .first() ) if exists is not None: return _append_event( db, task.id, "binding_sync_rejected", detail={ "sourceTaskId": int(source.id), "sourceTaskType": str(source.task_type or ""), "reason": reason, "confirmedRoleName": confirmed_role[:128], "targetRoleName": target_role[:128], "bindingStatus": task.binding_status, "executionStatus": task.execution_status, }, ) def _mark_role_locked( db: Session, task: PlatformFulfillmentTask, source: DouyuTask | None, lock: RoleLock, ) -> bool: """角色 7 天内已绑定其他账号:转人工,不调 actBind。""" if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False message = lock.message() lease = _lease_for_task(db, task) if source is not None and int(source.id) > int(task.bind_task_id or 0): # 保留本次待确认任务,详情/时间线能看到尝试的角色;状态已转人工, # 不会因为 bind_task_id 变化被自动推回 role_ready。 task.bind_task_id = int(source.id) task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = ROLE_LOCK_ISSUE task.last_error = message task.updated_at = _now() detail = { "roleName": lock.role_name, "roleLockAccountId": lock.account_id, "roleLockAccountName": lock.account_name, "roleLockBoundAt": lock.bound_at.isoformat(), "roleLockReusableAt": lock.reusable_at.isoformat(), "roleLockLeasePurpose": lock.lease_purpose, "roleLockLeaseBatchId": lock.lease_batch_id, "allocatedAccountId": task.account_id, "message": message, } if source is not None: detail["sourceTaskId"] = int(source.id) detail["sourceTaskType"] = str(source.task_type or "") _append_event(db, task.id, "binding_role_locked_elsewhere", detail=detail) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _mark_account_locked( db: Session, task: PlatformFulfillmentTask, source: DouyuTask | None, lock: AccountLock, ) -> bool: """当前分配的账号 7 天内绑过别的角色:转人工,不调 actBind。""" if str(task.issue_code or "") == ACCOUNT_LOCK_ISSUE: return False message = lock.message() lease = _lease_for_task(db, task) if source is not None and int(source.id) > int(task.bind_task_id or 0): task.bind_task_id = int(source.id) task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = ACCOUNT_LOCK_ISSUE task.last_error = message task.updated_at = _now() detail = { "accountRoleName": lock.role_name, "accountBoundAt": lock.bound_at.isoformat(), "accountReusableAt": lock.reusable_at.isoformat(), "allocatedAccountId": task.account_id, "allocatedAccountName": lock.account_name, "message": message, } if source is not None: detail["sourceTaskId"] = int(source.id) detail["sourceTaskType"] = str(source.task_type or "") _append_event(db, task.id, "binding_account_locked_elsewhere", detail=detail) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _block_on_account_lock( db: Session, task: PlatformFulfillmentTask, role_name: str, source: DouyuTask | None = None, ) -> bool: if str(task.issue_code or "") == ACCOUNT_LOCK_ISSUE: return False lock = find_account_lock(db, task.account_id, role_name) if lock is None: return False return _mark_account_locked(db, task, source, lock) def _block_on_role_lock( db: Session, task: PlatformFulfillmentTask, role_name: str, source: DouyuTask | None = None, ) -> bool: """角色已绑在别的账号上时,把订单转人工;返回是否拦截。""" if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False lock = find_role_lock( db, role_name, current_account_id=task.account_id, ) if lock is None: return False return _mark_role_locked(db, task, source, lock) def _apply_binding_qr_display( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, owned: bool, is_current: bool, phase: str, lease: AccountLease, ) -> bool: """运行中/成功的绑码任务只推进二维码展示,不推进角色状态。""" result = source.result if isinstance(source.result, dict) else {} qr_url = str(result.get("url") or "") if not qr_url or phase == "confirming": return False if not (is_current or (owned and phase in ACTIVE_BINDING_STATUSES)): return False if task.binding_status == "qr_pending" and int(task.bind_task_id or 0) == int( source.id ): return False task.bind_task_id = int(source.id) task.binding_status = "qr_pending" task.execution_status = "waiting_bind" task.issue_code = "" task.last_error = "" task.updated_at = _now() _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _same_pair_reuse_role( result: dict[str, Any] | None, account: Account | None, ) -> str: """本次扫码角色已经绑在当前账号上:同一对,直接复用。 只认 **cjm/legacy 上出现的扫码角色**,并且要求动作 alias 上也是同一个 角色且 bindAct=1。动作 alias 上只要出现 bindAct=0 的 pending,就说明客户 扫的是新角色,必须走正常确认,不能复用旧角色。 """ if not isinstance(result, dict) or account is None: return "" if str(account.role_bind_status or "") != "bound": return "" current = str(account.game_name or "").strip() if not current: return "" raw_aliases = result.get("action_act_aliases") action_aliases = ( [str(value).strip() for value in raw_aliases if str(value).strip()] if isinstance(raw_aliases, (list, tuple)) else [] ) candidates = [ raw for raw in (result.get("bind_candidates") or []) if isinstance(raw, dict) ] action_candidates = [ raw for raw in candidates if str(raw.get("act_alias") or raw.get("alias") or "").strip() in action_aliases ] if any( str(raw.get("role_name") or "").strip() and not bool(raw.get("is_bound_act")) for raw in action_candidates ): # 动作 alias 上已有新的 pending:客户扫了新角色,交给正常确认。 return "" selected_alias = str(result.get("act_alias") or "").strip() legacy_role = next( ( str(raw.get("role_name") or "").strip() for raw in candidates if str(raw.get("act_alias") or raw.get("alias") or "").strip() not in action_aliases and str(raw.get("role_name") or "").strip() ), "", ) if selected_alias and selected_alias in action_aliases: scanned_role = legacy_role else: scanned_role = str( result.get("pending_role_name") or result.get("role_name") or legacy_role or "" ).strip() if not scanned_role or scanned_role != current: return "" if action_candidates: action_bound = any( str(raw.get("role_name") or "").strip() == current and bool(raw.get("is_bound_act")) for raw in action_candidates ) return current if action_bound else "" if ( (not action_aliases or selected_alias not in action_aliases) and str(result.get("current_role_name") or "").strip() == current ): return current return "" def _mark_reused_pair( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, role_name: str, account: Account | None, ) -> bool: lease = _lease_for_task(db, task) task.bind_task_id = int(source.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_reused_existing_pair", detail={ "roleName": role_name[:128], "accountId": task.account_id, "accountName": ( (account.nickname or account.username) if account is not None else "" ), "sourceTaskId": int(source.id), "sourceTaskType": str(source.task_type or ""), "reason": "same_account_same_role", }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True def _apply_binding_task( db: Session, task: PlatformFulfillmentTask, source: DouyuTask, *, owned: bool, ) -> bool: """把一条绑定任务合并进订单状态。 ``owned=True``:任务带 ``platform_task_id == task.id``,是订单自己的证据; ``owned=False``:只允许订单当前已经挂着的任务(兼容旧数据)。 """ if _frozen(task): return False if str(task.issue_code or "") in {ROLE_LOCK_ISSUE, ACCOUNT_LOCK_ISSUE}: # 7 天锁只能由人工重置后重新进入流程。 return False if not task.account_id or not source.account_id: return False if int(source.account_id) != int(task.account_id): return False if str(source.handbook_scope or "") != "elite": return False lease = _lease_for_task(db, task) if not lease_is_active(lease): return False if not owned and not source_created_within_lease(lease, source): return False if ( not owned and source.platform_task_id is not None and int(source.platform_task_id) != int(task.id) ): # 明确属于另一张订单的任务,不能写到本单。 return False phase = str(task.binding_status or "") is_current = bool(task.bind_task_id) and int(task.bind_task_id) == int(source.id) if not owned and not is_current: return False if not is_current and int(source.id) < int(task.bind_task_id or 0): return False account = db.get(Account, int(task.account_id)) if str(source.task_type or "") == "get_bind_qr" and phase != "confirming": reused_role = _same_pair_reuse_role(source.result, account) if reused_role: return _mark_reused_pair( db, task, source, role_name=reused_role, account=account, ) binding = resolve_fulfillment_binding( source, account=account, binding_status=phase, ) result = source.result if isinstance(source.result, dict) else {} previous_bind_task_id = task.bind_task_id if source.status in {"failed", "error", "stopped"}: # 只有订单当前挂着的任务失败才允许判失败;工作台额外任务失败不能打死订单。 if not is_current: return False if phase not in ACTIVE_BINDING_STATUSES | {"confirming", "failed"}: return False issue_code = _binding_failure_issue(source, result) if ( task.binding_status == "failed" and task.issue_code == issue_code and int(task.bind_task_id or 0) == int(source.id) ): return False task.binding_status = "failed" task.execution_status = "manual_required" task.issue_code = issue_code task.last_error = _customer_task_message(task) task.updated_at = _now() _append_event( db, task.id, "binding_failed", detail={ "issueCode": task.issue_code, "bindTaskId": int(source.id), "bindPhase": str(result.get("bind_phase") or ""), "rawError": _binding_failure_raw_message( task.issue_code, result, fallback=str(source.message or ""), )[:1000], }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True if source.status != "success": # 运行中的绑码任务可以展示二维码,但不能据此推进角色/结算。 return _apply_binding_qr_display( db, task, source, owned=owned, is_current=is_current, phase=phase, lease=lease, ) if binding.status == BINDING_VIEW_CONFIRMED: confirmed_role = binding.confirmed_role_name target_role = _order_target_role( db, task, before_task_id=int(source.id) if source.task_type == "confirm_bind" else None, ) if is_current: # 订单自己的当前任务(订单创建的或兼容路径挂上的)回查到 bindAct=1。 # 查询类任务不会走到这里:resolve_fulfillment_binding 会把观测降级。 accepted = source.task_type in BINDING_EVIDENCE_TASK_TYPES elif not owned: accepted = False elif phase == "confirming": # 订单已经在确认中,只认它自己当前那条确认任务。 accepted = False elif source.task_type == "confirm_bind": accepted = ( phase in CONFIRMABLE_BINDING_STATUSES and bool(target_role) and role_names_match(confirmed_role, target_role) ) else: # 订单自己的绑码任务直接被官网确认:有目标时必须一致,无目标视为全新绑定。 accepted = phase in ACTIVE_BINDING_STATUSES and ( not target_role or role_names_match(confirmed_role, target_role) ) if not accepted: _record_binding_rejection( db, task, source, reason=( "target_mismatch" if target_role and not role_names_match(confirmed_role, target_role) else "untrusted_confirmation" ), confirmed_role=confirmed_role, target_role=target_role, ) return False task.bind_task_id = int(source.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_confirmed", detail={ "bindTaskId": int(source.id), "previousBindTaskId": previous_bind_task_id, "sourceTaskType": str(source.task_type or ""), "baselineRoleName": str( result.get("baseline_role_name") or result.get("current_role_name") or "" )[:128], "targetRoleName": target_role[:128], "confirmedRoleName": confirmed_role[:128], "confirmedChannel": binding.confirmed_channel, }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True if binding.status == BINDING_VIEW_PENDING: role_name = binding.pending_role_name if not role_name: return False if not _actionable_pending_role(source.result, role_name): # cjm/legacy 先出现的新角色:订单继续保持等待动作通道。 return False if phase == "confirming": # 确认任务执行中,后到的扫码结果不能把订单打回待确认、丢掉确认任务指针。 return False if not is_current and phase not in ACTIVE_BINDING_STATUSES: return False if ( task.binding_status == "role_ready" and int(task.bind_task_id or 0) == int(source.id) and not task.issue_code and not task.last_error ): return False if _block_on_role_lock(db, task, role_name, source): return True if _block_on_account_lock(db, task, role_name, source): return True task.bind_task_id = int(source.id) task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = "" task.updated_at = _now() if previous_bind_task_id != source.id: _append_event( db, task.id, "binding_pending_task_linked", detail={ "bindTaskId": int(source.id), "previousBindTaskId": previous_bind_task_id, "roleName": role_name[:128], "source": "owned" if owned else "legacy-current", }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) return True if ( is_current and str(source.task_type or "") == "get_bind_qr" and bool(result.get("bind_ready_for_confirm")) and not _pending_role_of(source) ): # 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针,让客户页重新出码。 task.bind_task_id = None task.binding_status = "not_started" task.execution_status = "allocated" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_stale_role_ignored", detail={ "bindTaskId": int(source.id), "previousBindTaskId": previous_bind_task_id, "roleName": str(result.get("role_name") or "")[:100], "baselineRoleName": str( result.get("baseline_role_name") or result.get("current_role_name") or "" )[:100], }, ) _emit_order_site_binding_state(db, task.id) _apply_task_lease_policy(db, task, lease=lease) return True return _apply_binding_qr_display( db, task, source, owned=owned, is_current=is_current, phase=phase, lease=lease, ) def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]: """从订单当前挂着的绑定任务刷新订单状态。 只消费订单自己的证据:当前 ``bind_task_id`` 指向的任务、以及显式带 ``platform_task_id`` 的任务。账号上的其它任务不能改写订单。 """ task = _load_task(db, task_id) if _frozen(task): return get_task_detail(db, task.id) if task.binding_status in ACTIVE_BINDING_STATUSES: latest_pending = _latest_pending_binding_task(db, task) if latest_pending is not None and _attach_pending_binding_task( db, task, latest_pending, ): db.commit() task = _load_task(db, task.id) if not task.bind_task_id: return get_task_detail(db, task.id) bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == int(task.bind_task_id)).first() ) if bind_task is None: return get_task_detail(db, task.id) if bind_task.platform_task_id not in (None, int(task.id)): # 数据异常:当前指针指向了别的订单的任务。只记录,不据此改状态。 _record_binding_rejection( db, task, bind_task, reason="foreign_current_task", ) db.commit() return get_task_detail(db, task.id) owned = bind_task.platform_task_id is not None _apply_binding_task(db, task, bind_task, owned=owned) db.commit() return get_task_detail(db, task.id) def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: """斗鱼绑定任务落库后,把订单自己的绑定证据合并回履约任务。""" douyu_task = db.get(DouyuTask, int(douyu_task_id)) if ( douyu_task is None or not douyu_task.account_id or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES or str(douyu_task.handbook_scope or "") != "elite" ): # 电竞/和平小店任务与精英履约是不同作用域,绝不互相投影。 return 0 linked_task_ids = [ int(row.id) for row in ( db.query(PlatformFulfillmentTask.id) .filter(PlatformFulfillmentTask.bind_task_id == int(douyu_task.id)) .all() ) ] for task_id in linked_task_ids: refresh_binding(db, task_id=task_id) changed = len(linked_task_ids) if douyu_task.task_type in BINDING_OBSERVATION_TASK_TYPES: # 查询任务只用于展示账号当前角色,永远不能结算订单。 return changed if douyu_task.platform_task_id: task = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.id == int(douyu_task.platform_task_id) ) .with_for_update() .first() ) if ( task is not None and task.id not in linked_task_ids and task.account_id and int(task.account_id) == int(douyu_task.account_id) and not _frozen(task) and _apply_binding_task(db, task, douyu_task, owned=True) ): db.commit() changed += 1 return changed # 兼容旧数据:部署前创建、没有 platform_task_id 的工作台绑定任务。 if ( str(douyu_task.task_type or "") == "get_bind_qr" and douyu_task.status == "success" ): binding = resolve_fulfillment_binding( douyu_task, account=db.get(Account, int(douyu_task.account_id)), binding_status="role_ready", ) if binding.status == BINDING_VIEW_PENDING: active_task = ( db.query(PlatformFulfillmentTask) .join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id) .filter( PlatformFulfillmentTask.account_id == int(douyu_task.account_id), PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status.in_( ACTIVE_BINDING_STATUSES ), PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled", "manual_required") ), AccountLease.status == "active", AccountLease.purpose == "platform_fulfillment", ) .order_by( PlatformFulfillmentTask.updated_at.desc(), PlatformFulfillmentTask.id.desc(), ) .with_for_update() .first() ) if active_task is not None and _attach_pending_binding_task( db, active_task, douyu_task, ): _apply_task_lease_policy(db, active_task) _emit_order_site_binding_state(db, active_task.id) db.commit() changed += 1 return changed if ( str(douyu_task.task_type or "") == "confirm_bind" and douyu_task.status == "success" ): changed += sync_active_task_from_account_binding( db, account_id=int(douyu_task.account_id), scope=str(douyu_task.handbook_scope or ""), source_task_id=int(douyu_task.id), ) return changed def reconcile_binding_observations( db: Session, *, limit: int = 500, ) -> int: """启动时收敛已落库但回调丢失的绑定证据。 只处理订单自己的证据(``platform_task_id``)和兼容路径的旧待确认任务; 账号上的查询任务不再参与订单结算。 """ tasks = ( db.query(PlatformFulfillmentTask) .filter( PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.binding_status.in_( tuple(ACTIVE_BINDING_STATUSES) + ("confirming", "failed") ), PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled") ), ) .order_by(PlatformFulfillmentTask.id.asc()) .limit(max(1, min(limit, 2000))) .all() ) reconciled = 0 for task in tasks: if _frozen(task): continue changed = False current = ( db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None ) if ( current is not None and current.status == "success" and current.platform_task_id in (None, int(task.id)) ): changed = _apply_binding_task( db, task, current, owned=current.platform_task_id is not None, ) if not changed: for evidence in _owned_binding_tasks( db, task, newer_than=int(task.bind_task_id or 0), ): if evidence.status != "success": continue if _apply_binding_task(db, task, evidence, owned=True): changed = True break if not changed and task.binding_status in ACTIVE_BINDING_STATUSES: latest_pending = _latest_pending_binding_task(db, task) if latest_pending is not None and _attach_pending_binding_task( db, task, latest_pending, ): changed = True if not changed and task.binding_status == "role_ready": # 部署前已经 role_ready 的订单:启动时补一次角色 7 天锁检查。 target_role_name = _order_target_role(db, task) if target_role_name and ( _block_on_role_lock( db, task, target_role_name, current, ) or _block_on_account_lock( db, task, target_role_name, current, ) ): changed = True if changed: reconciled += 1 if reconciled: db.commit() return reconciled def _latest_pending_binding_task( db: Session, task: PlatformFulfillmentTask, ) -> DouyuTask | None: if ( not task.account_id or task.binding_status not in ACTIVE_BINDING_STATUSES ): return None lease = _lease_for_task(db, task) if not lease_is_active(lease): return None rows = ( db.query(DouyuTask) .filter( DouyuTask.account_id == int(task.account_id), DouyuTask.task_type.in_(PENDING_BINDING_TASK_TYPES), DouyuTask.handbook_scope == "elite", DouyuTask.status == "success", DouyuTask.id > int(task.bind_task_id or 0), ( (DouyuTask.platform_task_id == int(task.id)) | DouyuTask.platform_task_id.is_(None) ), ) .order_by(DouyuTask.id.desc()) .limit(20) .all() ) account = db.get(Account, int(task.account_id)) for row in rows: if not source_created_within_lease(lease, row): continue binding = resolve_douyu_binding(row, account=account) if binding.status != BINDING_VIEW_PENDING: continue if _actionable_pending_role(row.result, binding.pending_role_name): return row return None def _attach_pending_binding_task( db: Session, task: PlatformFulfillmentTask, bind_task: DouyuTask, ) -> bool: account = ( db.get(Account, int(task.account_id)) if task.account_id else None ) lease = _lease_for_task(db, task) binding = resolve_douyu_binding(bind_task, account=account) if ( task.binding_status not in ACTIVE_BINDING_STATUSES or not task.account_id or int(bind_task.account_id or 0) != int(task.account_id) or bind_task.task_type not in PENDING_BINDING_TASK_TYPES or binding.status != BINDING_VIEW_PENDING or not _actionable_pending_role( bind_task.result if isinstance(bind_task.result, dict) else {}, binding.pending_role_name, ) or not lease_is_active(lease) or not source_created_within_lease(lease, bind_task) or ( bind_task.platform_task_id is not None and int(bind_task.platform_task_id) != int(task.id) ) ): return False current_id = int(task.bind_task_id or 0) if int(bind_task.id) == current_id: return False if current_id and int(bind_task.id) < current_id: return False if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False if _block_on_role_lock(db, task, binding.pending_role_name, bind_task): return True if _block_on_account_lock(db, task, binding.pending_role_name, bind_task): return True previous_bind_task_id = task.bind_task_id task.bind_task_id = int(bind_task.id) task.binding_status = "role_ready" task.execution_status = "role_ready" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_pending_task_linked", detail={ "bindTaskId": int(bind_task.id), "previousBindTaskId": previous_bind_task_id, "roleName": binding.pending_role_name, "source": "account_workbench", }, ) _emit_order_site_binding_state(db, task.id) return True def sync_active_task_from_account_binding( db: Session, *, account_id: int, scope: str, source_task_id: int | None = None, ) -> int: """兼容旧流程:精英宝典工作台的无归属确认任务结算当前待确认订单。 必须同时满足:订单还在 role_ready、确认任务创建于本订单租约期间、 确认角色等于订单当前待确认角色。任何一条不满足都不改订单,只记录 ``binding_sync_rejected``。 """ if scope != "elite": return 0 source_task = ( db.get(DouyuTask, int(source_task_id)) if source_task_id is not None else None ) if ( source_task is None or source_task.status != "success" or str(source_task.task_type or "") != "confirm_bind" ): return 0 account = db.get(Account, int(account_id)) binding = resolve_douyu_binding(source_task, account=account) if binding.status != BINDING_VIEW_CONFIRMED: return 0 task = ( db.query(PlatformFulfillmentTask) .join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id) .filter( PlatformFulfillmentTask.account_id == int(account_id), PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status == "role_ready", PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled") ), AccountLease.status == "active", AccountLease.purpose == "platform_fulfillment", ) .order_by( PlatformFulfillmentTask.updated_at.desc(), PlatformFulfillmentTask.id.desc(), ) .with_for_update() .first() ) if task is None: return 0 lease = _lease_for_task(db, task) if not lease_is_active(lease) or not source_created_within_lease( lease, source_task, ): _record_binding_rejection( db, task, source_task, reason="source_outside_lease", confirmed_role=binding.confirmed_role_name, ) db.commit() return 0 target_role = _order_target_role(db, task, before_task_id=int(source_task.id)) if not target_role or not role_names_match( binding.confirmed_role_name, target_role, ): _record_binding_rejection( db, task, source_task, reason="target_mismatch" if target_role else "missing_target", confirmed_role=binding.confirmed_role_name, target_role=target_role, ) db.commit() return 0 task.bind_task_id = int(source_task.id) task.binding_status = "bound" task.execution_status = "bound" task.issue_code = "" task.last_error = "" task.updated_at = _now() _append_event( db, task.id, "binding_synced_from_account", detail={ "accountId": int(account_id), "accountName": ( account.nickname or account.username if account is not None else "" ), "roleName": binding.confirmed_role_name, "gameChannel": ( binding.confirmed_channel or binding.effective_channel or binding.current_channel ), "targetRoleName": target_role, "sourceTaskId": int(source_task.id), "roleChangeAvailableAt": ( account.role_change_available_at.isoformat() if account is not None and account.role_change_available_at else None ), }, ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) db.commit() return 1 def requires_account_binding_sync(task_type: str) -> bool: return str(task_type or "") in BINDING_SYNC_TASK_TYPES def reconcile_binding_state_outbox( db: Session, *, limit: int = 500, after_task_id: int = 0, ) -> dict[str, Any]: """按 ID 游标补齐 active 快照;批次只限制吞吐,不形成永久扫描窗口。""" batch_size = max(1, min(limit, 500)) normalized_after = max(0, int(after_task_id or 0)) task_ids = [ int(row.id) for row in ( db.query(PlatformFulfillmentTask.id) .filter( PlatformFulfillmentTask.id > normalized_after, PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] ), ) .order_by(PlatformFulfillmentTask.id.asc()) .limit(batch_size) .all() ) ] queued = sum( 1 for task_id in task_ids if _emit_order_site_binding_state(db, task_id) ) db.commit() return { "queued": queued, "nextTaskId": max(task_ids, default=normalized_after), "hasMore": len(task_ids) == batch_size, } def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[str, Any]: task = _load_task_for_update(db, task_id) task = _load_task(db, refresh_binding(db, task_id=task.id)["task"]["id"]) if str(task.issue_code or "") == ROLE_LOCK_ISSUE: # 刷新时已经判定角色被其他账号占用:直接返回人工状态,不再创建确认任务。 return get_task_detail(db, task.id) if task.binding_status != "role_ready": raise HTTPException(status_code=409, detail="当前没有待确认的游戏角色") if not task.account_id or not task.lease_id: raise HTTPException(status_code=409, detail="账号租约不存在") lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease is None or lease.status != "active": raise HTTPException(status_code=409, detail="账号租约已失效") current_bind_task = ( db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if task.bind_task_id else None ) current_bind_result = (current_bind_task.result or {}) if current_bind_task else {} # 兼容部署前已经进入 role_ready 的订单:确认前再查一次角色 7 天锁。 target_role_name = _order_target_role(db, task) if target_role_name and _block_on_role_lock( db, task, target_role_name, current_bind_task, ): db.commit() return get_task_detail(db, task.id) if target_role_name and _block_on_account_lock( db, task, target_role_name, current_bind_task, ): db.commit() return get_task_detail(db, task.id) expected_role_name = str(current_bind_result.get("role_name") or "").strip() if expected_role_name and not _actionable_pending_role( current_bind_result, expected_role_name, ): raise HTTPException( status_code=409, detail="当前动作通道没有待确认角色,请客户重新扫码后再确认", ) baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip() batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}" confirm_task = DouyuTask( batch_id=batch_id, account_id=task.account_id, account_assigned_to=current.id, task_type="confirm_bind", handbook_scope="elite", status="planned", message="等待确认角色绑定", result={ "payload": {}, "expected_role_name": expected_role_name, "baseline_role_name": baseline_role_name, }, created_by=current.id, platform_task_id=task.id, ) db.add(confirm_task) db.flush() account = db.query(Account).filter(Account.id == task.account_id).first() if account is not None: record_douyu_task_started( db, account, task_id=int(confirm_task.id), task_type="confirm_bind", task_label="确认绑定", scope="elite", actor_id=current.id, ) task.bind_task_id = confirm_task.id task.binding_status = "confirming" task.execution_status = "binding_confirming" task.operator_id = current.id task.updated_at = _now() _apply_task_lease_policy(db, task, lease=lease) _append_event( db, task.id, "binding_confirm_started", actor_type="user", actor_id=current.id, detail={"confirmTaskId": confirm_task.id}, ) _emit_order_site_binding_state(db, task.id) enqueue_execution_job( db, job_type=JOB_DOUYU_BINDING, lane_scope=LANE_FULFILLMENT, batch_id=batch_id, payload={ "task_type": "confirm_bind", "payload": {}, "concurrency": 1, }, created_by=int(current.id), priority=10, max_attempts=1, ) db.commit() return get_task_detail(db, task.id) async def confirm_binding( db: Session, *, task_id: int, current: User ) -> dict[str, Any]: return await run_in_threadpool( confirm_binding_sync, db, task_id=task_id, current=current, )