perf(douyu): 拆分任务槽并改造绑定扫码调度
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
from collections.abc import Iterable
|
||||
@@ -12,7 +13,7 @@ from loguru import logger
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...database import SessionLocal
|
||||
from ...database import WorkerSessionLocal
|
||||
from ...models import PlatformFulfillmentTask
|
||||
from . import service
|
||||
|
||||
@@ -142,6 +143,21 @@ def run_auto_allocation_once(
|
||||
if allocated_task is not None:
|
||||
allocated_task.next_allocate_at = None
|
||||
db.commit()
|
||||
try:
|
||||
asyncio.run(
|
||||
service.start_binding(
|
||||
db,
|
||||
task_id=candidate_task_id,
|
||||
current=actor,
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - allocation remains valid
|
||||
db.rollback()
|
||||
logger.warning(
|
||||
"直播账号履约自动开始绑定失败 task_id={}: {}",
|
||||
candidate_task_id,
|
||||
exc,
|
||||
)
|
||||
else:
|
||||
failed += 1
|
||||
_schedule_retry(
|
||||
@@ -171,6 +187,48 @@ def run_auto_allocation_once(
|
||||
}
|
||||
|
||||
|
||||
def start_allocated_bindings_once(
|
||||
db: Session,
|
||||
*,
|
||||
limit: int = DEFAULT_BATCH_SIZE,
|
||||
) -> int:
|
||||
"""Start durable binding preparation for allocated, unstarted sessions."""
|
||||
rows = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.execution_status == "allocated",
|
||||
PlatformFulfillmentTask.binding_status == "not_started",
|
||||
PlatformFulfillmentTask.account_id.isnot(None),
|
||||
PlatformFulfillmentTask.lease_id.isnot(None),
|
||||
)
|
||||
.order_by(PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc())
|
||||
.limit(max(1, limit))
|
||||
.all()
|
||||
)
|
||||
if not rows:
|
||||
return 0
|
||||
actor = service._integration_actor(db)
|
||||
started = 0
|
||||
for task in rows:
|
||||
try:
|
||||
asyncio.run(
|
||||
service.start_binding(
|
||||
db,
|
||||
task_id=int(task.id),
|
||||
current=actor,
|
||||
)
|
||||
)
|
||||
started += 1
|
||||
except Exception as exc: # noqa: BLE001 - one session cannot block the rest
|
||||
db.rollback()
|
||||
logger.warning(
|
||||
"直播账号履约补启动绑定失败 task_id={}: {}",
|
||||
task.id,
|
||||
exc,
|
||||
)
|
||||
return started
|
||||
|
||||
|
||||
def _run() -> None:
|
||||
interval = _env_int(
|
||||
"PLATFORM_FULFILLMENT_AUTO_ALLOCATE_SECONDS",
|
||||
@@ -179,7 +237,7 @@ def _run() -> None:
|
||||
3600,
|
||||
)
|
||||
while not _stop_event.is_set():
|
||||
db = SessionLocal()
|
||||
db = WorkerSessionLocal()
|
||||
try:
|
||||
pending_ids = _take_pending_task_ids(
|
||||
_env_int(
|
||||
@@ -190,8 +248,11 @@ def _run() -> None:
|
||||
)
|
||||
)
|
||||
result = run_auto_allocation_once(db, task_ids=pending_ids or None)
|
||||
started = start_allocated_bindings_once(db)
|
||||
if result["checked"]:
|
||||
logger.info("直播账号履约自动选号: {}", result)
|
||||
if started:
|
||||
logger.info("直播账号履约补启动绑定: {} 条", started)
|
||||
except Exception as exc: # noqa: BLE001 - worker 不能因单轮异常退出
|
||||
db.rollback()
|
||||
logger.warning("直播账号履约自动选号轮次失败: {}", exc)
|
||||
|
||||
@@ -29,6 +29,8 @@ def _state_dedupe_key(payload: dict[str, Any]) -> str:
|
||||
"platName": payload.get("platName"),
|
||||
"bindReadyForConfirm": payload.get("bindReadyForConfirm"),
|
||||
"bindConfirmed": payload.get("bindConfirmed"),
|
||||
"queueState": payload.get("queueState"),
|
||||
"queueLane": payload.get("queueLane"),
|
||||
"customerProfileReset": payload.get("customerProfileReset"),
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
|
||||
@@ -7,7 +7,7 @@ import threading
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from ...database import SessionLocal
|
||||
from ...database import WorkerSessionLocal
|
||||
|
||||
_stop_event = threading.Event()
|
||||
_thread: threading.Thread | None = None
|
||||
@@ -31,7 +31,7 @@ def _run() -> None:
|
||||
# 不抢占启动时的 Webhook;首轮延后一分钟。
|
||||
if _stop_event.wait(min(60, _interval_seconds())):
|
||||
break
|
||||
db = SessionLocal()
|
||||
db = WorkerSessionLocal()
|
||||
try:
|
||||
queued = 0
|
||||
for _page in range(20):
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user