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