# -*- 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 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.websocket("/ws") async def ws(websocket: WebSocket): if not _sess_account(websocket): # WS 握手需有效统一账户会话 await websocket.close(code=1008) return await HUB.connect(websocket)