// 插件执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。 // 对齐 Python runner.py 完整执行链:spawn python plugin_runner(★ 逐字节协议) // → stdin 单行 JSON fields → stdout JSON 事件行 → 超时整树强杀(taskkill /T /F)。 "use strict"; const { spawn } = require("child_process"); const readline = require("readline"); const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const config = require("./config"); const state = require("./state"); const scheduler = require("./scheduler"); const queue = require("./queue"); const licensing = require("./licensing"); const runHistory = require("./run-history"); const notes = require("./notes"); const platformAuth = require("./platform-auth"); const platformCreds = require("./platform-creds"); const sdkResolver = require("./sdk-resolver"); const sdkSync = require("./sdk-sync"); const { HUB } = require("./hub"); const { makeLogger } = require("./logger"); const logger = makeLogger("runner"); // 内存 MB → 展示文案(日志/历史共用口径) function fmtMemText(mb) { const n = Number(mb) || 0; if (n <= 0) return "—"; return n >= 1024 ? `${(n / 1024).toFixed(n >= 10240 ? 0 : 1)} GB` : `${n} MB`; } // 定时任务的最长排队等待:到点时前面还有任务在跑,超过这个时长就不跑了(避免堆到下班后)。 // 手动执行不设限(用户自己点的,愿意等)。 const SCHEDULE_MAX_WAIT_SEC = 30 * 60; // 手动停止登记:run_id → 停止标记 const _USER_STOPPED = new Set(); // run_id → kill 函数(执行中,供整树强杀) const _ACTIVE = new Map(); // run_id → resolve(执行结束回调):队列 worker 靠它知道"这一次真的跑完了"才能出队下一个 const _DONE = new Map(); // 需要"开始/结束"系统通知的运行:排队等过的任务(用户可能在别的窗口,需要主动告知) const _QUEUED_RUNS = new Set(); // 实际等待超过这个秒数才算"排队过"(前一个任务秒结的情况不打扰) const WAIT_NOTIFY_SEC = 3; function fmtWaited(sec) { const s = Math.max(0, Math.round(sec)); if (s < 60) return `${s} 秒`; const m = Math.floor(s / 60); if (m < 60) return `${m} 分 ${s % 60} 秒`; return `${Math.floor(m / 60)} 小时 ${m % 60} 分`; } // 系统通知(右下角自定义 toast):只在 Electron 下弹,CLI 模式静默 function notifyUser(title, body, level) { if (!process.versions || !process.versions.electron) return; try { require("./notify-toast").show(title, body, level || "info"); } catch (e) { logger.warning(`系统通知失败:${e.message}`); } } function isUserStopped(runId) { return _USER_STOPPED.has(runId); } // 等待某次运行真正收尾(排队时不会用到;executor 在子进程 spawn 后调用) function waitDone(runId) { return new Promise((resolve) => { const rec = state.RUNS.get(runId); // 极端情况:spawn 成功后立刻收尾,还没来得及登记等待者 if (!rec || (rec.status !== "running" && rec.status !== "queued")) return resolve(); _DONE.set(runId, resolve); }); } function resolveDone(runId) { const fn = _DONE.get(runId); if (fn) { _DONE.delete(runId); fn(); } } function treeKill(pid) { // Windows 整树强杀(含 DrissionPage 浏览器等孙进程);非 Windows 直接 kill 子进程组 try { if (process.platform === "win32") { const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore", detached: true, }); killer.unref(); } else { try { process.kill(-pid, "SIGKILL"); } catch (e) { process.kill(pid, "SIGKILL"); } } } catch (e) { logger.warning(`整树强杀失败 pid=${pid}: ${e.message}`); } } function terminateRun(runId) { // 排队中:直接从队列摘除并落「已取消」终态,不占执行槽、不必等轮到它 const dropped = queue.cancel(runId); if (dropped) { // 用户自己点的取消:应用内已有反馈,不再弹系统通知 _QUEUED_RUNS.delete(runId); const rec = state.RUNS.get(runId) || {}; const info = { id: dropped.plugin_id || rec.plugin_id || "", name: dropped.name || rec.name || dropped.plugin_id || "", version: dropped.version || rec.version || "0", }; finishRun(runId, info, "cancelled", "用户取消了排队任务", ""); try { // 用户取消不是失败:上报 cancelled(中心统计只把 error/failed 计入失败,cancelled 不进成功率分母) licensing.report(dropped.account || rec.account || "", "", info.id, info.version, "cancelled", "用户取消了排队任务", 0); } catch (e) { logger.warning(`取消排队任务上报失败:${e.message}`); } return true; } _USER_STOPPED.add(runId); const kill = _ACTIVE.get(runId); if (kill) { try { kill(); } catch (e) { /* 忽略 */ } return true; } // 已出队但子进程还没拉起的极短窗口:留着停止标记,startFn 会在拉起前中止 const rt = queue.runningItem(); if (rt && rt.run_id === runId) return true; _USER_STOPPED.delete(runId); // 该任务确实已结束,别把标记留给后续同名 run return false; } // 平台命名空间并发闸键:按(账号, 平台)隔离,保护该账号各自的平台登录态 cookies function nsKey(account, platform) { return `${account || "anon"}:${platform || "local"}`; } // 平台登录态预检(HR/OA):点击执行后、拉起插件前,按插件声明(plugin.json 的 platforms // 数组,缺省回退 platform 单字段)逐个校验登录态(真实轻量 API 探测),失效时自动调 // platform-auth.login 纯接口补登(无浏览器,凭据来自平台账号配置)。任一平台补登失败 // 则本次运行直接报错中止,不进入插件执行。在(账号, 平台)命名空间锁内调用,天然避免 // 并发双开登录。 const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" }; function pluginPlatforms(plugin) { if (Array.isArray(plugin.platforms) && plugin.platforms.length) { return plugin.platforms.filter((p) => PLATFORM_LABELS[p]); } const pid = plugin.platform; return pid && PLATFORM_LABELS[pid] ? [pid] : []; } async function ensurePlatformSession(plugin, runId, account) { for (const pid of pluginPlatforms(plugin)) { if (await platformAuth.isOnline(pid, account)) continue; // 登录态有效,无需处理 if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); const label = PLATFORM_LABELS[pid]; emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…`); const r = await platformAuth.login(pid, account); if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止 if (!r || !r.online) { const msg = (r && r.message) || "登录未生效"; throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」检查账号密码配置后重试`); } emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`); } } // 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放) function emitLog(runId, pluginId, level, msg) { const text = String(msg === undefined || msg === null ? "" : msg); state.appendRunLog(runId, { t: new Date().toLocaleTimeString("zh-CN", { hour12: false }), level: level || "INFO", msg: text, }); HUB.publish({ t: "log", run_id: runId, plugin_id: pluginId, level: level || "INFO", msg: text }); } // 结束一次运行:写终态 → 落盘运行历史 → 广播 run_done。 // 所有结束路径(队列拒绝 / 队列异常 / 子进程收尾)共用,避免漏记历史。 function finishRun(runId, plugin, status, error, summary) { const ok = status === "done"; const finished = Date.now() / 1000; const run = state.RUNS.get(runId) || {}; // 幂等:排队取消与子进程收尾可能先后到达,只认第一次终态,避免历史里出现两条记录 if (run.status === "done" || run.status === "error" || run.status === "cancelled") { return; } const durationSec = run.started ? Math.max(0, Math.round(finished - run.started)) : 0; state.setRun(runId, { status, error: ok ? "" : error || "", summary: summary || "", finished, duration_sec: durationSec, }); runHistory.append({ run_id: runId, account: run.account || "", plugin_id: plugin.id, name: run.name || plugin.name || plugin.id, version: run.version || plugin.version || "0", trigger: run.trigger || "manual", schedule_id: run.schedule_id || "", flow_run_id: run.flow_run_id || "", status, ok, error: ok ? "" : error || "", summary: summary || "", started: run.started || 0, finished, duration_sec: durationSec, note: run.note || "", peak_mem_mb: run.peak_mem_mb || 0, logs: Array.isArray(run.logs) ? run.logs : [], }); // 日志集中回传:整次运行日志上送中心机(离线自动暂存补报;失败不阻断运行收尾) try { require("./log-upload").uploadRun({ run_id: runId, account: run.account || "", plugin_id: plugin.id, name: run.name || plugin.name || plugin.id, version: run.version || plugin.version || "0", trigger: run.trigger || "manual", schedule_id: run.schedule_id || "", status, ok, error: ok ? "" : error || "", summary: summary || "", started: run.started || 0, finished, duration_sec: durationSec, note: run.note || "", peak_mem_mb: run.peak_mem_mb || 0, logs: Array.isArray(run.logs) ? run.logs : [], }); } catch (e) { logger.warning(`运行日志回传失败:${e.message}`); } HUB.publish({ t: "run_done", run_id: runId, account: run.account || "", plugin_id: plugin.id, name: run.name || plugin.name || plugin.id, trigger: run.trigger || "manual", schedule_id: run.schedule_id || "", status, ok, error: ok ? "" : error || "", duration_sec: durationSec, summary: summary || "", note: run.note || "", }); // 排队任务的结束提醒(用户手动取消队列里的任务不算:应用内已有明确反馈,不再二次打扰) if (_QUEUED_RUNS.delete(runId)) { const label = run.name || plugin.name || plugin.id; if (ok) { notifyUser("执行完成", `「${label}」· 耗时 ${durationSec}s`, "info"); } else if (status === "cancelled") { notifyUser("任务已取消", `「${label}」:${error || "已取消"}`, "warning"); } else { notifyUser("执行失败", `「${label}」:${error || "未知错误"}`, "important"); } } } // 提交一次插件运行(手动 POST /api/runs 与定时任务共用入口);立即返回 run_id。 // opts: { trigger: "manual" | "schedule", schedule_id } —— 用于区分"谁触发的",落进运行历史 // // 参数收口到插件侧:插件界面保存的配置(plugin_configs/.json,单配置 blob)是参数权威来源。 // 插件界面手动执行会显式传全量 fields,原样使用;壳子侧入口(定时任务未选方案等)传空 fields 时 // 回退到该配置,避免"界面配置了一套、定时任务用 plugin.fields 默认值跑"的参数漂移。 function loadUiSavedFields(pluginId) { try { const raw = fs.readFileSync(path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`), "utf-8"); const v = JSON.parse(raw); return v && typeof v === "object" && !Array.isArray(v) ? v : null; } catch (_) { return null; // 无保存配置/损坏:维持空 fields(插件走自身默认值) } } // 环境包未就绪时的拒绝提示:环境包正在下载/解压时提示等待,云端有包但未装时引导状态栏安装 function throwEnvNotReady() { let msg = "插件执行环境未就绪,暂时无法执行"; try { const es = require("./env-sync").status(); if (es.dl && (es.dl.status === "downloading" || es.dl.status === "extracting")) { msg = "环境包正在安装中(下载/解压),完成后即可执行,请稍候"; } else if (es.cloud_available) { msg = "环境包未安装,请点击状态栏「环境」完成安装后再执行"; } } catch (_) { /* env-sync 不可用时忽略 */ } throw new Error(msg); } // 提交一次运行 = 入队(不再直接拉起进程)。返回 { run_id, queue_position }。 function submitRun(account, plugin, fields, opts) { const o = opts && typeof opts === "object" ? opts : {}; // manual=用户点击;schedule=定时任务;flow=流程编排里的节点 const trigger = ["manual", "schedule", "flow"].includes(o.trigger) ? o.trigger : "manual"; // 环境未就绪预防:提交前校验执行链路(入口脚本/解释器),缺失时直接拒绝并给可读提示, // 避免子进程 spawn ENOENT 后用户只看到"执行进程异常退出(exit=-4058)且未返回结果"。 // 打包态无环境包且未显式配置解释器时也拒绝(系统 python 不可依赖)。 if (!fs.existsSync(config.runnerScript()) || (!process.env.PYTHON_EXE && !config.pythonEnvRoot() && config.IS_FROZEN)) { throwEnvNotReady(); } let effFields = fields && typeof fields === "object" && !Array.isArray(fields) ? fields : {}; if (Object.keys(effFields).length === 0) { const saved = loadUiSavedFields(plugin.id); if (saved) effFields = saved; } const runId = crypto.randomBytes(16).toString("hex"); const enqueuedAt = Date.now() / 1000; const name = plugin.name || plugin.id; const version = plugin.version || "0"; // 运行备注:调用方显式传入优先;定时任务/流程编排未传时取该账号对该插件的长期备注 let note = String(o.note === undefined || o.note === null ? "" : o.note).trim(); if (!note) { try { note = notes.get(account, plugin.id); } catch (_) { note = ""; } } state.registerRun(runId, { status: "queued", // 排队中:尚未占用执行槽,started 为空 account, plugin_id: plugin.id, name, version, trigger, note, schedule_id: o.schedule_id || "", flow_run_id: o.flow_run_id || "", node_id: o.node_id || "", enqueued_at: enqueuedAt, started: 0, result: null, error: null, logs: [], }); // 排队超时:定时任务默认 30 分钟(可被 opts.max_wait_sec 覆盖),手动执行默认不限 const maxWaitSec = Number(o.max_wait_sec) > 0 ? Number(o.max_wait_sec) : (trigger === "schedule" ? SCHEDULE_MAX_WAIT_SEC : 0); let position; try { position = queue.enqueue({ run_id: runId, account, plugin_id: plugin.id, name, version, platform: plugin.platform || "", trigger, schedule_id: o.schedule_id || "", fields: effFields, enqueued_at: enqueuedAt, max_wait_sec: maxWaitSec, }); } catch (e) { // 入队失败(队列已满):直接把刚登记的记录落终态,避免留下永远 queued 的僵尸 finishRun(runId, plugin, "error", e.message, ""); throw e; } HUB.publish({ t: "run_queued", run_id: runId, account, plugin_id: plugin.id, name, trigger, schedule_id: o.schedule_id || "", position, max_wait_sec: maxWaitSec, at: new Date().toLocaleTimeString("zh-CN", { hour12: false }), }); // 排在别人后面 → 这次值得在"真正开始"和"结束"时各提醒一次 if (position > 1) _QUEUED_RUNS.add(runId); return { run_id: runId, queue_position: position }; } // 队列 worker 的执行体:等设备空闲 → 拉起子进程 → 阻塞到该次运行真正收尾。 // 注意:run_start 只在"真正开始执行"时广播,排队阶段对外只有 queued 状态, // 避免前端把排队任务误显示成运行中(并清空上一个任务的实时日志)。 async function executeQueued(item) { const { run_id: runId, plugin_id: pluginId, account } = item; let plugin; try { plugin = require("./registry").find(pluginId); } catch (e) { finishRun(runId, { id: pluginId, name: item.name || pluginId, version: item.version || "0" }, "error", `场景已不存在(${pluginId}),排队任务已取消`, ""); return; } const fields = item.fields || {}; try { // 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies)。 // 单 worker 已保证整机串行,这里保留语义,便于将来放开并发粒度。 await scheduler.withNsLock(nsKey(account, plugin.platform), async () => { const startFn = async () => { if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 平台登录态预检:HR/OA 失效时自动登录(手动登录入口保留) await ensurePlatformSession(plugin, runId, account); await startChild(plugin, fields, runId, account); return runId; }; const r = await scheduler.requestStart(account, plugin.id, plugin.version || "0", startFn); if (!r.ok) { // 用户点了强制停止(子进程还没真正拉起):按「已取消」收尾,不记失败 const stopped = isUserStopped(runId); if (stopped) _USER_STOPPED.delete(runId); finishRun(runId, plugin, stopped ? "cancelled" : "error", stopped ? "用户手动强制停止" : r.error, ""); return; } // 真正开始执行:此刻才写 started(排队时长不计入运行耗时)并广播 run_start const started = Date.now() / 1000; state.setRun(runId, { status: "running", started }); queue.markStarted(runId, started); HUB.publish({ t: "run_start", run_id: runId, plugin_id: plugin.id, name: plugin.name || plugin.id, trigger: item.trigger || "manual", at: new Date().toLocaleTimeString("zh-CN", { hour12: false }), }); licensing.report(account, "", plugin.id, plugin.version || "0", "start"); // 排队等过:真正开始时提醒一次(用户此刻可能已经切到别的窗口/页面) const waited = item.enqueued_at ? started - item.enqueued_at : 0; if (waited >= WAIT_NOTIFY_SEC) { _QUEUED_RUNS.add(runId); notifyUser( "开始执行", `「${plugin.name || plugin.id}」已从队列开始(等待 ${fmtWaited(waited)})`, "info" ); } await waitDone(runId); // 阻塞到子进程 close(终态已在 finalize 落库) }); } catch (e) { logger.error(`运行队列异常:${e.message}`); finishRun(runId, plugin, isUserStopped(runId) ? "cancelled" : "error", isUserStopped(runId) ? "用户取消了排队任务" : `运行队列异常:${e.message}`, ""); _USER_STOPPED.delete(runId); // 若卡在"已写 switching 但没起来",确保设备槽位回到空闲,避免后续任务永远等下去 scheduler.markDone(plugin.id, runId); } } // 拉起执行子进程:子进程 spawn 成功后立即 resolve(runId)(requestStart 随即标记 running); // 执行结束(close)后异步落终态 + 上报 + 回空闲。 function startChild(plugin, fields, runId, account) { return new Promise((resolve, reject) => { // 磁盘预检(不阻断):数据盘/插件盘余量过低时先记一条 WARN, // 导出写到一半失败时能直接对上原因;是否清理由用户决定。 try { for (const d of require("./sysinfo").lowDisks(1)) { emitLog(runId, plugin.id, "WARN", `磁盘剩余不足:${d.label} ${d.root} 仅剩 ${d.free_gb}GB,导出/写表可能失败,请先清理`); } } catch (e) { /* 统计失败不影响执行 */ } // 插件级超时优先(plugin.json runTimeoutSeconds,0=不限时),缺省回退壳默认 RUN_TIMEOUT const timeout = config.runTimeoutFor(plugin); // 执行环境解析:便携环境包(python-env)优先 → 经 job_guard(Job Object 内存上限 // + 整树托管)拉起 plugin_runner;无环境包(dev 直接 .venv)保持原直拉链路。 // 两种模式协议逐字节一致(plugin_runner stdout JSON 事件行经 stdio 原样透传)。 const python = config.pythonExe(); const envRoot = config.pythonEnvRoot(); const guard = config.jobGuardScript(); const baseArgs = ["-u", config.runnerScript(), "--plugin", plugin.id, "--run", runId]; if (state.ALLOWED !== null) { baseArgs.push("--allowed", [...state.ALLOWED].sort().join(",")); } // SDK 挂载参数:只有插件声明了 requires.sdks 才传(存量插件零影响)。 // 本地解析不到兼容版本时直接拒绝启动,绝不"先用着再说"——老插件挂错 SDK 比不跑更糟。 { const resolved = sdkResolver.resolveForPlugin({ pluginRoot: config.pluginRoot(), pluginId: plugin.id, sdkRoot: config.sdkRoot(), allow: sdkSync.loadAllow(), }); if (resolved.missing.length) { reject(new Error(`SDK 未就绪:${sdkResolver.describeMissing(resolved.missing)}`)); return; } if (resolved.mount) { baseArgs.push("--sdk-root", config.sdkRoot(), "--sdk-mount", resolved.mount); } } let cmd; let cwd; if (envRoot && guard) { // 环境包模式:python -u job_guard.py --mem --timeout -- python -u plugin_runner.py ... cmd = [ python, "-u", guard, "--mem", String(config.runMaxMemMb()), "--timeout", String(timeout), "--", python, ...baseArgs, ]; cwd = envRoot; } else { cmd = [python, ...baseArgs]; cwd = envRoot || config.REPO_ROOT; } let child; try { child = spawn(cmd[0], cmd.slice(1), { cwd, windowsHide: true, env: { ...process.env, PYTHONIOENCODING: "utf-8", PYTHONUTF8: "1", PLATFORM_ACCOUNT: account || "", // 平台凭据:供插件内登录态失效时自动补登录(未配置的平台/账号不注入, // 此时登录模块回退读共享 .env) ...(platformCreds.envFor(account, "hr") || {}), ...(platformCreds.envFor(account, "oa") || {}), // 环境包插件加载器据此定位插件根(dev 直拉模式传了也无害) PLUGINS_ROOT: config.pluginRoot(), }, stdio: ["pipe", "pipe", "pipe"], }); } catch (e) { reject(new Error(`拉起执行子进程失败: ${e.message}`)); return; } let resolved = false; const killFn = () => treeKill(child.pid); _ACTIVE.set(runId, killFn); const result = {}; const publish = (ev) => { const t = ev.ev; if (t === "log") { emitLog(runId, plugin.id, ev.level, ev.msg); } else if (t === "progress") { HUB.publish({ t: "progress", run_id: runId, plugin_id: plugin.id, pct: Math.max(0, Math.min(100, parseInt(ev.pct, 10) || 0)) }); } else if (t === "result") { Object.assign(result, ev); } }; const rlOut = readline.createInterface({ input: child.stdout }); rlOut.on("line", (line) => { const s = String(line).trim(); if (!s) return; try { const ev = JSON.parse(s); if (ev && typeof ev === "object" && ev.ev) publish(ev); } catch (e) { /* 非 JSON 行忽略 */ } }); const rlErr = readline.createInterface({ input: child.stderr }); // 内存超限的表现是"分配失败 → MemoryError → 进程退出",Python 侧若来不及回 result, // 这里用 stderr 尾部兜底识别,避免前端只显示一个没有原因的"执行失败"。 const stderrTail = []; let peakMemMb = 0; rlErr.on("line", (line) => { const s = String(line).trim(); if (s) { // job_guard 收尾上报的峰值内存:解析后落运行历史,不再当作错误行刷进日志面板 const peak = s.match(/^\[job_guard\]\s+peak_job_mb=(\d+)/); if (peak) { peakMemMb = parseInt(peak[1], 10) || 0; emitLog(runId, plugin.id, "INFO", `内存峰值:${fmtMemText(peakMemMb)}`); return; } stderrTail.push(s); if (stderrTail.length > 20) stderrTail.shift(); emitLog(runId, plugin.id, "ERROR", s); } }); // 写 fields(单行 JSON,UTF-8)并关闭 stdin try { child.stdin.write(Buffer.from(JSON.stringify(fields || {}), "utf-8")); child.stdin.end(); } catch (e) { /* 子进程可能已退出 */ } let timedOut = false; let finalized = false; let timer = null; const finalize = (code, spawnErr) => { if (finalized) return; finalized = true; if (timer) clearTimeout(timer); _ACTIVE.delete(runId); const hasResult = result && Object.keys(result).length > 0; // 内存上限是 Job Object 的 commit 硬顶:超限时 Python 抛 MemoryError(str 为空), // 旧版 runner 会回 ok=false + error="",前端只有"失败"看不出原因。 const memHit = stderrTail.some((l) => /MemoryError|Cannot allocate memory|内存不足/i.test(l)); const MEM_MSG = "内存不足:执行进程达到内存上限(可在客户端「设置 → 内存上限」调大," + "或让插件分批/流式处理大表)"; let status; let error; if (hasResult) { status = result.ok ? "done" : "error"; error = result.error || (memHit ? MEM_MSG : ""); } else if (spawnErr) { status = "error"; error = spawnErr; } else if (isUserStopped(runId)) { // 用户主动强制停止:不是失败,落「已取消」(error 保留原因,历史仍可回看这次运行) status = "cancelled"; error = "用户手动强制停止"; } else if (timedOut) { status = "error"; error = `插件执行超时(${timeout}s)已强制终止`; } else if (memHit) { status = "error"; error = MEM_MSG; } else { status = "error"; error = `执行进程异常退出(exit=${code})且未返回结果`; } state.setRun(runId, { result: hasResult ? result.result : null }); // 峰值内存先写进运行态,finishRun 会带进运行历史(0 = 旧环境包/直拉模式没有数据) if (peakMemMb > 0) state.setRun(runId, { peak_mem_mb: peakMemMb }); finishRun( runId, plugin, status, status === "done" ? "" : error, hasResult ? ((result.result || {}).summary || "") : "" ); _USER_STOPPED.delete(runId); scheduler.markDone(plugin.id, runId); // 单活槽位回空闲并唤醒排队请求 reportRun(plugin, runId); // 运行上报(联网实时/离线暂存补报) resolveDone(runId); // 放行队列 worker,出队下一个 }; child.once("spawn", () => { resolved = true; // 超时整树强杀:timeout>0 起定时器;timeout=0(插件声明不限时)不设定时器、进程永不自动杀 if (timeout > 0) { timer = setTimeout(() => { timedOut = true; logger.warning(`插件执行超时(${timeout}s)已强制终止:${plugin.id}`); killFn(); }, timeout * 1000); } resolve(runId); }); child.on("error", (err) => { if (!resolved) { _ACTIVE.delete(runId); reject(new Error(`拉起执行子进程失败: ${err.message}`)); return; } finalize(null, `执行子进程异常: ${err.message}`); }); child.on("close", (code) => { finalize(code, null); }); }); } function reportRun(plugin, runId) { try { const run = state.RUNS.get(runId) || {}; const account = run.account || ""; // 状态原样上报:done / cancelled / error(中心只把 error/failed 计入失败,取消不进成功率分母) const status = ["done", "cancelled", "running"].includes(run.status) ? run.status : "error"; const msg = run.error || ""; const duration = run.started ? Math.floor(Date.now() / 1000 - run.started) : 0; licensing.report(account, "", plugin.id, run.version || "", status, msg, duration); } catch (e) { logger.warning(`运行上报失败:${e.message}`); } } // 排队超时:由 queue 的巡检回调,落「已取消」终态并通知前端 function onQueueExpire(item) { const minutes = Math.round((item.max_wait_sec || 0) / 60); const reason = minutes >= 1 ? `排队等待超过 ${minutes} 分钟,已自动取消` : "排队等待超时,已自动取消"; const info = { id: item.plugin_id, name: item.name || item.plugin_id, version: item.version || "0" }; finishRun(item.run_id, info, "cancelled", reason, ""); try { // 排队超时是系统自动取消,同样不算失败 licensing.report(item.account || "", "", item.plugin_id || "", item.version || "", "cancelled", reason, 0); } catch (e) { logger.warning(`排队超时上报失败:${e.message}`); } } // 启动恢复:上次异常退出(崩溃/更新/掉电)时还在排队或执行中的记录, // 落「已中断」历史并广播给前端提示一次,而不是让它们凭空消失。 function init() { let left = { running: null, items: [] }; try { left = queue.recover(); } catch (e) { logger.warning(`队列遗留记录恢复失败:${e.message}`); } const all = [...(left.running ? [left.running] : []), ...(left.items || [])].filter((x) => x && x.run_id); if (!all.length) return 0; const finished = Date.now() / 1000; for (const it of all) { try { runHistory.append({ run_id: it.run_id, account: it.account || "", plugin_id: it.plugin_id || "", name: it.name || it.plugin_id || "", version: it.version || "0", trigger: it.trigger || "manual", schedule_id: it.schedule_id || "", status: "interrupted", ok: false, error: "客户端退出,该任务未执行完成", summary: "", started: it.started_at || 0, finished, duration_sec: 0, logs: [], }); } catch (e) { logger.warning(`中断任务落库失败(${it.run_id}):${e.message}`); } } logger.warning(`检测到上次退出遗留的 ${all.length} 个未执行任务,已标记为「已中断」`); HUB.publish({ t: "queue_recovered", count: all.length, items: all }); return all.length; } // 退出清理:把还在排队、来不及跑的任务落「已取消」,避免下次启动才"神秘消失" function shutdown() { let dropped = []; try { dropped = queue.clear("app-quit"); } catch (e) { logger.warning(`退出清空队列失败:${e.message}`); } for (const it of dropped) { _QUEUED_RUNS.delete(it.run_id); // 正在退出的进程不弹通知 const info = { id: it.plugin_id, name: it.name || it.plugin_id, version: it.version || "0" }; finishRun(it.run_id, info, "cancelled", "客户端退出,排队任务已取消", ""); } return dropped.length; } // 队列 worker 的执行体与超时回调在此注册(queue 只负责排队,执行语义留在 runner) queue.setExecutor(executeQueued); queue.setOnExpire(onQueueExpire); module.exports = { submitRun, terminateRun, isUserStopped, executeQueued, init, shutdown };