feat(automation): 持久执行队列与重复充值确认

This commit is contained in:
yml
2026-11-23 15:47:56 +08:00
parent 2549511598
commit aaacbea10a
29 changed files with 2147 additions and 178 deletions
+264 -33
View File
@@ -3,7 +3,8 @@
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import secrets
from datetime import UTC, datetime, timedelta
from typing import Any, cast
from weakref import WeakKeyDictionary
@@ -39,10 +40,12 @@ from ..models import (
DouyuConfig,
DouyuEsportsGoodsSnapshot,
DouyuGoodsSnapshot,
DouyuRechargeConfirmation,
DouyuTask,
DouyuWorkbench,
DouyuWorkbenchAccount,
DouyuXpdGoodsSnapshot,
ExecutionJob,
PlatformFulfillmentTask,
User,
)
@@ -89,7 +92,6 @@ from ..services.douyu_activity_query import activity_client, query_activity_good
from ..services.douyu_batch_launcher import (
DOUYU_BATCH_CREATE_CONCURRENCY,
DOUYU_MAX_ACTIVE_BATCHES,
start_douyu_batch,
)
from ..services.douyu_exchange_result_image import (
ExchangeResultImageError,
@@ -112,6 +114,17 @@ from ..services.douyu_service import (
douyu_task_payload,
ensure_douyu_config,
)
from ..services.execution_jobs import (
JOB_DOUYU_BATCH,
LANE_FULFILLMENT,
STATUS_QUEUED,
STATUS_RUNNING,
TERMINAL_STATUSES,
event_payload,
execution_events_after,
get_execution_job,
request_execution_cancel,
)
from ..services.file_service import FileUploadError
from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes
from ..services.platform_fulfillment import service as platform_fulfillment_service
@@ -721,6 +734,9 @@ def _config_out(config: DouyuConfig) -> DouyuConfigOut:
gold_recharge_channel=text("gold_recharge_channel"),
gold_api_product_id=text("gold_api_product_id"),
gold_api_account_template_name=text("gold_api_account_template_name"),
recharge_duplicate_confirm_minutes=number(
"recharge_duplicate_confirm_minutes"
),
gift_id=text("gift_id"),
skin_id=text("skin_id"),
updated_at=config.updated_at,
@@ -1311,11 +1327,127 @@ def list_xpd_goods(
return rows
def _api_recharge_duplicate_guard(
db: Session,
*,
req: DouyuTaskBatchRequest,
current: User,
config: DouyuConfig,
account_ids: list[int],
amount: int,
) -> dict[str, Any] | None:
"""API 直充二次确认:令牌一次性消费,任务与令牌在同一事务落库。"""
normalized_ids = sorted({int(account_id) for account_id in account_ids})
now = datetime.now(UTC)
if req.recharge_confirmation_token:
confirmation = (
db.query(DouyuRechargeConfirmation)
.filter(
DouyuRechargeConfirmation.token
== req.recharge_confirmation_token,
)
.with_for_update()
.first()
)
stored_ids = (
sorted(
{
int(account_id)
for account_id in (confirmation.account_ids_json or [])
}
)
if confirmation
else []
)
if (
confirmation is None
or confirmation.user_id != current.id
or confirmation.used_at is not None
or confirmation.expires_at <= now
or confirmation.amount != amount
or stored_ids != normalized_ids
):
raise HTTPException(
status_code=409,
detail="充值确认已失效,请重新发起充值",
)
confirmation.used_at = now
return None
window_minutes = max(
0,
int(
douyu_config_value(
"recharge_duplicate_confirm_minutes",
config.recharge_duplicate_confirm_minutes,
)
or 0
),
)
if window_minutes <= 0:
return None
cutoff = now - timedelta(minutes=window_minutes)
previous = (
db.query(DouyuTask)
.filter(
DouyuTask.account_id.in_(normalized_ids),
DouyuTask.task_type == "create_gold_qr",
DouyuTask.recharge_channel == "supplier_api",
DouyuTask.recharge_amount == amount,
DouyuTask.recharge_requested_at.isnot(None),
DouyuTask.recharge_requested_at >= cutoff,
DouyuTask.status.notin_(DOUYU_ACTIVE_TASK_STATUSES),
)
.order_by(DouyuTask.id.desc())
.all()
)
if not previous:
return None
duplicate_account_ids = {
int(task.account_id) for task in previous
}
account_rows = (
db.query(Account)
.filter(Account.id.in_(duplicate_account_ids))
.order_by(Account.id.asc())
.all()
)
token = secrets.token_urlsafe(32)
db.add(
DouyuRechargeConfirmation(
token=token,
user_id=int(current.id),
amount=amount,
account_ids_json=normalized_ids,
expires_at=now + timedelta(minutes=5),
)
)
db.commit()
names = [
row.nickname or row.username or row.uid or f"#{row.id}"
for row in account_rows
]
return {
"batch_id": "",
"count": 0,
"requires_confirmation": True,
"confirmation_token": token,
"window_minutes": window_minutes,
"amount": amount,
"account_names": names,
"message": (
f"所选账号在最近 {window_minutes} 分钟内已请求过相同金额的 API 充值,"
"请确认是否继续"
),
"success": False,
}
def _prepare_task_batch(
req: DouyuTaskBatchRequest,
db: Session,
current: User,
) -> tuple[str, int]:
) -> dict[str, Any]:
"""在线程池中完成全部同步 DB 工作,避免阻塞 Uvicorn 事件循环。"""
if not req.account_ids:
raise HTTPException(status_code=400, detail="请选择斗鱼账号")
@@ -1346,14 +1478,53 @@ def _prepare_task_batch(
)
platform_task = db.get(PlatformFulfillmentTask, int(platform_task.id))
active_batch_ids = douyu_batch_registry.active_ids()
cleanup_orphan_douyu_tasks(
db,
active_batch_ids=active_batch_ids,
statuses=DOUYU_ACTIVE_TASK_STATUSES,
message="任务已中断(无执行器接管)",
active_batches = int(
db.query(func.count(ExecutionJob.id))
.filter(
ExecutionJob.job_type == JOB_DOUYU_BATCH,
ExecutionJob.lane_scope == LANE_FULFILLMENT,
ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)),
)
.scalar()
or 0
)
_ensure_active_batch_budget(len(active_batch_ids))
_ensure_active_batch_budget(active_batches)
config = ensure_douyu_config(db)
recharge_channel = (
str(
douyu_config_value(
"gold_recharge_channel",
config.gold_recharge_channel,
)
).strip()
if req.task_type == "create_gold_qr"
else ""
)
recharge_amount = (
max(
1,
int(req.payload.get("amount") or req.payload.get("gold_amount") or 1),
)
if req.task_type == "create_gold_qr"
else None
)
if (
req.task_type == "create_gold_qr"
and recharge_channel == "supplier_api"
):
guard = _api_recharge_duplicate_guard(
db,
req=req,
current=current,
config=config,
account_ids=req.account_ids,
amount=int(recharge_amount or 1),
)
if guard is not None:
return guard
task_payload = dict(req.payload)
if req.recharge_confirmation_token:
task_payload["recharge_confirmation_used"] = True
try:
batch_id, count = create_douyu_planned_tasks(
@@ -1362,8 +1533,11 @@ def _prepare_task_batch(
req.task_type,
req.handbook_scope,
current.id,
req.payload,
task_payload,
platform_task_id=req.platform_task_id,
concurrency=req.concurrency,
recharge_channel=recharge_channel,
recharge_amount=recharge_amount,
)
except DouyuActivePaymentError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
@@ -1401,10 +1575,6 @@ def _prepare_task_batch(
)
if req.task_type == "create_gold_qr":
config = ensure_douyu_config(db)
recharge_channel = str(
douyu_config_value("gold_recharge_channel", config.gold_recharge_channel)
).strip()
payment_method = (
"API 直充支付" if recharge_channel == "supplier_api" else "微信扫码支付"
)
@@ -1431,6 +1601,8 @@ def _prepare_task_batch(
"account_count": len(req.account_ids),
"handbook_scope": req.handbook_scope,
"recharge_channel": recharge_channel,
"recharge_amount": recharge_amount,
"recharge_confirmed": bool(req.recharge_confirmation_token),
"payment_method": payment_method,
# 仅记录充值身份,禁止在审计中写入 Cookie、密码等凭据。
"recharge_accounts": [
@@ -1447,7 +1619,7 @@ def _prepare_task_batch(
)
db.commit()
return batch_id, count
return {"batch_id": batch_id, "count": count, "success": True}
@router.post("/tasks/batch")
@@ -1456,26 +1628,14 @@ async def create_task_batch(
db: Session = Depends(get_db),
current: User = Depends(require_permission("douyu:task")),
):
"""创建斗鱼任务记录并启动后台执行器。"""
# 同步 SQLAlchemy 段必须在线程池执行;事件循环只负责最后启动后台线程。
"""创建斗鱼任务记录和持久 execution job。"""
async with _batch_create_semaphore():
batch_id, count = await run_in_threadpool(
return await run_in_threadpool(
_prepare_task_batch,
req,
db,
current,
)
await run_in_threadpool(
start_douyu_batch,
batch_id=batch_id,
task_type=req.task_type,
payload=req.payload,
concurrency=req.concurrency,
loop=asyncio.get_running_loop(),
log_queue=asyncio.Queue(),
)
return {"batch_id": batch_id, "count": count, "success": True}
@router.get("/tasks")
@@ -1664,6 +1824,33 @@ def stop_batch(
.first()
is not None
)
job = get_execution_job(db, batch_id=batch_id)
if job is not None:
if job.status not in TERMINAL_STATUSES:
request_execution_cancel(db, batch_id=batch_id)
if is_recharge_batch:
record_audit(
db,
current,
action="recharge:douyu:stop",
target=f"douyu_batch:{batch_id}",
detail={"batch_id": batch_id, "mode": "durable_queue"},
)
db.commit()
return {"message": "已发送停止信号", "success": True}
cleaned = cleanup_orphan_douyu_tasks(
db,
batch_id=batch_id,
include_durable=True,
message="批次已结束",
)
if cleaned:
return {
"message": f"批次已结束,已清理 {cleaned} 个残留任务",
"success": True,
}
raise HTTPException(status_code=404, detail="批次已结束")
batch = douyu_batch_registry.get(batch_id)
if batch:
if batch.get("finished"):
@@ -1738,9 +1925,53 @@ async def ws_douyu_logs(websocket: WebSocket, batch_id: str):
batch = douyu_batch_registry.get(batch_id)
if not batch:
await websocket.send_json({"level": "error", "message": "批次不存在或已结束"})
await websocket.close()
return
initial_db = WorkerSessionLocal()
try:
job = get_execution_job(initial_db, batch_id=batch_id)
finally:
initial_db.close()
if job is None:
await websocket.send_json(
{"level": "error", "message": "批次不存在或已结束"}
)
await websocket.close()
return
last_event_id = 0
idle_seconds = 0
while True:
poll_db = WorkerSessionLocal()
try:
events = execution_events_after(
poll_db,
batch_id=batch_id,
after_id=last_event_id,
limit=200,
)
job = get_execution_job(poll_db, batch_id=batch_id)
finally:
poll_db.close()
if events:
idle_seconds = 0
for event in events:
last_event_id = int(event.id)
payload = event_payload(event)
await websocket.send_json(payload)
if payload.get("level") == "result":
await asyncio.sleep(0.1)
return
continue
if job is None or job.status in TERMINAL_STATUSES:
await websocket.send_json(
{"level": "result", "message": "批次已结束"}
)
return
await asyncio.sleep(0.5)
idle_seconds += 0.5
if idle_seconds >= 30:
await websocket.send_json(
{"level": "heartbeat", "message": ""}
)
idle_seconds = 0
log_queue: asyncio.Queue = batch["log_queue"]
try: