feat(electron-shell): 1.8.0 执行队列、流程编排、流程定时与版本回滚
- 执行队列:多任务串行排队,可单独取消,超时自动放弃,异常退出后标记已中断 - 流程编排:画布多场景依赖图,内置确保登录/等待/通知/人工确认节点 - 流程定时:场景与流程统一配置定时(每天/工作日/每周/每月/每隔N小时) - 流程版本历史:自动留档 20 版,画布一键回滚且回滚可撤销 - 流程配置云备份:随定时任务备份到中心机,换机自动恢复 - 总览页/场景库布局调整,通知浮窗右下角堆叠显示
This commit is contained in:
@@ -79,6 +79,18 @@ async function init(options = {}) {
|
||||
// 现已改用 APP_DATA/plugins —— 必须在权限清单/插件扫描/同步之前执行
|
||||
pluginSync.migrateLegacyPluginRoot();
|
||||
scheduler.initActive();
|
||||
// 执行队列遗留记录:上次异常退出时还在排队/执行的任务,落「已中断」历史并广播提示
|
||||
try {
|
||||
require("./runner").init();
|
||||
} catch (e) {
|
||||
logger.warning(`执行队列恢复失败:${e.message}`);
|
||||
}
|
||||
// 流程编排的定时调度(与定时任务同一套 cron 语义)
|
||||
try {
|
||||
require("./flows").init();
|
||||
} catch (e) {
|
||||
logger.warning(`流程定时调度启动失败:${e.message}`);
|
||||
}
|
||||
|
||||
// 账号:优先 .env,其次最近活跃本机会话
|
||||
const account = config.CONTROLPLANE_ACCOUNT || session.sessActiveAccount();
|
||||
|
||||
@@ -96,6 +96,14 @@ if (!app.requestSingleInstanceLock()) {
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
},
|
||||
});
|
||||
// 渲染层报错转发到主进程日志:白屏时能直接在 shell-dev.log 里看到原因
|
||||
mainWindow.webContents.on("console-message", (_ev, level, message) => {
|
||||
if (!message) return;
|
||||
if (level >= 2) logger.warning(`[renderer] ${message}`);
|
||||
});
|
||||
mainWindow.webContents.on("render-process-gone", (_ev, d) => {
|
||||
logger.error(`渲染进程异常退出:${JSON.stringify(d)}`);
|
||||
});
|
||||
mainWindow.loadURL(URL);
|
||||
// 推送最大化状态变化:渲染层顶栏切换最大化/还原图标
|
||||
const sendMaxState = () => {
|
||||
@@ -199,6 +207,12 @@ if (!app.requestSingleInstanceLock()) {
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true; // 放行主窗口真正关闭
|
||||
// 队列里还没跑的任务落「已取消」终态:否则用户以为它们还在等,下次启动也只剩一条「中断」
|
||||
try {
|
||||
require("./runner").shutdown();
|
||||
} catch (e) {
|
||||
/* 忽略:退出路径不再抛错 */
|
||||
}
|
||||
try {
|
||||
if (server) server.close();
|
||||
} catch (e) {
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// 流程版本快照:每次"内容变化"(名称/失败策略/节点)前保存一份上一版,供回滚。
|
||||
//
|
||||
// 刻意不存 schedule:定时开关与 cron 属于运行期配置,回滚一个旧版本不应该把
|
||||
// 用户后来改的排期一起改回去(计划页与流程编辑器共用同一份 schedule)。
|
||||
//
|
||||
// 存储:flow_versions.json,按 flow_id 分组,每组最多 MAX_PER_FLOW 条(先进先出)。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const config = require("./config");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("flow-versions");
|
||||
|
||||
const VERSIONS_PATH = path.join(config.APP_DATA, "flow_versions.json");
|
||||
const MAX_PER_FLOW = 20;
|
||||
|
||||
let _data = {}; // flow_id -> [{ vid, at, name, on_fail, nodes }]
|
||||
let _loaded = false;
|
||||
|
||||
function load() {
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try {
|
||||
if (fs.existsSync(VERSIONS_PATH)) {
|
||||
const d = JSON.parse(fs.readFileSync(VERSIONS_PATH, "utf-8"));
|
||||
if (d && typeof d === "object" && !Array.isArray(d)) _data = d;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`流程版本读取失败:${e.message}`);
|
||||
_data = {};
|
||||
}
|
||||
}
|
||||
|
||||
function persist() {
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
const tmp = VERSIONS_PATH + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(_data, null, 2), "utf-8");
|
||||
fs.renameSync(tmp, VERSIONS_PATH);
|
||||
} catch (e) {
|
||||
logger.warning(`流程版本写入失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function nowStr() {
|
||||
const d = new Date();
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
// 只保留"内容"字段,schedule 等运行期配置不进快照
|
||||
function snapshotOf(flow) {
|
||||
return {
|
||||
name: flow.name || "",
|
||||
on_fail: flow.on_fail === "continue" ? "continue" : "abort",
|
||||
nodes: (flow.nodes || []).map((n) => ({ ...n })),
|
||||
};
|
||||
}
|
||||
|
||||
function contentKey(flow) {
|
||||
const s = snapshotOf(flow);
|
||||
return JSON.stringify({ name: s.name, on_fail: s.on_fail, nodes: s.nodes });
|
||||
}
|
||||
|
||||
// 保存一份快照(由 flows.update / rollback 在变更前调用)
|
||||
function push(flowId, flow) {
|
||||
load();
|
||||
if (!flowId || !flow) return null;
|
||||
const snap = snapshotOf(flow);
|
||||
const rec = { vid: crypto.randomBytes(6).toString("hex"), at: nowStr(), ...snap };
|
||||
const list = _data[flowId] || [];
|
||||
// 与最新一条完全相同就不重复记(比如连续点保存)
|
||||
if (list.length && JSON.stringify(list[list.length - 1].nodes) === JSON.stringify(rec.nodes)
|
||||
&& list[list.length - 1].name === rec.name
|
||||
&& list[list.length - 1].on_fail === rec.on_fail) {
|
||||
return null;
|
||||
}
|
||||
list.push(rec);
|
||||
while (list.length > MAX_PER_FLOW) list.shift();
|
||||
_data[flowId] = list;
|
||||
persist();
|
||||
return rec;
|
||||
}
|
||||
|
||||
// 新的在前(前端直接遍历展示)
|
||||
function list(flowId) {
|
||||
load();
|
||||
return [...(_data[flowId] || [])].reverse().map((v) => ({
|
||||
vid: v.vid,
|
||||
at: v.at,
|
||||
name: v.name,
|
||||
on_fail: v.on_fail,
|
||||
node_count: (v.nodes || []).length,
|
||||
// 只给摘要,不把整份节点喂给列表
|
||||
type_counts: (v.nodes || []).reduce((m, n) => {
|
||||
const t = n.type || "plugin";
|
||||
m[t] = (m[t] || 0) + 1;
|
||||
return m;
|
||||
}, {}),
|
||||
}));
|
||||
}
|
||||
|
||||
function get(flowId, vid) {
|
||||
load();
|
||||
return (_data[flowId] || []).find((v) => v.vid === vid) || null;
|
||||
}
|
||||
|
||||
// 流程删除时清理它的历史,避免文件无限增长
|
||||
function removeAll(flowId) {
|
||||
load();
|
||||
if (!_data[flowId]) return;
|
||||
delete _data[flowId];
|
||||
persist();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
VERSIONS_PATH,
|
||||
MAX_PER_FLOW,
|
||||
load,
|
||||
push,
|
||||
list,
|
||||
get,
|
||||
removeAll,
|
||||
snapshotOf,
|
||||
contentKey,
|
||||
};
|
||||
@@ -0,0 +1,805 @@
|
||||
// 流程编排(DAG):把多个场景按依赖关系组织成一张有向无环图,按拓扑顺序执行。
|
||||
//
|
||||
// 执行模型(当前版本刻意保持"单活串行"):
|
||||
// 流程本身不占执行槽,而是把每个节点当作"一次普通运行"提交给 queue,
|
||||
// 等 run_done 再做下一个 → 因此节点天然共享设备单活、登录态、超时与日志体系,
|
||||
// 不会出现"流程跑一半被别的任务插进来抢浏览器"的并发事故。
|
||||
//
|
||||
// executor 里 ready 集合已经算好,将来放开并发只需要把 `for (const node of ready)`
|
||||
// 换成 `await Promise.all(ready.map(runNode))`,配合按平台命名空间的槽位隔离即可,
|
||||
// 不需要改数据结构。
|
||||
//
|
||||
// 失败策略:abort(默认,一个节点失败 → 后续依赖它的节点标记跳过,整条流程结束)
|
||||
// continue(失败也继续跑其余不依赖它的分支)
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
const config = require("./config");
|
||||
const registry = require("./registry");
|
||||
const pluginConfigs = require("./plugin-configs");
|
||||
const tasks = require("./tasks");
|
||||
const versions = require("./flow-versions");
|
||||
const runner = require("./runner");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("flows");
|
||||
|
||||
const FLOWS_PATH = path.join(config.APP_DATA, "flows.json");
|
||||
const MAX_NODES = 50;
|
||||
// 节点类型:场景(默认)/ 等待 / 通知 / 人工确认 / 确保登录(客户端内置能力)
|
||||
const NODE_TYPES = new Set(["plugin", "delay", "notify", "confirm", "login"]);
|
||||
const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" };
|
||||
// 人工确认最长等待(超时按失败处理,避免流程永远挂着)
|
||||
const CONFIRM_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
// 等单次运行结束的兜底上限(节点运行本身有自己的超时,这里只防事件丢失)
|
||||
const NODE_WAIT_MS = 24 * 3600 * 1000;
|
||||
|
||||
let _flows = [];
|
||||
let _loaded = false;
|
||||
// flow_run_id -> { id, name, account, status, started, finished, nodes: [{id,name,state,run_id,error}], cursor }
|
||||
const _runs = new Map();
|
||||
const MAX_RUNS = 20;
|
||||
|
||||
// ==================== 存储 ====================
|
||||
function nowStr() {
|
||||
const d = new Date();
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function load() {
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
try {
|
||||
if (fs.existsSync(FLOWS_PATH)) {
|
||||
const d = JSON.parse(fs.readFileSync(FLOWS_PATH, "utf-8"));
|
||||
_flows = Array.isArray(d) ? d : Array.isArray(d.flows) ? d.flows : [];
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`流程配置读取失败:${e.message}`);
|
||||
_flows = [];
|
||||
}
|
||||
}
|
||||
|
||||
function persist() {
|
||||
try {
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
const tmp = FLOWS_PATH + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify({ flows: _flows }, null, 2), "utf-8");
|
||||
fs.renameSync(tmp, FLOWS_PATH);
|
||||
} catch (e) {
|
||||
logger.warning(`流程配置写入失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function list(account) {
|
||||
load();
|
||||
return _flows
|
||||
.filter((f) => f.account === account)
|
||||
.map((f) => ({
|
||||
...f,
|
||||
nodes: f.nodes.map((n) => ({ ...n })),
|
||||
// 运行态优先取内存里的;壳子重启后回落成"上次定时结论",至少不会显示成从未运行
|
||||
last_run: lastRunOf(f.id) || lastRunFromSchedule(f.schedule),
|
||||
// 下次触发时间:计划页要和场景定时任务并排展示,口径保持一致("YYYY-MM-DD HH:mm:ss")
|
||||
next_run_at: nextRunOf(f.schedule),
|
||||
}));
|
||||
}
|
||||
|
||||
// 下次触发:cron 合法且启用时才算,算不出返回空串(计划页显示「无下次触发」)
|
||||
function nextRunOf(schedule) {
|
||||
if (!schedule || !schedule.enabled || !schedule.cron) return "";
|
||||
try {
|
||||
const n = tasks.nextMatch(tasks.parseCron(schedule.cron), new Date());
|
||||
if (!n) return "";
|
||||
const p = (v) => String(v).padStart(2, "0");
|
||||
return `${n.getFullYear()}-${p(n.getMonth() + 1)}-${p(n.getDate())} ${p(n.getHours())}:${p(n.getMinutes())}:${p(n.getSeconds())}`;
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function get(id) {
|
||||
load();
|
||||
return _flows.find((f) => f.id === id) || null;
|
||||
}
|
||||
|
||||
// 备份导出:只带可重建流程的字段(随「定时任务备份」同一个槽一起推送)
|
||||
function exportByAccount(account) {
|
||||
load();
|
||||
return _flows
|
||||
.filter((f) => f.account === account)
|
||||
.map((f) => ({
|
||||
id: f.id,
|
||||
account: f.account,
|
||||
name: f.name,
|
||||
on_fail: f.on_fail,
|
||||
nodes: f.nodes,
|
||||
schedule: f.schedule,
|
||||
created_at: f.created_at,
|
||||
updated_at: f.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
// 云端合并:只补本地没有的 id,绝不覆盖本地已有流程(本地可能是用户刚改过的)
|
||||
function mergeFromCloud(account, list) {
|
||||
if (!Array.isArray(list) || !list.length) return 0;
|
||||
load();
|
||||
const localIds = new Set(_flows.map((f) => f.id));
|
||||
let added = 0;
|
||||
for (const raw of list) {
|
||||
if (!raw || typeof raw !== "object" || !raw.id || raw.account !== account) continue;
|
||||
if (localIds.has(raw.id)) continue;
|
||||
try {
|
||||
const nodes = normalizeNodes(raw.nodes || []);
|
||||
const schedule = normalizeSchedule(raw.schedule || {});
|
||||
_flows.push({
|
||||
id: String(raw.id),
|
||||
account,
|
||||
name: String(raw.name || "").trim() || "云端恢复的流程",
|
||||
on_fail: raw.on_fail === "continue" ? "continue" : "abort",
|
||||
nodes,
|
||||
schedule,
|
||||
created_at: raw.created_at || nowStr(),
|
||||
updated_at: nowStr(),
|
||||
});
|
||||
localIds.add(raw.id);
|
||||
added++;
|
||||
} catch (e) {
|
||||
logger.warning(`云端流程 ${raw.id} 恢复失败(跳过):${e.message}`);
|
||||
}
|
||||
}
|
||||
if (added) persist();
|
||||
return added;
|
||||
}
|
||||
|
||||
function lastRunOf(flowId) {
|
||||
let out = null;
|
||||
for (const r of _runs.values()) {
|
||||
if (r.flow_id !== flowId) continue;
|
||||
if (!out || r.started > out.started) out = r;
|
||||
}
|
||||
return out ? { status: out.status, started: out.started, finished: out.finished } : null;
|
||||
}
|
||||
|
||||
// 壳子重启后内存运行态丢失:用流程记录里持久化的"上次结论"补一个(只有结论,没有节点明细)
|
||||
function lastRunFromSchedule(schedule) {
|
||||
if (!schedule || !schedule.last_run_at) return null;
|
||||
const t = Date.parse(String(schedule.last_run_at).replace(" ", "T"));
|
||||
return {
|
||||
status: schedule.last_status === "ok" ? "done" : "error",
|
||||
started: Number.isNaN(t) ? 0 : Math.floor(t / 1000),
|
||||
finished: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 校验 ====================
|
||||
function newNodeId() {
|
||||
return crypto.randomBytes(6).toString("hex");
|
||||
}
|
||||
|
||||
// 拓扑排序:返回执行层级;有环则抛错
|
||||
function topoLayers(nodes) {
|
||||
const byId = new Map(nodes.map((n) => [n.id, n]));
|
||||
const indeg = new Map(nodes.map((n) => [n.id, 0]));
|
||||
for (const n of nodes) for (const d of n.deps || []) indeg.set(n.id, (indeg.get(n.id) || 0) + 1);
|
||||
let frontier = nodes.filter((n) => (indeg.get(n.id) || 0) === 0).map((n) => n.id);
|
||||
const layers = [];
|
||||
let seen = 0;
|
||||
while (frontier.length) {
|
||||
layers.push(frontier);
|
||||
seen += frontier.length;
|
||||
const next = [];
|
||||
for (const id of frontier) {
|
||||
for (const n of nodes) {
|
||||
if (!(n.deps || []).includes(id)) continue;
|
||||
indeg.set(n.id, indeg.get(n.id) - 1);
|
||||
if (indeg.get(n.id) === 0) next.push(n.id);
|
||||
}
|
||||
}
|
||||
frontier = next;
|
||||
}
|
||||
if (seen !== byId.size) throw new Error("节点依赖存在循环,无法形成执行顺序");
|
||||
return layers;
|
||||
}
|
||||
|
||||
function normalizeNodes(raw) {
|
||||
if (!Array.isArray(raw) || !raw.length) throw new Error("流程至少需要 1 个节点");
|
||||
if (raw.length > MAX_NODES) throw new Error(`单个流程最多 ${MAX_NODES} 个节点`);
|
||||
const ids = new Set();
|
||||
const nodes = raw.map((n) => {
|
||||
const id = String(n.id || "").trim() || newNodeId();
|
||||
if (ids.has(id)) throw new Error(`节点 ID 重复:${id}`);
|
||||
ids.add(id);
|
||||
const type = NODE_TYPES.has(n.type) ? n.type : "plugin";
|
||||
const base = {
|
||||
id,
|
||||
type,
|
||||
deps: Array.isArray(n.deps) ? [...new Set(n.deps.map(String))] : [],
|
||||
// 画布坐标(可视化编排用;缺省由前端自动排布)
|
||||
x: Number.isFinite(Number(n.x)) ? Math.round(Number(n.x)) : 0,
|
||||
y: Number.isFinite(Number(n.y)) ? Math.round(Number(n.y)) : 0,
|
||||
};
|
||||
|
||||
if (type === "delay") {
|
||||
const seconds = Math.max(1, Math.min(86400, parseInt(n.seconds, 10) || 60));
|
||||
return { ...base, name: String(n.name || "").trim() || `等待 ${seconds} 秒`, seconds };
|
||||
}
|
||||
if (type === "notify") {
|
||||
return {
|
||||
...base,
|
||||
name: String(n.name || "").trim() || "发送通知",
|
||||
title: String(n.title || "").trim() || "流程通知",
|
||||
message: String(n.message || "").trim(),
|
||||
};
|
||||
}
|
||||
if (type === "confirm") {
|
||||
return {
|
||||
...base,
|
||||
name: String(n.name || "").trim() || "人工确认",
|
||||
message: String(n.message || "").trim() || "请确认是否继续执行后续节点",
|
||||
};
|
||||
}
|
||||
if (type === "login") {
|
||||
const list = Array.isArray(n.platforms)
|
||||
? [...new Set(n.platforms.map(String).filter((p) => PLATFORM_LABELS[p]))]
|
||||
: [];
|
||||
if (!list.length) throw new Error("「确保登录」节点至少要选择一个平台");
|
||||
const label = list.map((p) => PLATFORM_LABELS[p]).join("、");
|
||||
return { ...base, name: String(n.name || "").trim() || `确保登录:${label}`, platforms: list };
|
||||
}
|
||||
|
||||
// plugin:默认节点类型
|
||||
const pluginId = String(n.plugin_id || "").trim();
|
||||
if (!pluginId) throw new Error("场景节点必须选择场景");
|
||||
let plugin;
|
||||
try {
|
||||
plugin = registry.find(pluginId);
|
||||
} catch (e) {
|
||||
throw new Error(`节点引用的场景不存在:${pluginId}`);
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
name: String(n.name || "").trim() || plugin.name || pluginId,
|
||||
plugin_id: pluginId,
|
||||
config_id: String(n.config_id || "").trim(),
|
||||
fields: n.fields && typeof n.fields === "object" && !Array.isArray(n.fields) ? n.fields : null,
|
||||
};
|
||||
});
|
||||
// 依赖必须存在且不能自依赖
|
||||
for (const n of nodes) {
|
||||
for (const d of n.deps) {
|
||||
if (d === n.id) throw new Error(`节点「${n.name}」不能依赖自己`);
|
||||
if (!ids.has(d)) throw new Error(`节点「${n.name}」依赖了不存在的节点`);
|
||||
}
|
||||
}
|
||||
topoLayers(nodes); // 有环直接抛
|
||||
return nodes;
|
||||
}
|
||||
|
||||
// 定时调度配置:与「定时任务」共用同一套 cron 解析与最小间隔(1 小时)约束
|
||||
function normalizeSchedule(raw) {
|
||||
const s = raw && typeof raw === "object" ? raw : {};
|
||||
const cron = String(s.cron || "").trim();
|
||||
if (cron) tasks.assertHourlyMin(tasks.parseCron(cron)); // cron 非法/过频直接抛给接口
|
||||
return {
|
||||
enabled: !!s.enabled && !!cron,
|
||||
cron,
|
||||
last_run_at: String(s.last_run_at || ""),
|
||||
last_status: String(s.last_status || ""),
|
||||
last_error: String(s.last_error || ""),
|
||||
};
|
||||
}
|
||||
|
||||
function create(account, body) {
|
||||
load();
|
||||
const name = String((body && body.name) || "").trim();
|
||||
if (!name) throw new Error("请填写流程名称");
|
||||
const nodes = normalizeNodes(body.nodes);
|
||||
const rec = {
|
||||
id: crypto.randomBytes(8).toString("hex"),
|
||||
account,
|
||||
name,
|
||||
on_fail: body.on_fail === "continue" ? "continue" : "abort",
|
||||
nodes,
|
||||
schedule: normalizeSchedule(body.schedule),
|
||||
created_at: nowStr(),
|
||||
updated_at: nowStr(),
|
||||
};
|
||||
_flows.push(rec);
|
||||
persist();
|
||||
return rec;
|
||||
}
|
||||
|
||||
function update(id, account, body) {
|
||||
load();
|
||||
const rec = _flows.find((f) => f.id === id);
|
||||
if (!rec) return null;
|
||||
if (rec.account !== account) throw Object.assign(new Error("仅创建者可管理该流程"), { status: 403 });
|
||||
// 变更前留档:只有"内容"(名称/失败策略/节点)变了才记版本,
|
||||
// 计划页改开关或 cron 不该造出一堆无意义的历史
|
||||
const beforeKey = versions.contentKey(rec);
|
||||
const beforeFlow = { name: rec.name, on_fail: rec.on_fail, nodes: rec.nodes };
|
||||
if (body.name !== undefined) {
|
||||
const name = String(body.name || "").trim();
|
||||
if (!name) throw new Error("请填写流程名称");
|
||||
rec.name = name;
|
||||
}
|
||||
if (body.nodes !== undefined) rec.nodes = normalizeNodes(body.nodes);
|
||||
if (body.on_fail !== undefined) rec.on_fail = body.on_fail === "continue" ? "continue" : "abort";
|
||||
if (body.schedule !== undefined) rec.schedule = normalizeSchedule({ ...(rec.schedule || {}), ...body.schedule });
|
||||
rec.updated_at = nowStr();
|
||||
if (versions.contentKey(rec) !== beforeKey) versions.push(rec.id, beforeFlow);
|
||||
persist();
|
||||
return rec;
|
||||
}
|
||||
|
||||
function remove(id, account) {
|
||||
load();
|
||||
const idx = _flows.findIndex((f) => f.id === id);
|
||||
if (idx < 0) return false;
|
||||
if (_flows[idx].account !== account) throw Object.assign(new Error("仅创建者可管理该流程"), { status: 403 });
|
||||
_flows.splice(idx, 1);
|
||||
versions.removeAll(id); // 清掉它的历史,避免版本文件无限增长
|
||||
persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ==================== 版本历史 / 回滚 ====================
|
||||
function listVersions(id, account) {
|
||||
load();
|
||||
const rec = _flows.find((f) => f.id === id);
|
||||
if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||||
if (rec.account !== account) throw Object.assign(new Error("仅创建者可查看该流程"), { status: 403 });
|
||||
return versions.list(id);
|
||||
}
|
||||
|
||||
function rollback(id, account, vid) {
|
||||
load();
|
||||
const rec = _flows.find((f) => f.id === id);
|
||||
if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||||
if (rec.account !== account) throw Object.assign(new Error("仅创建者可管理该流程"), { status: 403 });
|
||||
const ver = versions.get(id, vid);
|
||||
if (!ver) throw Object.assign(new Error("该版本不存在或已被清理"), { status: 404 });
|
||||
// 回滚前把当前状态也存一份:万一回滚错了还能再滚回来
|
||||
versions.push(id, { name: rec.name, on_fail: rec.on_fail, nodes: rec.nodes });
|
||||
rec.name = String(ver.name || rec.name);
|
||||
rec.on_fail = ver.on_fail === "continue" ? "continue" : "abort";
|
||||
rec.nodes = normalizeNodes(ver.nodes || []);
|
||||
rec.updated_at = nowStr();
|
||||
persist();
|
||||
logger.info(`流程「${rec.name}」回滚到版本 ${vid}(${ver.at})`);
|
||||
return rec;
|
||||
}
|
||||
|
||||
// ==================== 执行 ====================
|
||||
function publicRun(r) {
|
||||
return {
|
||||
flow_run_id: r.flow_run_id,
|
||||
flow_id: r.flow_id,
|
||||
name: r.name,
|
||||
account: r.account,
|
||||
status: r.status,
|
||||
started: r.started,
|
||||
finished: r.finished,
|
||||
waiting_confirm: r.waiting_confirm || null,
|
||||
nodes: r.nodes.map((n) => ({ id: n.id, name: n.name, state: n.state, run_id: n.run_id, error: n.error })),
|
||||
};
|
||||
}
|
||||
|
||||
function activeRuns(account) {
|
||||
return [..._runs.values()].filter((r) => !account || r.account === account).map(publicRun);
|
||||
}
|
||||
|
||||
function getRun(flowRunId) {
|
||||
const r = _runs.get(flowRunId);
|
||||
return r ? publicRun(r) : null;
|
||||
}
|
||||
|
||||
function pruneRuns() {
|
||||
if (_runs.size <= MAX_RUNS) return;
|
||||
const list = [..._runs.entries()].sort((a, b) => a[1].started - b[1].started);
|
||||
for (let i = 0; i < list.length - MAX_RUNS; i++) _runs.delete(list[i][0]);
|
||||
}
|
||||
|
||||
function waitRunDone(runId) {
|
||||
return new Promise((resolve) => {
|
||||
const onEvent = (ev) => {
|
||||
if (!ev || ev.t !== "run_done" || ev.run_id !== runId) return;
|
||||
cleanup();
|
||||
resolve(ev);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve({ ok: false, error: "等待节点运行结束超时(事件丢失)" });
|
||||
}, NODE_WAIT_MS);
|
||||
if (timer.unref) timer.unref();
|
||||
function cleanup() {
|
||||
clearTimeout(timer);
|
||||
HUB.removeListener("event", onEvent);
|
||||
}
|
||||
HUB.on("event", onEvent);
|
||||
});
|
||||
}
|
||||
|
||||
// 人工确认:等待用户在流程页点「继续 / 终止」
|
||||
const _confirmWaiters = new Map(); // `${flowRunId}:${nodeId}` -> resolve(ok)
|
||||
|
||||
function waitConfirm(flowRunId, nodeId) {
|
||||
return new Promise((resolve) => {
|
||||
const key = `${flowRunId}:${nodeId}`;
|
||||
const timer = setTimeout(() => {
|
||||
_confirmWaiters.delete(key);
|
||||
resolve(false);
|
||||
}, CONFIRM_TIMEOUT_MS);
|
||||
if (timer.unref) timer.unref();
|
||||
_confirmWaiters.set(key, (ok) => {
|
||||
clearTimeout(timer);
|
||||
resolve(!!ok);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 由 HTTP 接口调用:用户点了继续/终止
|
||||
function confirmNode(flowRunId, nodeId, ok) {
|
||||
const key = `${flowRunId}:${nodeId}`;
|
||||
const fn = _confirmWaiters.get(key);
|
||||
if (!fn) return false;
|
||||
_confirmWaiters.delete(key);
|
||||
fn(!!ok);
|
||||
return true;
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((r) => {
|
||||
const t = setTimeout(r, ms);
|
||||
if (t.unref) t.unref();
|
||||
});
|
||||
}
|
||||
|
||||
// 系统通知(右下角 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}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 节点参数:引用配置方案 → 取该方案最新 fields;否则用节点自带 fields(空则交给 runner 回退)
|
||||
function resolveFields(account, pluginId, node) {
|
||||
if (node.config_id) {
|
||||
const cfg = pluginConfigs.getConfig(account, pluginId, node.config_id);
|
||||
if (!cfg) throw new Error("引用的配置方案已被删除,请重新选择");
|
||||
return cfg.fields || {};
|
||||
}
|
||||
return node.fields || {};
|
||||
}
|
||||
|
||||
async function runNode(run, node, account) {
|
||||
const idx = run.nodes.findIndex((n) => n.id === node.id);
|
||||
const slot = run.nodes[idx];
|
||||
|
||||
// ---- 通用节点:等待 ----
|
||||
if (node.type === "delay") {
|
||||
slot.state = "running";
|
||||
publishNode(run, slot);
|
||||
logger.info(`流程「${run.name}」等待 ${node.seconds} 秒`);
|
||||
await sleep(node.seconds * 1000);
|
||||
slot.state = "ok";
|
||||
publishNode(run, slot);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 通用节点:通知(右下角系统通知 + 流程日志) ----
|
||||
if (node.type === "notify") {
|
||||
slot.state = "running";
|
||||
publishNode(run, slot);
|
||||
notifyUser(node.title || "流程通知", node.message || `「${run.name}」执行到通知节点`, "info");
|
||||
logger.info(`流程「${run.name}」发送通知:${node.title || ""}`);
|
||||
slot.state = "ok";
|
||||
publishNode(run, slot);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 通用节点:人工确认(阻塞等待,30 分钟超时按失败) ----
|
||||
if (node.type === "confirm") {
|
||||
slot.state = "waiting";
|
||||
run.waiting_confirm = { node_id: node.id, message: node.message };
|
||||
publishNode(run, slot);
|
||||
HUB.publish({
|
||||
t: "flow_confirm",
|
||||
flow_run_id: run.flow_run_id,
|
||||
flow_id: run.flow_id,
|
||||
node_id: node.id,
|
||||
name: slot.name,
|
||||
message: node.message,
|
||||
});
|
||||
notifyUser("流程等待确认", `「${run.name}」:${node.message}`, "warning");
|
||||
const ok = await waitConfirm(run.flow_run_id, node.id);
|
||||
run.waiting_confirm = null;
|
||||
slot.state = ok ? "ok" : "error";
|
||||
slot.error = ok ? "" : "人工确认未通过或超时(30 分钟)";
|
||||
publishNode(run, slot);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ---- 客户端内置能力:确保平台登录态(失效时用平台账号密码自动补登,不开浏览器) ----
|
||||
if (node.type === "login") {
|
||||
slot.state = "running";
|
||||
publishNode(run, slot);
|
||||
try {
|
||||
const auth = require("./platform-auth");
|
||||
for (const pid of node.platforms || []) {
|
||||
const label = PLATFORM_LABELS[pid] || pid;
|
||||
if (await auth.isOnline(pid, account)) {
|
||||
logger.info(`流程「${run.name}」:${label}登录态有效`);
|
||||
continue;
|
||||
}
|
||||
logger.info(`流程「${run.name}」:${label}登录态失效,正在自动登录…`);
|
||||
const r = await auth.login(pid, account);
|
||||
if (!r || !r.online) {
|
||||
throw new Error(`${label}登录失败:${(r && r.message) || "登录未生效"}(请在「平台账号」检查账号密码)`);
|
||||
}
|
||||
}
|
||||
slot.state = "ok";
|
||||
publishNode(run, slot);
|
||||
return true;
|
||||
} catch (e) {
|
||||
slot.state = "error";
|
||||
slot.error = e.message || String(e);
|
||||
publishNode(run, slot);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 场景节点 ----
|
||||
let plugin;
|
||||
try {
|
||||
plugin = registry.find(node.plugin_id);
|
||||
} catch (e) {
|
||||
slot.state = "error";
|
||||
slot.error = "场景不存在或已下架";
|
||||
publishNode(run, slot);
|
||||
return false;
|
||||
}
|
||||
// 授权检查:与定时任务同一口径(未授权/离线时不该因为走流程就绕过)
|
||||
try {
|
||||
const licensing = require("./licensing");
|
||||
const deny = await licensing.runCheckAllowed(plugin.id, account, licensing.isOnline());
|
||||
if (deny) {
|
||||
slot.state = "error";
|
||||
slot.error = deny;
|
||||
publishNode(run, slot);
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`流程「${run.name}」授权检查异常(按放行处理):${e.message}`);
|
||||
}
|
||||
let fields;
|
||||
try {
|
||||
fields = resolveFields(account, plugin.id, node);
|
||||
} catch (e) {
|
||||
slot.state = "error";
|
||||
slot.error = e.message;
|
||||
publishNode(run, slot);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const r = runner.submitRun(account, plugin, fields, {
|
||||
trigger: "flow",
|
||||
flow_run_id: run.flow_run_id,
|
||||
node_id: node.id,
|
||||
});
|
||||
slot.run_id = r.run_id;
|
||||
slot.state = "running";
|
||||
publishNode(run, slot);
|
||||
logger.info(`流程「${run.name}」节点「${slot.name}」开始执行(run ${r.run_id},队列第 ${r.queue_position} 位)`);
|
||||
const ev = await waitRunDone(r.run_id);
|
||||
slot.state = ev.ok ? "ok" : "error";
|
||||
slot.error = ev.ok ? "" : ev.error || "执行失败";
|
||||
publishNode(run, slot);
|
||||
return !!ev.ok;
|
||||
} catch (e) {
|
||||
slot.state = "error";
|
||||
slot.error = e.message || String(e);
|
||||
publishNode(run, slot);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function publishNode(run, slot) {
|
||||
HUB.publish({
|
||||
t: "flow_node",
|
||||
flow_run_id: run.flow_run_id,
|
||||
flow_id: run.flow_id,
|
||||
node_id: slot.id,
|
||||
name: slot.name,
|
||||
state: slot.state,
|
||||
run_id: slot.run_id || "",
|
||||
error: slot.error || "",
|
||||
});
|
||||
}
|
||||
|
||||
async function execute(run, flow, account) {
|
||||
const done = new Map(); // node_id -> 'ok' | 'error' | 'skipped'
|
||||
let remaining = new Set(flow.nodes.map((n) => n.id));
|
||||
let aborted = false;
|
||||
|
||||
while (remaining.size) {
|
||||
const ready = flow.nodes.filter(
|
||||
(n) => remaining.has(n.id) && (n.deps || []).every((d) => done.get(d) === "ok")
|
||||
);
|
||||
if (!ready.length) {
|
||||
// 剩下的节点要么依赖失败/跳过,要么形成环(保存时已拦,理论到不了)
|
||||
for (const n of flow.nodes.filter((x) => remaining.has(x.id))) {
|
||||
const slot = run.nodes.find((x) => x.id === n.id);
|
||||
slot.state = "skipped";
|
||||
slot.error = "前置节点未成功,已跳过";
|
||||
publishNode(run, slot);
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (const node of ready) {
|
||||
remaining.delete(node.id);
|
||||
const ok = await runNode(run, node, account);
|
||||
done.set(node.id, ok ? "ok" : "error");
|
||||
if (!ok && flow.on_fail !== "continue") {
|
||||
aborted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (aborted) {
|
||||
for (const n of flow.nodes.filter((x) => remaining.has(x.id))) {
|
||||
const slot = run.nodes.find((x) => x.id === n.id);
|
||||
slot.state = "skipped";
|
||||
slot.error = "流程因节点失败而中止";
|
||||
publishNode(run, slot);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const ok = run.nodes.every((n) => n.state === "ok");
|
||||
run.status = ok ? "done" : "error";
|
||||
run.finished = Math.floor(Date.now() / 1000);
|
||||
// 回写定时任务视图需要的"上次结论"
|
||||
if (flow.schedule) {
|
||||
const bad = run.nodes.find((n) => n.state === "error");
|
||||
flow.schedule.last_status = ok ? "ok" : "error";
|
||||
flow.schedule.last_error = ok ? "" : (bad && bad.error) || "执行失败";
|
||||
persist();
|
||||
}
|
||||
logger.info(`流程「${run.name}」${ok ? "执行完成" : "执行结束(含失败节点)"}`);
|
||||
HUB.publish({ t: "flow_done", flow_run_id: run.flow_run_id, flow_id: run.flow_id, ok, status: run.status });
|
||||
pruneRuns();
|
||||
}
|
||||
|
||||
function run(account, flowId) {
|
||||
load();
|
||||
const flow = _flows.find((f) => f.id === flowId);
|
||||
if (!flow) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||||
if (flow.account !== account) throw Object.assign(new Error("仅创建者可运行该流程"), { status: 403 });
|
||||
if (!flow.nodes.length) throw new Error("流程没有节点");
|
||||
const running = [..._runs.values()].find((r) => r.flow_id === flowId && r.status === "running");
|
||||
if (running) throw Object.assign(new Error("该流程正在运行中,请等待结束"), { status: 409 });
|
||||
|
||||
const flowRunId = crypto.randomBytes(16).toString("hex");
|
||||
const rec = {
|
||||
flow_run_id: flowRunId,
|
||||
flow_id: flow.id,
|
||||
name: flow.name,
|
||||
account,
|
||||
status: "running",
|
||||
started: Math.floor(Date.now() / 1000),
|
||||
finished: 0,
|
||||
waiting_confirm: null,
|
||||
nodes: flow.nodes.map((n) => ({ id: n.id, name: n.name, state: "pending", run_id: "", error: "" })),
|
||||
};
|
||||
_runs.set(flowRunId, rec);
|
||||
pruneRuns();
|
||||
HUB.publish({
|
||||
t: "flow_start",
|
||||
flow_run_id: flowRunId,
|
||||
flow_id: flow.id,
|
||||
name: flow.name,
|
||||
nodes: rec.nodes.map((n) => ({ id: n.id, name: n.name, state: n.state })),
|
||||
});
|
||||
void execute(rec, flow, account).catch((e) => {
|
||||
logger.error(`流程执行异常:${e.message}`);
|
||||
rec.status = "error";
|
||||
rec.finished = Math.floor(Date.now() / 1000);
|
||||
HUB.publish({ t: "flow_done", flow_run_id: flowRunId, flow_id: flow.id, ok: false, status: "error" });
|
||||
});
|
||||
return publicRun(rec);
|
||||
}
|
||||
|
||||
// ==================== 定时调度 ====================
|
||||
// 复用「定时任务」的 cron 解析与语义:最小间隔 1 小时、错过不补跑、同一时刻只触发一次
|
||||
const TICK_SECS = 30;
|
||||
let _started = false;
|
||||
let _ticking = false;
|
||||
|
||||
function start() {
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
setInterval(() => {
|
||||
void tick();
|
||||
}, TICK_SECS * 1000);
|
||||
logger.info(`流程定时检查已启动(每 ${TICK_SECS}s 一次)`);
|
||||
}
|
||||
|
||||
function init() {
|
||||
load();
|
||||
start();
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
if (_ticking) return;
|
||||
_ticking = true;
|
||||
try {
|
||||
const now = new Date();
|
||||
for (const f of _flows) {
|
||||
const s = f.schedule;
|
||||
if (!s || !s.enabled || !s.cron) continue;
|
||||
let cron;
|
||||
try {
|
||||
cron = tasks.parseCron(s.cron);
|
||||
if (tasks.minGapMinutes(cron) < 60) continue;
|
||||
} catch (e) {
|
||||
continue; // 非法 cron 不触发(保存时已拦)
|
||||
}
|
||||
let last = null;
|
||||
if (s.last_run_at) {
|
||||
const t = Date.parse(s.last_run_at.replace(" ", "T"));
|
||||
if (!Number.isNaN(t)) last = new Date(t);
|
||||
}
|
||||
const anchor = last || new Date(now.getTime() - tasks.CATCHUP_SKIP_MS);
|
||||
const nxt = tasks.nextMatch(cron, anchor);
|
||||
if (!nxt || nxt.getTime() > now.getTime()) continue;
|
||||
if (!tasks.isDueNow(nxt, now)) {
|
||||
// 错过:跳过不补跑,last_run_at 推进到现在,避免对同一失效点反复判定
|
||||
s.last_run_at = nowStr();
|
||||
persist();
|
||||
logger.info(`流程「${f.name}」错过触发点(客户端停机/离线),跳过`);
|
||||
continue;
|
||||
}
|
||||
s.last_run_at = nowStr();
|
||||
persist();
|
||||
try {
|
||||
const r = run(f.account, f.id);
|
||||
logger.info(`流程「${f.name}」定时触发(${r.flow_run_id})`);
|
||||
} catch (e) {
|
||||
logger.warning(`流程「${f.name}」定时触发失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
_ticking = false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FLOWS_PATH,
|
||||
load,
|
||||
init,
|
||||
start,
|
||||
tick,
|
||||
list,
|
||||
get,
|
||||
exportByAccount,
|
||||
mergeFromCloud,
|
||||
create,
|
||||
update,
|
||||
remove,
|
||||
listVersions,
|
||||
rollback,
|
||||
run,
|
||||
confirmNode,
|
||||
activeRuns,
|
||||
getRun,
|
||||
topoLayers,
|
||||
};
|
||||
@@ -6,7 +6,49 @@ const { makeLogger } = require("./logger");
|
||||
const logger = makeLogger("notify-toast");
|
||||
|
||||
const W = 380, H = 132, GAP = 10, MARGIN = 16, TTL = 9000;
|
||||
let lastBottom = null;
|
||||
// 同屏最多几条(超出后关掉最早的那条,避免糊满屏幕)
|
||||
const MAX_VISIBLE = 4;
|
||||
// 当前在显示的窗口,自下而上排列:末尾 = 最新(最靠下)
|
||||
const _stack = [];
|
||||
|
||||
// 重新排布:最新的一条贴着屏幕右下角,其余依次往上叠。
|
||||
// 关键点是"有窗口消失时也要重排",否则会留下空洞、新通知从半空中冒出来。
|
||||
function layout() {
|
||||
let wa;
|
||||
try {
|
||||
wa = require("electron").screen.getPrimaryDisplay().workArea;
|
||||
} catch (e) {
|
||||
return; // 非 Electron 环境
|
||||
}
|
||||
const x = Math.round(wa.x + wa.width - W - MARGIN);
|
||||
let bottom = wa.y + wa.height - MARGIN;
|
||||
for (let i = _stack.length - 1; i >= 0; i--) {
|
||||
const y = Math.round(bottom - H);
|
||||
const win = _stack[i].win;
|
||||
try {
|
||||
if (!win.isDestroyed()) win.setPosition(x, y);
|
||||
} catch (e) {
|
||||
/* 窗口正在销毁:忽略 */
|
||||
}
|
||||
bottom = y - GAP;
|
||||
}
|
||||
}
|
||||
|
||||
// 从栈里摘掉并让剩下的整体下沉(补上空位)
|
||||
function removeFromStack(win) {
|
||||
const i = _stack.findIndex((it) => it.win === win);
|
||||
if (i < 0) return;
|
||||
_stack.splice(i, 1);
|
||||
layout();
|
||||
}
|
||||
|
||||
function closeToast(win) {
|
||||
try {
|
||||
if (!win.isDestroyed()) win.destroy();
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
function levelColor(level) {
|
||||
return { info: "#2f5cf0", warning: "#d97706", important: "#d6453d" }[level] || "#2f5cf0";
|
||||
@@ -60,28 +102,37 @@ function buildHTML(title, body, level) {
|
||||
function show(title, body, level) {
|
||||
try {
|
||||
const { BrowserWindow, screen } = require("electron");
|
||||
const display = screen.getPrimaryDisplay();
|
||||
const wa = display.workArea;
|
||||
const x = wa.x + wa.width - W - MARGIN;
|
||||
if (lastBottom === null) lastBottom = wa.y + wa.height - H - MARGIN;
|
||||
const y = lastBottom;
|
||||
lastBottom = lastBottom - H - GAP;
|
||||
if (lastBottom < wa.y + MARGIN) lastBottom = null; // 满屏后下一轮回到底部
|
||||
const wa = screen.getPrimaryDisplay().workArea;
|
||||
|
||||
// 超过上限:先关掉最早的一条(它的 closed 会把自己从栈里摘掉)
|
||||
while (_stack.length >= MAX_VISIBLE) {
|
||||
closeToast(_stack[0].win);
|
||||
if (_stack.length >= MAX_VISIBLE) _stack.shift(); // 兜底:closed 没触发也不能死循环
|
||||
}
|
||||
|
||||
const win = new BrowserWindow({
|
||||
width: W, height: H, x, y,
|
||||
width: W, height: H,
|
||||
x: Math.round(wa.x + wa.width - W - MARGIN),
|
||||
y: Math.round(wa.y + wa.height - H - MARGIN),
|
||||
frame: false, transparent: true, resizable: false, movable: false,
|
||||
alwaysOnTop: true, skipTaskbar: true, hasShadow: false, show: false, focusable: false,
|
||||
backgroundColor: "#00000000",
|
||||
webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },
|
||||
});
|
||||
win.setAlwaysOnTop(true, "pop-up-menu");
|
||||
_stack.push({ win });
|
||||
layout(); // 先摆好位置再显示,避免出现"闪一下再跳"
|
||||
|
||||
win.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(buildHTML(title, body, level)));
|
||||
win.once("ready-to-show", () => {
|
||||
try { win.showInactive(); } catch (e) { win.show(); }
|
||||
});
|
||||
const t = setTimeout(() => { try { win.destroy(); } catch (e) { /* 忽略 */ } }, TTL);
|
||||
win.on("closed", () => { clearTimeout(t); });
|
||||
|
||||
const t = setTimeout(() => closeToast(win), TTL);
|
||||
win.on("closed", () => {
|
||||
clearTimeout(t);
|
||||
removeFromStack(win); // 摘掉后剩余的立刻下沉,补上空位
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.warning(`自定义通知弹窗失败:${e.message}`);
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
// 执行队列:显式 FIFO 队列 + 单 worker 串行执行,队列状态实时广播给前端。
|
||||
//
|
||||
// 为什么要独立队列(相对旧的 Promise 门闩):
|
||||
// 1. 状态可见:排队中的任务有 queued 状态、明确的位置(第几位)、等待时长,前端可展示可取消;
|
||||
// 2. 顺序确定:手动「一键执行」与定时任务共用同一条 FIFO,先到先跑,不存在插队;
|
||||
// 3. 计时准确:started 只在真正拉起子进程时写入,排队时长不再计入运行耗时;
|
||||
// 4. 可取消:排队项直接从队列摘除,不需要等轮到自己再失败;
|
||||
// 5. 可超时:定时任务排队超过 max_wait_sec 自动放弃,避免堆到下班后;
|
||||
// 6. 可追溯:排队项只在内存跑,但会落一份"不含执行参数"的元数据,客户端异常退出后
|
||||
// 下次启动能把它们标成「已中断」,而不是凭空消失。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const config = require("./config");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("queue");
|
||||
|
||||
// 队列上限:超长排队说明用户误操作或定时任务挤在同一时刻,直接拒绝比无限堆积更可控
|
||||
const MAX_QUEUE = 100;
|
||||
// 排队超时巡检间隔(秒)
|
||||
const SWEEP_SECS = 10;
|
||||
// 遗留任务元数据(不含 fields,可安全落盘)
|
||||
const PENDING_PATH = path.join(config.APP_DATA, "queue_pending.json");
|
||||
|
||||
// 等待中的任务(含完整 fields,仅内存持有,绝不进快照/日志/落盘)
|
||||
const _items = [];
|
||||
// 当前执行中的任务(公开摘要,可广播)
|
||||
let _running = null;
|
||||
// 执行器由 runner 注入:async (item) => void,item 为完整入队对象
|
||||
let _executor = null;
|
||||
// 超时回掉由 runner 注入:(item) => void,负责落终态
|
||||
let _onExpire = null;
|
||||
// worker 重入保护
|
||||
let _draining = false;
|
||||
// 入队自增序号(快照排序/调试用)
|
||||
let _seq = 0;
|
||||
// 最近一次启动恢复的遗留任务概要:随快照下发,前端登录后提示一次
|
||||
// (init 发生在 listen 之前,当时的 WS 广播没有客户端,不能只靠事件)
|
||||
let _lastRecovered = null;
|
||||
|
||||
function setExecutor(fn) {
|
||||
_executor = typeof fn === "function" ? fn : null;
|
||||
}
|
||||
|
||||
function setOnExpire(fn) {
|
||||
_onExpire = typeof fn === "function" ? fn : null;
|
||||
}
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function nowSec() {
|
||||
return Date.now() / 1000;
|
||||
}
|
||||
|
||||
// 对外公开字段白名单:fields(可能含密码)与内部序号一律不出网
|
||||
function publicItem(item, position) {
|
||||
return {
|
||||
run_id: item.run_id,
|
||||
account: item.account || "",
|
||||
plugin_id: item.plugin_id || "",
|
||||
name: item.name || item.plugin_id || "",
|
||||
version: item.version || "0",
|
||||
platform: item.platform || "",
|
||||
trigger: item.trigger === "schedule" ? "schedule" : "manual",
|
||||
schedule_id: item.schedule_id || "",
|
||||
enqueued_at: item.enqueued_at || 0,
|
||||
position: position,
|
||||
max_wait_sec: item.max_wait_sec || 0,
|
||||
expire_at: item.expire_at || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 队列快照:account 为空表示全量(WS 广播用),否则只返回该账号可见的部分
|
||||
// position 口径统一为"含正在执行的那个":有任务在执行时,第一个等待项显示为第 2 位
|
||||
function snapshot(account) {
|
||||
const offset = _running ? 1 : 0;
|
||||
const all = _items.map((it, i) => publicItem(it, i + 1 + offset));
|
||||
const items = account ? all.filter((x) => x.account === account) : all;
|
||||
const running = _running && (!account || _running.account === account) ? { ..._running } : null;
|
||||
return {
|
||||
running,
|
||||
items,
|
||||
waiting: items.length,
|
||||
busy: !!_running,
|
||||
recovered: _lastRecovered,
|
||||
updated_at: nowIso(),
|
||||
};
|
||||
}
|
||||
|
||||
function publish() {
|
||||
try {
|
||||
HUB.publish({ t: "queue", ...snapshot("") });
|
||||
} catch (e) {
|
||||
logger.warning(`队列广播失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 遗留任务元数据(崩溃/更新后可追溯) ====================
|
||||
// 只写"谁、什么场景、什么时候排上的",不写 fields:执行参数可能含账号密码,不落盘。
|
||||
function persist() {
|
||||
try {
|
||||
const payload = {
|
||||
updated_at: nowIso(),
|
||||
running: _running ? { ..._running } : null,
|
||||
items: _items.map((it) => publicItem(it, 0)),
|
||||
};
|
||||
fs.mkdirSync(config.APP_DATA, { recursive: true });
|
||||
const tmp = PENDING_PATH + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(payload), "utf-8");
|
||||
fs.renameSync(tmp, PENDING_PATH); // 原子写
|
||||
} catch (e) {
|
||||
logger.warning(`队列元数据落盘失败:${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function dropPersisted() {
|
||||
try {
|
||||
if (fs.existsSync(PENDING_PATH)) fs.unlinkSync(PENDING_PATH);
|
||||
} catch (e) {
|
||||
/* 忽略:删不掉也只是下次启动多报一次中断 */
|
||||
}
|
||||
}
|
||||
|
||||
// 启动时取出上次遗留的排队/执行记录(不清理无法恢复的字段,仅用于标记中断)
|
||||
function recover() {
|
||||
let payload = null;
|
||||
try {
|
||||
if (fs.existsSync(PENDING_PATH)) {
|
||||
payload = JSON.parse(fs.readFileSync(PENDING_PATH, "utf-8"));
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warning(`队列遗留记录读取失败:${e.message}`);
|
||||
}
|
||||
dropPersisted();
|
||||
if (!payload || typeof payload !== "object") return { running: null, items: [] };
|
||||
const items = Array.isArray(payload.items) ? payload.items.filter((x) => x && x.run_id) : [];
|
||||
const running = payload.running && payload.running.run_id ? payload.running : null;
|
||||
const count = items.length + (running ? 1 : 0);
|
||||
if (count > 0) _lastRecovered = { count, at: nowIso() };
|
||||
return { running, items };
|
||||
}
|
||||
|
||||
// ==================== 排队超时 ====================
|
||||
// 独立巡检:队列卡在一个长任务上时,后面等待超时的任务也要能及时下队(不能等轮到自己)
|
||||
function sweepExpired() {
|
||||
const now = nowSec();
|
||||
const expired = [];
|
||||
for (let i = _items.length - 1; i >= 0; i--) {
|
||||
const it = _items[i];
|
||||
if (it.expire_at && it.expire_at <= now) {
|
||||
_items.splice(i, 1);
|
||||
expired.push(it);
|
||||
}
|
||||
}
|
||||
if (!expired.length) return;
|
||||
logger.info(`排队超时自动取消 ${expired.length} 个任务`);
|
||||
publish();
|
||||
for (const it of expired) {
|
||||
if (_onExpire) {
|
||||
try {
|
||||
_onExpire(publicItem(it, 0));
|
||||
} catch (e) {
|
||||
logger.warning(`排队超时回调异常:${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const _sweeper = setInterval(sweepExpired, SWEEP_SECS * 1000);
|
||||
if (_sweeper.unref) _sweeper.unref();
|
||||
|
||||
// ==================== 队列操作 ====================
|
||||
function size() {
|
||||
return _items.length;
|
||||
}
|
||||
|
||||
function full() {
|
||||
return _items.length >= MAX_QUEUE;
|
||||
}
|
||||
|
||||
function busy() {
|
||||
return !!_running;
|
||||
}
|
||||
|
||||
function runningItem() {
|
||||
return _running ? { ..._running } : null;
|
||||
}
|
||||
|
||||
// 入队:返回该任务的排队位置(1 = 立刻执行;有任务在执行时第一个等待项为 2)。
|
||||
//
|
||||
// 优先级策略:手动「一键执行」优先于定时任务——手动任务插到所有定时任务之前(同优先级内仍严格 FIFO),
|
||||
// 定时任务一律排到队尾。理由:手动是用户此刻在等结果,定时只是到点执行,晚几分钟无感。
|
||||
// 注意:位置必须在 drain() 之前算好——drain 会同步把队首 shift 出来,之后 size 已经变了。
|
||||
function enqueue(item) {
|
||||
if (!item || !item.run_id) throw new Error("入队缺少 run_id");
|
||||
if (full()) {
|
||||
throw Object.assign(new Error(`执行队列已满(最多 ${MAX_QUEUE} 个等待任务),请稍后再试`), { status: 429 });
|
||||
}
|
||||
const enqueuedAt = item.enqueued_at || nowSec();
|
||||
const maxWait = Math.max(0, parseInt(item.max_wait_sec, 10) || 0);
|
||||
const it = {
|
||||
...item,
|
||||
seq: ++_seq,
|
||||
trigger: item.trigger === "schedule" ? "schedule" : "manual",
|
||||
enqueued_at: enqueuedAt,
|
||||
max_wait_sec: maxWait,
|
||||
expire_at: maxWait > 0 ? enqueuedAt + maxWait : 0,
|
||||
};
|
||||
// 插入位置:手动 → 第一个定时任务之前;定时 → 队尾
|
||||
let idx = _items.length;
|
||||
if (it.trigger === "manual") {
|
||||
const firstScheduled = _items.findIndex((x) => x.trigger !== "manual");
|
||||
if (firstScheduled >= 0) idx = firstScheduled;
|
||||
}
|
||||
const position = idx + (_running ? 2 : 1);
|
||||
_items.splice(idx, 0, it);
|
||||
publish();
|
||||
persist();
|
||||
void drain();
|
||||
return position;
|
||||
}
|
||||
|
||||
// 从队列摘除一个等待中的任务(不存在返回 null)
|
||||
function cancel(runId) {
|
||||
const idx = _items.findIndex((it) => it.run_id === runId);
|
||||
if (idx < 0) return null;
|
||||
const [item] = _items.splice(idx, 1);
|
||||
publish();
|
||||
persist();
|
||||
return item;
|
||||
}
|
||||
|
||||
function has(runId) {
|
||||
return _items.some((it) => it.run_id === runId);
|
||||
}
|
||||
|
||||
// 真正拉起子进程时刷新运行态(开始时间以此刻为准,排队时长不计入耗时)
|
||||
function markStarted(runId, started) {
|
||||
if (!_running || _running.run_id !== runId) return;
|
||||
_running = { ..._running, started_at: started || nowSec() };
|
||||
publish();
|
||||
persist();
|
||||
}
|
||||
|
||||
// 清空等待队列(客户端退出前调用;返回被清掉的任务,供调用方落终态)
|
||||
function clear(reason) {
|
||||
const dropped = _items.splice(0);
|
||||
if (dropped.length) {
|
||||
logger.info(`执行队列已清空(${reason || "shutdown"}),丢弃 ${dropped.length} 个等待任务`);
|
||||
}
|
||||
dropPersisted();
|
||||
publish();
|
||||
return dropped.map((it) => publicItem(it, 0));
|
||||
}
|
||||
|
||||
async function drain() {
|
||||
if (_draining) return;
|
||||
_draining = true;
|
||||
try {
|
||||
while (_items.length && _executor) {
|
||||
const item = _items.shift();
|
||||
// 出队瞬间再校验一次超时(巡检有 10s 间隔,避免"已超时但仍被拉起")
|
||||
if (item.expire_at && item.expire_at <= nowSec()) {
|
||||
publish();
|
||||
persist();
|
||||
if (_onExpire) {
|
||||
try {
|
||||
_onExpire(publicItem(item, 0));
|
||||
} catch (e) {
|
||||
logger.warning(`排队超时回调异常:${e.message}`);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_running = { ...publicItem(item, 0), started_at: 0 };
|
||||
publish();
|
||||
persist();
|
||||
try {
|
||||
await _executor(item);
|
||||
} catch (e) {
|
||||
// 执行器内部必须自行落终态;这里只兜底记录,避免 worker 被一次异常终止
|
||||
logger.error(`队列执行异常(${item.run_id}):${e.message}`);
|
||||
} finally {
|
||||
_running = null;
|
||||
publish();
|
||||
persist();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
_draining = false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
MAX_QUEUE,
|
||||
PENDING_PATH,
|
||||
setExecutor,
|
||||
setOnExpire,
|
||||
snapshot,
|
||||
publish,
|
||||
enqueue,
|
||||
cancel,
|
||||
has,
|
||||
size,
|
||||
full,
|
||||
busy,
|
||||
runningItem,
|
||||
markStarted,
|
||||
clear,
|
||||
recover,
|
||||
};
|
||||
@@ -11,6 +11,7 @@ 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 platformAuth = require("./platform-auth");
|
||||
@@ -20,15 +21,61 @@ const { makeLogger } = require("./logger");
|
||||
|
||||
const logger = makeLogger("runner");
|
||||
|
||||
// 定时任务的最长排队等待:到点时前面还有任务在跑,超过这个时长就不跑了(避免堆到下班后)。
|
||||
// 手动执行不设限(用户自己点的,愿意等)。
|
||||
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 {
|
||||
@@ -52,15 +99,40 @@ function treeKill(pid) {
|
||||
}
|
||||
|
||||
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 {
|
||||
licensing.report(dropped.account || rec.account || "", "", info.id, info.version, "error", "用户取消了排队任务", 0);
|
||||
} catch (e) {
|
||||
logger.warning(`取消排队任务上报失败:${e.message}`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
_USER_STOPPED.add(runId);
|
||||
const kill = _ACTIVE.get(runId);
|
||||
if (!kill) return false; // 尚未拉起执行子进程(排队中)或已结束
|
||||
try {
|
||||
kill();
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
if (kill) {
|
||||
try {
|
||||
kill();
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
// 已出队但子进程还没拉起的极短窗口:留着停止标记,startFn 会在拉起前中止
|
||||
const rt = queue.runningItem();
|
||||
if (rt && rt.run_id === runId) return true;
|
||||
_USER_STOPPED.delete(runId); // 该任务确实已结束,别把标记留给后续同名 run
|
||||
return false;
|
||||
}
|
||||
|
||||
// 平台命名空间并发闸键:按(账号, 平台)隔离,保护该账号各自的平台登录态 cookies
|
||||
@@ -114,6 +186,10 @@ 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,
|
||||
@@ -130,6 +206,7 @@ function finishRun(runId, plugin, status, error, summary) {
|
||||
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 || "",
|
||||
@@ -164,14 +241,28 @@ function finishRun(runId, plugin, status, error, summary) {
|
||||
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 || "",
|
||||
});
|
||||
// 排队任务的结束提醒(用户手动取消队列里的任务不算:应用内已有明确反馈,不再二次打扰)
|
||||
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。
|
||||
@@ -204,9 +295,11 @@ function throwEnvNotReady() {
|
||||
throw new Error(msg);
|
||||
}
|
||||
|
||||
// 提交一次运行 = 入队(不再直接拉起进程)。返回 { run_id, queue_position }。
|
||||
function submitRun(account, plugin, fields, opts) {
|
||||
const o = opts && typeof opts === "object" ? opts : {};
|
||||
const trigger = o.trigger === "schedule" ? "schedule" : "manual";
|
||||
// manual=用户点击;schedule=定时任务;flow=流程编排里的节点
|
||||
const trigger = ["manual", "schedule", "flow"].includes(o.trigger) ? o.trigger : "manual";
|
||||
// 环境未就绪预防:提交前校验执行链路(入口脚本/解释器),缺失时直接拒绝并给可读提示,
|
||||
// 避免子进程 spawn ENOENT 后用户只看到"执行进程异常退出(exit=-4058)且未返回结果"。
|
||||
// 打包态无环境包且未显式配置解释器时也拒绝(系统 python 不可依赖)。
|
||||
@@ -220,45 +313,86 @@ function submitRun(account, plugin, fields, opts) {
|
||||
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";
|
||||
state.registerRun(runId, {
|
||||
status: "running",
|
||||
status: "queued", // 排队中:尚未占用执行槽,started 为空
|
||||
account,
|
||||
plugin_id: plugin.id,
|
||||
name: plugin.name || plugin.id,
|
||||
version: plugin.version || "0",
|
||||
name,
|
||||
version,
|
||||
trigger,
|
||||
schedule_id: o.schedule_id || "",
|
||||
started: Date.now() / 1000,
|
||||
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_start",
|
||||
t: "run_queued",
|
||||
run_id: runId,
|
||||
account,
|
||||
plugin_id: plugin.id,
|
||||
name: plugin.name || plugin.id,
|
||||
name,
|
||||
trigger,
|
||||
schedule_id: o.schedule_id || "",
|
||||
position,
|
||||
max_wait_sec: maxWaitSec,
|
||||
at: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
|
||||
});
|
||||
licensing.report(account, "", plugin.id, plugin.version || "0", "start");
|
||||
|
||||
void runQueued(plugin, effFields, runId, account);
|
||||
return runId;
|
||||
// 排在别人后面 → 这次值得在"真正开始"和"结束"时各提醒一次
|
||||
if (position > 1) _QUEUED_RUNS.add(runId);
|
||||
return { run_id: runId, queue_position: position };
|
||||
}
|
||||
|
||||
async function runQueued(plugin, fields, runId, account) {
|
||||
// 队列 worker 的执行体:等设备空闲 → 拉起子进程 → 阻塞到该次运行真正收尾。
|
||||
// 注意:run_start 只在"真正开始执行"时广播,排队阶段对外只有 queued 状态,
|
||||
// 避免前端把排队任务误显示成运行中(并清空上一个任务的实时日志)。
|
||||
async function executeQueued(item) {
|
||||
const { run_id: runId, plugin_id: pluginId, account } = item;
|
||||
let plugin;
|
||||
try {
|
||||
// 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies)
|
||||
if (scheduler.nsLocked(nsKey(account, plugin.platform))) {
|
||||
emitLog(runId, plugin.id, "INFO", `同平台任务执行中,排队等待(命名空间 ${nsKey(account, plugin.platform)})…`);
|
||||
}
|
||||
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("用户已取消该排队任务");
|
||||
}
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
|
||||
// 平台登录态预检:HR/OA 失效时自动登录(手动登录入口保留)
|
||||
await ensurePlatformSession(plugin, runId, account);
|
||||
await startChild(plugin, fields, runId, account);
|
||||
@@ -269,11 +403,40 @@ async function runQueued(plugin, fields, runId, account) {
|
||||
const err = isUserStopped(runId) ? "用户手动强制停止" : r.error;
|
||||
if (isUserStopped(runId)) _USER_STOPPED.delete(runId);
|
||||
finishRun(runId, plugin, "error", err, "");
|
||||
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, "error", `运行队列异常:${e.message}`, "");
|
||||
finishRun(runId, plugin, isUserStopped(runId) ? "cancelled" : "error",
|
||||
isUserStopped(runId) ? "用户取消了排队任务" : `运行队列异常:${e.message}`, "");
|
||||
_USER_STOPPED.delete(runId);
|
||||
// 若卡在"已写 switching 但没起来",确保设备槽位回到空闲,避免后续任务永远等下去
|
||||
scheduler.markDone(plugin.id, runId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,6 +578,7 @@ function startChild(plugin, fields, runId, account) {
|
||||
_USER_STOPPED.delete(runId);
|
||||
scheduler.markDone(plugin.id, runId); // 单活槽位回空闲并唤醒排队请求
|
||||
reportRun(plugin, runId); // 运行上报(联网实时/离线暂存补报)
|
||||
resolveDone(runId); // 放行队列 worker,出队下一个
|
||||
};
|
||||
|
||||
child.once("spawn", () => {
|
||||
@@ -458,4 +622,80 @@ function reportRun(plugin, runId) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { submitRun, terminateRun, isUserStopped };
|
||||
// 排队超时:由 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 || "", "error", 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 };
|
||||
|
||||
|
||||
@@ -16,11 +16,13 @@ const licensing = require("./licensing");
|
||||
const registry = require("./registry");
|
||||
const meta = require("./meta");
|
||||
const runner = require("./runner");
|
||||
const queue = require("./queue");
|
||||
const runHistory = require("./run-history");
|
||||
const lastFields = require("./last-fields");
|
||||
const pluginConfigs = require("./plugin-configs");
|
||||
const scheduler = require("./scheduler");
|
||||
const tasks = require("./tasks");
|
||||
const flows = require("./flows");
|
||||
const platformAuth = require("./platform-auth");
|
||||
const platformCreds = require("./platform-creds");
|
||||
const shellUpdater = require("./shell-updater");
|
||||
@@ -262,6 +264,8 @@ async function route(req, res, url) {
|
||||
const body = await readJsonBody(req);
|
||||
const account = String(body.account || "").trim();
|
||||
if (!account) throw Object.assign(new Error("账号不能为空"), { status: 400 });
|
||||
// 已登录态下换号:同样受"任务执行中不可切换"约束(未登录时首次登录不受影响)
|
||||
if (session.sessAccount(cookies)) assertIdleForSwitch();
|
||||
const r = await cp.request("POST", "/api/admin/auth", {
|
||||
headers: {
|
||||
"X-Admin-User": account,
|
||||
@@ -280,6 +284,9 @@ async function route(req, res, url) {
|
||||
}
|
||||
|
||||
if (p === "/api/admin/logout" && method === "POST") {
|
||||
// 执行/排队中不允许切账号:一次运行带着账号上下文(平台 cookie、凭据注入、上报归属),
|
||||
// 半路换号会串号。必须等它跑完,或用户先在「执行队列」手动停止。
|
||||
assertIdleForSwitch();
|
||||
const token = cookies[session.SESSION_COOKIE] || "";
|
||||
session.clearSession(token);
|
||||
clearSessionCookie(res);
|
||||
@@ -288,6 +295,7 @@ async function route(req, res, url) {
|
||||
|
||||
// 离线登录:不依赖网络,仅校验本地 7 天离线授权票据(验签 + 未过期),消费票据直接进入工作台
|
||||
if (p === "/api/admin/offline-login" && method === "POST") {
|
||||
if (session.sessAccount(cookies)) assertIdleForSwitch();
|
||||
const st = licensing.licenseStatus();
|
||||
if (st.status !== "ok" || !st.payload || !st.payload.userId) {
|
||||
const reason =
|
||||
@@ -405,6 +413,10 @@ async function route(req, res, url) {
|
||||
}
|
||||
const account = String(info.account || "").trim();
|
||||
if (!account || !info.exists) return sendHtml(res, 200, authDonePage("账号未开通或未解析到有效工号,请联系管理员。"));
|
||||
// 钉钉扫码回调也是"换号"入口:执行/排队中直接拦掉,避免任务串到新账号
|
||||
if (hasActiveRuns()) {
|
||||
return sendHtml(res, 200, authDonePage("有任务正在执行或排队,请先在客户端停止任务后再切换账号。"));
|
||||
}
|
||||
const token = session.establishSession(account, info.token || "");
|
||||
setSessionCookie(res, token);
|
||||
if (config.CONTROLPLANE_URL) {
|
||||
@@ -593,8 +605,19 @@ async function route(req, res, url) {
|
||||
}
|
||||
// 记住本次参数(不含 password 字段),供执行台「恢复上次参数」
|
||||
lastFields.remember(account, plugin.id, body.fields || {}, plugin.fields);
|
||||
const runId = runner.submitRun(account, plugin, body.fields || {}, { trigger: "manual" });
|
||||
return sendJson(res, 202, { run_id: runId });
|
||||
// 提交即入队:返回排队位置,前端据此提示"已加入队列,第 N 位"
|
||||
const r = runner.submitRun(account, plugin, body.fields || {}, { trigger: "manual" });
|
||||
return sendJson(res, 202, {
|
||||
run_id: r.run_id,
|
||||
queue_position: r.queue_position,
|
||||
queued: r.queue_position > 1,
|
||||
});
|
||||
}
|
||||
|
||||
// 执行队列快照(当前执行 + 等待中的任务,带位置与等待时长)
|
||||
if (p === "/api/queue" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
return sendJson(res, 200, queue.snapshot(account));
|
||||
}
|
||||
|
||||
// 运行历史列表(当前账号,新的在前):右轨「最近运行」与执行台「已完成」态的数据源
|
||||
@@ -618,11 +641,15 @@ async function route(req, res, url) {
|
||||
const account = session.requireLogin(cookies);
|
||||
const run = state.RUNS.get(runMatch[1]);
|
||||
if (!run || run.account !== account) throw Object.assign(new Error("运行不存在"), { status: 404 });
|
||||
if (run.status !== "running") throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 });
|
||||
if (!runner.terminateRun(runMatch[1])) {
|
||||
throw Object.assign(new Error("任务尚未真正启动(排队中或刚结束),请稍候再试"), { status: 409 });
|
||||
// 排队中也能停:直接从队列摘除并落「已取消」,不必等轮到它再失败
|
||||
if (run.status !== "running" && run.status !== "queued") {
|
||||
throw Object.assign(new Error("运行已结束,无需停止"), { status: 409 });
|
||||
}
|
||||
return sendJson(res, 200, { ok: true });
|
||||
const wasQueued = run.status === "queued";
|
||||
if (!runner.terminateRun(runMatch[1])) {
|
||||
throw Object.assign(new Error("任务刚刚结束,请刷新后再试"), { status: 409 });
|
||||
}
|
||||
return sendJson(res, 200, { ok: true, was_queued: wasQueued });
|
||||
}
|
||||
|
||||
// ---------- 定时任务 ----------
|
||||
@@ -688,6 +715,104 @@ async function route(req, res, url) {
|
||||
return sendJson(res, 200, rec);
|
||||
}
|
||||
|
||||
// ---------- 流程编排(DAG) ----------
|
||||
if (p === "/api/flows" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
return sendJson(res, 200, { flows: flows.list(account) });
|
||||
}
|
||||
if (p === "/api/flows" && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
let rec;
|
||||
try {
|
||||
rec = flows.create(account, body);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(e.message), { status: 400 });
|
||||
}
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies)); // 流程配置随定时备份一起上云
|
||||
return sendJson(res, 201, rec);
|
||||
}
|
||||
// 运行态快照(含每个节点的状态),供流程页轮询/首屏兜底
|
||||
if (p === "/api/flows/runs" && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
return sendJson(res, 200, { runs: flows.activeRuns(account) });
|
||||
}
|
||||
const flowRunGet = p.match(/^\/api\/flows\/runs\/([^/]+)$/);
|
||||
if (flowRunGet && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const r = flows.getRun(flowRunGet[1]);
|
||||
// 同样的越权保护:别人的流程运行不对外暴露
|
||||
if (!r || r.account !== account) throw Object.assign(new Error("流程运行不存在"), { status: 404 });
|
||||
return sendJson(res, 200, r);
|
||||
}
|
||||
// 人工确认节点:流程跑到 confirm 节点会挂起,这里点「继续 / 终止」
|
||||
const flowConfirm = p.match(/^\/api\/flows\/runs\/([^/]+)\/confirm$/);
|
||||
if (flowConfirm && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const run = flows.getRun(flowConfirm[1]);
|
||||
if (!run || run.account !== account) throw Object.assign(new Error("流程运行不存在"), { status: 404 });
|
||||
const body = await readJsonBody(req);
|
||||
const done = flows.confirmNode(flowConfirm[1], String(body.node_id || ""), !!body.ok);
|
||||
if (!done) throw Object.assign(new Error("该确认节点已超时或已被处理"), { status: 409 });
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
// 流程版本历史:只给摘要(时间/名称/节点数/类型分布),节点明细走回滚接口
|
||||
const flowVer = p.match(/^\/api\/flows\/([^/]+)\/versions$/);
|
||||
if (flowVer && method === "GET") {
|
||||
const account = session.requireLogin(cookies);
|
||||
try {
|
||||
return sendJson(res, 200, { versions: flows.listVersions(flowVer[1], account) });
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||||
}
|
||||
}
|
||||
const flowRollback = p.match(/^\/api\/flows\/([^/]+)\/rollback$/);
|
||||
if (flowRollback && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
try {
|
||||
const rec = flows.rollback(flowRollback[1], account, String(body.vid || ""));
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 200, rec);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const flowMatch = p.match(/^\/api\/flows\/([^/]+)(\/run)?$/);
|
||||
if (flowMatch && flowMatch[2] && method === "POST") {
|
||||
const account = session.requireLogin(cookies);
|
||||
try {
|
||||
return sendJson(res, 202, flows.run(account, flowMatch[1]));
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||||
}
|
||||
}
|
||||
if (flowMatch && !flowMatch[2] && method === "PUT") {
|
||||
const account = session.requireLogin(cookies);
|
||||
const body = await readJsonBody(req);
|
||||
let rec;
|
||||
try {
|
||||
rec = flows.update(flowMatch[1], account, body);
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||||
}
|
||||
if (!rec) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 200, rec);
|
||||
}
|
||||
if (flowMatch && !flowMatch[2] && method === "DELETE") {
|
||||
const account = session.requireLogin(cookies);
|
||||
try {
|
||||
if (!flows.remove(flowMatch[1], account)) throw Object.assign(new Error("流程不存在"), { status: 404 });
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error(e.message), { status: e.status || 400 });
|
||||
}
|
||||
tasks.pushBackup(account, session.cpHeaders(cookies));
|
||||
return sendJson(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
// ---------- 插件配置 / UI ----------
|
||||
const cfgMatch = p.match(/^\/api\/plugin-config\/([^/]+)$/);
|
||||
if (cfgMatch && method === "GET") {
|
||||
@@ -755,6 +880,25 @@ async function route(req, res, url) {
|
||||
sendJson(res, 404, { detail: "Not Found" });
|
||||
}
|
||||
|
||||
// 是否有"带账号上下文"的任务在跑或在排队(切换账号的唯一阻断条件)
|
||||
function hasActiveRuns() {
|
||||
if (queue.busy() || queue.size() > 0) return true;
|
||||
for (const [, r] of state.RUNS) {
|
||||
if (r && (r.status === "running" || r.status === "queued")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function assertIdleForSwitch() {
|
||||
if (!hasActiveRuns()) return;
|
||||
const running = queue.runningItem();
|
||||
const tip = running && running.name ? `「${running.name}」正在执行` : "有任务正在执行或排队";
|
||||
throw Object.assign(
|
||||
new Error(`${tip},请先在「执行队列」停止任务后再切换账号`),
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
function findOwned(sid, account) {
|
||||
const s = tasks.getSchedule(sid);
|
||||
if (!s) throw Object.assign(new Error("任务不存在"), { status: 404 });
|
||||
|
||||
@@ -8,7 +8,9 @@ const PLATFORMS = {
|
||||
|
||||
// 运行会话:run_id -> {status, account, plugin_id, name, version, trigger, schedule_id, started, result, error, logs}
|
||||
const RUNS = new Map();
|
||||
const MAX_RUNS = 50;
|
||||
// 上限只约束"已结束"的运行留存量:排队/执行中的记录不参与淘汰(否则排队任务被淘汰后
|
||||
// 收尾时取不到记录,历史里的账号/触发方式/名称会变成空值)
|
||||
const MAX_RUNS = 120;
|
||||
|
||||
// 单次运行内存中累积的日志上限(结束后由 run-history 落盘,此处只服务"正在跑"的实时展示与回放)
|
||||
const MAX_RUN_LOGS = 800;
|
||||
@@ -39,8 +41,12 @@ function setRun(runId, fields) {
|
||||
|
||||
function registerRun(runId, record) {
|
||||
if (RUNS.size >= MAX_RUNS) {
|
||||
const oldest = RUNS.keys().next().value;
|
||||
RUNS.delete(oldest);
|
||||
// 从旧到新找第一条已结束的记录淘汰;全部活跃则不动(宁可短暂超限,也不丢运行中的记录)
|
||||
for (const [id, rec] of RUNS) {
|
||||
if (rec && (rec.status === "running" || rec.status === "queued")) continue;
|
||||
RUNS.delete(id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
RUNS.set(runId, record);
|
||||
}
|
||||
|
||||
@@ -305,7 +305,24 @@ function start() {
|
||||
logger.info(`定时任务后台检查已启动(每 ${TICK_SECS}s 一次)`);
|
||||
}
|
||||
|
||||
// tick 重入保护:单轮里 fire() 含授权检查(可能 5s 超时)与多个任务,30s 间隔并不保证一轮能在
|
||||
// 间隔内跑完;两轮重叠时 last_run_at 尚未推进,同一个 cron 点会被提交两次(即任务跑两遍)。
|
||||
let _ticking = false;
|
||||
|
||||
async function tick() {
|
||||
if (_ticking) {
|
||||
logger.warning("上一轮定时任务检查尚未结束,跳过本轮(避免同一触发点重复入队)");
|
||||
return;
|
||||
}
|
||||
_ticking = true;
|
||||
try {
|
||||
await tickOnce();
|
||||
} finally {
|
||||
_ticking = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function tickOnce() {
|
||||
const now = new Date();
|
||||
const due = [];
|
||||
const changed = []; // 触发成功或错过跳过都改了 last_run_at,需落盘
|
||||
@@ -389,12 +406,15 @@ async function fire(s) {
|
||||
}
|
||||
fields = cfg.fields;
|
||||
}
|
||||
const runId = runner.submitRun(account, plugin, fields, {
|
||||
const r = runner.submitRun(account, plugin, fields, {
|
||||
trigger: "schedule",
|
||||
schedule_id: s.id,
|
||||
});
|
||||
watchRun(s.id, runId);
|
||||
logger.info(`定时任务触发:「${s.name}」(插件 ${plugin.id},账号 ${account})`);
|
||||
watchRun(s.id, r.run_id);
|
||||
logger.info(
|
||||
`定时任务触发:「${s.name}」(插件 ${plugin.id},账号 ${account})` +
|
||||
(r.queue_position > 1 ? `,已入队第 ${r.queue_position} 位等待` : "")
|
||||
);
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.error(`定时任务「${s.name}」启动失败:${e.message}`);
|
||||
@@ -418,7 +438,8 @@ function watchRun(scheduleId, runId) {
|
||||
};
|
||||
HUB.on("event", onEvent);
|
||||
// 兜底:进程异常或事件丢失时不让监听器长期驻留(按该任务插件的执行超时上限 + 2 分钟宽限;
|
||||
// 插件声明不限时时给 7 天硬上限,避免 setTimeout 溢出提前移除监听)
|
||||
// 插件声明不限时时给 7 天硬上限,避免 setTimeout 溢出提前移除监听)。
|
||||
// 排队会拉长"触发 → 结束"的跨度:前面每多一个等待任务,就要多等一个执行时长上限。
|
||||
let boundSecs = config.RUN_TIMEOUT;
|
||||
const sched = _schedules.find((x) => x.id === scheduleId);
|
||||
if (sched && sched.plugin_id) {
|
||||
@@ -428,21 +449,34 @@ function watchRun(scheduleId, runId) {
|
||||
boundSecs = t > 0 ? t : 7 * 24 * 3600;
|
||||
} catch (e) { /* 插件缺失/解析失败:沿用壳默认 */ }
|
||||
}
|
||||
timer = setTimeout(() => HUB.removeListener("event", onEvent), (boundSecs + 120) * 1000);
|
||||
let queuedAhead = 0;
|
||||
try { queuedAhead = require("./queue").size(); } catch (e) { /* 队列不可用:按无排队估计 */ }
|
||||
const bound = boundSecs >= 7 * 24 * 3600
|
||||
? 7 * 24 * 3600
|
||||
: (boundSecs + 120) * (queuedAhead + 2);
|
||||
timer = setTimeout(() => HUB.removeListener("event", onEvent), bound * 1000);
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
|
||||
// ==================== 中心机备份(防丢失) ====================
|
||||
// 同一个备份槽同时存「场景定时」与「流程编排」:服务端只校验 data.schedules 是数组、
|
||||
// 其余字段原样 JSON 存储,所以多带一个 flows 字段不需要改中心机(旧版本读到会忽略)。
|
||||
function pushBackup(account, headers) {
|
||||
if (!config.CONTROLPLANE_URL || !account) return;
|
||||
const payload = { data: { schedules: exportByAccount(account) } };
|
||||
const data = { schedules: exportByAccount(account) };
|
||||
try {
|
||||
data.flows = require("./flows").exportByAccount(account);
|
||||
} catch (e) {
|
||||
logger.warning(`流程编排导出失败(本次只备份定时任务):${e.message}`);
|
||||
}
|
||||
const payload = { data };
|
||||
cp.request("POST", "/api/schedules/backup", {
|
||||
headers: { ...(headers || {}), "Content-Type": "application/json" },
|
||||
json: payload,
|
||||
timeout: 10,
|
||||
})
|
||||
.then(() => logger.info(`定时任务备份成功(账号 ${account})`))
|
||||
.catch((e) => logger.warning(`定时任务备份失败(账号 ${account}):${e.message}`));
|
||||
.then(() => logger.info(`定时任务/流程编排备份成功(账号 ${account})`))
|
||||
.catch((e) => logger.warning(`定时任务/流程编排备份失败(账号 ${account}):${e.message}`));
|
||||
}
|
||||
|
||||
function restoreFromCloud() {
|
||||
@@ -474,6 +508,16 @@ function restoreFromCloud() {
|
||||
persist();
|
||||
logger.info(`定时任务云端恢复 ${added} 条(账号 ${account})`);
|
||||
}
|
||||
// 流程编排一并恢复(只补本地缺失的,绝不覆盖本地已有流程)
|
||||
const remoteFlows = (r.data || {}).flows || [];
|
||||
if (Array.isArray(remoteFlows) && remoteFlows.length) {
|
||||
try {
|
||||
const n = require("./flows").mergeFromCloud(account, remoteFlows);
|
||||
if (n) logger.info(`流程编排云端恢复 ${n} 条(账号 ${account})`);
|
||||
} catch (e) {
|
||||
logger.warning(`流程编排云端恢复失败(跳过):${e.message}`);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((e) => logger.warning(`定时任务云端恢复失败(跳过):${e.message}`));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user