refactor(fulfillment): 拆分履约服务并修正换绑冷却分类
This commit is contained in:
@@ -0,0 +1,390 @@
|
||||
"""游戏角色绑定启动、确认与刷新。"""
|
||||
|
||||
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 ..douyu_batch_launcher import start_douyu_batch
|
||||
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
|
||||
|
||||
|
||||
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)
|
||||
db.commit()
|
||||
start_douyu_batch(
|
||||
batch_id=batch_id,
|
||||
task_type="get_bind_qr",
|
||||
payload={},
|
||||
concurrency=1,
|
||||
capture_event_loop=False,
|
||||
)
|
||||
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)
|
||||
return len(task_ids)
|
||||
|
||||
|
||||
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)
|
||||
db.commit()
|
||||
start_douyu_batch(
|
||||
batch_id=batch_id,
|
||||
task_type="confirm_bind",
|
||||
payload={},
|
||||
concurrency=1,
|
||||
capture_event_loop=False,
|
||||
)
|
||||
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,
|
||||
)
|
||||
Reference in New Issue
Block a user