847 lines
27 KiB
Python
847 lines
27 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 ..business_events import record_douyu_task_started
|
|
from ..douyu_binding import (
|
|
BINDING_OBSERVATION_TASK_TYPES,
|
|
BINDING_RECONCILE_CONFIRMED,
|
|
BINDING_RECONCILE_STALE_PENDING,
|
|
BINDING_VIEW_CONFIRMED,
|
|
BINDING_VIEW_PENDING,
|
|
DouyuBindingReconciliation,
|
|
reconcile_douyu_binding,
|
|
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 .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",
|
|
}
|
|
)
|
|
PENDING_BINDING_TASK_TYPES = frozenset({"get_bind_qr"})
|
|
ACTIVE_PENDING_TASK_STATUSES = frozenset(
|
|
{"allocated", "waiting_bind", "role_ready"}
|
|
)
|
|
|
|
|
|
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:
|
|
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 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 task.binding_status == "role_ready":
|
|
observation_task = _binding_observation_task(db, task)
|
|
if observation_task is not None and _apply_binding_observation(
|
|
db,
|
|
task,
|
|
observation_task,
|
|
):
|
|
db.commit()
|
|
task = _load_task(db, task.id)
|
|
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 == 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 {}
|
|
binding = resolve_fulfillment_binding(
|
|
bind_task,
|
|
account=db.get(Account, int(task.account_id)) if task.account_id else None,
|
|
binding_status=task.binding_status,
|
|
)
|
|
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 binding.status == BINDING_VIEW_CONFIRMED:
|
|
task.binding_status = "bound"
|
|
task.execution_status = "bound"
|
|
task.issue_code = ""
|
|
task.last_error = ""
|
|
elif binding.status == BINDING_VIEW_PENDING:
|
|
task.binding_status = "role_ready"
|
|
task.execution_status = "role_ready"
|
|
task.issue_code = ""
|
|
task.last_error = ""
|
|
elif binding.reported_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 binding.qr_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)
|
|
if douyu_task.task_type in BINDING_OBSERVATION_TASK_TYPES:
|
|
return len(task_ids) + _sync_binding_observation(db, douyu_task)
|
|
binding = resolve_douyu_binding(
|
|
douyu_task,
|
|
account=db.get(Account, int(douyu_task.account_id))
|
|
if douyu_task.account_id
|
|
else None,
|
|
)
|
|
if (
|
|
douyu_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
|
|
or binding.status != BINDING_VIEW_CONFIRMED
|
|
):
|
|
# 查询/出码任务只能证明“账号历史绑定是什么”,不能证明本次订单已经确认。
|
|
# 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把任务级
|
|
# 确认事实投影到履约任务。
|
|
linked = 0
|
|
if (
|
|
douyu_task.task_type in PENDING_BINDING_TASK_TYPES
|
|
and 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_PENDING_TASK_STATUSES
|
|
),
|
|
PlatformFulfillmentTask.execution_status.notin_(
|
|
("completed", "cancelled", "manual_required")
|
|
),
|
|
AccountLease.status == "active",
|
|
)
|
|
.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()
|
|
linked = 1
|
|
return len(task_ids) + linked
|
|
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 _binding_observation_task(
|
|
db: Session,
|
|
task: PlatformFulfillmentTask,
|
|
) -> DouyuTask | None:
|
|
if not task.account_id or not task.bind_task_id:
|
|
return None
|
|
return (
|
|
db.query(DouyuTask)
|
|
.filter(
|
|
DouyuTask.platform_task_id == int(task.id),
|
|
DouyuTask.account_id == int(task.account_id),
|
|
DouyuTask.task_type.in_(BINDING_OBSERVATION_TASK_TYPES),
|
|
DouyuTask.status == "success",
|
|
DouyuTask.id > int(task.bind_task_id),
|
|
)
|
|
.order_by(DouyuTask.id.desc())
|
|
.limit(1)
|
|
.first()
|
|
)
|
|
|
|
|
|
def _apply_binding_observation(
|
|
db: Session,
|
|
task: PlatformFulfillmentTask,
|
|
observation_task: DouyuTask,
|
|
*,
|
|
account: Account | None = None,
|
|
) -> DouyuBindingReconciliation | None:
|
|
if not task.account_id:
|
|
return None
|
|
current_task = (
|
|
db.get(DouyuTask, int(task.bind_task_id))
|
|
if task.bind_task_id
|
|
else None
|
|
)
|
|
resolved_account = account or db.get(Account, int(task.account_id))
|
|
current = resolve_douyu_binding(current_task, account=resolved_account)
|
|
observation = resolve_douyu_binding(
|
|
observation_task,
|
|
account=resolved_account,
|
|
)
|
|
reconciliation = reconcile_douyu_binding(current, observation)
|
|
if reconciliation.action not in {
|
|
BINDING_RECONCILE_CONFIRMED,
|
|
BINDING_RECONCILE_STALE_PENDING,
|
|
}:
|
|
return None
|
|
previous_bind_task_id = task.bind_task_id
|
|
task.bind_task_id = int(observation_task.id)
|
|
task.issue_code = ""
|
|
task.last_error = ""
|
|
task.updated_at = _now()
|
|
if reconciliation.action == BINDING_RECONCILE_CONFIRMED:
|
|
task.binding_status = "bound"
|
|
task.execution_status = "bound"
|
|
event_type = "binding_observation_confirmed"
|
|
else:
|
|
task.binding_status = "waiting_bind"
|
|
task.execution_status = "waiting_bind"
|
|
event_type = "binding_pending_observation_superseded"
|
|
_append_event(
|
|
db,
|
|
task.id,
|
|
event_type,
|
|
detail={
|
|
"bindTaskId": int(observation_task.id),
|
|
"previousBindTaskId": previous_bind_task_id,
|
|
"pendingRoleName": reconciliation.pending_role_name,
|
|
"observedRoleName": reconciliation.observed_role_name,
|
|
"sourceTaskType": observation_task.task_type,
|
|
},
|
|
)
|
|
_apply_task_lease_policy(db, task)
|
|
_emit_order_site_binding_state(db, task.id)
|
|
return reconciliation
|
|
|
|
|
|
def _sync_binding_observation(
|
|
db: Session,
|
|
observation_task: DouyuTask,
|
|
) -> int:
|
|
if (
|
|
not observation_task.platform_task_id
|
|
or not observation_task.account_id
|
|
or str(observation_task.handbook_scope or "") != "elite"
|
|
):
|
|
return 0
|
|
task = (
|
|
db.query(PlatformFulfillmentTask)
|
|
.filter(PlatformFulfillmentTask.id == int(observation_task.platform_task_id))
|
|
.with_for_update()
|
|
.first()
|
|
)
|
|
if task is None or task.execution_status in {"completed", "cancelled"}:
|
|
return 0
|
|
reconciled = _apply_binding_observation(
|
|
db,
|
|
task,
|
|
observation_task,
|
|
account=db.get(Account, int(observation_task.account_id)),
|
|
)
|
|
if reconciled is None:
|
|
return 0
|
|
db.commit()
|
|
return 1
|
|
|
|
|
|
def reconcile_binding_observations(
|
|
db: Session,
|
|
*,
|
|
limit: int = 500,
|
|
) -> int:
|
|
"""启动时收敛已落库但尚未触发的较新账号角色观测。"""
|
|
tasks = (
|
|
db.query(PlatformFulfillmentTask)
|
|
.filter(
|
|
PlatformFulfillmentTask.scope == "elite",
|
|
PlatformFulfillmentTask.binding_status == "role_ready",
|
|
PlatformFulfillmentTask.execution_status.notin_(
|
|
("completed", "cancelled", "manual_required")
|
|
),
|
|
PlatformFulfillmentTask.bind_task_id.isnot(None),
|
|
)
|
|
.order_by(PlatformFulfillmentTask.id.asc())
|
|
.limit(max(1, min(limit, 2000)))
|
|
.all()
|
|
)
|
|
reconciled = 0
|
|
for task in tasks:
|
|
observation_task = _binding_observation_task(db, task)
|
|
if observation_task is None:
|
|
continue
|
|
result = _apply_binding_observation(db, task, observation_task)
|
|
if result is not None:
|
|
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_PENDING_TASK_STATUSES
|
|
):
|
|
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),
|
|
)
|
|
.order_by(DouyuTask.id.desc())
|
|
.limit(20)
|
|
.all()
|
|
)
|
|
account = db.get(Account, int(task.account_id))
|
|
for row in rows:
|
|
if resolve_douyu_binding(
|
|
row,
|
|
account=account,
|
|
).status == BINDING_VIEW_PENDING:
|
|
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
|
|
)
|
|
binding = resolve_douyu_binding(bind_task, account=account)
|
|
if (
|
|
task.binding_status not in ACTIVE_PENDING_TASK_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
|
|
):
|
|
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
|
|
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:
|
|
"""确认任务成功后,把当前活跃履约任务同步到 bound。
|
|
|
|
精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看
|
|
``PlatformFulfillmentTask.bind_task_id``。这里的唯一事实是确认任务的
|
|
``result``:只有 ``resolve_douyu_binding`` 返回 confirmed 才允许投影。
|
|
账号上的 ``role_bind_status`` 只描述当前生效角色,不能证明本订单已确认。
|
|
"""
|
|
if scope != "elite":
|
|
return 0
|
|
source_task = (
|
|
db.get(DouyuTask, int(source_task_id))
|
|
if source_task_id is not None
|
|
else None
|
|
)
|
|
account = db.get(Account, int(account_id))
|
|
binding = (
|
|
resolve_douyu_binding(source_task, account=account)
|
|
if source_task is not None
|
|
else None
|
|
)
|
|
if (
|
|
source_task is None
|
|
or binding is None
|
|
or source_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
|
|
or 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.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
|
|
if account is not None
|
|
else ""
|
|
),
|
|
"roleName": (
|
|
binding.confirmed_role_name
|
|
or binding.effective_role_name
|
|
or binding.current_role_name
|
|
),
|
|
"gameChannel": (
|
|
binding.confirmed_channel
|
|
or binding.effective_channel
|
|
or binding.current_channel
|
|
),
|
|
"roleChangeAvailableAt": (
|
|
account.role_change_available_at.isoformat()
|
|
if account is not None and 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,
|
|
)
|