feat(automation): 持久执行队列与重复充值确认
This commit is contained in:
@@ -148,6 +148,7 @@ def list_jobs(
|
||||
from ..services.binding_poll_scheduler import (
|
||||
scheduler_status as binding_poll_status,
|
||||
)
|
||||
from ..services.execution_worker import execution_job_worker_status
|
||||
from ..services.payment_poll_scheduler import (
|
||||
scheduler_status as payment_poll_status,
|
||||
)
|
||||
@@ -164,6 +165,7 @@ def list_jobs(
|
||||
else "",
|
||||
"binding_poll": binding_poll_status(),
|
||||
"payment_poll": payment_poll_status(),
|
||||
"execution_jobs": execution_job_worker_status(),
|
||||
},
|
||||
"pending_relogin": pending_relogin,
|
||||
"jobs": [
|
||||
|
||||
@@ -18,7 +18,7 @@ CK 从 `login_tasks.cookie` 迁到 `accounts.cookie`,因此本页面的**记
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import UTC, datetime
|
||||
|
||||
@@ -27,11 +27,10 @@ from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import case, func, or_
|
||||
from sqlalchemy.orm import Session, defer, joinedload
|
||||
|
||||
from ..database import WorkerSessionLocal, get_db
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, require_permission
|
||||
from ..models import Account, AuditLog, LoginTask, User
|
||||
from ..models import ProxyConfig as ProxyConfigModel
|
||||
from ..permissions import get_user_permissions, user_has_permission
|
||||
from ..permissions import user_has_permission
|
||||
from ..schemas import CookieReloginRequest
|
||||
from ..services.account_lifecycle import on_ck_cleared
|
||||
from ..services.cookie_check_service import check_douyu_cookie
|
||||
@@ -41,7 +40,15 @@ from ..services.douyu_service import (
|
||||
cookie_holding_filter,
|
||||
cookie_operable_filter,
|
||||
)
|
||||
from ..services.login_service import BatchRegistry, LoginBatchRunner, get_relogin_limits
|
||||
from ..services.execution_jobs import (
|
||||
JOB_RELOGIN_BATCH,
|
||||
LANE_AUTH,
|
||||
TERMINAL_STATUSES,
|
||||
enqueue_execution_job,
|
||||
get_execution_job,
|
||||
request_execution_cancel,
|
||||
)
|
||||
from ..services.login_service import BatchRegistry, get_relogin_limits
|
||||
|
||||
|
||||
def _fmt_dt(dt) -> str | None:
|
||||
@@ -648,23 +655,26 @@ def _start_relogin_accounts(
|
||||
status_code=400, detail="没有可重登的账号,请检查账号凭据或当前重登状态"
|
||||
)
|
||||
|
||||
proxy = db.query(ProxyConfigModel).first()
|
||||
thread_db = WorkerSessionLocal()
|
||||
max_login_retries, max_total_time = get_relogin_limits()
|
||||
runner = LoginBatchRunner(
|
||||
db=thread_db,
|
||||
account_ids=account_ids,
|
||||
created_by=current.id,
|
||||
creator_permissions=get_user_permissions(current),
|
||||
max_login_retries=max_login_retries,
|
||||
max_total_time=max_total_time,
|
||||
proxy_config=proxy,
|
||||
log_queue=None,
|
||||
loop=None,
|
||||
concurrency=3,
|
||||
mode="relogin",
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_RELOGIN_BATCH,
|
||||
lane_scope=LANE_AUTH,
|
||||
batch_id=batch_id,
|
||||
payload={
|
||||
"account_ids": account_ids,
|
||||
"max_login_retries": max_login_retries,
|
||||
"max_total_time": max_total_time,
|
||||
"concurrency": 3,
|
||||
"api_strategy": "wgapi",
|
||||
"mode": "relogin",
|
||||
"trigger_source": "manual",
|
||||
},
|
||||
created_by=int(current.id),
|
||||
priority=15,
|
||||
max_attempts=2,
|
||||
)
|
||||
batch_id = runner.batch_id
|
||||
db.add(
|
||||
AuditLog(
|
||||
user_id=current.id,
|
||||
@@ -675,21 +685,6 @@ def _start_relogin_accounts(
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
cookie_relogin_registry.register(batch_id, None, None, runner, owner_id=current.id)
|
||||
|
||||
def run_relogin_batch():
|
||||
try:
|
||||
runner.run()
|
||||
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
|
||||
runner._push_log("error", f"批量重新登录异常: {exc}")
|
||||
message = f"重新登录异常: {exc}(旧 Cookie 已保留)"
|
||||
for account_id in account_ids:
|
||||
runner._mark_account_relogin_stopped(account_id, message)
|
||||
runner.db.close()
|
||||
finally:
|
||||
cookie_relogin_registry.pop(batch_id)
|
||||
|
||||
threading.Thread(target=run_relogin_batch, daemon=True).start()
|
||||
return {
|
||||
"batch_id": batch_id,
|
||||
"count": len(account_ids),
|
||||
@@ -708,15 +703,24 @@ def stop_cookie_relogin(
|
||||
_require_cookie_operation_perm(current)
|
||||
batch = cookie_relogin_registry.get(batch_id)
|
||||
if not batch:
|
||||
raise HTTPException(
|
||||
status_code=404, detail="重登批次不存在、已结束或服务已重启"
|
||||
)
|
||||
if batch.get("owner_id") != current.id and not user_has_permission(
|
||||
current, "login:view_all"
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="无权限停止该重登批次")
|
||||
|
||||
batch["runner"].stop()
|
||||
job = get_execution_job(db, batch_id=batch_id)
|
||||
if job is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail="重登批次不存在、已结束或服务已重启"
|
||||
)
|
||||
if job.created_by != current.id and not user_has_permission(
|
||||
current, "login:view_all"
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="无权限停止该重登批次")
|
||||
if job.status in TERMINAL_STATUSES:
|
||||
raise HTTPException(status_code=404, detail="重登批次已结束")
|
||||
request_execution_cancel(db, batch_id=batch_id)
|
||||
else:
|
||||
if batch.get("owner_id") != current.id and not user_has_permission(
|
||||
current, "login:view_all"
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="无权限停止该重登批次")
|
||||
batch["runner"].stop()
|
||||
db.add(
|
||||
AuditLog(
|
||||
user_id=current.id,
|
||||
|
||||
+264
-33
@@ -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:
|
||||
|
||||
+103
-41
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
import csv
|
||||
import io
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import (
|
||||
@@ -19,13 +19,22 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import WorkerSessionLocal, get_db
|
||||
from ..deps import authenticate_websocket, get_current_user, require_permission
|
||||
from ..models import Account, LoginTask, User
|
||||
from ..models import ProxyConfig as ProxyConfigModel
|
||||
from ..permissions import get_user_permissions, user_has_permission
|
||||
from ..models import Account, ExecutionJob, LoginTask, User
|
||||
from ..permissions import user_has_permission
|
||||
from ..schemas import LOGIN_BATCH_MAX_ACCOUNTS, LoginBatchRequest, LoginTaskOut
|
||||
from ..services.audit_service import record_audit
|
||||
from ..services.execution_jobs import (
|
||||
JOB_LOGIN_BATCH,
|
||||
LANE_AUTH,
|
||||
TERMINAL_STATUSES,
|
||||
enqueue_execution_job,
|
||||
event_payload,
|
||||
execution_events_after,
|
||||
get_execution_job,
|
||||
request_execution_cancel,
|
||||
)
|
||||
from ..services.login_failure import classify_failure, failure_kind_label
|
||||
from ..services.login_service import LoginBatchRunner, batch_registry
|
||||
from ..services.login_service import batch_registry
|
||||
|
||||
router = APIRouter(prefix="/api/login", tags=["登录任务"])
|
||||
|
||||
@@ -161,9 +170,6 @@ async def create_batch(
|
||||
if not req.account_ids:
|
||||
raise HTTPException(status_code=400, detail="请选择账号")
|
||||
|
||||
# 读取代理配置
|
||||
proxy = db.query(ProxyConfigModel).first()
|
||||
|
||||
# 权限过滤账号
|
||||
valid_ids = []
|
||||
seen_ids = set()
|
||||
@@ -185,35 +191,26 @@ async def create_batch(
|
||||
action_name = "检测" if req.mode == "check" else "登录"
|
||||
raise HTTPException(status_code=403, detail=f"没有可{action_name}的账号")
|
||||
|
||||
# 在主事件循环中创建 log_queue,传给后台线程
|
||||
log_queue = asyncio.Queue()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
# 创建执行器(用独立的 DB 会话,因为在线程中运行)
|
||||
thread_db = WorkerSessionLocal()
|
||||
runner = LoginBatchRunner(
|
||||
db=thread_db,
|
||||
account_ids=valid_ids,
|
||||
created_by=current.id,
|
||||
creator_permissions=get_user_permissions(current),
|
||||
max_login_retries=req.max_login_retries,
|
||||
max_total_time=req.max_total_time,
|
||||
proxy_config=proxy,
|
||||
log_queue=log_queue,
|
||||
loop=loop,
|
||||
concurrency=req.concurrency,
|
||||
api_strategy=req.api_strategy,
|
||||
mode=req.mode,
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_LOGIN_BATCH,
|
||||
lane_scope=LANE_AUTH,
|
||||
batch_id=batch_id,
|
||||
payload={
|
||||
"account_ids": valid_ids,
|
||||
"max_login_retries": req.max_login_retries,
|
||||
"max_total_time": req.max_total_time,
|
||||
"concurrency": req.concurrency,
|
||||
"api_strategy": req.api_strategy,
|
||||
"mode": req.mode,
|
||||
"trigger_source": "manual",
|
||||
},
|
||||
created_by=int(current.id),
|
||||
priority=20,
|
||||
max_attempts=2,
|
||||
)
|
||||
|
||||
batch_id = runner.batch_id
|
||||
|
||||
# 先注册到批次注册表,再启动线程,确保 WebSocket 连接时能找到
|
||||
batch_registry.register(batch_id, log_queue, loop, runner)
|
||||
|
||||
# 启动线程
|
||||
thread = threading.Thread(target=runner.run, daemon=True)
|
||||
thread.start()
|
||||
db.commit()
|
||||
|
||||
# 审计:批次是谁在什么时候发起、多少个账号、什么模式。
|
||||
# 自动重登与人工登录共用同一条链路,没有这条记录就无法追溯来源。
|
||||
@@ -671,6 +668,7 @@ def delete_tasks(
|
||||
@router.post("/stop/{batch_id}")
|
||||
def stop_batch(
|
||||
batch_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("login:batch")),
|
||||
):
|
||||
batch = batch_registry.get(batch_id)
|
||||
@@ -681,7 +679,18 @@ def stop_batch(
|
||||
raise HTTPException(status_code=404, detail="批次已结束")
|
||||
batch["runner"].stop()
|
||||
return {"message": "已发送停止信号", "success": True}
|
||||
raise HTTPException(status_code=404, detail="批次不存在或已结束")
|
||||
job = get_execution_job(db, batch_id=batch_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="批次不存在")
|
||||
if job.status in TERMINAL_STATUSES:
|
||||
raise HTTPException(status_code=404, detail="批次已结束")
|
||||
if job.created_by != current.id and not user_has_permission(
|
||||
current, "login:view_all"
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="无权停止该批次")
|
||||
request_execution_cancel(db, batch_id=batch_id)
|
||||
db.commit()
|
||||
return {"message": "已发送停止信号", "success": True}
|
||||
|
||||
|
||||
@router.websocket("/ws/login/{batch_id}")
|
||||
@@ -702,6 +711,15 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str):
|
||||
.filter(LoginTask.batch_id == batch_id, LoginTask.created_by == user.id)
|
||||
.first()
|
||||
)
|
||||
if not owned:
|
||||
owned = (
|
||||
check_db.query(ExecutionJob.id)
|
||||
.filter(
|
||||
ExecutionJob.batch_id == batch_id,
|
||||
ExecutionJob.created_by == user.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
finally:
|
||||
check_db.close()
|
||||
if not owned:
|
||||
@@ -710,12 +728,56 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str):
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
# 从已注册的批次中获取 log_queue(由 create_batch 创建)
|
||||
# 同进程兼容模式优先使用内存队列;生产 worker 模式回放数据库事件。
|
||||
batch = 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"]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user