Files
live-hub-py/web/backend/services/platform_fulfillment/binding.py
T

530 lines
17 KiB
Python

"""游戏角色绑定启动、确认与刷新。"""
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,
PlatformFulfillmentTask,
User,
)
from ..account_binding import (
pending_binding_role_from_result,
)
from ..business_events import record_douyu_task_started
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 .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",
}
)
ACCOUNT_CONFIRMATION_TASK_TYPES = frozenset(
{
"confirm_bind",
"confirm_esports_bind",
"confirm_xpd_bind",
}
)
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:
result = existing.result or {}
pending_role = pending_binding_role_from_result(result)
stale_pending = (
bool(result.get("bind_ready_for_confirm")) and not pending_role
)
if bool(result.get("bind_confirmed")) or pending_role:
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 refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
return get_task_detail(db, task.id)
if not task.bind_task_id:
return get_task_detail(db, task.id)
bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
if bind_task is None:
return get_task_detail(db, task.id)
before = (
task.binding_status,
task.execution_status,
task.exchange_status,
task.issue_code,
task.last_error,
)
result = bind_task.result or {}
pending_role = pending_binding_role_from_result(result)
if bind_task.status in {"failed", "error", "stopped"}:
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = _binding_failure_issue(bind_task, result)
task.last_error = _customer_task_message(task)
elif bool(result.get("bind_confirmed")):
task.binding_status = "bound"
task.execution_status = "bound"
task.issue_code = ""
task.last_error = ""
elif pending_role:
task.binding_status = "role_ready"
task.execution_status = "role_ready"
task.issue_code = ""
task.last_error = ""
elif bool(result.get("bind_ready_for_confirm")):
# 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会
# 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。
previous_bind_task_id = task.bind_task_id
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": 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)
db.commit()
return get_task_detail(db, task.id)
elif result.get("url"):
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
task.issue_code = ""
task.last_error = ""
after = (
task.binding_status,
task.execution_status,
task.exchange_status,
task.issue_code,
task.last_error,
)
if after != before:
task.updated_at = _now()
if task.binding_status == "failed":
_append_event(
db,
task.id,
"binding_failed",
detail={
"issueCode": task.issue_code,
"bindTaskId": bind_task.id,
"bindPhase": str(result.get("bind_phase") or ""),
"rawError": _binding_failure_raw_message(
task.issue_code,
result,
fallback=str(bind_task.message or ""),
)[:1000],
},
)
_emit_order_site_binding_state(db, task.id)
_apply_task_lease_policy(db, task)
db.commit()
return get_task_detail(db, task.id)
def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
"""斗鱼绑定任务落库后,把关联履约任务和 Outbox 一并刷新。"""
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 task_ids:
refresh_binding(db, task_id=task_id)
douyu_task = db.get(DouyuTask, int(douyu_task_id))
if douyu_task is None or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES:
return len(task_ids)
result = douyu_task.result or {}
if (
douyu_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
or result.get("bind_confirmed") is not True
):
# 查询/出码任务只能证明“账号历史绑定是什么”,不能证明本次订单已经确认。
# 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把账号权威
# 绑定投影到履约任务。
return len(task_ids)
return len(task_ids) + 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),
)
def sync_active_task_from_account_binding(
db: Session,
*,
account_id: int,
scope: str,
source_task_id: int | None = None,
) -> int:
"""账号权威绑定已确认时,把当前活跃履约任务同步到 bound。
精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看
``PlatformFulfillmentTask.bind_task_id``。账号上的绑定状态才是最终事实。
只在任务已经识别出待确认角色后同步,避免把账号历史绑定误当成当前订单结果。
"""
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.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
or (source_task.result or {}).get("bind_confirmed") is not True
):
return 0
account = db.get(Account, int(account_id))
if account is None or account.role_bind_status != "bound":
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.in_(("role_ready", "confirming")),
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
AccountLease.status == "active",
)
.order_by(
PlatformFulfillmentTask.updated_at.desc(),
PlatformFulfillmentTask.id.desc(),
)
.with_for_update()
.first()
)
if task is None:
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,
"roleName": str(account.game_name or ""),
"gameChannel": str(account.game_channel or ""),
"roleChangeAvailableAt": (
account.role_change_available_at.isoformat()
if account.role_change_available_at
else None
),
"sourceTaskId": source_task_id,
},
)
_apply_task_lease_policy(db, task)
_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 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 {}
expected_role_name = str(current_bind_result.get("role_name") or "").strip()
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,
)