fix(douyu): unify binding state and scheduler health
This commit is contained in:
@@ -2,13 +2,23 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from .database import SessionLocal
|
||||
|
||||
_started = False
|
||||
_heartbeat_thread: threading.Thread | None = None
|
||||
_heartbeat_stop = threading.Event()
|
||||
_heartbeat_lock = threading.Lock()
|
||||
_HEARTBEAT_INTERVAL_SECONDS = 5
|
||||
_HEARTBEAT_STALE_SECONDS = 30
|
||||
|
||||
|
||||
def _control_plane_enabled() -> bool:
|
||||
@@ -20,6 +30,103 @@ def _control_plane_enabled() -> bool:
|
||||
}
|
||||
|
||||
|
||||
def _runtime_heartbeat_path() -> Path:
|
||||
configured = os.getenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
return Path(__file__).resolve().parents[2] / "data" / "background_runtime.json"
|
||||
|
||||
|
||||
def _runtime_heartbeat_payload() -> dict[str, Any]:
|
||||
from .services.automation.scheduler import scheduler_status
|
||||
|
||||
return {
|
||||
"pid": os.getpid(),
|
||||
"updatedAt": datetime.now(UTC).isoformat(),
|
||||
"scheduler": scheduler_status(),
|
||||
}
|
||||
|
||||
|
||||
def _write_runtime_heartbeat() -> None:
|
||||
path = _runtime_heartbeat_path()
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(f"{path.suffix}.tmp")
|
||||
temporary.write_text(
|
||||
json.dumps(_runtime_heartbeat_payload(), ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary.replace(path)
|
||||
except Exception: # noqa: BLE001 - heartbeat must not stop background services
|
||||
logger.exception("写入后台运行时心跳失败: {}", path)
|
||||
|
||||
|
||||
def _heartbeat_loop() -> None:
|
||||
while not _heartbeat_stop.wait(_HEARTBEAT_INTERVAL_SECONDS):
|
||||
_write_runtime_heartbeat()
|
||||
|
||||
|
||||
def _start_runtime_heartbeat() -> None:
|
||||
global _heartbeat_thread
|
||||
with _heartbeat_lock:
|
||||
if _heartbeat_thread is not None and _heartbeat_thread.is_alive():
|
||||
return
|
||||
_heartbeat_stop.clear()
|
||||
_write_runtime_heartbeat()
|
||||
_heartbeat_thread = threading.Thread(
|
||||
target=_heartbeat_loop,
|
||||
name="background-runtime-heartbeat",
|
||||
daemon=True,
|
||||
)
|
||||
_heartbeat_thread.start()
|
||||
|
||||
|
||||
def _stop_runtime_heartbeat() -> None:
|
||||
global _heartbeat_thread
|
||||
with _heartbeat_lock:
|
||||
thread = _heartbeat_thread
|
||||
_heartbeat_thread = None
|
||||
_heartbeat_stop.set()
|
||||
if thread is not None and thread.is_alive():
|
||||
thread.join(timeout=2)
|
||||
try:
|
||||
_runtime_heartbeat_path().unlink(missing_ok=True)
|
||||
except OSError:
|
||||
logger.exception("清理后台运行时心跳失败")
|
||||
|
||||
|
||||
def background_runtime_status() -> dict[str, Any]:
|
||||
"""读取独立后台进程心跳;API 进程据此展示真实调度状态。"""
|
||||
path = _runtime_heartbeat_path()
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
heartbeat_at = datetime.fromisoformat(str(payload.get("updatedAt") or ""))
|
||||
if heartbeat_at.tzinfo is None:
|
||||
heartbeat_at = heartbeat_at.replace(tzinfo=UTC)
|
||||
age_seconds = max(
|
||||
0.0,
|
||||
(datetime.now(UTC) - heartbeat_at).total_seconds(),
|
||||
)
|
||||
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
||||
return {
|
||||
"running": False,
|
||||
"heartbeatAt": None,
|
||||
"ageSeconds": None,
|
||||
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
|
||||
"pid": None,
|
||||
"scheduler": {},
|
||||
}
|
||||
scheduler = payload.get("scheduler")
|
||||
return {
|
||||
"running": age_seconds <= _HEARTBEAT_STALE_SECONDS,
|
||||
"heartbeatAt": heartbeat_at.isoformat(),
|
||||
"ageSeconds": round(age_seconds, 1),
|
||||
"staleAfterSeconds": _HEARTBEAT_STALE_SECONDS,
|
||||
"pid": payload.get("pid"),
|
||||
"scheduler": scheduler if isinstance(scheduler, dict) else {},
|
||||
}
|
||||
|
||||
|
||||
def recover_orphaned_work() -> None:
|
||||
"""进程启动时收敛上次中断的任务和运行记录。"""
|
||||
from .models import ExecutionJob
|
||||
@@ -111,6 +218,7 @@ def start_background_services() -> bool:
|
||||
start_platform_fulfillment_auto_allocator()
|
||||
start_binding_poll_scheduler()
|
||||
start_payment_poll_scheduler()
|
||||
_start_runtime_heartbeat()
|
||||
_started = True
|
||||
logger.info("后台服务已启动")
|
||||
return True
|
||||
@@ -140,11 +248,13 @@ def stop_background_services() -> None:
|
||||
stop_integration_outbox_worker()
|
||||
stop_scheduler()
|
||||
stop_execution_job_worker()
|
||||
_stop_runtime_heartbeat()
|
||||
_started = False
|
||||
logger.info("后台服务已停止")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"background_runtime_status",
|
||||
"recover_orphaned_work",
|
||||
"start_background_services",
|
||||
"stop_background_services",
|
||||
|
||||
@@ -505,6 +505,10 @@
|
||||
"20261123_0126_repair_false_binding_sync.py": {
|
||||
"revision": "20261123_0126",
|
||||
"sha256": "86c201d2298845f7f3eb3e733760fe46911638dc1ef046d4518c02172cfaba6f"
|
||||
},
|
||||
"20261123_0127_link_latest_pending_binding.py": {
|
||||
"revision": "20261123_0127",
|
||||
"sha256": "cedfe2928e80a2d530906621b52373aab280afc19101311318512021cc093df7"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""link latest account-workbench pending role to active fulfillment tasks.
|
||||
|
||||
Revision ID: 20261123_0127
|
||||
Revises: 20261123_0126
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
from web.backend.services.account_binding import pending_binding_role_from_result
|
||||
|
||||
revision: str = "20261123_0127"
|
||||
down_revision: str | None = "20261123_0126"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
tasks = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT
|
||||
t.id AS task_id,
|
||||
t.account_id,
|
||||
t.bind_task_id,
|
||||
a.username,
|
||||
a.nickname
|
||||
FROM platform_fulfillment_tasks AS t
|
||||
JOIN accounts AS a ON a.id = t.account_id
|
||||
JOIN account_leases AS l ON l.id = t.lease_id
|
||||
WHERE t.scope = 'elite'
|
||||
AND t.binding_status IN ('allocated', 'waiting_bind', 'role_ready')
|
||||
AND t.execution_status NOT IN ('completed', 'cancelled', 'manual_required')
|
||||
AND l.status = 'active'
|
||||
"""
|
||||
)
|
||||
).mappings().all()
|
||||
now = datetime.now(UTC).replace(tzinfo=None)
|
||||
for task in tasks:
|
||||
candidates = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT id, result
|
||||
FROM douyu_tasks
|
||||
WHERE account_id = :account_id
|
||||
AND task_type = 'get_bind_qr'
|
||||
AND handbook_scope = 'elite'
|
||||
AND status = 'success'
|
||||
AND id > :current_bind_task_id
|
||||
ORDER BY id DESC
|
||||
LIMIT 20
|
||||
"""
|
||||
),
|
||||
{
|
||||
"account_id": int(task["account_id"]),
|
||||
"current_bind_task_id": int(task["bind_task_id"] or 0),
|
||||
},
|
||||
).mappings().all()
|
||||
latest: dict[str, object] | None = None
|
||||
role_name = ""
|
||||
for candidate in candidates:
|
||||
result = candidate["result"]
|
||||
if isinstance(result, str):
|
||||
try:
|
||||
result = json.loads(result)
|
||||
except json.JSONDecodeError:
|
||||
result = {}
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
role_name = pending_binding_role_from_result(result)
|
||||
if role_name:
|
||||
latest = dict(candidate)
|
||||
break
|
||||
if latest is None:
|
||||
continue
|
||||
task_id = int(task["task_id"])
|
||||
bind_task_id = int(latest["id"])
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_fulfillment_tasks
|
||||
SET bind_task_id = :bind_task_id,
|
||||
binding_status = 'role_ready',
|
||||
execution_status = 'role_ready',
|
||||
issue_code = '',
|
||||
last_error = '',
|
||||
updated_at = :now
|
||||
WHERE id = :task_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"bind_task_id": bind_task_id,
|
||||
"now": now,
|
||||
},
|
||||
)
|
||||
detail = {
|
||||
"accountId": int(task["account_id"]),
|
||||
"accountName": str(task["nickname"] or task["username"] or ""),
|
||||
"bindTaskId": bind_task_id,
|
||||
"previousBindTaskId": int(task["bind_task_id"] or 0),
|
||||
"roleName": role_name,
|
||||
"source": "account_workbench",
|
||||
"backfilled": True,
|
||||
}
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO platform_fulfillment_events (
|
||||
task_id,
|
||||
event_type,
|
||||
actor_type,
|
||||
actor_id,
|
||||
detail_json,
|
||||
created_at
|
||||
) VALUES (
|
||||
:task_id,
|
||||
'binding_pending_task_linked',
|
||||
'system',
|
||||
'',
|
||||
:detail_json,
|
||||
:created_at
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"detail_json": json.dumps(detail, ensure_ascii=False),
|
||||
"created_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""数据修复不回退,避免履约任务重新指向过期待确认角色。"""
|
||||
@@ -143,6 +143,7 @@ def list_jobs(
|
||||
# 巡检与重登是两个作业,但通过数据库联动:巡检把行标成 invalid,重登作业的
|
||||
# 候选条件正是这个字段。这里把「当前有多少条等着重登」一并返回,页面才能把
|
||||
# 这层上下游关系显示出来,而不是让人以为两个开关互不相干。
|
||||
from ..background_runtime import background_runtime_status
|
||||
from ..database import worker_engine
|
||||
from ..services.automation.jobs.ck_relogin import count_pending_relogin
|
||||
from ..services.binding_poll_scheduler import (
|
||||
@@ -155,9 +156,31 @@ def list_jobs(
|
||||
from ..services.task_runtime import lane_stats
|
||||
|
||||
pending_relogin = count_pending_relogin(db)
|
||||
scheduler_state = scheduler_status()
|
||||
background_runtime = background_runtime_status()
|
||||
background_scheduler = background_runtime.get("scheduler")
|
||||
if (
|
||||
not scheduler_state["running"]
|
||||
and background_runtime["running"]
|
||||
and isinstance(background_scheduler, dict)
|
||||
and background_scheduler.get("running") is True
|
||||
):
|
||||
scheduler_state = {
|
||||
**scheduler_state,
|
||||
"running": True,
|
||||
"process": "background",
|
||||
"pid": background_runtime.get("pid"),
|
||||
"heartbeatAt": background_runtime.get("heartbeatAt"),
|
||||
}
|
||||
else:
|
||||
scheduler_state = {
|
||||
**scheduler_state,
|
||||
"process": "api" if scheduler_state["running"] else "none",
|
||||
"heartbeatAt": background_runtime.get("heartbeatAt"),
|
||||
}
|
||||
|
||||
return {
|
||||
"scheduler": scheduler_status(),
|
||||
"scheduler": scheduler_state,
|
||||
"runtime": {
|
||||
"task_lanes": lane_stats(),
|
||||
"worker_db_pool": getattr(worker_engine.pool, "status", lambda: "")()
|
||||
@@ -166,6 +189,7 @@ def list_jobs(
|
||||
"binding_poll": binding_poll_status(),
|
||||
"payment_poll": payment_poll_status(),
|
||||
"execution_jobs": execution_job_worker_status(),
|
||||
"background_runtime": background_runtime,
|
||||
},
|
||||
"pending_relogin": pending_relogin,
|
||||
"jobs": [
|
||||
|
||||
@@ -1778,6 +1778,7 @@ class DouyuTaskOut(BaseModel):
|
||||
handbook_scope: str = "legacy"
|
||||
status: str
|
||||
message: str = ""
|
||||
binding: dict[str, Any] = Field(default_factory=dict)
|
||||
result: dict[str, Any] | None = None
|
||||
created_by: int
|
||||
created_at: datetime | None = None
|
||||
@@ -1798,6 +1799,7 @@ class DouyuTaskOut(BaseModel):
|
||||
"handbook_scope": self.handbook_scope,
|
||||
"status": self.status,
|
||||
"message": self.message,
|
||||
"binding": self.binding,
|
||||
"result": self.result,
|
||||
"created_by": self.created_by,
|
||||
"created_at": _isoformat(self.created_at),
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""斗鱼绑定任务的唯一读取模型。
|
||||
|
||||
``DouyuTask.result`` 是任务级绑定事实的来源:
|
||||
|
||||
- 本次扫码识别出的待确认角色只属于这个任务;
|
||||
- ``bind_confirmed`` 表示这个任务是否已经把角色确认生效;
|
||||
- ``accounts.game_name`` / ``role_bind_status`` 只表示账号当前状态,
|
||||
不能拿来判断某个履约订单是否已经确认。
|
||||
|
||||
精英宝典、履约详情、客户页和履约刷新都必须消费这里的结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .account_binding import (
|
||||
binding_channel,
|
||||
get_bind_status,
|
||||
pending_binding_role_from_result,
|
||||
)
|
||||
|
||||
BINDING_VIEW_NONE = "none"
|
||||
BINDING_VIEW_WAITING_SCAN = "waiting_scan"
|
||||
BINDING_VIEW_PENDING = "pending"
|
||||
BINDING_VIEW_CONFIRMED = "confirmed"
|
||||
BINDING_VIEW_FAILED = "failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DouyuBindingView:
|
||||
"""供所有绑定入口共享的稳定视图。"""
|
||||
|
||||
source_task_id: int | None
|
||||
source_task_type: str
|
||||
source_task_status: str
|
||||
status: str
|
||||
bind_phase: str
|
||||
pending_role_name: str
|
||||
pending_area_name: str
|
||||
pending_plat_name: str
|
||||
pending_channel: str
|
||||
confirmed_role_name: str
|
||||
confirmed_area_name: str
|
||||
confirmed_plat_name: str
|
||||
confirmed_channel: str
|
||||
effective_role_name: str
|
||||
effective_area_name: str
|
||||
effective_plat_name: str
|
||||
effective_channel: str
|
||||
current_role_name: str
|
||||
current_area_name: str
|
||||
current_plat_name: str
|
||||
current_channel: str
|
||||
qr_url: str
|
||||
reported_ready_for_confirm: bool
|
||||
bind_confirmed: bool
|
||||
bind_ready_for_confirm: bool
|
||||
account_bind_status: str
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def resolve_douyu_binding(
|
||||
task: DouyuTask | None,
|
||||
*,
|
||||
account: Account | None = None,
|
||||
) -> DouyuBindingView:
|
||||
"""从任务结果和账号当前状态生成唯一绑定视图。"""
|
||||
result = task.result if task is not None and isinstance(task.result, dict) else {}
|
||||
source_status = str(task.status or "") if task is not None else ""
|
||||
successful_task = source_status == "success"
|
||||
pending_role = pending_binding_role_from_result(result)
|
||||
bind_confirmed = successful_task and bool(result.get("bind_confirmed"))
|
||||
if pending_role:
|
||||
bind_confirmed = False
|
||||
|
||||
pending_area = str(result.get("area_name") or "").strip() if pending_role else ""
|
||||
pending_plat = str(result.get("plat_name") or "").strip() if pending_role else ""
|
||||
pending_channel = binding_channel(
|
||||
{
|
||||
"area_name": pending_area,
|
||||
"plat_name": pending_plat,
|
||||
}
|
||||
)
|
||||
|
||||
confirmed_role = (
|
||||
str(result.get("role_name") or result.get("current_role_name") or "").strip()
|
||||
if bind_confirmed
|
||||
else ""
|
||||
)
|
||||
confirmed_area = str(result.get("area_name") or "").strip() if bind_confirmed else ""
|
||||
confirmed_plat = str(result.get("plat_name") or "").strip() if bind_confirmed else ""
|
||||
confirmed_channel = binding_channel(
|
||||
{
|
||||
"area_name": confirmed_area,
|
||||
"plat_name": confirmed_plat,
|
||||
}
|
||||
)
|
||||
|
||||
account_bind_status = get_bind_status(account, "elite") if account else ""
|
||||
current_role = str(account.game_name or "").strip() if account else ""
|
||||
current_area = str(result.get("current_area_name") or "").strip()
|
||||
current_plat = str(result.get("current_plat_name") or "").strip()
|
||||
current_channel = str(account.game_channel or "").strip() if account else ""
|
||||
if not current_role:
|
||||
current_role = str(
|
||||
result.get("current_role_name") or result.get("baseline_role_name") or ""
|
||||
).strip()
|
||||
if not current_channel:
|
||||
current_channel = binding_channel(
|
||||
{
|
||||
"area_name": result.get("current_area_name"),
|
||||
"plat_name": result.get("current_plat_name"),
|
||||
}
|
||||
)
|
||||
|
||||
effective_role = pending_role or confirmed_role
|
||||
effective_area = pending_area or confirmed_area
|
||||
effective_plat = pending_plat or confirmed_plat
|
||||
effective_channel = pending_channel or confirmed_channel
|
||||
qr_url = str(result.get("url") or "")
|
||||
|
||||
if source_status in {"failed", "error", "stopped"}:
|
||||
status = BINDING_VIEW_FAILED
|
||||
elif bind_confirmed:
|
||||
status = BINDING_VIEW_CONFIRMED
|
||||
elif pending_role:
|
||||
status = BINDING_VIEW_PENDING
|
||||
elif qr_url:
|
||||
status = BINDING_VIEW_WAITING_SCAN
|
||||
else:
|
||||
status = BINDING_VIEW_NONE
|
||||
|
||||
return DouyuBindingView(
|
||||
source_task_id=int(task.id) if task is not None else None,
|
||||
source_task_type=str(task.task_type or "") if task is not None else "",
|
||||
source_task_status=source_status,
|
||||
status=status,
|
||||
bind_phase=str(result.get("bind_phase") or ""),
|
||||
pending_role_name=pending_role,
|
||||
pending_area_name=pending_area,
|
||||
pending_plat_name=pending_plat,
|
||||
pending_channel=pending_channel,
|
||||
confirmed_role_name=confirmed_role,
|
||||
confirmed_area_name=confirmed_area,
|
||||
confirmed_plat_name=confirmed_plat,
|
||||
confirmed_channel=confirmed_channel,
|
||||
effective_role_name=effective_role,
|
||||
effective_area_name=effective_area,
|
||||
effective_plat_name=effective_plat,
|
||||
effective_channel=effective_channel,
|
||||
current_role_name=current_role,
|
||||
current_area_name=current_area,
|
||||
current_plat_name=current_plat,
|
||||
current_channel=current_channel,
|
||||
qr_url=qr_url,
|
||||
reported_ready_for_confirm=bool(result.get("bind_ready_for_confirm")),
|
||||
bind_confirmed=status == BINDING_VIEW_CONFIRMED,
|
||||
bind_ready_for_confirm=status == BINDING_VIEW_PENDING,
|
||||
account_bind_status=account_bind_status,
|
||||
)
|
||||
@@ -41,10 +41,6 @@ from ..models import (
|
||||
User,
|
||||
)
|
||||
from ..permissions import user_has_permission
|
||||
from .account_binding import (
|
||||
binding_channel,
|
||||
binding_role_from_result,
|
||||
)
|
||||
from .account_events_service import (
|
||||
CATEGORY_OPS,
|
||||
EVENT_COLLAB_SYNCED,
|
||||
|
||||
@@ -17,9 +17,9 @@ from ..models import (
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from .account_binding import binding_channel, binding_role_from_result
|
||||
from .account_events_service import EVENT_COLLAB_SYNCED
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .douyu_binding import BINDING_VIEW_CONFIRMED, resolve_douyu_binding
|
||||
from .douyu_collab_common import (
|
||||
POINTS_THRESHOLD_DEFAULT,
|
||||
SOURCE_TYPE_PLATFORM_FULFILLMENT,
|
||||
@@ -101,15 +101,18 @@ def _apply_platform_fulfillment_binding(
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
result = (
|
||||
bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
|
||||
)
|
||||
role = binding_role_from_result(result)
|
||||
if not role:
|
||||
if bind_task is None:
|
||||
return
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=db.get(Account, int(task.account_id)) if task.account_id else None,
|
||||
)
|
||||
if binding.status != BINDING_VIEW_CONFIRMED:
|
||||
return
|
||||
role = binding.confirmed_role_name
|
||||
if overwrite or not order.bind_game_role:
|
||||
order.bind_game_role = _text(role, max_length=128)
|
||||
channel = binding_channel(result)
|
||||
channel = binding.confirmed_channel
|
||||
if channel and (overwrite or not order.bind_game_channel):
|
||||
order.bind_game_channel = _text(channel, max_length=128)
|
||||
if overwrite or not order.bind_snapshot_at:
|
||||
|
||||
@@ -15,6 +15,7 @@ from core.douyu.cookie_utils import cookie_value
|
||||
from ..models import Account, DouyuConfig, DouyuTask
|
||||
from . import account_query_filters as account_filters
|
||||
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
|
||||
from .douyu_binding import resolve_douyu_binding
|
||||
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
cookie_holding_filter = account_filters.cookie_holding_filter
|
||||
@@ -682,6 +683,7 @@ def sanitize_douyu_task_result(
|
||||
def douyu_task_payload(task: DouyuTask, *, include_detail: bool = False) -> dict:
|
||||
"""生成 REST 与 WebSocket 共用的斗鱼任务载荷。"""
|
||||
account = task.account
|
||||
binding = resolve_douyu_binding(task, account=account).as_dict()
|
||||
|
||||
def isoformat(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
@@ -701,6 +703,7 @@ def douyu_task_payload(task: DouyuTask, *, include_detail: bool = False) -> dict
|
||||
"handbook_scope": task.handbook_scope or "legacy",
|
||||
"status": task.status or "",
|
||||
"message": task.message or "",
|
||||
"binding": binding,
|
||||
"result": sanitize_douyu_task_result(
|
||||
task.result if isinstance(task.result, dict) else None,
|
||||
task.task_type or "",
|
||||
|
||||
@@ -17,10 +17,12 @@ from ...models import (
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from ..account_binding import (
|
||||
pending_binding_role_from_result,
|
||||
)
|
||||
from ..business_events import record_douyu_task_started
|
||||
from ..douyu_binding import (
|
||||
BINDING_VIEW_CONFIRMED,
|
||||
BINDING_VIEW_PENDING,
|
||||
resolve_douyu_binding,
|
||||
)
|
||||
from ..execution_jobs import (
|
||||
JOB_DOUYU_BINDING,
|
||||
LANE_FULFILLMENT,
|
||||
@@ -64,6 +66,10 @@ ACCOUNT_CONFIRMATION_TASK_TYPES = frozenset(
|
||||
"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(
|
||||
@@ -82,12 +88,18 @@ def start_binding_sync(
|
||||
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
|
||||
binding = resolve_douyu_binding(
|
||||
existing,
|
||||
account=db.get(Account, int(task.account_id)),
|
||||
)
|
||||
if bool(result.get("bind_confirmed")) or pending_role:
|
||||
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)
|
||||
@@ -193,6 +205,14 @@ 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)
|
||||
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()
|
||||
@@ -206,23 +226,26 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||
task.last_error,
|
||||
)
|
||||
result = bind_task.result or {}
|
||||
pending_role = pending_binding_role_from_result(result)
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=db.get(Account, int(task.account_id)) if task.account_id else None,
|
||||
)
|
||||
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")):
|
||||
elif binding.status == BINDING_VIEW_CONFIRMED:
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
elif pending_role:
|
||||
elif binding.status == BINDING_VIEW_PENDING:
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
elif bool(result.get("bind_ready_for_confirm")):
|
||||
elif binding.reported_ready_for_confirm:
|
||||
# 兼容旧快照:同名旧角色曾被误标为待确认。清掉绑定指针后,客户页会
|
||||
# 回到已分配状态,并在下一次刷新时自动生成新二维码、重新开始轮询。
|
||||
previous_bind_task_id = task.bind_task_id
|
||||
@@ -250,7 +273,7 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||
_apply_task_lease_policy(db, task)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
elif result.get("url"):
|
||||
elif binding.qr_url:
|
||||
task.binding_status = "qr_pending"
|
||||
task.execution_status = "waiting_bind"
|
||||
task.issue_code = ""
|
||||
@@ -301,15 +324,55 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
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)
|
||||
result = douyu_task.result or {}
|
||||
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 result.get("bind_confirmed") is not True
|
||||
or binding.status != BINDING_VIEW_CONFIRMED
|
||||
):
|
||||
# 查询/出码任务只能证明“账号历史绑定是什么”,不能证明本次订单已经确认。
|
||||
# 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把账号权威
|
||||
# 绑定投影到履约任务。
|
||||
return len(task_ids)
|
||||
# 只有明确执行成功并回查到 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),
|
||||
@@ -318,6 +381,83 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
)
|
||||
|
||||
|
||||
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",
|
||||
)
|
||||
.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,
|
||||
*,
|
||||
@@ -325,11 +465,12 @@ def sync_active_task_from_account_binding(
|
||||
scope: str,
|
||||
source_task_id: int | None = None,
|
||||
) -> int:
|
||||
"""账号权威绑定已确认时,把当前活跃履约任务同步到 bound。
|
||||
"""确认任务成功后,把当前活跃履约任务同步到 bound。
|
||||
|
||||
精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看
|
||||
``PlatformFulfillmentTask.bind_task_id``。账号上的绑定状态才是最终事实。
|
||||
只在任务已经识别出待确认角色后同步,避免把账号历史绑定误当成当前订单结果。
|
||||
``PlatformFulfillmentTask.bind_task_id``。这里的唯一事实是确认任务的
|
||||
``result``:只有 ``resolve_douyu_binding`` 返回 confirmed 才允许投影。
|
||||
账号上的 ``role_bind_status`` 只描述当前生效角色,不能证明本订单已确认。
|
||||
"""
|
||||
if scope != "elite":
|
||||
return 0
|
||||
@@ -338,15 +479,19 @@ def sync_active_task_from_account_binding(
|
||||
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 (source_task.result or {}).get("bind_confirmed") is not True
|
||||
or binding.status != BINDING_VIEW_CONFIRMED
|
||||
):
|
||||
return 0
|
||||
account = db.get(Account, int(account_id))
|
||||
if account is None or account.role_bind_status != "bound":
|
||||
return 0
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
@@ -379,13 +524,25 @@ def sync_active_task_from_account_binding(
|
||||
task.id,
|
||||
"binding_synced_from_account",
|
||||
detail={
|
||||
"accountId": int(account.id),
|
||||
"accountName": account.nickname or account.username,
|
||||
"roleName": str(account.game_name or ""),
|
||||
"gameChannel": str(account.game_channel or ""),
|
||||
"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.role_change_available_at
|
||||
if account is not None and account.role_change_available_at
|
||||
else None
|
||||
),
|
||||
"sourceTaskId": source_task_id,
|
||||
|
||||
@@ -24,9 +24,11 @@ from ...models import (
|
||||
User,
|
||||
)
|
||||
from ...permissions import ROLE_LABELS
|
||||
from ..account_binding import (
|
||||
binding_role_from_result,
|
||||
pending_binding_role_from_result,
|
||||
from ..douyu_binding import (
|
||||
BINDING_VIEW_CONFIRMED,
|
||||
BINDING_VIEW_FAILED,
|
||||
BINDING_VIEW_PENDING,
|
||||
resolve_douyu_binding,
|
||||
)
|
||||
from ..file_service import build_file_url
|
||||
from . import classification
|
||||
@@ -362,11 +364,9 @@ def _task_out(
|
||||
)
|
||||
collab_order = resolved.collab_orders.get(int(task.id))
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
bind_result_confirmed = bool(bind_result.get("bind_confirmed"))
|
||||
account_binding_confirmed = bool(
|
||||
bind_result_confirmed
|
||||
and account is not None
|
||||
and account.role_bind_status == "bound"
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=account,
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
effective_last_error = _effective_task_message(task, effective_issue)
|
||||
@@ -382,12 +382,6 @@ def _task_out(
|
||||
.limit(1)
|
||||
.scalar()
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
)
|
||||
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=sale_mode,
|
||||
@@ -486,20 +480,13 @@ def _task_out(
|
||||
"taskType": bind_task.task_type,
|
||||
"status": bind_task.status,
|
||||
"message": bind_task.message,
|
||||
"qrUrl": str(bind_result.get("url") or "") if include_qr else "",
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||
"bindReadyForConfirm": bool(pending_role),
|
||||
"bindConfirmed": bool(
|
||||
account_binding_confirmed
|
||||
or bind_result.get("bind_confirmed")
|
||||
),
|
||||
"qrUrl": binding.qr_url if include_qr else "",
|
||||
"roleName": binding.effective_role_name,
|
||||
"areaName": binding.effective_area_name,
|
||||
"platName": binding.effective_plat_name,
|
||||
"bindPhase": binding.bind_phase,
|
||||
"bindReadyForConfirm": binding.status == BINDING_VIEW_PENDING,
|
||||
"bindConfirmed": binding.bind_confirmed,
|
||||
}
|
||||
if bind_task
|
||||
else None
|
||||
@@ -612,19 +599,24 @@ def _customer_binding_queue_state(
|
||||
return "failed", 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":
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
)
|
||||
if binding.status == BINDING_VIEW_CONFIRMED:
|
||||
return "confirmed", 0
|
||||
if pending_binding_role_from_result(result):
|
||||
if binding.status == BINDING_VIEW_PENDING:
|
||||
return "role_ready", 0
|
||||
if bind_task.status in {"failed", "error", "stopped"}:
|
||||
if binding.status == BINDING_VIEW_FAILED:
|
||||
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
|
||||
if binding.qr_url:
|
||||
return (
|
||||
"waiting_scan",
|
||||
5000 if (bind_task.result or {}).get("bind_polling") else 0,
|
||||
)
|
||||
return "preparing", 1000
|
||||
|
||||
|
||||
@@ -638,16 +630,9 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
account = db.get(Account, int(task.account_id)) if task.account_id else None
|
||||
bind_result_confirmed = bool(bind_result.get("bind_confirmed"))
|
||||
account_binding_confirmed = bool(
|
||||
bind_result_confirmed
|
||||
and account is not None
|
||||
and account.role_bind_status == "bound"
|
||||
)
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
binding = resolve_douyu_binding(
|
||||
bind_task,
|
||||
account=account,
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
lease = (
|
||||
@@ -656,8 +641,6 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
else None
|
||||
)
|
||||
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,
|
||||
@@ -685,18 +668,11 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
"qrUrl": str(bind_result.get("url") or ""),
|
||||
"qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""),
|
||||
"qrExpiresAt": str(bind_result.get("qr_expires_at") or ""),
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindReadyForConfirm": (bool(pending_role) and not binding_failed),
|
||||
"bindConfirmed": bool(
|
||||
binding_confirmed
|
||||
and (account_binding_confirmed or bind_result.get("bind_confirmed"))
|
||||
),
|
||||
"roleName": binding.effective_role_name,
|
||||
"areaName": binding.effective_area_name,
|
||||
"platName": binding.effective_plat_name,
|
||||
"bindReadyForConfirm": binding.status == BINDING_VIEW_PENDING,
|
||||
"bindConfirmed": binding.bind_confirmed,
|
||||
"queueState": queue_state,
|
||||
"retryAfterMs": retry_after_ms,
|
||||
"queueLane": bind_task.queue_lane if bind_task else "",
|
||||
|
||||
Reference in New Issue
Block a user