fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性
This commit is contained in:
@@ -12,7 +12,7 @@ from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
@@ -21,6 +21,8 @@ from ..models import (
|
||||
Account,
|
||||
AutomationJob,
|
||||
AutomationRun,
|
||||
DouyuTask,
|
||||
ExecutionJob,
|
||||
LoginQuotaSetting,
|
||||
LoginTask,
|
||||
User,
|
||||
@@ -180,6 +182,8 @@ def list_jobs(
|
||||
from ..services.binding_poll_scheduler import (
|
||||
scheduler_status as binding_poll_status,
|
||||
)
|
||||
from ..services.douyu_runner_core import douyu_batch_registry
|
||||
from ..services.execution_jobs import STATUS_QUEUED, STATUS_RUNNING
|
||||
from ..services.execution_worker import execution_job_worker_status
|
||||
from ..services.payment_poll_scheduler import (
|
||||
scheduler_status as payment_poll_status,
|
||||
@@ -203,6 +207,8 @@ def list_jobs(
|
||||
"pid": background_runtime.get("pid"),
|
||||
"heartbeatAt": background_runtime.get("heartbeatAt"),
|
||||
}
|
||||
if "in_flight" in background_scheduler:
|
||||
scheduler_state["in_flight"] = background_scheduler["in_flight"]
|
||||
else:
|
||||
scheduler_state = {
|
||||
**scheduler_state,
|
||||
@@ -210,16 +216,91 @@ def list_jobs(
|
||||
"heartbeatAt": background_runtime.get("heartbeatAt"),
|
||||
}
|
||||
|
||||
bg_rt_raw = background_runtime.get("runtime")
|
||||
bg_rt = (
|
||||
bg_rt_raw
|
||||
if scheduler_state["process"] == "background" and isinstance(bg_rt_raw, dict)
|
||||
else {}
|
||||
)
|
||||
local_worker_pool = (
|
||||
getattr(worker_engine.pool, "status", lambda: "")()
|
||||
if callable(getattr(worker_engine.pool, "status", None))
|
||||
else ""
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
exec_rows = (
|
||||
db.query(
|
||||
ExecutionJob.lane_scope,
|
||||
ExecutionJob.status,
|
||||
func.count(ExecutionJob.id),
|
||||
)
|
||||
.filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)))
|
||||
.group_by(ExecutionJob.lane_scope, ExecutionJob.status)
|
||||
.all()
|
||||
)
|
||||
exec_backlog: dict[str, dict[str, int]] = {}
|
||||
for lane_scope, status, count in exec_rows:
|
||||
bucket = exec_backlog.setdefault(str(lane_scope), {"queued": 0, "running": 0})
|
||||
if status in bucket:
|
||||
bucket[str(status)] = int(count or 0)
|
||||
|
||||
poll_rows = (
|
||||
db.query(
|
||||
DouyuTask.queue_lane,
|
||||
func.count(DouyuTask.id),
|
||||
func.sum(
|
||||
case(
|
||||
(
|
||||
DouyuTask.next_run_at <= now,
|
||||
1,
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
)
|
||||
.filter(
|
||||
DouyuTask.queue_lane.in_(("binding_poll", "payment_poll")),
|
||||
DouyuTask.status == "running",
|
||||
)
|
||||
.group_by(DouyuTask.queue_lane)
|
||||
.all()
|
||||
)
|
||||
poll_backlog: dict[str, dict[str, int]] = {
|
||||
"binding_poll": {"running": 0, "due": 0},
|
||||
"payment_poll": {"running": 0, "due": 0},
|
||||
}
|
||||
for queue_lane, total, due in poll_rows:
|
||||
poll_backlog[str(queue_lane)] = {
|
||||
"running": int(total or 0),
|
||||
"due": int(due or 0),
|
||||
}
|
||||
|
||||
return {
|
||||
"scheduler": scheduler_state,
|
||||
"runtime": {
|
||||
"task_lanes": lane_stats(),
|
||||
"worker_db_pool": getattr(worker_engine.pool, "status", lambda: "")()
|
||||
if callable(getattr(worker_engine.pool, "status", None))
|
||||
else "",
|
||||
"binding_poll": binding_poll_status(),
|
||||
"payment_poll": payment_poll_status(),
|
||||
"execution_jobs": execution_job_worker_status(),
|
||||
"task_lanes": bg_rt.get("task_lanes")
|
||||
if isinstance(bg_rt.get("task_lanes"), dict)
|
||||
else lane_stats(),
|
||||
"worker_db_pool": bg_rt["worker_db_pool"]
|
||||
if isinstance(bg_rt.get("worker_db_pool"), str)
|
||||
else local_worker_pool,
|
||||
"binding_poll": bg_rt.get("binding_poll")
|
||||
if isinstance(bg_rt.get("binding_poll"), dict)
|
||||
else binding_poll_status(),
|
||||
"payment_poll": bg_rt.get("payment_poll")
|
||||
if isinstance(bg_rt.get("payment_poll"), dict)
|
||||
else payment_poll_status(),
|
||||
"execution_jobs": bg_rt.get("execution_jobs")
|
||||
if isinstance(bg_rt.get("execution_jobs"), dict)
|
||||
else execution_job_worker_status(),
|
||||
"douyu_batches": bg_rt.get("douyu_batches")
|
||||
if isinstance(bg_rt.get("douyu_batches"), dict)
|
||||
else douyu_batch_registry.stats(),
|
||||
"queues": {
|
||||
"execution_jobs": exec_backlog,
|
||||
**poll_backlog,
|
||||
},
|
||||
"background_runtime": background_runtime,
|
||||
},
|
||||
"pending_relogin": pending_relogin,
|
||||
|
||||
@@ -193,7 +193,13 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get
|
||||
except FishFinRechargeConfigError as exc:
|
||||
logger.error("[douyu] 供应商直充回调配置无效: {}", exc)
|
||||
raise HTTPException(status_code=503, detail="供应商直充回调未配置") from exc
|
||||
if not client.verify_response_sign(payload, "POST"):
|
||||
try:
|
||||
verified = client.verify_response_sign(payload, "POST")
|
||||
finally:
|
||||
close = getattr(client, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
if not verified:
|
||||
logger.warning("[douyu] 供应商直充回调验签失败: keys={}", sorted(payload))
|
||||
raise HTTPException(status_code=401, detail="供应商回调签名无效")
|
||||
|
||||
@@ -1285,14 +1291,19 @@ def list_live_goods(
|
||||
"""实时读取精英宝典活动商品,不依赖账号或本地刷新任务。"""
|
||||
del current
|
||||
config = ensure_douyu_config(db)
|
||||
client = activity_client()
|
||||
try:
|
||||
goods = query_activity_goods(
|
||||
activity_client(),
|
||||
client,
|
||||
manual_id=str(douyu_config_value("manual_id", config.manual_id)),
|
||||
rid=str(douyu_config_value("rid", config.rid)),
|
||||
)
|
||||
except DouyuActivityError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"活动商品加载失败:{exc}") from exc
|
||||
finally:
|
||||
close = getattr(client, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
now = datetime.now(UTC)
|
||||
return [
|
||||
DouyuGoodsOut(
|
||||
@@ -1858,10 +1869,18 @@ def cleanup_orphan_tasks(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
):
|
||||
"""手动清理没有内存执行器接管的斗鱼任务。"""
|
||||
"""手动清理没有内存执行器或持久队列接管的斗鱼任务。"""
|
||||
durable_batch_ids = {
|
||||
str(batch_id)
|
||||
for (batch_id,) in (
|
||||
db.query(ExecutionJob.batch_id)
|
||||
.filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)))
|
||||
.all()
|
||||
)
|
||||
}
|
||||
cleaned = cleanup_orphan_douyu_tasks(
|
||||
db,
|
||||
active_batch_ids=douyu_batch_registry.active_ids(),
|
||||
active_batch_ids=douyu_batch_registry.active_ids() | durable_batch_ids,
|
||||
statuses=DOUYU_ACTIVE_TASK_STATUSES,
|
||||
message="任务已中断(无执行器接管)",
|
||||
)
|
||||
|
||||
@@ -20,7 +20,7 @@ from fastapi import (
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..database import get_db, release_idle_session
|
||||
from ..deps import authenticate_websocket, get_current_user, require_permission
|
||||
from ..errors import ApiError
|
||||
from ..models import User
|
||||
@@ -425,6 +425,7 @@ def verify_external_orders_batch(
|
||||
interval = _verify_batch_interval()
|
||||
for index, order_id in enumerate(ids):
|
||||
if index and interval:
|
||||
release_idle_session(db)
|
||||
time.sleep(interval)
|
||||
try:
|
||||
order = collab.get_order(db, order_id)
|
||||
|
||||
Reference in New Issue
Block a user