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