// 运行历史(壳子本地持久化):每次运行的结论 + 该次运行的日志,供「最近运行 / 点击回放」使用。 // 存储:%LOCALAPPDATA%\37duAutomation\ // run_history.jsonl 索引(只存结论,一行一次运行,无日志) // run_history/.jsonl 该次运行的日志(一行一条) // 分离存储的原因:列表接口只读索引(几百行、恒定体积),详情才读单个日志文件, // 避免"列表要解析所有历史日志"这种随使用时长线性劣化的写法。 // 职责划分:state.RUNS 内存态只服务"正在跑的那一次";本模块服务"跑过的那些次"。 "use strict"; const fs = require("fs"); const path = require("path"); const config = require("./config"); const { makeLogger } = require("./logger"); const logger = makeLogger("run-history"); const HISTORY_PATH = path.join(config.APP_DATA, "run_history.jsonl"); const RUNS_DIR = path.join(config.APP_DATA, "run_history"); // 上限:历史是"回顾"用的,不追求全量归档 const MAX_RECORDS = 300; // 裁剪目标:每次裁剪后保留最近 300 次运行(实际条数在 300 ~ 350 之间浮动) const PRUNE_SLACK = 50; // 超出裁剪目标这么多条才做一次整体裁剪(避免每次运行都重写整个索引) const MAX_LOGS_PER_RUN = 400; // 单次运行最多保留 400 条日志 const MAX_MSG_LEN = 1000; // 单条日志最大长度(防插件打印大体积 JSON 灌爆历史) const MAX_LOG_BYTES_PER_RUN = 32 * 1024; // 单次运行日志总量上限,超出即停止记录(软截断) // run_id 形如 32 位 hex;做白名单校验,杜绝路径穿越 function safeRunId(runId) { const s = String(runId || ""); return /^[A-Za-z0-9_-]{8,64}$/.test(s) ? s : ""; } function logFilePath(runId) { const id = safeRunId(runId); return id ? path.join(RUNS_DIR, `${id}.jsonl`) : ""; } // 截断超长日志(对齐"正常 INFO 级别屏蔽大体积 JSON"的日志规范精神) function clip(msg) { const s = String(msg === undefined || msg === null ? "" : msg); return s.length > MAX_MSG_LEN ? s.slice(0, MAX_MSG_LEN) + "…(已截断)" : s; } // 逐行读取 JSONL;单行损坏(例如写入中断)只跳过该行,不拖垮整个文件 function readLines(file) { if (!file || !fs.existsSync(file)) return []; let text; try { text = fs.readFileSync(file, "utf-8"); } catch (e) { logger.warning(`运行历史读取失败(${path.basename(file)}):${e.message}`); return []; } const out = []; for (const line of text.split(/\r?\n/)) { const s = line.trim(); if (!s) continue; try { out.push(JSON.parse(s)); } catch (e) { /* 跳过损坏行 */ } } return out; } // 原子整体替换(临时文件 + rename),避免写一半留下半行 function writeLines(file, records) { try { fs.mkdirSync(path.dirname(file), { recursive: true }); const tmp = file + ".tmp"; const body = records.length ? records.map((r) => JSON.stringify(r)).join("\n") + "\n" : ""; fs.writeFileSync(tmp, body, "utf-8"); fs.renameSync(tmp, file); } catch (e) { logger.warning(`运行历史写入失败(${path.basename(file)}):${e.message}`); } } function readIndex() { return readLines(HISTORY_PATH).filter((r) => r && typeof r === "object" && r.run_id); } // 写单次运行的日志文件(受条数与总字节双上限约束) function writeRunLogs(runId, logs) { const file = logFilePath(runId); if (!file || !Array.isArray(logs) || !logs.length) return; const kept = []; let bytes = 0; for (const l of logs.slice(-MAX_LOGS_PER_RUN)) { const rec = { t: l && l.t ? String(l.t) : "", level: (l && l.level) || "INFO", msg: clip(l && l.msg), }; bytes += rec.msg.length + 32; if (bytes > MAX_LOG_BYTES_PER_RUN) { kept.push({ t: "", level: "WARN", msg: "(日志过长,后续内容已省略,完整日志请查看运行日志面板)" }); break; } kept.push(rec); } writeLines(file, kept); } // 索引条数缓存:本模块是索引的唯一写入方,可安全缓存,避免每次追加都整文件读取 let _count = -1; function indexCount() { if (_count < 0) _count = readIndex().length; return _count; } // 裁剪索引到上限,并清理不再被引用的日志文件(避免目录无限膨胀) function prune() { const all = readIndex(); _count = all.length; if (all.length <= MAX_RECORDS) return; const kept = all.slice(-MAX_RECORDS); writeLines(HISTORY_PATH, kept); _count = kept.length; const alive = new Set(kept.map((r) => safeRunId(r.run_id)).filter(Boolean)); let removed = 0; try { for (const name of fs.readdirSync(RUNS_DIR)) { const id = name.replace(/\.jsonl$/, ""); if (!name.endsWith(".jsonl") || alive.has(id)) continue; fs.unlinkSync(path.join(RUNS_DIR, name)); removed++; } } catch (e) { /* 目录不存在或个别文件被占用:忽略,不影响主流程 */ } if (removed) logger.info(`运行历史已裁剪至最近 ${MAX_RECORDS} 次,清理日志文件 ${removed} 个`); } // 追加一次已结束的运行(结论进索引,日志单独落文件) function append(rec) { if (!rec || !safeRunId(rec.run_id)) return; writeRunLogs(rec.run_id, rec.logs); const briefRec = { ...rec }; delete briefRec.logs; try { fs.mkdirSync(config.APP_DATA, { recursive: true }); fs.appendFileSync(HISTORY_PATH, JSON.stringify(briefRec) + "\n", "utf-8"); } catch (e) { logger.warning(`运行历史追加失败:${e.message}`); return; } _count = indexCount() + 1; // 留出 slack 再裁剪:否则一旦到达上限,之后每次运行都会重写整个索引 if (_count > MAX_RECORDS + PRUNE_SLACK) prune(); } // 列表视图:只给列表需要的字段(不含日志) function brief(rec) { return { run_id: rec.run_id, plugin_id: rec.plugin_id || "", name: rec.name || rec.plugin_id || "", version: rec.version || "", trigger: rec.trigger || "manual", schedule_id: rec.schedule_id || "", status: rec.status || "", ok: !!rec.ok, error: rec.error || "", 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 || "", }; } // 当前账号最近 limit 次运行(新的在前) function list(account, limit) { const n = Math.max(1, Math.min(100, parseInt(limit, 10) || 20)); const mine = readIndex().filter((r) => r.account === account); return mine.slice(-n).reverse().map(brief); } // 单次运行详情(结论 + 日志);account 用于隔离,取不到返回 null function get(runId, account) { const id = safeRunId(runId); if (!id) return null; const all = readIndex(); for (let i = all.length - 1; i >= 0; i--) { if (all[i].run_id === id && all[i].account === account) { return { ...brief(all[i]), logs: readLines(logFilePath(id)) }; } } return null; } module.exports = { HISTORY_PATH, RUNS_DIR, MAX_RECORDS, PRUNE_SLACK, MAX_LOGS_PER_RUN, MAX_MSG_LEN, MAX_LOG_BYTES_PER_RUN, append, list, get, };