feat(electron-shell): 1.11.0 新增设置中心与执行超时/内存分层,组件运行状态与运行历史峰值内存

This commit is contained in:
2026-11-13 13:53:20 +08:00
parent 89a7ad966a
commit e055adade5
29 changed files with 2200 additions and 572 deletions
+9 -4
View File
@@ -19,7 +19,8 @@ const chromeManager = require("./chrome-manager");
const envSync = require("./env-sync");
const notifier = require("./notifier");
const { HUB } = require("./hub");
const { makeLogger, setLogFile } = require("./logger");
const shellSettings = require("./settings");
const { makeLogger, setLogFile, setRotation } = require("./logger");
const logger = makeLogger("app");
@@ -175,11 +176,15 @@ function startUpdateScheduler() {
}
async function init(options = {}) {
// 崩溃现场落盘(窗口模式无控制台时排查唯一窗口):Electron 运行时都落盘(含打包版),
// CLI 纯 Node 模式日志走 stdout 即可。不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。
// 崩溃现场落盘:窗口模式与 CLI 模式都写同一份 shell.log,设置页的「日志保留 / 打开目录」
// 在两种模式下表现一致(CLI 仍同时输出到控制台)。需要纯 stdout 时设 SHELL_LOG_FILE=0。
// 不能依赖 ELECTRON_RENDERER_URL(本工程从不设置)。
// ★ 日志放数据根 %LOCALAPPDATA%\37duAutomation\logs\(打包态 SHELL_ROOT 在 app.asar 内只读,不能写)
if (process.versions && process.versions.electron) {
if (process.env.SHELL_LOG_FILE !== "0") {
setLogFile(path.join(config.APP_DATA, "logs", "shell.log"));
// 日志保留策略按设置中心(单文件上限 / 保留份数)生效,未配置回退内置默认(10MB × 3 份)
const rot = shellSettings.logRotation();
setRotation({ maxMb: rot.maxMb === null ? undefined : rot.maxMb, keep: rot.keep === null ? undefined : rot.keep });
}
state.setBootStep("加载配置与本地服务");
+34 -3
View File
@@ -2,6 +2,7 @@
"use strict";
const fs = require("fs");
const os = require("os");
const path = require("path");
// 打包态判定:Electron 运行时 + resources 下存在 app.asar(打包版独有,dev `electron .` 无 asar)。
@@ -103,10 +104,24 @@ const PYTHON_EXE = process.env.PYTHON_EXE || "python";
// 可整体覆盖(.env / 环境变量 RUN_TIMEOUT,0=全局不限时);单个插件可用 plugin.json 的
// runTimeoutSeconds 覆盖(见 runTimeoutFor)。两处都按 0=不限时、缺省回退壳默认处理。
const RUN_TIMEOUT = parseInt(process.env.RUN_TIMEOUT || "21600", 10);
const RUN_MAX_MEM_MB = parseInt(process.env.RUN_MAX_MEM_MB || "2048", 10);
// 插件进程内存上限(MB):默认按本机物理内存 70%,下限 4GB、上限 16GB。
// 旧默认 2048 会把 openpyxl 整簿加载、Excel COM、带多标签的 Chrome 子进程误伤(Job Object 是
// 进程 commit 硬上限,超限直接分配失败,不是限速)。可用 .env RUN_MAX_MEM_MB 覆盖(0=不限),
// 设置中心的用户覆盖优先(见 runMaxMemMb)。
function defaultMaxMemMb() {
const totalMb = Math.floor(os.totalmem() / (1024 * 1024));
return Math.min(16384, Math.max(4096, Math.round(totalMb * 0.7)));
}
function parseMemMb(raw) {
const n = parseInt(raw, 10);
return Number.isFinite(n) && n >= 0 ? n : defaultMaxMemMb();
}
const RUN_MAX_MEM_MB = parseMemMb(process.env.RUN_MAX_MEM_MB);
// 插件执行超时(秒):插件 plugin.json 声明 runTimeoutSeconds 优先(0=不限时),
// 否则回退壳默认 RUN_TIMEOUT。传入 registry.find() 产出的插件对象。
// 其次「设置中心」的用户覆盖值,最后回退 .env 默认 RUN_TIMEOUT。
// 传入 registry.find() 产出的插件对象。
function runTimeoutFor(plugin) {
if (plugin && typeof plugin === "object") {
const raw = plugin.timeout_seconds;
@@ -116,7 +131,22 @@ function runTimeoutFor(plugin) {
if (Number.isFinite(v) && v >= 0) return v;
}
}
return RUN_TIMEOUT;
return userOverride("runTimeoutSec") ?? RUN_TIMEOUT;
}
// 内存上限(MB):设置中心覆盖优先,否则 .env 默认 RUN_MAX_MEM_MB(仅环境包 Job Object 模式生效)
function runMaxMemMb() {
return userOverride("runMaxMemMb") ?? RUN_MAX_MEM_MB;
}
// 设置中心是本模块的下游(settings 会延迟 require 本模块取数据根),这里同样延迟读取,避免循环依赖
function userOverride(fn) {
try {
const v = require("./settings")[fn]();
return typeof v === "number" && Number.isFinite(v) ? v : null;
} catch (e) {
return null;
}
}
// ==================== 便携 Python 环境包(python-env) ====================
@@ -209,6 +239,7 @@ module.exports = {
RUN_TIMEOUT,
RUN_MAX_MEM_MB,
runTimeoutFor,
runMaxMemMb,
IS_FROZEN,
pluginRoot,
sdkRoot,
@@ -5,6 +5,7 @@ const fs = require("fs");
const { app, BrowserWindow, Tray, Menu, nativeImage, dialog, screen, ipcMain } = require("electron");
const path = require("path");
const config = require("./config");
const settings = require("./settings");
const { makeLogger } = require("./logger");
const trayMenu = require("./tray-menu");
@@ -129,7 +130,14 @@ if (!app.requestSingleInstanceLock()) {
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
return; // 真正退出:放行关闭
}
// 关闭按钮 → 收托盘(隐藏窗口,服务/插件继续运行),从托盘菜单「退出」才真正退出
// 关闭行为由「设置 → 启动与关闭」决定:
// tray(默认)= 收托盘,服务/插件继续跑,托盘菜单「退出」才真正退出;
// quit = 关闭即退出,队列中任务按正常退出路径落「已取消」。
if (settings.closeBehavior() === "quit") {
isQuitting = true;
if (mainWindow && !mainWindow.isDestroyed()) saveWindowState(mainWindow);
return; // 放行关闭 → window-all-closed → app.quit()
}
e.preventDefault();
mainWindow.hide();
});
+51 -6
View File
@@ -6,9 +6,12 @@ const path = require("path");
const LEVELS = { DEBUG: 10, INFO: 20, WARNING: 30, ERROR: 40 };
const DEBUG = process.env.DEBUG === "1" || process.env.DEBUG === "true";
const MAX_LOG_BYTES = 10 * 1024 * 1024; // 单文件 10MB,超出轮转(保留 3 份)
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024; // 单文件 10MB
const DEFAULT_KEEP = 3; // 保留 3 份轮转文件(.1/.2/.3)
let _file = null; // { fd 简化:按行 append 即可 }
let _file = null; // 日志文件路径(按行 append)
let _maxBytes = DEFAULT_MAX_BYTES;
let _keep = DEFAULT_KEEP;
function setLogFile(filePath) {
_file = filePath;
@@ -19,13 +22,47 @@ function setLogFile(filePath) {
}
}
// 按大小轮转:shell.log → shell.log.1 → .2 → .3(丢弃最旧)
// 设置中心可调:单文件上限(MB)与保留份数;传 null/非法值回退内置默认
function setRotation(opts) {
const o = opts || {};
const mb = Number(o.maxMb);
const keep = Number(o.keep);
_maxBytes = Number.isFinite(mb) && mb >= 1 ? Math.round(mb * 1024 * 1024) : DEFAULT_MAX_BYTES;
_keep = Number.isFinite(keep) && keep >= 1 ? Math.round(keep) : DEFAULT_KEEP;
}
function rotation() {
return { maxMb: Math.round((_maxBytes / 1024 / 1024) * 10) / 10, keep: _keep };
}
function logDir() {
return _file ? path.dirname(_file) : "";
}
// 当前日志文件清单(base + .1..keep),供设置页展示占用
function logFiles() {
if (!_file) return [];
const out = [];
const names = [_file];
for (let i = 1; i <= _keep; i++) names.push(`${_file}.${i}`);
for (const f of names) {
try {
const st = fs.statSync(f);
out.push({ name: path.basename(f), size: st.size, mtime: st.mtime.toISOString() });
} catch (e) {
/* 未生成的文件跳过 */
}
}
return out;
}
// 按大小轮转:shell.log → shell.log.1 → ... → shell.log.<keep>(丢弃最旧)
function rotateIfNeeded() {
if (!_file) return;
try {
const st = fs.statSync(_file);
if (st.size < MAX_LOG_BYTES) return;
for (let i = 2; i >= 1; i--) {
if (st.size < _maxBytes) return;
for (let i = _keep - 1; i >= 1; i--) {
const a = `${_file}.${i}`;
const b = `${_file}.${i + 1}`;
if (fs.existsSync(a)) fs.renameSync(a, b);
@@ -65,4 +102,12 @@ function makeLogger(name) {
};
}
module.exports = { makeLogger, setLogFile, isDebug: DEBUG };
module.exports = {
makeLogger,
setLogFile,
setRotation,
rotation,
logDir,
logFiles,
isDebug: DEBUG,
};
@@ -167,6 +167,7 @@ function brief(rec) {
started: rec.started || 0,
finished: rec.finished || 0,
duration_sec: rec.duration_sec || 0,
peak_mem_mb: rec.peak_mem_mb || 0,
summary: rec.summary || "",
note: rec.note || "",
};
+43 -2
View File
@@ -24,6 +24,13 @@ const { makeLogger } = require("./logger");
const logger = makeLogger("runner");
// 内存 MB → 展示文案(日志/历史共用口径)
function fmtMemText(mb) {
const n = Number(mb) || 0;
if (n <= 0) return "—";
return n >= 1024 ? `${(n / 1024).toFixed(n >= 10240 ? 0 : 1)} GB` : `${n} MB`;
}
// 定时任务的最长排队等待:到点时前面还有任务在跑,超过这个时长就不跑了(避免堆到下班后)。
// 手动执行不设限(用户自己点的,愿意等)。
const SCHEDULE_MAX_WAIT_SEC = 30 * 60;
@@ -219,6 +226,7 @@ function finishRun(runId, plugin, status, error, summary) {
finished,
duration_sec: durationSec,
note: run.note || "",
peak_mem_mb: run.peak_mem_mb || 0,
logs: Array.isArray(run.logs) ? run.logs : [],
});
// 日志集中回传:整次运行日志上送中心机(离线自动暂存补报;失败不阻断运行收尾)
@@ -239,6 +247,7 @@ function finishRun(runId, plugin, status, error, summary) {
finished,
duration_sec: durationSec,
note: run.note || "",
peak_mem_mb: run.peak_mem_mb || 0,
logs: Array.isArray(run.logs) ? run.logs : [],
});
} catch (e) {
@@ -459,6 +468,15 @@ async function executeQueued(item) {
// 执行结束(close)后异步落终态 + 上报 + 回空闲。
function startChild(plugin, fields, runId, account) {
return new Promise((resolve, reject) => {
// 磁盘预检(不阻断):数据盘/插件盘余量过低时先记一条 WARN,
// 导出写到一半失败时能直接对上原因;是否清理由用户决定。
try {
for (const d of require("./sysinfo").lowDisks(1)) {
emitLog(runId, plugin.id, "WARN",
`磁盘剩余不足:${d.label} ${d.root} 仅剩 ${d.free_gb}GB,导出/写表可能失败,请先清理`);
}
} catch (e) { /* 统计失败不影响执行 */ }
// 插件级超时优先(plugin.json runTimeoutSeconds,0=不限时),缺省回退壳默认 RUN_TIMEOUT
const timeout = config.runTimeoutFor(plugin);
// 执行环境解析:便携环境包(python-env)优先 → 经 job_guard(Job Object 内存上限
@@ -494,7 +512,7 @@ function startChild(plugin, fields, runId, account) {
// 环境包模式:python -u job_guard.py --mem <MB> --timeout <s> -- python -u plugin_runner.py ...
cmd = [
python, "-u", guard,
"--mem", String(config.RUN_MAX_MEM_MB),
"--mem", String(config.runMaxMemMb()),
"--timeout", String(timeout),
"--", python, ...baseArgs,
];
@@ -556,9 +574,22 @@ function startChild(plugin, fields, runId, account) {
});
const rlErr = readline.createInterface({ input: child.stderr });
// 内存超限的表现是"分配失败 → MemoryError → 进程退出",Python 侧若来不及回 result,
// 这里用 stderr 尾部兜底识别,避免前端只显示一个没有原因的"执行失败"。
const stderrTail = [];
let peakMemMb = 0;
rlErr.on("line", (line) => {
const s = String(line).trim();
if (s) {
// job_guard 收尾上报的峰值内存:解析后落运行历史,不再当作错误行刷进日志面板
const peak = s.match(/^\[job_guard\]\s+peak_job_mb=(\d+)/);
if (peak) {
peakMemMb = parseInt(peak[1], 10) || 0;
emitLog(runId, plugin.id, "INFO", `内存峰值:${fmtMemText(peakMemMb)}`);
return;
}
stderrTail.push(s);
if (stderrTail.length > 20) stderrTail.shift();
emitLog(runId, plugin.id, "ERROR", s);
}
});
@@ -581,11 +612,16 @@ function startChild(plugin, fields, runId, account) {
if (timer) clearTimeout(timer);
_ACTIVE.delete(runId);
const hasResult = result && Object.keys(result).length > 0;
// 内存上限是 Job Object 的 commit 硬顶:超限时 Python 抛 MemoryError(str 为空),
// 旧版 runner 会回 ok=false + error="",前端只有"失败"看不出原因。
const memHit = stderrTail.some((l) => /MemoryError|Cannot allocate memory|内存不足/i.test(l));
const MEM_MSG = "内存不足:执行进程达到内存上限(可在客户端「设置 → 内存上限」调大,"
+ "或让插件分批/流式处理大表)";
let status;
let error;
if (hasResult) {
status = result.ok ? "done" : "error";
error = result.error || "";
error = result.error || (memHit ? MEM_MSG : "");
} else if (spawnErr) {
status = "error";
error = spawnErr;
@@ -596,11 +632,16 @@ function startChild(plugin, fields, runId, account) {
} else if (timedOut) {
status = "error";
error = `插件执行超时(${timeout}s)已强制终止`;
} else if (memHit) {
status = "error";
error = MEM_MSG;
} else {
status = "error";
error = `执行进程异常退出(exit=${code})且未返回结果`;
}
state.setRun(runId, { result: hasResult ? result.result : null });
// 峰值内存先写进运行态,finishRun 会带进运行历史(0 = 旧环境包/直拉模式没有数据)
if (peakMemMb > 0) state.setRun(runId, { peak_mem_mb: peakMemMb });
finishRun(
runId,
plugin,
+143 -2
View File
@@ -31,8 +31,11 @@ const chromeManager = require("./chrome-manager");
const pluginSync = require("./plugin-sync");
const sdkSync = require("./sdk-sync");
const envSync = require("./env-sync");
const shellSettings = require("./settings");
const sysinfo = require("./sysinfo");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
const loggerMod = require("./logger"); // 设置中心要读写日志轮转/日志文件清单(模块级 API)
const { makeLogger } = loggerMod;
const logger = makeLogger("server");
@@ -268,6 +271,72 @@ async function dingtalkEstablish(account, nickname, dingtalkUid, res) {
};
}
// ==================== 设置中心(用户级偏好:关闭行为 / 执行限制 / 日志保留) ====================
// 开机自启写系统登录项(Windows 注册表),不进 JSON;读取时实时问系统,与托盘菜单开关天然一致。
function electronApp() {
try {
const { app } = require("electron");
return app && typeof app.getLoginItemSettings === "function" ? app : null;
} catch (e) {
return null; // CLI 模式(纯 Node,无 Electron)
}
}
function autostartEnabled() {
const app = electronApp();
if (!app) return null;
try {
return !!app.getLoginItemSettings().openAtLogin;
} catch (e) {
return null;
}
}
function setAutostart(on) {
const app = electronApp();
if (!app) throw Object.assign(new Error("仅客户端内可设置开机自启"), { status: 400 });
app.setLoginItemSettings({ openAtLogin: !!on });
}
/** 设置页快照:生效值 + 用户覆盖值 + 默认值(前端据此显示"跟随默认/已自定义") */
function settingsSnapshot() {
const s = shellSettings.get();
const rot = loggerMod.rotation();
return {
version: config.runtimeVersion(),
data_dir: config.APP_DATA,
settings_file: shellSettings.filePath(),
autostart: autostartEnabled(),
close_behavior: s.close_behavior,
run_timeout_sec: config.runTimeoutFor(null),
run_timeout_override: s.run_timeout_sec,
run_timeout_default: config.RUN_TIMEOUT,
run_max_mem_mb: config.runMaxMemMb(),
run_max_mem_override: s.run_max_mem_mb,
run_max_mem_default: config.RUN_MAX_MEM_MB,
log_max_mb: rot.maxMb,
log_keep: rot.keep,
log_max_mb_override: s.log_max_mb,
log_keep_override: s.log_keep,
log_dir: loggerMod.logDir(),
log_files: loggerMod.logFiles(),
};
}
// 更新日志(关于):dev 读仓库根 CHANGELOG.md;打包态读 extraResources 带入的 resources/CHANGELOG.md
function readChangelog() {
const candidates = [path.join(config.SHELL_ROOT, "CHANGELOG.md")];
if (process.resourcesPath) candidates.push(path.join(process.resourcesPath, "CHANGELOG.md"));
for (const f of candidates) {
try {
if (fs.existsSync(f)) return fs.readFileSync(f, "utf-8");
} catch (e) {
/* 尝试下一个候选路径 */
}
}
return "";
}
// ==================== 路由表 ====================
async function route(req, res, url) {
const cookies = parseCookies(req);
@@ -637,7 +706,79 @@ async function route(req, res, url) {
}
if (p === "/api/env/rollback" && method === "POST") {
session.requireLogin(cookies);
return sendJson(res, 200, envSync.rollback());
if (scheduler.isBusy()) {
throw Object.assign(new Error("设备正在执行任务,请结束后再回滚环境包"), { status: 409 });
}
const r = envSync.rollback();
if (r && r.ok) logger.info(`环境包已回滚到 v${r.version}`);
return sendJson(res, 200, r);
}
// ---------- 本机运行状态(CPU / 内存 / 磁盘;只读展示,不上报) ----------
if (p === "/api/system/stats" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, sysinfo.stats());
}
// ---------- 设置中心(开机自启 / 关闭行为 / 执行限制 / 日志保留) ----------
if (p === "/api/settings" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, settingsSnapshot());
}
if (p === "/api/settings" && method === "PUT") {
session.requireLogin(cookies);
const body = await readJsonBody(req);
const patch = {};
for (const k of ["close_behavior", "run_timeout_sec", "run_max_mem_mb", "log_max_mb", "log_keep"]) {
if (Object.prototype.hasOwnProperty.call(body, k)) patch[k] = body[k];
}
let next;
try {
next = shellSettings.update(patch);
} catch (e) {
throw Object.assign(new Error(e.message), { status: 400 });
}
// 开机自启:写系统登录项(与托盘菜单同一个开关,下一次打开托盘菜单即可看到新状态)
const touchedAutostart = Object.prototype.hasOwnProperty.call(body, "autostart");
if (touchedAutostart) setAutostart(!!body.autostart);
// 日志轮转立刻生效,不必重启客户端
loggerMod.setRotation({
maxMb: next.log_max_mb === null ? undefined : next.log_max_mb,
keep: next.log_keep === null ? undefined : next.log_keep,
});
logger.info(
`设置已更新:${JSON.stringify(patch)}${touchedAutostart ? ` 开机自启=${!!body.autostart}` : ""}`
);
return sendJson(res, 200, settingsSnapshot());
}
// 打开日志目录(排障用:用户不必自己找 %LOCALAPPDATA% 路径)
if (p === "/api/log/open" && method === "POST") {
session.requireLogin(cookies);
const dir = loggerMod.logDir();
if (!dir) throw Object.assign(new Error("当前未落盘日志(CLI 模式)"), { status: 400 });
let shellApi;
try {
shellApi = require("electron").shell;
} catch (e) {
throw Object.assign(new Error("仅客户端内可打开日志目录"), { status: 400 });
}
const err = await shellApi.openPath(dir);
if (err) throw Object.assign(new Error(err), { status: 500 });
return sendJson(res, 200, { ok: true, dir });
}
// 关于:版本 + 更新日志 + 本机关键目录(排障一步到位)
if (p === "/api/about" && method === "GET") {
session.requireLogin(cookies);
return sendJson(res, 200, {
version: config.runtimeVersion(),
changelog: readChangelog(),
data_dir: config.APP_DATA,
log_dir: loggerMod.logDir(),
env_dir: config.envRootDir(),
plugin_root: config.pluginRoot(),
sdk_root: config.sdkRoot(),
is_frozen: config.IS_FROZEN,
});
}
// ---------- 平台登录(按账号隔离会话与账号密码) ----------
+145
View File
@@ -0,0 +1,145 @@
// 设置中心持久化:用户级可调项(关闭行为 / 执行超时与内存 / 日志保留)。
// 明文 JSON:%LOCALAPPDATA%\37duAutomation\shell-settings.json(与插件配置同根,重装不丢)。
// 只做「存取 + 校验」,不碰 HTTP、不碰 Electron API(开机自启由调用方读写系统设置)。
// 取值语义:null = 跟随默认(.env / 内置常量);数字 = 用户覆盖值。
"use strict";
const fs = require("fs");
const path = require("path");
const FILE_NAME = "shell-settings.json";
// 可写入的键与合法范围(范围外一律拒绝,避免手改坏文件/前端传错把设备跑废)
const RULES = {
close_behavior: { type: "enum", values: ["tray", "quit"] },
run_timeout_sec: { type: "num", min: 0, max: 7 * 24 * 3600, nullable: true, integer: true },
run_max_mem_mb: { type: "num", min: 0, max: 32768, nullable: true, integer: true },
log_max_mb: { type: "num", min: 1, max: 512, nullable: true, integer: true },
log_keep: { type: "num", min: 1, max: 20, nullable: true, integer: true },
};
let _cache = null;
// 延迟 require config:本模块被 config 间接依赖,模块加载期不能反向读 config(避免循环)
function dataDir() {
try {
return require("./config").APP_DATA;
} catch (e) {
return path.join(process.env.LOCALAPPDATA || process.env.APPDATA || require("os").homedir(), "37duAutomation");
}
}
function filePath() {
return path.join(dataDir(), FILE_NAME);
}
function defaults() {
return {
close_behavior: "tray", // tray = 关闭窗口收托盘继续跑;quit = 关闭即退出程序
run_timeout_sec: null, // 空 = 用 .env 的 RUN_TIMEOUT(默认 21600 = 6 小时;0 = 不限时)
run_max_mem_mb: null, // 空 = 用 .env / 内置默认(物理内存 70%,4GB~16GB;0 = 不限)
log_max_mb: null, // 空 = 内置默认 10MB 单文件
log_keep: null, // 空 = 内置默认保留 3 份
};
}
function readRaw() {
const f = filePath();
try {
if (!fs.existsSync(f)) return {};
const text = fs.readFileSync(f, "utf-8").replace(/^\uFEFF/, "");
const obj = JSON.parse(text);
return obj && typeof obj === "object" && !Array.isArray(obj) ? obj : {};
} catch (e) {
return {};
}
}
/** 当前设置(已合并默认值;未知/非法值丢弃,防止脏文件影响运行) */
function get() {
if (_cache) return { ..._cache };
const raw = readRaw();
const out = defaults();
for (const key of Object.keys(RULES)) {
if (raw[key] === undefined) continue;
try {
out[key] = normalize(key, raw[key]);
} catch (e) {
/* 脏值忽略,回默认 */
}
}
_cache = out;
return { ...out };
}
function normalize(key, value) {
const rule = RULES[key];
if (!rule) throw new Error(`未知设置项:${key}`);
if (value === null || value === undefined || value === "") {
if (rule.nullable) return null;
throw new Error(`设置项 ${key} 不可为空`);
}
if (rule.type === "enum") {
const v = String(value);
if (!rule.values.includes(v)) throw new Error(`设置项 ${key} 取值非法:${v}`);
return v;
}
const n = Number(value);
if (!Number.isFinite(n)) throw new Error(`设置项 ${key} 必须是数字`);
if (rule.integer && !Number.isInteger(n)) throw new Error(`设置项 ${key} 必须是整数`);
if (n < rule.min || n > rule.max) throw new Error(`设置项 ${key} 超出范围(${rule.min}~${rule.max})`);
return n;
}
function save(obj) {
const f = filePath();
fs.mkdirSync(path.dirname(f), { recursive: true });
const tmp = `${f}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2), "utf-8");
fs.renameSync(tmp, f); // 原子替换:断电/崩溃不会留下半截 JSON
_cache = { ...obj };
}
/** 局部更新(只写传入的键);返回更新后的完整设置。非法值抛 Error。 */
function update(patch) {
const cur = get();
const next = { ...cur };
for (const key of Object.keys(patch || {})) {
if (!RULES[key]) continue; // 未知键忽略(前向兼容)
next[key] = normalize(key, patch[key]);
}
save(next);
return { ...next };
}
// ==================== 运行链路取值(供 config / runner / tasks 调用) ====================
/** 壳默认执行超时(秒);null = 跟随 .env 默认 */
function runTimeoutSec() {
return get().run_timeout_sec;
}
/** 内存上限(MB);null = 跟随 .env 默认 */
function runMaxMemMb() {
return get().run_max_mem_mb;
}
/** 日志轮转参数(未配置的项由调用方用内置默认) */
function logRotation() {
const s = get();
return { maxMb: s.log_max_mb, keep: s.log_keep };
}
function closeBehavior() {
return get().close_behavior || "tray";
}
module.exports = {
filePath,
defaults,
get,
update,
runTimeoutSec,
runMaxMemMb,
logRotation,
closeBehavior,
};
+104
View File
@@ -0,0 +1,104 @@
// 本机运行状态:CPU / 内存 / 磁盘(只读展示,不上报中心机)。
// CPU 用 os.cpus() 前后差分算占用率(Windows 没有 loadavg);磁盘用 fs.statfsSync(Node 18+,Windows 可用)。
// 说明:这里给的是「整机」视角;单次插件进程的内存峰值由 job_guard 从 Job Object 查询后随运行记录落库。
"use strict";
const os = require("os");
const fs = require("fs");
const path = require("path");
const config = require("./config");
const GB = 1024 * 1024 * 1024;
function round1(n) {
return Math.round(Number(n) * 10) / 10;
}
// ---------- CPU:两次采样之间的占用率 ----------
let _lastCpu = null;
function sampleCpu() {
const cpus = os.cpus() || [];
let idle = 0;
let total = 0;
for (const c of cpus) {
const t = c.times || {};
idle += t.idle || 0;
total += (t.user || 0) + (t.nice || 0) + (t.sys || 0) + (t.idle || 0) + (t.irq || 0);
}
let pct = 0;
if (_lastCpu && total > _lastCpu.total) {
const dTotal = total - _lastCpu.total;
const dIdle = idle - _lastCpu.idle;
pct = Math.round((1 - dIdle / dTotal) * 100);
}
_lastCpu = { idle, total };
return Math.max(0, Math.min(100, pct));
}
sampleCpu(); // 预热:首个 /api/system/stats 请求就能算出差值,而不是先返回 0
// ---------- 磁盘:按盘符去重 ----------
function diskInfo(target) {
let root;
try {
root = path.parse(path.resolve(String(target || ""))).root || String(target || "");
} catch (e) {
return null;
}
if (!root) return null;
try {
const st = fs.statfsSync(root);
const total = st.bsize * st.blocks;
const free = st.bsize * st.bavail;
if (!total) return null;
return {
root,
total_gb: round1(total / GB),
free_gb: round1(free / GB),
used_pct: Math.max(0, Math.min(100, Math.round((1 - free / total) * 100))),
};
} catch (e) {
return null; // 盘符不可读(已拔出/无权限):不展示这一项,不影响整页
}
}
function collectDisks() {
const out = [];
const seen = new Set();
const targets = [
["数据盘", config.APP_DATA],
["插件盘", config.pluginRoot()],
];
for (const [label, target] of targets) {
const d = diskInfo(target);
if (!d || seen.has(d.root)) continue;
seen.add(d.root);
out.push({ label, ...d });
}
return out;
}
// ---------- 汇总 ----------
function stats() {
const total = os.totalmem();
const free = os.freemem();
const used = Math.max(0, total - free);
return {
cpu_pct: sampleCpu(),
mem: {
total_gb: round1(total / GB),
used_gb: round1(used / GB),
used_pct: total ? Math.max(0, Math.min(100, Math.round((used / total) * 100))) : 0,
},
disks: collectDisks(),
uptime_sec: Math.round(os.uptime()),
ts: Date.now(),
};
}
// 磁盘余量过低(默认 < 1GB):执行前提示,避免导出写到一半磁盘满
function lowDisks(thresholdGb = 1) {
return stats().disks.filter((d) => d.free_gb < thresholdGb);
}
module.exports = { stats, lowDisks };
+2 -1
View File
@@ -441,7 +441,7 @@ function watchRun(scheduleId, runId) {
// 兜底:进程异常或事件丢失时不让监听器长期驻留(按该任务插件的执行超时上限 + 2 分钟宽限;
// 插件声明不限时时给 7 天硬上限,避免 setTimeout 溢出提前移除监听)。
// 排队会拉长"触发 → 结束"的跨度:前面每多一个等待任务,就要多等一个执行时长上限。
let boundSecs = config.RUN_TIMEOUT;
let boundSecs = config.runTimeoutFor(null);
const sched = _schedules.find((x) => x.id === scheduleId);
if (sched && sched.plugin_id) {
try {
@@ -539,6 +539,7 @@ module.exports = {
assertHourlyMin,
CATCHUP_SKIP_MS,
load,
start, // 离线本地模式(未配置 CONTROLPLANE_URL)由 app.js 直接 load + start,不走云端恢复
persist,
getSchedule,
listSchedules,