feat(fulfillment): 自动选号并补充精英宝典操作

- 增加直播履约自动选号 worker、重试与任务扫描
- 履约详情复用斗鱼任务能力开通宝典、充值和兑换皮肤
- 补充自动选号与精英宝典操作测试
This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent bba3d9dac9
commit 8ba6379687
6 changed files with 501 additions and 6 deletions
+6
View File
@@ -105,6 +105,10 @@ async def lifespan(app: FastAPI):
start_integration_outbox_worker,
stop_integration_outbox_worker,
)
from .services.platform_fulfillment.auto_allocator import (
start_platform_fulfillment_auto_allocator,
stop_platform_fulfillment_auto_allocator,
)
from .services.platform_fulfillment.reconciler import (
start_platform_fulfillment_reconciler,
stop_platform_fulfillment_reconciler,
@@ -112,9 +116,11 @@ async def lifespan(app: FastAPI):
start_integration_outbox_worker()
start_platform_fulfillment_reconciler()
start_platform_fulfillment_auto_allocator()
try:
yield
finally:
stop_platform_fulfillment_auto_allocator()
stop_platform_fulfillment_reconciler()
stop_integration_outbox_worker()
stop_scheduler()
@@ -0,0 +1,139 @@
"""自动为待处理直播账号履约任务选号;异常任务保留给人工处理。"""
from __future__ import annotations
import os
import threading
from datetime import UTC, datetime, timedelta
from typing import Any
from loguru import logger
from sqlalchemy.orm import Session
from ...database import SessionLocal
from ...models import PlatformFulfillmentTask
from . import service
DEFAULT_INTERVAL_SECONDS = 20
DEFAULT_BATCH_SIZE = 2
DEFAULT_RETRY_SECONDS = 45
_stop_event = threading.Event()
_thread: threading.Thread | None = None
_lock = threading.Lock()
def _env_int(name: str, default: int, minimum: int, maximum: int) -> int:
try:
value = int(os.getenv(name, str(default)))
except ValueError:
return default
return max(minimum, min(maximum, value))
def run_auto_allocation_once(
db: Session,
*,
limit: int | None = None,
now: datetime | None = None,
) -> dict[str, int]:
"""扫描 ready 且尚未分配账号的任务,逐笔调用统一选号逻辑。"""
moment = now or datetime.now(UTC)
batch_size = limit or _env_int(
"PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH",
DEFAULT_BATCH_SIZE,
1,
20,
)
retry_seconds = _env_int(
"PLATFORM_FULFILLMENT_AUTO_ALLOCATE_RETRY_SECONDS",
DEFAULT_RETRY_SECONDS,
10,
3600,
)
candidates = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.execution_status == "ready",
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.commodity_id != "",
PlatformFulfillmentTask.updated_at
<= moment - timedelta(seconds=retry_seconds),
)
.order_by(PlatformFulfillmentTask.updated_at.asc())
.limit(batch_size)
.all()
)
if not candidates:
return {"checked": 0, "allocated": 0, "failed": 0}
actor = service._integration_actor(db)
allocated = 0
failed = 0
for task in candidates:
try:
detail: dict[str, Any] = service.allocate_task(
db,
task_id=int(task.id),
current=actor,
)
if detail.get("task", {}).get("account"):
allocated += 1
else:
failed += 1
except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批
db.rollback()
failed += 1
logger.warning(
"直播账号履约自动选号失败 task_id={}: {}", task.id, exc
)
return {
"checked": len(candidates),
"allocated": allocated,
"failed": failed,
}
def _run() -> None:
interval = _env_int(
"PLATFORM_FULFILLMENT_AUTO_ALLOCATE_SECONDS",
DEFAULT_INTERVAL_SECONDS,
5,
3600,
)
while not _stop_event.wait(interval):
db = SessionLocal()
try:
result = run_auto_allocation_once(db)
if result["checked"]:
logger.info("直播账号履约自动选号: {}", result)
except Exception as exc: # noqa: BLE001 - worker 不能因单轮异常退出
db.rollback()
logger.warning("直播账号履约自动选号轮次失败: {}", exc)
finally:
db.close()
def start_platform_fulfillment_auto_allocator() -> bool:
global _thread
with _lock:
if _thread is not None and _thread.is_alive():
return False
_stop_event.clear()
_thread = threading.Thread(
target=_run,
name="platform-fulfillment-auto-allocator",
daemon=True,
)
_thread.start()
return True
def stop_platform_fulfillment_auto_allocator() -> None:
global _thread
_stop_event.set()
with _lock:
thread = _thread
_thread = None
if thread is not None and thread.is_alive():
thread.join(timeout=3)
@@ -560,12 +560,30 @@ def _customer_task_message(task: PlatformFulfillmentTask) -> str:
"points_short": "账号正在补充积分,请稍后重试",
"commodity_limit_reached": "当前商品暂时无法兑换,请联系客服",
"binding_failed": "暂未识别到绑定角色,请继续使用当前二维码完成扫码",
"account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理",
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
"eligibility_check_failed": "状态查询异常,请稍后刷新",
"manual_required": "当前需要人工处理,请联系客服",
}
return messages.get(task.issue_code, "") if task.issue_code else ""
def _binding_failure_issue(bind_task: DouyuTask, result: dict[str, Any]) -> str:
phase = str(result.get("bind_phase") or "")
message = str(bind_task.message or "")
if phase == "change_waiting" or "暂不能换绑" in message:
task_issue = "account_role_cooldown"
elif phase == "confirm_failed" or "待绑定游戏账号" in message or "未到换绑时间" in message:
task_issue = "customer_role_cooldown"
else:
return "binding_failed"
messages = {
"account_role_cooldown": "当前绑定账号暂不可换绑,请截图本页面并联系客服处理",
"customer_role_cooldown": "该游戏角色仍在换绑冷却期,请截图本页面并联系客服处理",
}
return task_issue if messages.get(task_issue) else "binding_failed"
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
task = _load_task(db, task_id)
@@ -1093,8 +1111,8 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
if bind_task.status in {"failed", "error", "stopped"}:
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = "binding_failed"
task.last_error = bind_task.message or "绑定任务失败"
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"
@@ -1119,6 +1137,21 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
)
if after != before:
task.updated_at = _now()
if task.issue_code in {
"account_role_cooldown",
"customer_role_cooldown",
}:
_append_event(
db,
task.id,
"binding_failed",
detail={
"issueCode": task.issue_code,
"bindTaskId": bind_task.id,
"bindPhase": str(result.get("bind_phase") or ""),
"rawError": str(bind_task.message or "")[:1000],
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)