perf(douyu): 拆分任务槽并改造绑定扫码调度

This commit is contained in:
yml
2026-11-20 22:03:20 +08:00
parent 8869e427d2
commit 071d45ad1d
40 changed files with 1635 additions and 245 deletions
@@ -12,6 +12,7 @@ from typing import Any
from fastapi import HTTPException
from loguru import logger
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ...models import (
@@ -763,6 +764,19 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
return task
def _load_task_for_update(db: Session, task_id: int) -> PlatformFulfillmentTask:
task = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id == int(task_id))
.populate_existing()
.with_for_update()
.first()
)
if task is None:
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
return task
def _retain_lease_for_active_collab(
db: Session,
*,
@@ -1241,6 +1255,40 @@ def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str:
return task_issue if messages.get(task_issue) else "binding_failed"
def _customer_binding_queue_state(
task: PlatformFulfillmentTask,
bind_task: DouyuTask | None,
*,
lease_ready: bool,
) -> tuple[str, int]:
if task.execution_status == "completed":
return "completed", 0
if task.execution_status == "cancelled":
return "cancelled", 0
if task.issue_code == "mapping_missing":
return "mapping_missing", 0
if not task.account_id or not task.lease_id:
return "allocation_queued", 2000
if not lease_ready:
return "lease_inactive", 0
if bind_task is None:
return "ready_to_start", 0
result = bind_task.result or {}
if bool(result.get("bind_confirmed")) or task.binding_status == "bound":
return "confirmed", 0
if pending_binding_role_from_result(result):
return "role_ready", 0
if bind_task.status in {"failed", "error", "stopped"}:
return "failed", 0
if task.binding_status == "confirming":
return "confirming", 1000
if bind_task.status in {"planned", "pending"}:
return "qr_queued", 1000
if result.get("url"):
return "waiting_scan", 5000 if result.get("bind_polling") else 0
return "preparing", 1000
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
task = _load_task(db, task_id)
@@ -1259,6 +1307,11 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
lease_ready = bool(task.account_id and lease and lease.status == "active")
binding_failed = task.binding_status == "failed"
binding_confirmed = task.binding_status == "bound"
queue_state, retry_after_ms = _customer_binding_queue_state(
task,
bind_task,
lease_ready=lease_ready,
)
return {
"sessionId": task.id,
"platformOrderId": task.platform_order_id,
@@ -1282,6 +1335,10 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"platName": str(bind_result.get("plat_name") or ""),
"bindReadyForConfirm": (bool(pending_role) and not binding_failed),
"bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed,
"queueState": queue_state,
"retryAfterMs": retry_after_ms,
"queueLane": bind_task.queue_lane if bind_task else "",
"accepted": False,
"stateVersion": int(task.state_version or 0),
"completedAt": _jsonable(task.completed_at),
"updatedAt": _jsonable(task.updated_at),
@@ -1318,8 +1375,9 @@ def ensure_customer_session(
if task.execution_status in {"pending_mapping", "ready", "manual_required"}:
if task.issue_code == "mapping_missing":
return customer_binding_out(db, task.id)
actor = _integration_actor(db)
allocate_task(db, task_id=task.id, current=actor)
from .auto_allocator import wake_auto_allocator
wake_auto_allocator([int(task.id)])
return customer_binding_out(db, task.id)
@@ -1330,18 +1388,40 @@ async def customer_start_binding(
force_refresh: bool = False,
) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
return customer_binding_out(db, task.id)
if task.issue_code == "mapping_missing":
return customer_binding_out(db, task.id)
if not task.account_id or not task.lease_id:
from .auto_allocator import wake_auto_allocator
wake_auto_allocator([int(task.id)])
payload = customer_binding_out(db, task.id)
payload["accepted"] = True
payload["queueState"] = "allocation_queued"
payload["retryAfterMs"] = 2000
return payload
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease is None or lease.status != "active":
return customer_binding_out(db, task.id)
previous_bind_task_id = task.bind_task_id
actor = _integration_actor(db)
if task.execution_status not in {"completed", "cancelled"} and (
not task.account_id or not task.lease_id
):
allocate_task(db, task_id=task.id, current=actor)
await start_binding(
db,
task_id=task.id,
current=actor,
force_refresh=force_refresh,
)
return customer_binding_out(db, task.id)
payload = customer_binding_out(db, task.id)
accepted = task.bind_task_id != previous_bind_task_id
payload["accepted"] = accepted
if accepted:
payload["queueState"] = "qr_queued"
payload["retryAfterMs"] = 1000
return payload
def customer_refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
@@ -1881,7 +1961,7 @@ async def start_binding(
current: User,
force_refresh: bool = False,
) -> dict[str, Any]:
task = _load_task(db, task_id)
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()
@@ -1924,9 +2004,16 @@ async def start_binding(
message="等待生成绑定二维码",
result={"payload": {}},
created_by=current.id,
platform_task_id=task.id,
)
db.add(bind_task)
db.flush()
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(
@@ -2113,7 +2200,7 @@ def reconcile_binding_state_outbox(
async def confirm_binding(
db: Session, *, task_id: int, current: User
) -> dict[str, Any]:
task = _load_task(db, task_id)
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="当前没有待确认的游戏角色")
@@ -2146,6 +2233,7 @@ async def confirm_binding(
"baseline_role_name": baseline_role_name,
},
created_by=current.id,
platform_task_id=task.id,
)
db.add(confirm_task)
db.flush()