feat(electron-shell): 1.8.0 执行队列、流程编排、流程定时与版本回滚
- 执行队列:多任务串行排队,可单独取消,超时自动放弃,异常退出后标记已中断 - 流程编排:画布多场景依赖图,内置确保登录/等待/通知/人工确认节点 - 流程定时:场景与流程统一配置定时(每天/工作日/每周/每月/每隔N小时) - 流程版本历史:自动留档 20 版,画布一键回滚且回滚可撤销 - 流程配置云备份:随定时任务备份到中心机,换机自动恢复 - 总览页/场景库布局调整,通知浮窗右下角堆叠显示
This commit is contained in:
@@ -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 };
|
||||
|
||||
|
||||
Reference in New Issue
Block a user