Files
37duAutomation/desktop/electron-shell/electron/settings.js
T

146 lines
4.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 设置中心持久化:用户级可调项(关闭行为 / 执行超时与内存 / 日志保留)。
// 明文 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,
};