@maiyunnet/kebab 9.29.6 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/abox/proxy.js +24 -2
  2. package/abox/response.js +36 -17
  3. package/abox/session-login.js +1 -13
  4. package/doc/kebab-rag.md +1687 -1061
  5. package/index.d.ts +14 -2
  6. package/index.js +1 -1
  7. package/lib/ai.d.ts +4 -0
  8. package/lib/ai.js +32 -16
  9. package/lib/cookie.d.ts +2 -0
  10. package/lib/cookie.js +47 -45
  11. package/lib/core.d.ts +26 -0
  12. package/lib/core.js +36 -13
  13. package/lib/cron.js +1 -8
  14. package/lib/crypto.js +20 -6
  15. package/lib/db/conn.d.ts +4 -2
  16. package/lib/db/conn.js +1 -0
  17. package/lib/db/pool.d.ts +17 -4
  18. package/lib/db/pool.js +41 -23
  19. package/lib/db/tran.d.ts +6 -4
  20. package/lib/db.d.ts +10 -5
  21. package/lib/db.js +36 -6
  22. package/lib/fs.js +78 -31
  23. package/lib/kv.d.ts +182 -79
  24. package/lib/kv.js +518 -214
  25. package/lib/s3.d.ts +2 -0
  26. package/lib/s3.js +14 -27
  27. package/lib/session.d.ts +7 -0
  28. package/lib/session.js +23 -2
  29. package/lib/socket.d.ts +4 -1
  30. package/lib/socket.js +1 -0
  31. package/lib/sql.d.ts +0 -5
  32. package/lib/sql.js +48 -12
  33. package/lib/text.d.ts +10 -5
  34. package/lib/text.js +22 -12
  35. package/lib/turnstile.d.ts +6 -0
  36. package/lib/turnstile.js +16 -9
  37. package/lib/undici/response.d.ts +1 -1
  38. package/lib/undici.d.ts +7 -1
  39. package/lib/undici.js +72 -36
  40. package/lib/ws.d.ts +1 -1
  41. package/lib/ws.js +85 -128
  42. package/lib/zip.js +46 -45
  43. package/package.json +2 -2
  44. package/sys/child.js +178 -146
  45. package/sys/cmd.js +196 -210
  46. package/sys/ctr.d.ts +16 -16
  47. package/sys/ctr.js +147 -61
  48. package/sys/master.js +111 -80
  49. package/sys/mod.d.ts +24 -2
  50. package/sys/mod.js +56 -26
  51. package/sys/monitor/files.d.ts +2 -1
  52. package/sys/monitor/files.js +77 -21
  53. package/sys/monitor/watchdog.d.ts +7 -0
  54. package/sys/monitor/watchdog.js +311 -203
  55. package/sys/monitor.d.ts +59 -54
  56. package/sys/monitor.js +742 -681
  57. package/sys/route.d.ts +4 -4
  58. package/sys/route.js +93 -52
  59. package/www/example/ctr/test.d.ts +1 -1
  60. package/www/example/ctr/test.js +34 -15
  61. package/www/example/mod/test.js +0 -1
package/sys/monitor.js CHANGED
@@ -1,113 +1,108 @@
1
1
  /**
2
2
  * Project: Kebab, User: JianSuoQiYue
3
3
  * Date: 2026-02-07
4
- * Last: 2026-10-05
5
- * --- 性能监控库,用于确认 CPU/内存持续超阈值,保存相关请求、资源采样和诊断文件 ---
6
- * --- 包含 Worker 看门狗线程,用于在事件循环完全阻塞时实时检测并记录 ---
4
+ * Last: 2026-11-24
5
+ * --- 性能监控库,持续监测 CPU/内存/事件循环延迟,保存现场快照和诊断文件 ---
6
+ * --- 配套看门狗 Worker 线程,在主线程完全阻塞时独立采样并抓栈 ---
7
7
  */
8
+ // --- 系统 ---
8
9
  import * as os from 'os';
9
10
  import * as v8 from 'v8';
10
11
  import * as inspector from 'inspector';
11
12
  import * as perfHooks from 'perf_hooks';
12
13
  import * as workerThreads from 'worker_threads';
14
+ // --- 库和定义 ---
13
15
  import * as kebab from '#kebab/index.js';
14
16
  import * as lCore from '#kebab/lib/core.js';
15
17
  import * as lText from '#kebab/lib/text.js';
16
18
  import * as lTime from '#kebab/lib/time.js';
17
19
  import * as lFs from '#kebab/lib/fs.js';
20
+ // --- 固定参数与共享内存槽位 ---
21
+ /** --- 主线程采样间隔(ms) --- */
22
+ const INTERVAL = 1_000;
23
+ /** --- CPU Profile 采集时长(ms) --- */
24
+ const PROFILE_MS = 5_000;
25
+ /** --- 同一持续异常重复采集重型诊断的冷却时间(ms) --- */
26
+ const DIAG_COOLDOWN = 60_000;
27
+ /** --- 单次快照最多保留的活跃/近期请求条数 --- */
28
+ const MAX_REQS = 100;
29
+ /** --- 看门狗轮询间隔(ms) --- */
30
+ const WD_INTERVAL = 1_000;
31
+ /** --- 看门狗同一阻塞的重复告警冷却(秒) --- */
32
+ const WD_COOLDOWN = 30;
33
+ /** --- 看门狗异常退出后的重启延迟(ms) --- */
34
+ const WD_RETRY_MS = 5_000;
35
+ /** --- 共享内存槽位:0-心跳 ms, 1-调试标志, 2-Inspector 锁, 3-同步诊断中, 4-已保存阻塞现场的心跳 --- */
36
+ const SLOT_HB = 0;
37
+ const SLOT_DEBUG = 1;
38
+ const SLOT_LOCK = 2;
39
+ const SLOT_DIAG = 3;
40
+ const SLOT_SAVED = 4;
18
41
  // --- 阈值配置 ---
19
42
  /** --- CPU 使用率阈值,100 代表占满一个逻辑核心 --- */
20
- let cpuThreshold = 80;
21
- /** --- 内存使用率阈值,单位 MB --- */
22
- let memThreshold = 0;
23
- /** --- 事件循环延迟阈值,单位 ms --- */
24
- let eloopThreshold = 500;
25
- /** --- 是否在内存超阈值时自动采集堆快照 --- */
26
- let heapSnapshotEnabled = false;
27
- /** --- 监控间隔,单位 ms;主线程被阻塞时由 Worker 独立采样 --- */
28
- const INTERVAL = 1_000;
29
- /** --- 同一指标持续超阈值的确认时间,单位 ms --- */
30
- let spikeDuration = 10_000;
31
- /** --- CPU Profile 采集时长,单位 ms --- */
32
- const PROFILE_DURATION = 5_000;
33
- /** --- 同一持续异常重复采集的间隔,单位 ms;新事件或指标复发不受此限制 --- */
34
- const DIAGNOSTIC_COOLDOWN = 60_000;
35
- /** --- 单次快照或日志最多输出的活跃请求详情数 --- */
36
- const MAX_ACTIVE_REQUEST_DETAILS = 100;
43
+ let cpuLimit = 80;
44
+ /** --- 内存 RSS 阈值(MB),0 表示自动推算 --- */
45
+ let memLimit = 0;
46
+ /** --- 事件循环 P99 延迟阈值(ms) --- */
47
+ let eloopLimit = 500;
48
+ /** --- 同一指标持续超阈值的确认时长(ms) --- */
49
+ let spikeMs = 10_000;
50
+ /** --- 主线程心跳中断的阻塞确认时长(ms) --- */
51
+ let blockMs = 5_000;
52
+ /** --- 内存超阈值时是否自动采集堆快照 --- */
53
+ let heapSnap = false;
37
54
  // --- 内部状态 ---
38
- /** --- 定时器 --- */
55
+ /** --- 周期检查定时器 --- */
39
56
  let timer = null;
40
- /** --- 周期检查的上次 CPU 累计用量 --- */
41
- let lastCheckCpuUsage = null;
42
- /** --- 周期检查的上次 CPU 采样时间戳 --- */
43
- let lastCheckCpuTime = 0;
44
- /** --- 周期检查的上次系统各核 CPU 时间快照 --- */
45
- let lastCheckOsCpus = null;
46
- /** --- 对外快照的上次 CPU 累计用量 --- */
47
- let lastSnapshotCpuUsage = null;
48
- /** --- 对外快照的上次 CPU 采样时间戳 --- */
49
- let lastSnapshotCpuTime = 0;
50
- /** --- 对外快照的上次系统各核 CPU 时间快照 --- */
51
- let lastSnapshotOsCpus = null;
57
+ /** --- 周期检查的 CPU 采样基准 --- */
58
+ let checkMark = null;
59
+ /** --- 对外 getSnapshot 的 CPU 采样基准 --- */
60
+ let snapMark = null;
52
61
  /** --- 事件循环延迟直方图 --- */
53
- let eloopHistogram = null;
54
- /** --- 各指标首次超阈值的单调时钟时间,不能跨指标累计 --- */
55
- let spikeSince = {
56
- 'cpu': null, 'mem': null, 'eloop': null,
62
+ let eloop = null;
63
+ /** --- 各指标首次超阈值的单调时钟时间(ms),不能跨指标累计 --- */
64
+ let spikeAt = {
65
+ 'cpu': null,
66
+ 'mem': null,
67
+ 'eloop': null,
57
68
  };
58
- /** --- 请求自增计数器 --- */
59
- let requestCounter = 0;
60
- /** --- 是否正在采集诊断数据 --- */
61
- let diagnosing = false;
62
- /** --- 是否正在进行 CPU Profile 采集 --- */
63
- let profiling = false;
64
- /** --- 同步 Report/HeapSnapshot 会影响本采样窗口,完成后重新建立检测基准 --- */
65
- let diagnosticOverhead = false;
66
- /**
67
- * --- 检测当前是否处于调试模式(以 --inspect 启动或 IDE 调试器已连接) ---
68
- * @returns 是否处于调试模式
69
- */
70
- function isDebugMode() {
71
- return !!inspector.url();
72
- }
73
- /**
74
- * --- 获取单调时钟毫秒数,避免系统校时影响 CPU 比例和心跳 ---
75
- * @returns 单调时钟毫秒数
76
- */
77
- function clockMs() {
78
- return Number(process.hrtime.bigint() / 1000000n);
79
- }
80
- // --- 看门狗相关 ---
69
+ /** --- 请求追踪自增序号 --- */
70
+ let reqSeq = 0;
71
+ /** --- 是否正在执行重型诊断采集 --- */
72
+ let diagBusy = false;
73
+ /** --- 是否正在通过看门狗采集 CPU Profile --- */
74
+ let profBusy = false;
75
+ /** --- 同步 Report/HeapSnapshot 产生的阻塞标记,下一采样周期据此跳过误判 --- */
76
+ let diagSkip = false;
81
77
  /** --- 看门狗 Worker 实例 --- */
82
- let watchdog = null;
83
- /** --- 心跳共享内存,协议见 monitor/watchdog.ts --- */
84
- let heartbeatBuffer = null;
78
+ let wd = null;
79
+ /** --- 心跳共享内存 --- */
80
+ let shmBuf = null;
85
81
  /** --- 心跳共享内存视图 --- */
86
- let heartbeatView = null;
87
- /** --- 主线程持续未更新心跳的确认时间,单位 ms --- */
88
- let watchdogThreshold = 5_000;
89
- /** --- 看门狗检测间隔,单位 ms --- */
90
- const WATCHDOG_INTERVAL = 1_000;
91
- /** --- 看门狗告警冷却时间,持续阻塞时不会每次都写日志,单位秒 --- */
92
- const WATCHDOG_COOLDOWN = 30;
93
- /** --- 看门狗异常退出后的重启延迟,单位 ms --- */
94
- const WATCHDOG_RESTART_DELAY = 5_000;
82
+ let shm = null;
95
83
  /** --- 看门狗重启定时器 --- */
96
- let watchdogRestartTimer = null;
84
+ let wdRetryTimer = null;
97
85
  /** --- 活跃请求池 --- */
98
- const activeRequests = new Map();
99
- /** --- 有界保存最近完成的请求,避免采集时请求已经移出活跃池 --- */
100
- const recentRequests = [];
101
- /** --- 最近一分钟的资源采样,不包含请求参数或请求体 --- */
102
- const sampleHistory = [];
103
- let lastWatchdogDiagnostic = null;
104
- const watchdogIncidents = new Map();
105
- /** --- 当前持续异常及其上次重型诊断时间 --- */
86
+ const reqs = new Map();
87
+ /** --- 最近一分钟完成的请求(最多 MAX_REQS 条) --- */
88
+ const recent = [];
89
+ /** --- 最近 60 秒的资源采样历史 --- */
90
+ const history = [];
91
+ /** --- 当前进行中的持续异常事件 --- */
106
92
  let incident = null;
107
- let lastDiagnosticTime = 0;
108
- let lastEventSaveTime = 0;
109
- /** --- 串行写入事件摘要,避免初次保存覆盖恢复或采集结果 --- */
110
- let eventWrites = Promise.resolve();
93
+ /** --- 上次触发重型诊断的单调时钟(ms) --- */
94
+ let lastDiagMs = 0;
95
+ /** --- 上次落盘事件摘要的时间戳(ms) --- */
96
+ let lastSaveMs = 0;
97
+ /** --- 最近一次收到的看门狗诊断结果 --- */
98
+ let lastWdDiag = null;
99
+ /** --- 等待看门狗回传结果的事件表,按心跳值索引 --- */
100
+ const wdPending = new Map();
101
+ /** --- 事件摘要串行写入链,避免并发落盘互相覆盖 --- */
102
+ let saveChain = Promise.resolve();
103
+ // ================
104
+ // --- 公开 API ---
105
+ // ================
111
106
  /**
112
107
  * --- 启动性能监控 ---
113
108
  * @param opt 可选的阈值配置
@@ -117,78 +112,74 @@ export function start(opt) {
117
112
  if (timer) {
118
113
  return true;
119
114
  }
120
- const nextCpuThreshold = opt?.cpu ?? 80;
121
- const nextMemThreshold = opt?.mem ?? 0;
122
- const nextEloopThreshold = opt?.eloop ?? 500;
123
- const nextDuration = opt?.duration ?? 10_000;
124
- const nextBlocked = opt?.blocked ?? 5_000;
125
- if (!Number.isFinite(nextCpuThreshold) || nextCpuThreshold <= 0) {
115
+ // --- 校验配置参数 ---
116
+ const cpu = opt?.cpu ?? 80;
117
+ const mem = opt?.mem ?? 0;
118
+ const lag = opt?.eloop ?? 500;
119
+ const dur = opt?.duration ?? 10_000;
120
+ const blk = opt?.blocked ?? 5_000;
121
+ if (!Number.isFinite(cpu) || cpu <= 0) {
126
122
  return false;
127
123
  }
128
- if (!Number.isFinite(nextMemThreshold) || nextMemThreshold < 0) {
124
+ if (!Number.isFinite(mem) || mem < 0) {
129
125
  return false;
130
126
  }
131
- if (!Number.isFinite(nextEloopThreshold) || nextEloopThreshold <= 0) {
127
+ if (!Number.isFinite(lag) || lag <= 0) {
132
128
  return false;
133
129
  }
134
- if (!Number.isFinite(nextDuration) || nextDuration < INTERVAL) {
130
+ if (!Number.isFinite(dur) || dur < INTERVAL) {
135
131
  return false;
136
132
  }
137
- if (!Number.isFinite(nextBlocked) || nextBlocked < INTERVAL) {
133
+ if (!Number.isFinite(blk) || blk < INTERVAL) {
138
134
  return false;
139
135
  }
140
- cpuThreshold = nextCpuThreshold;
141
- memThreshold = nextMemThreshold;
142
- eloopThreshold = nextEloopThreshold;
143
- spikeDuration = nextDuration;
144
- watchdogThreshold = nextBlocked;
145
- heapSnapshotEnabled = opt?.heapSnapshot ?? false;
146
- if (memThreshold === 0) {
147
- // --- 同时考虑容器/系统约束和 V8 堆上限,避免默认阈值高于进程实际可用范围 ---
148
- const constrainedMemory = process.constrainedMemory();
149
- const systemLimit = constrainedMemory > 0
150
- ? Math.min(constrainedMemory, os.totalmem())
151
- : os.totalmem();
152
- const heapLimit = v8.getHeapStatistics().heap_size_limit;
153
- memThreshold = Math.floor(Math.min(systemLimit * 0.8, heapLimit * 0.9) / 1024 / 1024);
154
- }
155
- const cpuUsage = process.cpuUsage();
156
- const cpuTime = clockMs();
157
- const osCpus = os.cpus();
158
- lastCheckCpuUsage = cpuUsage;
159
- lastCheckCpuTime = cpuTime;
160
- lastCheckOsCpus = osCpus;
161
- lastSnapshotCpuUsage = cpuUsage;
162
- lastSnapshotCpuTime = cpuTime;
163
- lastSnapshotOsCpus = osCpus;
164
- spikeSince = { 'cpu': null, 'mem': null, 'eloop': null };
165
- sampleHistory.length = 0;
166
- recentRequests.length = 0;
136
+ // --- 应用阈值,内存为 0 时按容器上限和 V8 堆上限推算默认值 ---
137
+ cpuLimit = cpu;
138
+ memLimit = mem;
139
+ eloopLimit = lag;
140
+ spikeMs = dur;
141
+ blockMs = blk;
142
+ heapSnap = opt?.heapSnapshot ?? false;
143
+ if (memLimit === 0) {
144
+ const cgroup = process.constrainedMemory();
145
+ const sysMem = cgroup > 0 ? Math.min(cgroup, os.totalmem()) : os.totalmem();
146
+ const heapMax = v8.getHeapStatistics().heap_size_limit;
147
+ memLimit = Math.floor(Math.min(sysMem * 0.8, heapMax * 0.9) / 1024 / 1024);
148
+ }
149
+ // --- 重置采样基准与运行状态 ---
150
+ const t = nowMs();
151
+ const mark = {
152
+ 'usage': process.cpuUsage(),
153
+ 'time': t,
154
+ 'cpus': os.cpus(),
155
+ };
156
+ checkMark = mark;
157
+ snapMark = { ...mark };
158
+ spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
159
+ history.length = 0;
160
+ recent.length = 0;
167
161
  incident = null;
168
- lastWatchdogDiagnostic = null;
169
- watchdogIncidents.clear();
170
- diagnosticOverhead = false;
171
- lastDiagnosticTime = 0;
172
- // --- 0: 单调时钟心跳, 1: 调试标志, 2: Inspector 占用, 3: 主线程诊断开销, 4: 已采集阻塞的心跳 ---
173
- heartbeatBuffer = new SharedArrayBuffer(40);
174
- heartbeatView = new BigInt64Array(heartbeatBuffer);
175
- Atomics.store(heartbeatView, 0, BigInt(cpuTime));
176
- Atomics.store(heartbeatView, 1, isDebugMode() ? 1n : 0n);
177
- // --- 启用事件循环延迟直方图 ---
178
- eloopHistogram = perfHooks.monitorEventLoopDelay({ 'resolution': 20 });
179
- eloopHistogram.enable();
162
+ lastWdDiag = null;
163
+ wdPending.clear();
164
+ diagSkip = false;
165
+ lastDiagMs = 0;
166
+ // --- 初始化心跳共享内存、延迟直方图、定时器和看门狗 ---
167
+ shmBuf = new SharedArrayBuffer(40);
168
+ shm = new BigInt64Array(shmBuf);
169
+ Atomics.store(shm, SLOT_HB, BigInt(t));
170
+ Atomics.store(shm, SLOT_DEBUG, isDebug() ? 1n : 0n);
171
+ eloop = perfHooks.monitorEventLoopDelay({ 'resolution': 20 });
172
+ eloop.enable();
180
173
  timer = setInterval(check, INTERVAL);
181
- // --- 启动看门狗线程 ---
182
- startWatchdog();
183
- lCore.debug(`[MONITOR] [PARENT] [${process.pid}] Started, CPU Threshold: ${cpuThreshold}%, MEM Threshold: ${memThreshold}MB, ELOOP Threshold: ${eloopThreshold}ms`);
174
+ startWd();
175
+ lCore.debug(`[MONITOR] [PARENT] [${process.pid}] Started, CPU Threshold: ${cpuLimit}%, MEM Threshold: ${memLimit}MB, ELOOP Threshold: ${eloopLimit}ms`);
184
176
  return true;
185
177
  }
186
178
  /**
187
179
  * --- 停止性能监控 ---
188
- * @returns 无返回值
189
180
  */
190
181
  export function stop() {
191
- watchdogIncidents.clear();
182
+ wdPending.clear();
192
183
  if (incident) {
193
184
  incident.endedAt = Date.now();
194
185
  incident.endReason = 'stopped';
@@ -199,109 +190,26 @@ export function stop() {
199
190
  clearInterval(timer);
200
191
  timer = null;
201
192
  }
202
- if (eloopHistogram) {
203
- eloopHistogram.disable();
204
- eloopHistogram = null;
205
- }
206
- if (watchdog) {
207
- watchdog.terminate().catch(() => {
208
- // --- 忽略终止错误 ---
209
- });
210
- watchdog = null;
211
- }
212
- if (watchdogRestartTimer) {
213
- clearTimeout(watchdogRestartTimer);
214
- watchdogRestartTimer = null;
215
- }
216
- activeRequests.clear();
217
- recentRequests.length = 0;
218
- sampleHistory.length = 0;
219
- lastCheckCpuUsage = null;
220
- lastCheckCpuTime = 0;
221
- lastCheckOsCpus = null;
222
- lastSnapshotCpuUsage = null;
223
- lastSnapshotCpuTime = 0;
224
- lastSnapshotOsCpus = null;
225
- spikeSince = { 'cpu': null, 'mem': null, 'eloop': null };
226
- heartbeatBuffer = null;
227
- heartbeatView = null;
228
- }
229
- /**
230
- * --- 启动看门狗 Worker 线程,独立事件循环监控主线程心跳 ---
231
- * --- 实现代码见 monitor/watchdog.ts ---
232
- * @returns 无返回值
233
- */
234
- function startWatchdog() {
235
- if (!heartbeatBuffer) {
236
- return;
237
- }
238
- const workerUrl = new URL('./monitor/watchdog.js', import.meta.url);
239
- try {
240
- const worker = new workerThreads.Worker(workerUrl, {
241
- 'workerData': {
242
- 'buffer': heartbeatBuffer,
243
- 'logDir': kebab.LOG_CWD,
244
- 'logFormat': lCore.globalConfig.logFormat ?? 'jsonl',
245
- 'pid': process.pid,
246
- 'threshold': watchdogThreshold,
247
- 'cooldown': WATCHDOG_COOLDOWN,
248
- 'interval': WATCHDOG_INTERVAL,
249
- 'profileDuration': PROFILE_DURATION,
250
- 'requests': Array.from(activeRequests.entries()),
251
- },
252
- });
253
- watchdog = worker;
254
- // --- 不阻止进程退出 ---
255
- worker.unref();
256
- worker.on('message', (message) => {
257
- if (watchdog !== worker || message.type !== 'diagnostic') {
258
- return;
259
- }
260
- lastWatchdogDiagnostic = message;
261
- const pending = watchdogIncidents.get(message.heartbeat);
262
- if (pending) {
263
- pending.result.status = `watchdog-${message.status}`;
264
- pending.result.files = [`${message.dir}/blocked-event.json`, ...message.files];
265
- pending.result.errors.push(...message.errors);
266
- watchdogIncidents.delete(message.heartbeat);
267
- saveIncident(pending.event);
268
- }
269
- });
270
- worker.on('error', (err) => {
271
- lCore.log({}, `WATCHDOG_ERROR ${lText.stringifyError(err)}`, '-monitor');
272
- lCore.display('[MONITOR] Watchdog error', err);
273
- });
274
- worker.on('exit', (exitCode) => {
275
- if (exitCode !== 0 && timer) {
276
- lCore.debug(`[MONITOR] Watchdog exited: ${exitCode}`);
277
- }
278
- // --- 仅当当前 watchdog 仍是本实例时才置空,避免 stop→start 重启时竞态 ---
279
- if (watchdog === worker) {
280
- watchdog = null;
281
- }
282
- scheduleWatchdogRestart();
283
- });
284
- lCore.debug(`[MONITOR] [THREAD] [${process.pid}] Watchdog started`);
285
- }
286
- catch (e) {
287
- lCore.log({}, `WATCHDOG_START_FAILED ${lText.stringifyError(e)}`, '-monitor');
288
- lCore.display('[MONITOR] Failed to start watchdog', e);
289
- scheduleWatchdogRestart();
290
- }
291
- }
292
- /**
293
- * --- 看门狗异常退出后延迟重启,避免失去阻塞检测能力 ---
294
- * @returns 无返回值
295
- */
296
- function scheduleWatchdogRestart() {
297
- if (!timer || watchdog || watchdogRestartTimer) {
298
- return;
299
- }
300
- watchdogRestartTimer = setTimeout(() => {
301
- watchdogRestartTimer = null;
302
- startWatchdog();
303
- }, WATCHDOG_RESTART_DELAY);
304
- watchdogRestartTimer.unref();
193
+ if (eloop) {
194
+ eloop.disable();
195
+ eloop = null;
196
+ }
197
+ if (wd) {
198
+ wd.terminate().catch(() => { });
199
+ wd = null;
200
+ }
201
+ if (wdRetryTimer) {
202
+ clearTimeout(wdRetryTimer);
203
+ wdRetryTimer = null;
204
+ }
205
+ reqs.clear();
206
+ recent.length = 0;
207
+ history.length = 0;
208
+ checkMark = null;
209
+ snapMark = null;
210
+ spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
211
+ shmBuf = null;
212
+ shm = null;
305
213
  }
306
214
  /**
307
215
  * --- 注册一个活跃请求,返回追踪 ID ---
@@ -311,574 +219,727 @@ function scheduleWatchdogRestart() {
311
219
  */
312
220
  export function track(url, method) {
313
221
  const now = Date.now();
314
- const id = `${++requestCounter}-${now}`;
315
- const queryIndex = url.search(/[?#]/u);
316
- activeRequests.set(id, {
317
- // --- 查询参数可能含凭据或个人信息,诊断中只保留请求路径 ---
318
- 'url': queryIndex === -1 ? url : url.slice(0, queryIndex),
222
+ const id = `${++reqSeq}-${now}`;
223
+ const qIdx = url.search(/[?#]/u);
224
+ const item = {
225
+ // --- 去掉查询参数,避免把凭据或隐私写入诊断文件 ---
226
+ 'url': qIdx === -1 ? url : url.slice(0, qIdx),
319
227
  'method': method,
320
228
  'start': now,
321
229
  'startCpu': process.cpuUsage(),
322
230
  'startMem': process.memoryUsage.rss(),
231
+ };
232
+ reqs.set(id, item);
233
+ wd?.postMessage({
234
+ 'type': 'request',
235
+ 'id': id,
236
+ 'request': item,
323
237
  });
324
- watchdog?.postMessage({ 'type': 'request', id, 'request': activeRequests.get(id) });
325
238
  return id;
326
239
  }
327
240
  /**
328
241
  * --- 移除已完成的请求追踪 ---
329
242
  * @param id 追踪 ID
330
- * @returns 无返回值
331
243
  */
332
244
  export function untrack(id) {
333
- const req = activeRequests.get(id);
245
+ const req = reqs.get(id);
334
246
  if (req) {
335
247
  const now = Date.now();
336
- const completed = snapshotRequest(req, now, process.cpuUsage(), process.memoryUsage.rss());
337
- completed.completedAt = now;
338
- recentRequests.push(completed);
339
- trimRecentRequests(now);
340
- watchdog?.postMessage({ 'type': 'complete', id, 'request': completed });
341
- }
342
- activeRequests.delete(id);
343
- }
344
- /**
345
- * --- 获取请求存续期间的进程资源增量,不能据此认定请求独占资源 ---
346
- * @param req 追踪中的请求
347
- * @param now 当前时间戳 ms
348
- * @param cpu 当前进程 CPU 累计用量
349
- * @param rss 当前进程 RSS
350
- * @returns 请求快照
351
- */
352
- function snapshotRequest(req, now, cpu, rss) {
353
- return {
354
- 'url': req.url, 'method': req.method, 'duration': now - req.start,
355
- 'cpuUser': cpu.user - req.startCpu.user, 'cpuSystem': cpu.system - req.startCpu.system,
356
- 'memDelta': rss - req.startMem,
357
- };
358
- }
359
- /**
360
- * --- 限制最近请求的保留时长及条数 ---
361
- * @param now 当前时间戳 ms
362
- * @returns 无返回值
363
- */
364
- function trimRecentRequests(now) {
365
- while (recentRequests.length > MAX_ACTIVE_REQUEST_DETAILS ||
366
- recentRequests.length && now - (recentRequests[0].completedAt ?? 0) > 60_000) {
367
- recentRequests.shift();
248
+ const done = snapReq(req, now, process.cpuUsage(), process.memoryUsage.rss());
249
+ done.completedAt = now;
250
+ recent.push(done);
251
+ trimRecent(now);
252
+ wd?.postMessage({
253
+ 'type': 'complete',
254
+ 'id': id,
255
+ 'request': done,
256
+ });
368
257
  }
258
+ reqs.delete(id);
369
259
  }
370
260
  /**
371
261
  * --- 获取当前资源快照 ---
372
262
  * @returns 资源与请求快照
373
263
  */
374
264
  export function getSnapshot() {
375
- const cpuUsage = process.cpuUsage();
376
- const cpuTime = clockMs();
377
- // --- 计算进程 CPU 使用率(单核基准) ---
378
- let cpuProcess = 0;
379
- if (lastSnapshotCpuUsage && lastSnapshotCpuTime) {
380
- /** --- 经过的时间(微秒) --- */
381
- const elapsed = (cpuTime - lastSnapshotCpuTime) * 1_000;
382
- const userDiff = cpuUsage.user - lastSnapshotCpuUsage.user;
383
- const sysDiff = cpuUsage.system - lastSnapshotCpuUsage.system;
384
- if (elapsed > 0) {
385
- cpuProcess = ((userDiff + sysDiff) / elapsed) * 100;
386
- }
387
- }
388
- lastSnapshotCpuUsage = cpuUsage;
389
- lastSnapshotCpuTime = cpuTime;
390
- // --- 计算系统总 CPU 使用率 ---
391
- const osCpus = os.cpus();
392
- const cpuOs = getOsCpuPercent(lastSnapshotOsCpus, osCpus);
393
- lastSnapshotOsCpus = osCpus;
394
- return createSnapshot(Math.round(cpuProcess * 100) / 100, cpuOs);
395
- }
396
- /**
397
- * --- 组装资源与请求快照,不推进对外查询的 CPU 采样基准 ---
398
- * @param cpuProcess 当前采样窗口进程 CPU 百分比
399
- * @param cpuOs 当前采样窗口系统 CPU 百分比
400
- * @returns 资源快照
401
- */
402
- function createSnapshot(cpuProcess, cpuOs) {
403
- const mem = process.memoryUsage();
404
- const heapStats = v8.getHeapStatistics();
405
- const cpuUsage = process.cpuUsage();
406
- const now = Date.now();
407
- // --- 计算事件循环延迟(P99,纳秒转毫秒) ---
408
- let eloopLag = 0;
409
- let eloopMax = 0;
410
- if (eloopHistogram) {
411
- eloopLag = Math.round(eloopHistogram.percentile(99) / 1_000_000);
412
- eloopMax = Math.round(eloopHistogram.max / 1_000_000);
413
- }
414
- // --- 收集活跃请求 ---
415
- const requests = [];
416
- for (const [, req] of activeRequests) {
417
- if (requests.length >= MAX_ACTIVE_REQUEST_DETAILS) {
418
- break;
419
- }
420
- requests.push(snapshotRequest(req, now, cpuUsage, mem.rss));
421
- }
422
- trimRecentRequests(now);
423
- return {
424
- 'pid': process.pid,
425
- 'time': now,
426
- 'cpuProcess': Math.round(cpuProcess * 100) / 100,
427
- 'cpuOs': cpuOs,
428
- 'mem': {
429
- 'rss': mem.rss,
430
- 'heapTotal': mem.heapTotal,
431
- 'heapUsed': mem.heapUsed,
432
- 'external': mem.external,
433
- 'arrayBuffers': mem.arrayBuffers,
434
- },
435
- 'heap': {
436
- 'totalSize': heapStats.total_heap_size,
437
- 'usedSize': heapStats.used_heap_size,
438
- 'sizeLimit': heapStats.heap_size_limit,
439
- },
440
- 'osMem': {
441
- 'total': os.totalmem(),
442
- 'free': os.freemem(),
443
- },
444
- 'eloopLag': eloopLag,
445
- 'eloopMax': eloopMax,
446
- 'activeRequests': requests,
447
- 'activeCount': activeRequests.size,
448
- 'recentRequests': [...recentRequests],
449
- };
265
+ const usage = process.cpuUsage();
266
+ const t = nowMs();
267
+ const cpus = os.cpus();
268
+ let cpuProc = 0;
269
+ if (snapMark && t > snapMark.time) {
270
+ const dtUs = (t - snapMark.time) * 1_000;
271
+ const diff = (usage.user - snapMark.usage.user) + (usage.system - snapMark.usage.system);
272
+ cpuProc = (diff / dtUs) * 100;
273
+ }
274
+ const cpuOs = calcOsCpu(snapMark?.cpus ?? null, cpus);
275
+ snapMark = { 'usage': usage, 'time': t, 'cpus': cpus };
276
+ return buildSnap(Math.round(cpuProc * 100) / 100, cpuOs);
450
277
  }
278
+ // ==========================
279
+ // --- 周期检查与异常记录 ---
280
+ // ==========================
451
281
  /**
452
- * --- 周期检查:独立确认各指标,按一次持续异常记录开始、现场及恢复 ---
453
- * @returns 无返回值
282
+ * --- 每秒周期检查:采样资源、更新心跳、判定持续异常与恢复 ---
454
283
  */
455
284
  function check() {
456
- const cpuUsage = process.cpuUsage();
285
+ // --- 计算本周期 CPU 占比并刷新共享心跳 ---
286
+ const usage = process.cpuUsage();
457
287
  const now = Date.now();
458
- const cpuTime = clockMs();
459
- const previousTime = lastCheckCpuTime;
460
- const actualElapsed = cpuTime - previousTime;
461
- let cpuPercent = 0;
462
- if (lastCheckCpuUsage && actualElapsed > 0) {
463
- cpuPercent = (cpuUsage.user - lastCheckCpuUsage.user + cpuUsage.system - lastCheckCpuUsage.system)
464
- / (actualElapsed * 1_000) * 100;
465
- }
466
- lastCheckCpuUsage = cpuUsage;
467
- lastCheckCpuTime = cpuTime;
468
- const osCpus = os.cpus();
469
- const cpuOs = getOsCpuPercent(lastCheckOsCpus, osCpus);
470
- lastCheckOsCpus = osCpus;
471
- if (heartbeatView) {
472
- Atomics.store(heartbeatView, 0, BigInt(cpuTime));
473
- Atomics.store(heartbeatView, 1, isDebugMode() ? 1n : 0n);
474
- }
475
- const snapshot = createSnapshot(Math.round(cpuPercent * 100) / 100, cpuOs);
476
- // --- 采样时同步配置,框架 reload 后看门狗也使用当前日志格式 ---
477
- watchdog?.postMessage({ 'type': 'snapshot', snapshot, 'logFormat': lCore.globalConfig.logFormat ?? 'jsonl' });
478
- eloopHistogram?.reset();
479
- // --- 调试暂停和同步诊断不能冒充业务阻塞,也不能连接暂停前后的异常计数 ---
480
- if (isDebugMode()) {
481
- spikeSince = { 'cpu': null, 'mem': null, 'eloop': null };
288
+ const t = nowMs();
289
+ const prevT = checkMark?.time ?? 0;
290
+ const dt = t - prevT;
291
+ let cpuPct = 0;
292
+ if (checkMark && dt > 0) {
293
+ const diff = (usage.user - checkMark.usage.user) + (usage.system - checkMark.usage.system);
294
+ cpuPct = (diff / (dt * 1_000)) * 100;
295
+ }
296
+ const cpus = os.cpus();
297
+ const cpuOs = calcOsCpu(checkMark?.cpus ?? null, cpus);
298
+ checkMark = { 'usage': usage, 'time': t, 'cpus': cpus };
299
+ if (shm) {
300
+ Atomics.store(shm, SLOT_HB, BigInt(t));
301
+ Atomics.store(shm, SLOT_DEBUG, isDebug() ? 1n : 0n);
302
+ }
303
+ // --- 生成快照并同步给看门狗 ---
304
+ const snap = buildSnap(Math.round(cpuPct * 100) / 100, cpuOs);
305
+ wd?.postMessage({
306
+ 'type': 'snapshot',
307
+ 'snapshot': snap,
308
+ 'logFormat': lCore.globalConfig.logFormat ?? 'jsonl',
309
+ });
310
+ eloop?.reset();
311
+ // --- 调试或同步诊断窗口跳过告警判定 ---
312
+ if (isDebug()) {
313
+ spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
482
314
  return;
483
315
  }
484
- if (diagnosticOverhead) {
485
- diagnosticOverhead = false;
486
- // --- 已确认事件继续等待正常采样恢复,未确认的连续性重新计时 ---
316
+ if (diagSkip) {
317
+ diagSkip = false;
487
318
  if (!incident?.reasons.includes('PROC_CPU')) {
488
- spikeSince.cpu = null;
319
+ spikeAt.cpu = null;
489
320
  }
490
321
  if (!incident?.reasons.includes('MEM')) {
491
- spikeSince.mem = null;
322
+ spikeAt.mem = null;
492
323
  }
493
324
  if (!incident?.reasons.includes('ELOOP_LAG')) {
494
- spikeSince.eloop = null;
325
+ spikeAt.eloop = null;
495
326
  }
496
327
  return;
497
328
  }
329
+ // --- 记录最近 60 秒采样历史 ---
498
330
  const sample = {
499
- 'time': now, 'elapsed': actualElapsed, 'cpu': snapshot.cpuProcess, 'cpuOs': cpuOs,
500
- 'rss': snapshot.mem.rss, 'heapUsed': snapshot.mem.heapUsed,
501
- 'external': snapshot.mem.external, 'arrayBuffers': snapshot.mem.arrayBuffers,
502
- 'eloop': snapshot.eloopLag, 'eloopMax': snapshot.eloopMax,
331
+ 'time': now,
332
+ 'elapsed': dt,
333
+ 'cpu': snap.cpuProcess,
334
+ 'cpuOs': cpuOs,
335
+ 'rss': snap.mem.rss,
336
+ 'heapUsed': snap.mem.heapUsed,
337
+ 'external': snap.mem.external,
338
+ 'arrayBuffers': snap.mem.arrayBuffers,
339
+ 'eloop': snap.eloopLag,
340
+ 'eloopMax': snap.eloopMax,
503
341
  };
504
- sampleHistory.push(sample);
505
- while (sampleHistory.length > 60) {
506
- sampleHistory.shift();
507
- }
508
- const alerts = [];
509
- const blocked = actualElapsed - INTERVAL >= watchdogThreshold;
510
- if (blocked) {
511
- alerts.push('ELOOP_BLOCKED');
512
- // --- 延迟检查只能证明这一窗口发生过阻塞,不能证明资源持续超阈值 ---
513
- spikeSince = { 'cpu': null, 'mem': null, 'eloop': null };
514
- }
515
- else {
516
- if (snapshot.cpuProcess >= cpuThreshold) {
517
- spikeSince.cpu ??= previousTime;
518
- if (cpuTime - spikeSince.cpu >= spikeDuration) {
519
- alerts.push('PROC_CPU');
520
- }
521
- }
522
- else {
523
- spikeSince.cpu = null;
524
- }
525
- if (snapshot.mem.rss / 1024 / 1024 >= memThreshold) {
526
- // --- 内存是时点值,首次超阈值之前的一个采样周期不能计入持续时间 ---
527
- spikeSince.mem ??= cpuTime;
528
- if (cpuTime - spikeSince.mem >= spikeDuration) {
529
- alerts.push('MEM');
530
- }
531
- }
532
- else {
533
- spikeSince.mem = null;
534
- }
535
- if (snapshot.eloopLag >= eloopThreshold) {
536
- spikeSince.eloop ??= previousTime;
537
- if (cpuTime - spikeSince.eloop >= spikeDuration) {
538
- alerts.push('ELOOP_LAG');
539
- }
540
- }
541
- else {
542
- spikeSince.eloop = null;
543
- }
342
+ history.push(sample);
343
+ while (history.length > 60) {
344
+ history.shift();
544
345
  }
346
+ // --- 判定阻塞及各项资源是否持续超阈值 ---
347
+ const blocked = dt - INTERVAL >= blockMs;
348
+ const alerts = detectAlerts(snap, blocked, prevT, t);
545
349
  if (!alerts.length) {
546
350
  if (incident) {
547
351
  incident.endedAt = now;
548
352
  incident.endReason = 'recovered';
549
353
  incident.activeReasons = [];
550
- incident.recoveredSnapshot = snapshot;
354
+ incident.recoveredSnapshot = snap;
551
355
  saveIncident(incident);
552
356
  lCore.log({}, `RECOVERED PID:${process.pid} EVENT:${incident.dir}`, '-monitor');
553
357
  incident = null;
554
358
  }
555
359
  return;
556
360
  }
557
- recordIncident(alerts, snapshot, sample, blocked, previousTime);
361
+ recordIncident(alerts, snap, sample, blocked, prevT);
558
362
  }
559
363
  /**
560
- * --- 串行保存事件摘要,重型诊断失败不影响基础现场保存 ---
561
- * @param event 要保存的事件
562
- * @returns 无返回值
364
+ * --- 根据当前快照和持续时长判定触发的告警项 ---
365
+ * @param snap 当前快照
366
+ * @param blocked 本周期是否发生事件循环阻塞
367
+ * @param prevT 本周期起点单调时钟(ms)
368
+ * @param t 当前单调时钟(ms)
369
+ * @returns 已确认的告警项列表
563
370
  */
564
- function saveIncident(event) {
565
- const content = lText.stringifyJson(event, 2);
566
- eventWrites = eventWrites.then(async () => {
567
- if (!await lFs.mkdir(event.dir, 0o700) || !await lFs.chmod(event.dir, 0o700) ||
568
- !await lFs.putContent(`${event.dir}event.json`, content, { 'mode': 0o600 }) ||
569
- !await lFs.chmod(`${event.dir}event.json`, 0o600)) {
570
- lCore.display('[MONITOR] Failed to save event:', event.dir);
571
- }
572
- }).catch((error) => {
573
- lCore.display('[MONITOR] Failed to save event:', error);
574
- });
371
+ function detectAlerts(snap, blocked, prevT, t) {
372
+ if (blocked) {
373
+ // --- 阻塞窗口只能确认阻塞本身,不能顺带证明其他资源持续超标 ---
374
+ spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
375
+ return ['ELOOP_BLOCKED'];
376
+ }
377
+ const alerts = [];
378
+ if (snap.cpuProcess >= cpuLimit) {
379
+ spikeAt.cpu ??= prevT;
380
+ if (t - spikeAt.cpu >= spikeMs) {
381
+ alerts.push('PROC_CPU');
382
+ }
383
+ }
384
+ else {
385
+ spikeAt.cpu = null;
386
+ }
387
+ if (snap.mem.rss / 1024 / 1024 >= memLimit) {
388
+ // --- 内存是时点值,不把超阈值前的一个周期算入持续时间 ---
389
+ spikeAt.mem ??= t;
390
+ if (t - spikeAt.mem >= spikeMs) {
391
+ alerts.push('MEM');
392
+ }
393
+ }
394
+ else {
395
+ spikeAt.mem = null;
396
+ }
397
+ if (snap.eloopLag >= eloopLimit) {
398
+ spikeAt.eloop ??= prevT;
399
+ if (t - spikeAt.eloop >= spikeMs) {
400
+ alerts.push('ELOOP_LAG');
401
+ }
402
+ }
403
+ else {
404
+ spikeAt.eloop = null;
405
+ }
406
+ return alerts;
575
407
  }
576
408
  /**
577
- * --- 记录一次已确认异常;同一事件定期更新,新事件不受上一事件冷却限制 ---
578
- * @param alerts 已确认的指标
579
- * @param snapshot 检测现场快照
409
+ * --- 记录或更新持续异常事件,并按冷却条件触发重型诊断 ---
410
+ * @param alerts 已确认的告警项
411
+ * @param snap 当前快照
580
412
  * @param sample 当前采样
581
- * @param blocked 是否刚从主线程阻塞恢复
582
- * @param previousTime 本采样窗口起点的单调时钟毫秒数
583
- * @returns 无返回值
413
+ * @param blocked 是否刚从阻塞恢复
414
+ * @param prevT 本周期起点单调时钟(ms)
584
415
  */
585
- function recordIncident(alerts, snapshot, sample, blocked, previousTime) {
586
- const now = snapshot.time;
587
- const first = incident === null;
416
+ function recordIncident(alerts, snap, sample, blocked, prevT) {
417
+ const now = snap.time;
418
+ const isNew = incident === null;
419
+ // --- 首次触发时创建异常事件对象 ---
588
420
  if (!incident) {
589
- const date = new Date(now);
590
- const dir = `${kebab.LOG_CWD}monitor/${lTime.format(null, 'Y/m/d/His', date)}-pid-${process.pid}-${now}/`;
421
+ const dir = `${kebab.LOG_CWD}monitor/${lTime.format(null, 'Y/m/d/His', new Date(now))}-pid-${process.pid}-${now}/`;
422
+ const earliest = Math.min(spikeAt.cpu ?? Infinity, spikeAt.mem ?? Infinity, spikeAt.eloop ?? Infinity, blocked ? prevT : Infinity);
591
423
  incident = {
592
- dir, 'startedAt': now - Math.max(0, clockMs() - Math.min(spikeSince.cpu ?? Infinity, spikeSince.mem ?? Infinity, spikeSince.eloop ?? Infinity, blocked ? previousTime : Infinity)),
593
- 'confirmedAt': now, 'endedAt': null, 'endReason': null, 'reasons': [], 'activeReasons': [], 'impact': 'resource-high',
424
+ 'dir': dir,
425
+ 'startedAt': now - Math.max(0, nowMs() - earliest),
426
+ 'confirmedAt': now,
427
+ 'endedAt': null,
428
+ 'endReason': null,
429
+ 'reasons': [],
430
+ 'activeReasons': [],
431
+ 'impact': 'resource-high',
594
432
  'thresholds': {
595
- 'cpu': cpuThreshold, 'mem': memThreshold, 'eloop': eloopThreshold,
596
- 'duration': spikeDuration, 'blocked': watchdogThreshold,
433
+ 'cpu': cpuLimit,
434
+ 'mem': memLimit,
435
+ 'eloop': eloopLimit,
436
+ 'duration': spikeMs,
437
+ 'blocked': blockMs,
597
438
  },
598
- 'before': [...sampleHistory], 'samples': [],
439
+ 'before': [...history],
440
+ 'samples': [],
599
441
  'peaks': { 'cpu': 0, 'rss': 0, 'heapUsed': 0, 'eloop': 0 },
600
- snapshot, 'diagnostics': [],
442
+ 'snapshot': snap,
443
+ 'diagnostics': [],
601
444
  };
602
- lastDiagnosticTime = 0;
603
- lastEventSaveTime = 0;
604
- }
605
- const event = incident;
606
- // --- 内存事件尚未恢复时,CPU 恢复后再次升高仍是新的采集时机 ---
607
- const newReason = alerts.some(alert => !event.activeReasons.includes(alert));
608
- event.activeReasons = [...alerts];
609
- for (const alert of alerts) {
610
- if (!event.reasons.includes(alert)) {
611
- event.reasons.push(alert);
445
+ lastDiagMs = 0;
446
+ lastSaveMs = 0;
447
+ }
448
+ // --- 更新告警原因、采样序列与峰值 ---
449
+ const ev = incident;
450
+ const hasNewReason = alerts.some(a => !ev.activeReasons.includes(a));
451
+ ev.activeReasons = [...alerts];
452
+ for (const a of alerts) {
453
+ if (!ev.reasons.includes(a)) {
454
+ ev.reasons.push(a);
612
455
  }
613
456
  }
614
457
  if (alerts.includes('ELOOP_BLOCKED') || alerts.includes('ELOOP_LAG')) {
615
- event.impact = 'event-loop-delayed';
458
+ ev.impact = 'event-loop-delayed';
616
459
  }
617
- event.samples.push(sample);
618
- if (event.samples.length > 300) {
619
- event.samples.shift();
460
+ ev.samples.push(sample);
461
+ if (ev.samples.length > 300) {
462
+ ev.samples.shift();
620
463
  }
621
- event.peaks.cpu = Math.max(event.peaks.cpu, sample.cpu);
622
- event.peaks.rss = Math.max(event.peaks.rss, sample.rss);
623
- event.peaks.heapUsed = Math.max(event.peaks.heapUsed, sample.heapUsed);
624
- event.peaks.eloop = Math.max(event.peaks.eloop, sample.eloopMax, sample.elapsed - INTERVAL);
625
- if (first || newReason) {
464
+ ev.peaks.cpu = Math.max(ev.peaks.cpu, sample.cpu);
465
+ ev.peaks.rss = Math.max(ev.peaks.rss, sample.rss);
466
+ ev.peaks.heapUsed = Math.max(ev.peaks.heapUsed, sample.heapUsed);
467
+ ev.peaks.eloop = Math.max(ev.peaks.eloop, sample.eloopMax, sample.elapsed - INTERVAL);
468
+ if (isNew || hasNewReason) {
626
469
  const msg = `RESOURCE_HIGH [${alerts.join(', ')}] PID:${process.pid} ` +
627
- `PROC_CPU:${snapshot.cpuProcess}% RSS:${lText.sizeFormat(snapshot.mem.rss, '')} ` +
628
- `ELOOP_LAG:${snapshot.eloopLag}ms ACTIVE_REQ:${snapshot.activeCount} EVENT:${event.dir}`;
470
+ `PROC_CPU:${snap.cpuProcess}% RSS:${lText.sizeFormat(snap.mem.rss, '')} ` +
471
+ `ELOOP_LAG:${snap.eloopLag}ms ACTIVE_REQ:${snap.activeCount} EVENT:${ev.dir}`;
629
472
  lCore.log({}, msg, '-monitor');
630
473
  lCore.display('[MONITOR]', msg);
631
474
  }
632
- if (first || newReason || clockMs() - lastDiagnosticTime >= DIAGNOSTIC_COOLDOWN) {
633
- lastDiagnosticTime = clockMs();
634
- const result = { 'time': now, 'status': 'pending', 'files': [], 'errors': [], snapshot };
635
- event.diagnostics.push(result);
636
- if (event.diagnostics.length > 60) {
637
- event.diagnostics.shift();
638
- }
639
- const view = heartbeatView;
640
- // --- 只有看门狗确实保存过这一窗口的现场时,才省略恢复后的重复 Profile ---
641
- const watchdogCaptured = blocked && view !== null && Atomics.load(view, 4) >= BigInt(previousTime);
642
- if (watchdogCaptured) {
643
- const heartbeat = Number(Atomics.load(view, 4));
644
- if (lastWatchdogDiagnostic?.heartbeat === heartbeat) {
645
- result.status = `watchdog-${lastWatchdogDiagnostic.status}`;
646
- result.files = [`${lastWatchdogDiagnostic.dir}/blocked-event.json`, ...lastWatchdogDiagnostic.files];
647
- result.errors.push(...lastWatchdogDiagnostic.errors);
648
- }
649
- else {
650
- result.status = 'watchdog-captured';
651
- watchdogIncidents.set(heartbeat, { event, result });
652
- }
653
- }
654
- else if (diagnosing || view && Atomics.load(view, 2) !== 0n) {
655
- result.status = 'skipped-busy';
656
- lastDiagnosticTime = clockMs() - DIAGNOSTIC_COOLDOWN + 5_000;
475
+ // --- 按冷却周期触发重型诊断,或复用看门狗已采集的阻塞现场 ---
476
+ if (isNew || hasNewReason || nowMs() - lastDiagMs >= DIAG_COOLDOWN) {
477
+ triggerDiag(ev, alerts, snap, blocked, prevT);
478
+ }
479
+ // --- 定期将事件摘要落盘 ---
480
+ if (isNew || hasNewReason || now - lastSaveMs >= 5_000) {
481
+ lastSaveMs = now;
482
+ saveIncident(ev);
483
+ }
484
+ }
485
+ /**
486
+ * --- 触发一次重型诊断,或在看门狗已保存阻塞现场时直接关联 ---
487
+ * @param ev 当前事件
488
+ * @param alerts 告警项
489
+ * @param snap 当前快照
490
+ * @param blocked 是否阻塞恢复
491
+ * @param prevT 本周期起点单调时钟(ms)
492
+ */
493
+ function triggerDiag(ev, alerts, snap, blocked, prevT) {
494
+ const now = snap.time;
495
+ lastDiagMs = nowMs();
496
+ const res = {
497
+ 'time': now,
498
+ 'status': 'pending',
499
+ 'files': [],
500
+ 'errors': [],
501
+ 'snapshot': snap,
502
+ };
503
+ ev.diagnostics.push(res);
504
+ if (ev.diagnostics.length > 60) {
505
+ ev.diagnostics.shift();
506
+ }
507
+ const view = shm;
508
+ const wdSaved = blocked && view !== null && Atomics.load(view, SLOT_SAVED) >= BigInt(prevT);
509
+ if (wdSaved) {
510
+ // --- 看门狗已经保存了本次阻塞现场,直接关联而不再重复采 Profile ---
511
+ const hb = Number(Atomics.load(view, SLOT_SAVED));
512
+ if (lastWdDiag?.heartbeat === hb) {
513
+ res.status = `watchdog-${lastWdDiag.status}`;
514
+ res.files = [`${lastWdDiag.dir}/blocked-event.json`, ...lastWdDiag.files];
515
+ res.errors.push(...lastWdDiag.errors);
657
516
  }
658
517
  else {
659
- diagnosing = true;
660
- const ts = `${lTime.format(null, 'YmdHis', new Date(now))}-${now}`;
661
- // --- 阻塞恢复后的 Profile 只能记录后续执行,摘要保留这个采集时机限制 ---
662
- if (blocked) {
663
- result.errors.push('The blocking stack was not captured; this profile starts after recovery.');
664
- }
665
- void collectDiagnostics(event.dir, ts, alerts.includes('PROC_CPU') || blocked, alerts.includes('MEM') && heapSnapshotEnabled, result, view).catch((error) => {
666
- result.status = 'failed';
667
- result.errors.push(lText.stringifyError(error));
668
- }).finally(() => {
669
- diagnosing = false;
670
- saveIncident(event);
671
- });
518
+ res.status = 'watchdog-captured';
519
+ wdPending.set(hb, { 'event': ev, 'result': res });
672
520
  }
521
+ return;
673
522
  }
674
- if (first || newReason || now - lastEventSaveTime >= 5_000) {
675
- lastEventSaveTime = now;
676
- saveIncident(event);
523
+ if (diagBusy || (view && Atomics.load(view, SLOT_LOCK) !== 0n)) {
524
+ res.status = 'skipped-busy';
525
+ lastDiagMs = nowMs() - DIAG_COOLDOWN + 5_000;
526
+ return;
677
527
  }
528
+ diagBusy = true;
529
+ const ts = `${lTime.format(null, 'YmdHis', new Date(now))}-${now}`;
530
+ if (blocked) {
531
+ res.errors.push('The blocking stack was not captured; this profile starts after recovery.');
532
+ }
533
+ void runDiag(ev.dir, ts, alerts.includes('PROC_CPU') || blocked, alerts.includes('MEM') && heapSnap, res, view).catch((err) => {
534
+ res.status = 'failed';
535
+ res.errors.push(lText.stringifyError(err));
536
+ }).finally(() => {
537
+ diagBusy = false;
538
+ saveIncident(ev);
539
+ });
678
540
  }
679
541
  /**
680
- * --- 通过 os.cpus() 两次采样的 Delta 计算系统总 CPU 使用率 ---
681
- * @param previous 上次系统各核 CPU 时间快照
682
- * @param current 当前系统各核 CPU 时间快照
683
- * @returns 0-100 的百分比值,和任务管理器/top 命令一致
542
+ * --- 串行落盘事件摘要,避免多次保存互相覆盖 ---
543
+ * @param ev 事件对象
684
544
  */
685
- function getOsCpuPercent(previous, current) {
686
- if (previous?.length !== current.length) {
687
- return 0;
545
+ function saveIncident(ev) {
546
+ const text = lText.stringifyJson(ev, 2);
547
+ saveChain = saveChain.then(async () => {
548
+ if (!await lFs.mkdir(ev.dir, 0o700) ||
549
+ !await lFs.chmod(ev.dir, 0o700) ||
550
+ !await lFs.putContent(`${ev.dir}event.json`, text, { 'mode': 0o600 }) ||
551
+ !await lFs.chmod(`${ev.dir}event.json`, 0o600)) {
552
+ lCore.display('[MONITOR] Failed to save event:', ev.dir);
553
+ }
554
+ }).catch((err) => {
555
+ lCore.display('[MONITOR] Failed to save event:', err);
556
+ });
557
+ }
558
+ // ============================
559
+ // --- 诊断采集与看门狗线程 ---
560
+ // ============================
561
+ /**
562
+ * --- 启动看门狗 Worker 线程 ---
563
+ */
564
+ function startWd() {
565
+ if (!shmBuf) {
566
+ return;
688
567
  }
689
- let totalIdle = 0;
690
- let totalTick = 0;
691
- for (let i = 0; i < current.length; ++i) {
692
- const cur = current[i].times;
693
- const prev = previous[i].times;
694
- const idleDiff = cur.idle - prev.idle;
695
- const totalDiff = (cur.user - prev.user) +
696
- (cur.nice - prev.nice) +
697
- (cur.sys - prev.sys) +
698
- (cur.irq - prev.irq) +
699
- idleDiff;
700
- totalIdle += idleDiff;
701
- totalTick += totalDiff;
702
- }
703
- if (totalTick <= 0) {
704
- return 0;
568
+ const workerUrl = new URL('./monitor/watchdog.js', import.meta.url);
569
+ try {
570
+ const worker = new workerThreads.Worker(workerUrl, {
571
+ 'workerData': {
572
+ 'buffer': shmBuf,
573
+ 'logDir': kebab.LOG_CWD,
574
+ 'logFormat': lCore.globalConfig.logFormat ?? 'jsonl',
575
+ 'pid': process.pid,
576
+ 'threshold': blockMs,
577
+ 'cooldown': WD_COOLDOWN,
578
+ 'interval': WD_INTERVAL,
579
+ 'profileDuration': PROFILE_MS,
580
+ 'requests': Array.from(reqs.entries()),
581
+ },
582
+ });
583
+ wd = worker;
584
+ worker.unref();
585
+ worker.on('message', (msg) => {
586
+ if (wd !== worker || msg.type !== 'diagnostic') {
587
+ return;
588
+ }
589
+ lastWdDiag = msg;
590
+ const item = wdPending.get(msg.heartbeat);
591
+ if (item) {
592
+ item.result.status = `watchdog-${msg.status}`;
593
+ item.result.files = [`${msg.dir}/blocked-event.json`, ...msg.files];
594
+ item.result.errors.push(...msg.errors);
595
+ wdPending.delete(msg.heartbeat);
596
+ saveIncident(item.event);
597
+ }
598
+ });
599
+ worker.on('error', (err) => {
600
+ lCore.log({}, `WATCHDOG_ERROR ${lText.stringifyError(err)}`, '-monitor');
601
+ lCore.display('[MONITOR] Watchdog error', err);
602
+ });
603
+ worker.on('exit', (code) => {
604
+ if (code !== 0 && timer) {
605
+ lCore.debug(`[MONITOR] Watchdog exited: ${code}`);
606
+ }
607
+ if (wd === worker) {
608
+ wd = null;
609
+ }
610
+ retryWd();
611
+ });
612
+ lCore.debug(`[MONITOR] [THREAD] [${process.pid}] Watchdog started`);
613
+ }
614
+ catch (err) {
615
+ lCore.log({}, `WATCHDOG_START_FAILED ${lText.stringifyError(err)}`, '-monitor');
616
+ lCore.display('[MONITOR] Failed to start watchdog', err);
617
+ retryWd();
618
+ }
619
+ }
620
+ /**
621
+ * --- 看门狗异常退出后延迟重启 ---
622
+ */
623
+ function retryWd() {
624
+ if (!timer || wd || wdRetryTimer) {
625
+ return;
705
626
  }
706
- const percent = (1 - totalIdle / totalTick) * 100;
707
- return Math.round(Math.max(0, Math.min(100, percent)) * 100) / 100;
627
+ wdRetryTimer = setTimeout(() => {
628
+ wdRetryTimer = null;
629
+ startWd();
630
+ }, WD_RETRY_MS);
631
+ wdRetryTimer.unref();
708
632
  }
709
633
  /**
710
- * --- 独立保存 Report/Profile/HeapSnapshot,单项失败不阻止其他采集 ---
634
+ * --- 依次执行 Report、CPU Profile 与堆快照采集,单项失败不阻塞后续项 ---
711
635
  * @param dir 诊断目录
712
- * @param ts 唯一采集时间标识
713
- * @param hasCpuSpike 是否需要 CPU Profile
714
- * @param collectHeapSnapshot 是否采集堆快照
715
- * @param result 写入事件摘要的采集结果
636
+ * @param ts 唯一时间标识
637
+ * @param needCpu 是否采集 CPU Profile
638
+ * @param needHeap 是否采集堆快照
639
+ * @param res 采集结果对象
716
640
  * @param view 本次监控实例的共享内存
717
- * @returns 无返回值,失败原因保留在 result 中
718
641
  */
719
- async function collectDiagnostics(dir, ts, hasCpuSpike, collectHeapSnapshot, result, view) {
642
+ async function runDiag(dir, ts, needCpu, needHeap, res, view) {
720
643
  try {
721
644
  if (!await lFs.mkdir(dir, 0o700) || !await lFs.chmod(dir, 0o700)) {
722
- result.status = 'failed';
723
- result.errors.push('Failed to create or secure diagnostic directory.');
645
+ res.status = 'failed';
646
+ res.errors.push('Failed to create or secure diagnostic directory.');
724
647
  return;
725
648
  }
726
- if (view !== heartbeatView) {
727
- result.status = 'cancelled';
649
+ if (view !== shm) {
650
+ res.status = 'cancelled';
728
651
  return;
729
652
  }
730
- const reportPath = `${dir}report-${ts}.json`;
731
- try {
732
- // --- 同步诊断本身的阻塞不作为业务异常;Worker 在这段时间只保留采样 ---
733
- diagnosticOverhead = true;
734
- if (view) {
735
- Atomics.store(view, 3, 1n);
736
- }
737
- const report = process.report.getReport();
738
- if (report.header) {
739
- report.header.commandLine = [];
740
- delete report.header.networkInterfaces;
741
- }
742
- delete report.environmentVariables;
743
- for (const handle of report.libuv ?? []) {
744
- delete handle.localEndpoint;
745
- delete handle.remoteEndpoint;
746
- }
747
- if (view) {
748
- Atomics.store(view, 0, BigInt(clockMs()));
749
- Atomics.store(view, 3, 0n);
750
- }
751
- if (await lFs.putContent(reportPath, lText.stringifyJson(report, 2), { 'mode': 0o600 }) &&
752
- await lFs.chmod(reportPath, 0o600)) {
753
- result.files.push(reportPath);
653
+ // --- 1. 采集脱敏后的诊断报告 ---
654
+ await writeReport(dir, ts, res, view);
655
+ // --- 2. 采集 CPU Profile ---
656
+ if (needCpu) {
657
+ if (await runProfile(dir, ts, res)) {
658
+ res.files.push(`${dir}cpu-${ts}.cpuprofile`);
754
659
  }
755
660
  else {
756
- result.errors.push('Failed to write or secure diagnostic report.');
661
+ res.errors.push('CPU profile collection failed.');
757
662
  }
758
663
  }
759
- catch (error) {
760
- result.errors.push(`Report: ${lText.stringifyError(error)}`);
664
+ if (view !== shm) {
665
+ res.status = 'cancelled';
666
+ return;
761
667
  }
762
- finally {
763
- if (view) {
764
- Atomics.store(view, 0, BigInt(clockMs()));
765
- Atomics.store(view, 3, 0n);
766
- }
668
+ // --- 3. 按可用内存条件采集堆快照 ---
669
+ if (needHeap) {
670
+ await writeHeap(dir, ts, res, view);
767
671
  }
768
- if (hasCpuSpike) {
769
- if (await collectCpuProfile(dir, ts, result)) {
770
- result.files.push(`${dir}cpu-${ts}.cpuprofile`);
771
- }
772
- else {
773
- result.errors.push('CPU profile collection failed.');
774
- }
672
+ res.status = res.errors.length ? 'partial' : 'complete';
673
+ }
674
+ catch (err) {
675
+ res.status = 'failed';
676
+ res.errors.push(lText.stringifyError(err));
677
+ }
678
+ }
679
+ /**
680
+ * --- 采集脱敏后的 Node.js 诊断报告 ---
681
+ * @param dir 诊断目录
682
+ * @param ts 时间标识
683
+ * @param res 采集结果
684
+ * @param view 共享内存视图
685
+ */
686
+ async function writeReport(dir, ts, res, view) {
687
+ const file = `${dir}report-${ts}.json`;
688
+ try {
689
+ diagSkip = true;
690
+ if (view) {
691
+ Atomics.store(view, SLOT_DIAG, 1n);
775
692
  }
776
- if (view !== heartbeatView) {
777
- result.status = 'cancelled';
778
- return;
693
+ const report = process.report.getReport();
694
+ if (report.header) {
695
+ report.header.commandLine = [];
696
+ delete report.header.networkInterfaces;
779
697
  }
780
- if (collectHeapSnapshot) {
781
- // --- 堆快照会额外使用约两倍堆内存,不在剩余内存明显不足时尝试 ---
782
- const constrained = process.constrainedMemory();
783
- const available = constrained > 0
784
- ? Math.min(os.freemem(), Math.max(0, constrained - process.memoryUsage.rss()))
785
- : os.freemem();
786
- if (available < v8.getHeapStatistics().total_heap_size * 2) {
787
- result.errors.push('Heap snapshot skipped: insufficient available memory.');
788
- }
789
- else {
790
- try {
791
- diagnosticOverhead = true;
792
- if (view) {
793
- Atomics.store(view, 3, 1n);
794
- }
795
- const heapFile = v8.writeHeapSnapshot(`${dir}heap-${ts}.heapsnapshot`);
796
- if (view) {
797
- Atomics.store(view, 0, BigInt(clockMs()));
798
- Atomics.store(view, 3, 0n);
799
- }
800
- if (await lFs.chmod(heapFile, 0o600)) {
801
- result.files.push(heapFile);
802
- }
803
- else {
804
- result.errors.push('Failed to secure heap snapshot.');
805
- }
806
- }
807
- catch (error) {
808
- result.errors.push(`Heap snapshot: ${lText.stringifyError(error)}`);
809
- }
810
- finally {
811
- if (view) {
812
- Atomics.store(view, 0, BigInt(clockMs()));
813
- Atomics.store(view, 3, 0n);
814
- }
815
- }
816
- }
698
+ delete report.environmentVariables;
699
+ for (const h of report.libuv ?? []) {
700
+ delete h.localEndpoint;
701
+ delete h.remoteEndpoint;
702
+ }
703
+ if (view) {
704
+ Atomics.store(view, SLOT_HB, BigInt(nowMs()));
705
+ Atomics.store(view, SLOT_DIAG, 0n);
706
+ }
707
+ if (await lFs.putContent(file, lText.stringifyJson(report, 2), { 'mode': 0o600 }) &&
708
+ await lFs.chmod(file, 0o600)) {
709
+ res.files.push(file);
710
+ }
711
+ else {
712
+ res.errors.push('Failed to write or secure diagnostic report.');
817
713
  }
818
- result.status = result.errors.length ? 'partial' : 'complete';
819
714
  }
820
- catch (error) {
821
- result.status = 'failed';
822
- result.errors.push(lText.stringifyError(error));
715
+ catch (err) {
716
+ res.errors.push(`Report: ${lText.stringifyError(err)}`);
717
+ }
718
+ finally {
719
+ if (view) {
720
+ Atomics.store(view, SLOT_HB, BigInt(nowMs()));
721
+ Atomics.store(view, SLOT_DIAG, 0n);
722
+ }
823
723
  }
824
724
  }
825
725
  /**
826
- * --- 由 Worker 定时采集主线程 Profile,主线程再次阻塞也能按时停止并落盘 ---
726
+ * --- 剩余内存充足时采集 V8 堆快照 ---
827
727
  * @param dir 诊断目录
828
- * @param ts 唯一采集时间标识
829
- * @param result 接收 Worker 的文件和失败原因
830
- * @returns 是否保存成功;无可用 Worker、超时或监控停止时返回 false
728
+ * @param ts 时间标识
729
+ * @param res 采集结果
730
+ * @param view 共享内存视图
831
731
  */
832
- function collectCpuProfile(dir, ts, result) {
833
- if (profiling || !watchdog) {
732
+ async function writeHeap(dir, ts, res, view) {
733
+ // --- 堆快照约需额外两倍堆内存,剩余内存不足时跳过 ---
734
+ const cgroup = process.constrainedMemory();
735
+ const free = cgroup > 0
736
+ ? Math.min(os.freemem(), Math.max(0, cgroup - process.memoryUsage.rss()))
737
+ : os.freemem();
738
+ if (free < v8.getHeapStatistics().total_heap_size * 2) {
739
+ res.errors.push('Heap snapshot skipped: insufficient available memory.');
740
+ return;
741
+ }
742
+ try {
743
+ diagSkip = true;
744
+ if (view) {
745
+ Atomics.store(view, SLOT_DIAG, 1n);
746
+ }
747
+ const file = v8.writeHeapSnapshot(`${dir}heap-${ts}.heapsnapshot`);
748
+ if (view) {
749
+ Atomics.store(view, SLOT_HB, BigInt(nowMs()));
750
+ Atomics.store(view, SLOT_DIAG, 0n);
751
+ }
752
+ if (await lFs.chmod(file, 0o600)) {
753
+ res.files.push(file);
754
+ }
755
+ else {
756
+ res.errors.push('Failed to secure heap snapshot.');
757
+ }
758
+ }
759
+ catch (err) {
760
+ res.errors.push(`Heap snapshot: ${lText.stringifyError(err)}`);
761
+ }
762
+ finally {
763
+ if (view) {
764
+ Atomics.store(view, SLOT_HB, BigInt(nowMs()));
765
+ Atomics.store(view, SLOT_DIAG, 0n);
766
+ }
767
+ }
768
+ }
769
+ /**
770
+ * --- 通知看门狗采集主线程 CPU Profile 并等待完成 ---
771
+ * @param dir 诊断目录
772
+ * @param ts 时间标识
773
+ * @param res 采集结果
774
+ * @returns 是否保存成功
775
+ */
776
+ function runProfile(dir, ts, res) {
777
+ if (profBusy || !wd) {
834
778
  return Promise.resolve(false);
835
779
  }
836
- const worker = watchdog;
837
- profiling = true;
780
+ const worker = wd;
781
+ profBusy = true;
838
782
  const file = `cpu-${ts}.cpuprofile`;
839
783
  return new Promise((resolve) => {
840
- let finished = false;
841
- const onMessage = (message) => {
842
- if (message.type === 'profile' && message.file === file) {
843
- result.errors.push(...message.errors);
844
- if (message.recorded) {
845
- result.files.push(`${dir}profile-${ts}.json`);
784
+ let done = false;
785
+ const onMsg = (msg) => {
786
+ if (msg.type === 'profile' && msg.file === file) {
787
+ res.errors.push(...msg.errors);
788
+ if (msg.recorded) {
789
+ res.files.push(`${dir}profile-${ts}.json`);
846
790
  }
847
- finish(message.saved);
791
+ finish(msg.saved);
848
792
  }
849
793
  };
850
794
  const onExit = () => {
851
- result.errors.push('Profile aborted because the watchdog exited.');
795
+ res.errors.push('Profile aborted because the watchdog exited.');
852
796
  finish(false);
853
797
  };
854
- const timeout = setTimeout(() => {
855
- result.errors.push('Profile Worker response timed out.');
798
+ const t = setTimeout(() => {
799
+ res.errors.push('Profile Worker response timed out.');
856
800
  finish(false);
857
- }, PROFILE_DURATION + 15_000);
858
- /**
859
- * --- 正常响应、退出和超时共享清理,旧 Worker 不会继续持有监听器 ---
860
- * @param saved 是否保存成功
861
- * @returns 无返回值
862
- */
801
+ }, PROFILE_MS + 15_000);
802
+ /** --- 正常响应、退出与超时共用清理入口 --- */
863
803
  function finish(saved) {
864
- if (finished) {
804
+ if (done) {
865
805
  return;
866
806
  }
867
- finished = true;
868
- clearTimeout(timeout);
869
- worker.off('message', onMessage);
807
+ done = true;
808
+ clearTimeout(t);
809
+ worker.off('message', onMsg);
870
810
  worker.off('exit', onExit);
871
- profiling = false;
811
+ profBusy = false;
872
812
  resolve(saved);
873
813
  }
874
- worker.on('message', onMessage);
814
+ worker.on('message', onMsg);
875
815
  worker.once('exit', onExit);
876
816
  try {
877
- worker.postMessage({ 'type': 'profile', dir, ts });
817
+ worker.postMessage({
818
+ 'type': 'profile',
819
+ 'dir': dir,
820
+ 'ts': ts,
821
+ });
878
822
  }
879
- catch (error) {
880
- lCore.display('[MONITOR] Failed to request CPU profile:', error);
823
+ catch (err) {
824
+ lCore.display('[MONITOR] Failed to request CPU profile:', err);
881
825
  finish(false);
882
826
  }
883
827
  });
884
828
  }
829
+ // ====================
830
+ // --- 内部工具函数 ---
831
+ // ====================
832
+ /**
833
+ * --- 检测当前是否处于调试模式 ---
834
+ */
835
+ function isDebug() {
836
+ return !!inspector.url();
837
+ }
838
+ /**
839
+ * --- 获取单调时钟毫秒数 ---
840
+ */
841
+ function nowMs() {
842
+ return Number(process.hrtime.bigint() / 1000000n);
843
+ }
844
+ /**
845
+ * --- 计算单个请求存续期间的进程资源增量 ---
846
+ * @param req 活跃请求
847
+ * @param now 当前时间戳(ms)
848
+ * @param cpu 当前进程 CPU 累计用量
849
+ * @param rss 当前进程 RSS
850
+ */
851
+ function snapReq(req, now, cpu, rss) {
852
+ return {
853
+ 'url': req.url,
854
+ 'method': req.method,
855
+ 'duration': now - req.start,
856
+ 'cpuUser': cpu.user - req.startCpu.user,
857
+ 'cpuSystem': cpu.system - req.startCpu.system,
858
+ 'memDelta': rss - req.startMem,
859
+ };
860
+ }
861
+ /**
862
+ * --- 裁剪最近完成请求列表(最多保留 60 秒且不超过 MAX_REQS 条) ---
863
+ * @param now 当前时间戳(ms)
864
+ */
865
+ function trimRecent(now) {
866
+ while (recent.length > MAX_REQS || (recent.length && now - (recent[0].completedAt ?? 0) > 60_000)) {
867
+ recent.shift();
868
+ }
869
+ }
870
+ /**
871
+ * --- 组装当前完整资源快照 ---
872
+ * @param cpuProc 本周期进程 CPU 占比
873
+ * @param cpuOs 本周期系统 CPU 占比
874
+ */
875
+ function buildSnap(cpuProc, cpuOs) {
876
+ const mem = process.memoryUsage();
877
+ const heap = v8.getHeapStatistics();
878
+ const cpu = process.cpuUsage();
879
+ const now = Date.now();
880
+ let eloopLag = 0;
881
+ let eloopMax = 0;
882
+ if (eloop) {
883
+ eloopLag = Math.round(eloop.percentile(99) / 1_000_000);
884
+ eloopMax = Math.round(eloop.max / 1_000_000);
885
+ }
886
+ const active = [];
887
+ for (const req of reqs.values()) {
888
+ if (active.length >= MAX_REQS) {
889
+ break;
890
+ }
891
+ active.push(snapReq(req, now, cpu, mem.rss));
892
+ }
893
+ trimRecent(now);
894
+ return {
895
+ 'pid': process.pid,
896
+ 'time': now,
897
+ 'cpuProcess': Math.round(cpuProc * 100) / 100,
898
+ 'cpuOs': cpuOs,
899
+ 'mem': {
900
+ 'rss': mem.rss,
901
+ 'heapTotal': mem.heapTotal,
902
+ 'heapUsed': mem.heapUsed,
903
+ 'external': mem.external,
904
+ 'arrayBuffers': mem.arrayBuffers,
905
+ },
906
+ 'heap': {
907
+ 'totalSize': heap.total_heap_size,
908
+ 'usedSize': heap.used_heap_size,
909
+ 'sizeLimit': heap.heap_size_limit,
910
+ },
911
+ 'osMem': {
912
+ 'total': os.totalmem(),
913
+ 'free': os.freemem(),
914
+ },
915
+ 'eloopLag': eloopLag,
916
+ 'eloopMax': eloopMax,
917
+ 'activeRequests': active,
918
+ 'activeCount': reqs.size,
919
+ 'recentRequests': [...recent],
920
+ };
921
+ }
922
+ /**
923
+ * --- 通过两次 os.cpus() 采样差值计算系统总 CPU 使用率(0-100) ---
924
+ * @param prev 上次采样
925
+ * @param cur 本次采样
926
+ */
927
+ function calcOsCpu(prev, cur) {
928
+ if (prev?.length !== cur.length) {
929
+ return 0;
930
+ }
931
+ let idle = 0;
932
+ let total = 0;
933
+ for (let i = 0; i < cur.length; ++i) {
934
+ const c = cur[i].times;
935
+ const p = prev[i].times;
936
+ const dIdle = c.idle - p.idle;
937
+ idle += dIdle;
938
+ total += (c.user - p.user) + (c.nice - p.nice) + (c.sys - p.sys) + (c.irq - p.irq) + dIdle;
939
+ }
940
+ if (total <= 0) {
941
+ return 0;
942
+ }
943
+ const pct = (1 - idle / total) * 100;
944
+ return Math.round(Math.max(0, Math.min(100, pct)) * 100) / 100;
945
+ }