feat(automation): 持久执行队列与重复充值确认
This commit is contained in:
+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