Files
37duAutomation/desktop/webhost/backend/apis/runs.py
T
puddy 78aa8c361c release: bump version to 1.1.7, update xq0031_xq0032 plugin to 1.0.8
主要变更:
1. 整体版本升级至1.1.7,更新安装包与shell版本号
2. 新增API与后端能力:
   - 新增停止运行接口,支持强制终止插件进程与浏览器子进程
   - 云端会话令牌与下载票据落库,适配多worker部署
   - 优化Chrome版本读取逻辑,避免弹窗与编码问题
3. xq0031_xq0032插件升级至1.0.8:
   - 新增仓库中文名自动筛选功能,简化用户操作
   - 优化ERP登录与报表导出流程,修复标签页残留问题
   - 新增前端强制停止按钮,支持实时终止运行
   - 修复中文编码与乱码问题,兼容Windows非UTF-8环境
4. 修复授权校验逻辑,确保账号与授权匹配
5. 更新文档与部署脚本,修正发版流程说明
2026-09-17 23:25:33 +08:00

117 lines
5.2 KiB
Python

# -*- coding: utf-8 -*-
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
from __future__ import annotations
import logging
import threading
import time
import uuid
from datetime import datetime
from fastapi import APIRouter, HTTPException, Request, WebSocket
from webhost.backend import licensing
from webhost.backend import scheduler as _scheduler
from webhost.backend import state as _st
from webhost.backend.core.runner import RunReq, _run_target, terminate_run
from webhost.backend.core.hub import HUB
from webhost.backend.plugins import PLUGINS
from webhost.backend.core.session import _require_login, _sess_account
_LOGGER = logging.getLogger(__name__)
router = APIRouter()
@router.post("/api/runs", status_code=202)
def start_run(req: RunReq, request: Request) -> dict:
account = _require_login(request)
try:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
raise HTTPException(404, "插件不存在")
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
online = licensing.is_online()
deny = licensing.run_check_allowed(plugin.id, account, online)
if deny:
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
raise HTTPException(403, deny)
run_id = uuid.uuid4().hex
with _st.RUN_LOCK:
if len(_st.RUNS) >= _st.MAX_RUNS:
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
_st.RUNS[run_id] = {"status": "running", "account": account,
"version": getattr(plugin, "version", "0"),
"started": time.time(),
"result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
licensing.report(account=account, device_id="", plugin_id=plugin.id,
version=getattr(plugin, "version", "0"), status="start")
def _queued():
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
gate = _st._ns_gate(plugin.platform)
if gate.locked():
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "INFO",
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
with gate:
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
if _scheduler._is_busy():
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "INFO",
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
# start_fn 无参调用(scheduler 约定):run_id 由外层闭包捕获;
# 之前签名带 _run_id 形参会因 TypeError 启动失败且被静默吞掉,运行记录永久卡 running
def _start():
threading.Thread(target=_run_target,
args=(plugin, req.fields, run_id),
daemon=True, name=f"exec-{plugin.id}").start()
return run_id
r = _scheduler.request_start(account, plugin.id,
getattr(plugin, "version", "0"), _start)
if not r.get("ok"):
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
_st._set_run(run_id, status="error", result=None,
error=r.get("error") or "启动失败")
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
"error": r.get("error") or "启动失败"})
threading.Thread(target=_queued, daemon=True,
name=f"run-{plugin.id}").start()
return {"run_id": run_id}
@router.get("/api/runs/{run_id}")
def get_run(run_id: str, request: Request) -> dict:
account = _require_login(request)
with _st.RUN_LOCK:
run = _st.RUNS.get(run_id)
if not run or run.get("account") != account: # 仅属主可读运行结果
raise HTTPException(404, "运行不存在")
return run
@router.post("/api/runs/{run_id}/stop")
def stop_run(run_id: str, request: Request) -> dict:
"""手动强制停止指定运行:仅运行属主可操作,整树强杀执行子进程(含浏览器)。"""
account = _require_login(request)
with _st.RUN_LOCK:
run = _st.RUNS.get(run_id)
if not run or run.get("account") != account:
raise HTTPException(404, "运行不存在")
if run.get("status") != "running":
raise HTTPException(409, "运行已结束,无需停止")
if not terminate_run(run_id):
raise HTTPException(409, "任务尚未真正启动(排队中或刚结束),请稍候再试")
return {"ok": True}
@router.websocket("/ws")
async def ws(websocket: WebSocket):
if not _sess_account(websocket): # WS 握手需有效统一账户会话
await websocket.close(code=1008)
return
await HUB.connect(websocket)