168 lines
6.3 KiB
Python
168 lines
6.3 KiB
Python
"""
|
||
远程控制路由:云端下发开始/结束投递任务,客户端轮询执行并回调。
|
||
|
||
- 状态快照 rpa_status:心跳携带全量状态上报,每用户一行(单设备)
|
||
- 任务 rpa_task:pending → running → done/failed,pending 超时 → expired
|
||
- 去重(服务端权威拦截):同类型任务未达终态时拒绝重复下发
|
||
"""
|
||
import json
|
||
from datetime import datetime, timedelta
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ..auth import get_current_user
|
||
from ..database import get_db
|
||
from ..models import User, RpaStatus, RpaTask
|
||
from ..online import is_online
|
||
from ..schemas import RpaTaskIn, RpaTaskFinishIn, Message
|
||
|
||
router = APIRouter(prefix="/api/rpa", tags=["远程控制"])
|
||
|
||
# 任务终态:达到终态后同类型任务才允许再次下发
|
||
TERMINAL_STATUS = ("done", "failed", "expired")
|
||
# pending 超过该时长未客户端认领则过期,防止离线恢复后执行过时任务
|
||
PENDING_EXPIRE_MINUTES = 10
|
||
|
||
|
||
def _task_dict(t: RpaTask) -> dict:
|
||
return {
|
||
"id": t.id,
|
||
"task_type": t.task_type,
|
||
"params": json.loads(t.params) if t.params else None,
|
||
"status": t.status,
|
||
"result": t.result,
|
||
"created_at": (t.created_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||
"updated_at": (t.updated_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||
}
|
||
|
||
|
||
@router.get("/status", response_model=dict)
|
||
def get_rpa_status(
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""RPA 状态快照(控制端展示):在线 + Boss登录 + 浏览器 + 投递状态"""
|
||
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||
return {
|
||
"online": is_online(current_user),
|
||
"boss_login": st.boss_login if st else "unknown",
|
||
"browser": st.browser if st else "unknown",
|
||
"apply_status": st.apply_status if st else "idle",
|
||
"current": st.current if st else None,
|
||
"applied": st.applied if st else 0,
|
||
"skipped": st.skipped if st else 0,
|
||
"updated_at": (st.updated_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") if st else None,
|
||
}
|
||
|
||
|
||
@router.post("/tasks", response_model=dict)
|
||
def create_task(
|
||
req: RpaTaskIn,
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""控制端下发任务。服务端权威去重:同类型非终态任务存在时拒绝"""
|
||
if req.task_type not in ("start_apply", "stop_apply"):
|
||
raise HTTPException(status_code=422, detail="未知任务类型")
|
||
|
||
if not is_online(current_user):
|
||
raise HTTPException(status_code=409, detail="RPA 客户端离线,无法下发任务")
|
||
|
||
# 去重拦截:同类型任务未达终态,禁止重复下发
|
||
dup = db.query(RpaTask).filter(
|
||
RpaTask.user_id == current_user.id,
|
||
RpaTask.task_type == req.task_type,
|
||
RpaTask.status.in_(("pending", "running")),
|
||
).first()
|
||
if dup:
|
||
raise HTTPException(
|
||
status_code=409,
|
||
detail=f"已有同类型任务未结束(#{dup.id} 状态={dup.status}),请勿重复下发")
|
||
|
||
# 基于状态快照的业务预检,避免下发必然失败的任务
|
||
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||
if req.task_type == "start_apply" and st and st.apply_status == "running":
|
||
raise HTTPException(status_code=409, detail="投递任务已在运行中")
|
||
if req.task_type == "stop_apply" and st and st.apply_status != "running":
|
||
raise HTTPException(status_code=409, detail="当前没有运行中的投递任务")
|
||
|
||
if req.task_type == "start_apply":
|
||
params = req.params or {}
|
||
if not params.get("keywords") or not params.get("city"):
|
||
raise HTTPException(status_code=422, detail="开始投递必须提供 keywords 与 city")
|
||
|
||
task = RpaTask(
|
||
user_id=current_user.id,
|
||
task_type=req.task_type,
|
||
params=json.dumps(req.params or {}, ensure_ascii=False),
|
||
)
|
||
db.add(task)
|
||
db.commit()
|
||
db.refresh(task)
|
||
return _task_dict(task)
|
||
|
||
|
||
@router.get("/tasks", response_model=dict)
|
||
def list_tasks(
|
||
limit: int = Query(20, ge=1, le=100),
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""控制端任务历史(倒序)"""
|
||
rows = db.query(RpaTask).filter(RpaTask.user_id == current_user.id) \
|
||
.order_by(RpaTask.id.desc()).limit(limit).all()
|
||
return {"items": [_task_dict(t) for t in rows]}
|
||
|
||
|
||
@router.get("/tasks/pending", response_model=dict)
|
||
def fetch_pending_task(
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""客户端轮询:取走最早一条 pending 并标记 running(认领即占位,防重复拉取)"""
|
||
# 顺带过期清理:pending 超时未认领 → expired
|
||
cutoff = datetime.utcnow() - timedelta(minutes=PENDING_EXPIRE_MINUTES)
|
||
stale = db.query(RpaTask).filter(
|
||
RpaTask.user_id == current_user.id,
|
||
RpaTask.status == "pending",
|
||
RpaTask.created_at < cutoff,
|
||
).all()
|
||
for t in stale:
|
||
t.status = "expired"
|
||
t.result = f"超过 {PENDING_EXPIRE_MINUTES} 分钟未执行,自动过期"
|
||
|
||
task = db.query(RpaTask).filter(
|
||
RpaTask.user_id == current_user.id,
|
||
RpaTask.status == "pending",
|
||
).order_by(RpaTask.id.asc()).first()
|
||
if not task:
|
||
db.commit()
|
||
return {"task": None}
|
||
task.status = "running"
|
||
db.commit()
|
||
db.refresh(task)
|
||
return {"task": _task_dict(task)}
|
||
|
||
|
||
@router.post("/tasks/{task_id}/finish", response_model=Message)
|
||
def finish_task(
|
||
task_id: int,
|
||
req: RpaTaskFinishIn,
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""客户端执行完回调:更新任务终态与结果"""
|
||
if req.status not in ("done", "failed"):
|
||
raise HTTPException(status_code=422, detail="回调状态只能为 done/failed")
|
||
task = db.query(RpaTask).filter(
|
||
RpaTask.id == task_id,
|
||
RpaTask.user_id == current_user.id,
|
||
).first()
|
||
if not task:
|
||
raise HTTPException(status_code=404, detail="任务不存在")
|
||
task.status = req.status
|
||
task.result = (req.result or "")[:500]
|
||
db.commit()
|
||
return Message(msg="ok")
|