@maiyunnet/kebab 9.29.6 → 10.0.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 (52) 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 +1522 -1034
  5. package/index.d.ts +12 -1
  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.js +1 -0
  16. package/lib/fs.js +78 -31
  17. package/lib/kv.d.ts +182 -79
  18. package/lib/kv.js +518 -214
  19. package/lib/s3.d.ts +2 -0
  20. package/lib/s3.js +14 -27
  21. package/lib/session.d.ts +7 -0
  22. package/lib/session.js +23 -2
  23. package/lib/socket.d.ts +4 -1
  24. package/lib/socket.js +1 -0
  25. package/lib/sql.d.ts +0 -5
  26. package/lib/sql.js +48 -12
  27. package/lib/text.d.ts +10 -5
  28. package/lib/text.js +22 -12
  29. package/lib/turnstile.d.ts +6 -0
  30. package/lib/turnstile.js +16 -9
  31. package/lib/undici.d.ts +7 -1
  32. package/lib/undici.js +72 -36
  33. package/lib/ws.d.ts +1 -1
  34. package/lib/ws.js +85 -128
  35. package/lib/zip.js +46 -45
  36. package/package.json +2 -2
  37. package/sys/child.js +178 -146
  38. package/sys/cmd.js +196 -197
  39. package/sys/ctr.d.ts +14 -14
  40. package/sys/ctr.js +145 -59
  41. package/sys/master.js +111 -80
  42. package/sys/mod.d.ts +8 -2
  43. package/sys/mod.js +23 -11
  44. package/sys/monitor/files.d.ts +2 -1
  45. package/sys/monitor/files.js +77 -21
  46. package/sys/monitor/watchdog.d.ts +7 -0
  47. package/sys/monitor/watchdog.js +311 -203
  48. package/sys/monitor.d.ts +59 -54
  49. package/sys/monitor.js +742 -681
  50. package/sys/route.d.ts +4 -4
  51. package/sys/route.js +93 -52
  52. package/www/example/ctr/test.js +8 -8
@@ -1,339 +1,447 @@
1
1
  /**
2
2
  * Project: Kebab, User: JianSuoQiYue
3
3
  * Date: 2026-02-08
4
- * Last: 2026-10-05
4
+ * Last: 2026-11-24
5
5
  * --- 独立线程监测主线程心跳,阻塞期间保存资源采样、请求、调用栈和 CPU Profile ---
6
6
  * --- 只依赖 Node.js;主线程无法运行时,日志与 Inspector 超时仍可独立处理 ---
7
7
  */
8
+ // --- 系统 ---
8
9
  import * as workerThreads from 'worker_threads';
9
10
  import * as fs from 'fs';
10
11
  import * as path from 'path';
11
12
  import * as os from 'os';
12
13
  import * as inspector from 'inspector/promises';
13
- const data = workerThreads.workerData;
14
- /** --- 0: 心跳 ms, 1: 调试, 2: Inspector 所有者(0-空闲,1-常规 Profile,2-阻塞 Profile), 3: 同步诊断, 4: 已保存现场的心跳 --- */
15
- const view = new BigInt64Array(data.buffer);
16
- const activeRequests = new Map(data.requests);
17
- const recentRequests = [];
14
+ // --- 共享内存槽位定义(与 sys/monitor.ts 保持一致) ---
15
+ /** --- 槽位 0:主线程单调时钟心跳(ms) --- */
16
+ const SLOT_HB = 0;
17
+ /** --- 槽位 1:调试标志(1 表示调试中) --- */
18
+ const SLOT_DEBUG = 1;
19
+ /** --- 槽位 2:Inspector 锁(0-空闲, 1-常规 Profile, 2-阻塞采集) --- */
20
+ const SLOT_LOCK = 2;
21
+ /** --- 槽位 3:主线程同步诊断标志(1 表示正在同步采集,不判定为阻塞) --- */
22
+ const SLOT_DIAG = 3;
23
+ /** --- 槽位 4:已保存阻塞现场的心跳值 --- */
24
+ const SLOT_SAVED = 4;
25
+ // --- 内部状态 ---
26
+ /** --- 启动时传入的 Worker 配置 --- */
27
+ const cfg = workerThreads.workerData;
28
+ /** --- 共享心跳内存视图 --- */
29
+ const shm = new BigInt64Array(cfg.buffer);
30
+ /** --- 主线程同步过来的活跃请求池 --- */
31
+ const reqs = new Map(cfg.requests);
32
+ /** --- 主线程同步过来的最近完成请求,最多保留 100 条 --- */
33
+ const recent = [];
34
+ /** --- 最近 60 秒的独立资源采样 --- */
18
35
  const samples = [];
19
- let snapshot = null;
20
- let lastAlertHeartbeat = 0n;
21
- let lastAlertTime = 0;
22
- let capturing = false;
36
+ /** --- 主线程最近一次推送的完整快照 --- */
37
+ let lastSnap = null;
38
+ /** --- 上次告警对应的心跳值 --- */
39
+ let lastAlertHb = 0n;
40
+ /** --- 上次告警的单调时钟(ms) --- */
41
+ let lastAlertMs = 0;
42
+ /** --- 是否正在采集阻塞现场 --- */
43
+ let busy = false;
44
+ /** --- 上次采样的进程 CPU 累计用量 --- */
23
45
  let lastCpu = process.cpuUsage();
24
- let lastTime = Number(process.hrtime.bigint() / 1000000n);
25
- workerThreads.parentPort?.on('message', (message) => {
26
- if (message.type === 'snapshot') {
27
- snapshot = message.snapshot;
28
- data.logFormat = message.logFormat;
46
+ /** --- 上次采样的单调时钟(ms) --- */
47
+ let lastMs = nowMs();
48
+ // --- 接收主线程消息 ---
49
+ workerThreads.parentPort?.on('message', (msg) => {
50
+ if (msg.type === 'snapshot') {
51
+ lastSnap = msg.snapshot;
52
+ cfg.logFormat = msg.logFormat;
29
53
  }
30
- else if (message.type === 'request') {
31
- activeRequests.set(message.id, message.request);
54
+ else if (msg.type === 'request') {
55
+ reqs.set(msg.id, msg.request);
32
56
  }
33
- else if (message.type === 'complete') {
34
- activeRequests.delete(message.id);
35
- recentRequests.push(message.request);
36
- if (recentRequests.length > 100) {
37
- recentRequests.shift();
57
+ else if (msg.type === 'complete') {
58
+ reqs.delete(msg.id);
59
+ recent.push(msg.request);
60
+ if (recent.length > 100) {
61
+ recent.shift();
38
62
  }
39
63
  }
40
64
  else {
41
- collectProfile(message.dir, message.ts).catch((error) => {
42
- writeLog(`WATCHDOG: Unexpected profile failure: ${String(error)}`);
65
+ runProfile(msg.dir, msg.ts).catch((err) => {
66
+ writeLog(`WATCHDOG: Unexpected profile failure: ${String(err)}`);
43
67
  });
44
68
  }
45
69
  });
70
+ // --- 启动定时采样与阻塞检测 ---
71
+ setInterval(tick, cfg.interval);
46
72
  /**
47
- * --- 格式化本地时间,用于日志目录和文件名 ---
48
- * @param date 要格式化的时间
49
- * @returns YmdHis 字符串
73
+ * --- 获取单调时钟毫秒数 ---
50
74
  */
51
- function fmtTs(date) {
52
- return String(date.getFullYear()) + String(date.getMonth() + 1).padStart(2, '0') +
53
- String(date.getDate()).padStart(2, '0') + String(date.getHours()).padStart(2, '0') +
54
- String(date.getMinutes()).padStart(2, '0') + String(date.getSeconds()).padStart(2, '0');
75
+ function nowMs() {
76
+ return Number(process.hrtime.bigint() / 1000000n);
55
77
  }
56
78
  /**
57
- * --- 独立写入看门狗日志,格式和字段与 Core.log 一致,失败时保留标准错误输出 ---
58
- * --- 不向主线程转发,也不加载 Core 的控制器、网络等依赖 ---
79
+ * --- 格式化本地时间为 YmdHis,用于目录和文件名 ---
80
+ * @param d 日期对象
81
+ */
82
+ function fmtTs(d) {
83
+ return String(d.getFullYear()) +
84
+ String(d.getMonth() + 1).padStart(2, '0') +
85
+ String(d.getDate()).padStart(2, '0') +
86
+ String(d.getHours()).padStart(2, '0') +
87
+ String(d.getMinutes()).padStart(2, '0') +
88
+ String(d.getSeconds()).padStart(2, '0');
89
+ }
90
+ /**
91
+ * --- 独立写入看门狗日志,格式与 Core.log 一致 ---
59
92
  * @param msg 日志内容
60
- * @returns 无返回值
61
93
  */
62
94
  function writeLog(msg) {
63
95
  const now = new Date();
64
96
  const ts = fmtTs(now);
65
- const dir = path.join(data.logDir, 'system-monitor', ts.slice(0, 4), ts.slice(4, 6), ts.slice(6, 8));
97
+ const dir = path.join(cfg.logDir, 'system-monitor', ts.slice(0, 4), ts.slice(4, 6), ts.slice(6, 8));
66
98
  try {
67
99
  fs.mkdirSync(dir, { 'recursive': true, 'mode': 0o700 });
68
- const format = data.logFormat ?? 'jsonl';
69
- const file = path.join(dir, `${ts.slice(8, 10)}.${format}`);
70
- // --- Worker 没有单个请求上下文;内存使用 MB,保持日志字段可直接展示 ---
100
+ const fmt = cfg.logFormat ?? 'jsonl';
101
+ const file = path.join(dir, `${ts.slice(8, 10)}.${fmt}`);
102
+ // --- 组装日志条目(内存用 MB 方便直接阅读) ---
71
103
  const entry = {
72
104
  'time': `${ts.slice(8, 10)}:${ts.slice(10, 12)}:${ts.slice(12, 14)}`,
73
105
  'unix': Math.floor(now.getTime() / 1000),
74
- 'url': '', 'userAgent': '',
75
- 'realIp': '', 'cfIp': '', 'xIp': '',
106
+ 'url': '',
107
+ 'userAgent': '',
108
+ 'realIp': '',
109
+ 'cfIp': '',
110
+ 'xIp': '',
76
111
  'osMem': `${Math.round((os.totalmem() - os.freemem()) / 1024 / 1024 * 100) / 100}MB`,
77
112
  'procMem': `${Math.round(process.memoryUsage.rss() / 1024 / 1024 * 100) / 100}MB`,
78
113
  'message': msg,
79
114
  };
80
- let content;
81
- if (format === 'jsonl') {
82
- content = JSON.stringify(entry) + '\n';
115
+ // --- 按格式写入日志文件 ---
116
+ let line;
117
+ if (fmt === 'jsonl') {
118
+ line = JSON.stringify(entry) + '\n';
83
119
  }
84
120
  else {
85
121
  if (!fs.existsSync(file)) {
86
122
  fs.writeFileSync(file, 'TIME,UNIX,URL,USER_AGENT,REALIP,CFIP,XIP,OS,PROCESS,MESSAGE\n', { 'mode': 0o600 });
87
123
  }
88
- const fields = [
124
+ const cols = [
89
125
  entry.time, String(entry.unix), entry.url, 'No HTTP_USER_AGENT',
90
126
  entry.realIp, entry.cfIp, entry.xIp, entry.osMem, entry.procMem, entry.message,
91
127
  ];
92
- content = fields.map(field => `"${field.replace(/"/g, '""')}"`).join(',') + '\n';
128
+ line = cols.map(v => `"${v.replace(/"/g, '""')}"`).join(',') + '\n';
93
129
  }
94
- fs.appendFileSync(file, content, { 'mode': 0o600 });
130
+ fs.appendFileSync(file, line, { 'mode': 0o600 });
95
131
  }
96
- catch (error) {
97
- process.stderr.write(`[MONITOR] Watchdog log failed: ${String(error)}\n`);
132
+ catch (err) {
133
+ process.stderr.write(`[MONITOR] Watchdog log failed: ${String(err)}\n`);
98
134
  }
99
135
  }
100
136
  /**
101
- * --- 写入权限受限的诊断文件 ---
137
+ * --- 写入 0600 权限的诊断文件 ---
102
138
  * @param dir 诊断目录
103
139
  * @param name 文件名
104
- * @param content 文件内容
140
+ * @param text 文件内容
105
141
  * @returns 是否保存成功
106
142
  */
107
- function writeFile(dir, name, content) {
143
+ function saveFile(dir, name, text) {
144
+ const file = path.join(dir, name);
108
145
  try {
109
- fs.writeFileSync(path.join(dir, name), content, { 'mode': 0o600 });
110
- fs.chmodSync(path.join(dir, name), 0o600);
146
+ fs.writeFileSync(file, text, { 'mode': 0o600 });
147
+ fs.chmodSync(file, 0o600);
111
148
  return true;
112
149
  }
113
- catch (error) {
114
- process.stderr.write(`[MONITOR] Watchdog diagnostic write failed: ${String(error)}\n`);
150
+ catch (err) {
151
+ process.stderr.write(`[MONITOR] Watchdog diagnostic write failed: ${String(err)}\n`);
115
152
  return false;
116
153
  }
117
154
  }
118
155
  /**
119
- * --- 按主线程请求采集 Profile,开始、停止、超时和文件写入都不依赖主线程事件循环 ---
156
+ * --- 每秒采样资源并检测主线程心跳是否阻塞 ---
157
+ */
158
+ function tick() {
159
+ // --- 记录本周期资源占用和心跳延迟 ---
160
+ const t = nowMs();
161
+ const cpu = process.cpuUsage();
162
+ const dt = t - lastMs;
163
+ const hb = Atomics.load(shm, SLOT_HB);
164
+ const lag = t - Number(hb);
165
+ const cpuPct = dt > 0
166
+ ? (cpu.user - lastCpu.user + cpu.system - lastCpu.system) / (dt * 1_000) * 100
167
+ : 0;
168
+ lastCpu = cpu;
169
+ lastMs = t;
170
+ samples.push({
171
+ 'time': Date.now(),
172
+ 'elapsed': dt,
173
+ 'cpu': Math.round(cpuPct * 100) / 100,
174
+ 'rss': process.memoryUsage.rss(),
175
+ 'heartbeatLag': lag,
176
+ });
177
+ if (samples.length > 60) {
178
+ samples.shift();
179
+ }
180
+ // --- 调试、同步诊断中、未超阈值或处于同一心跳冷却期时跳过 ---
181
+ if (hb <= 0n ||
182
+ lag < cfg.threshold ||
183
+ Atomics.load(shm, SLOT_DEBUG) === 1n ||
184
+ Atomics.load(shm, SLOT_DIAG) === 1n) {
185
+ return;
186
+ }
187
+ if (busy || (hb === lastAlertHb && t - lastAlertMs < cfg.cooldown * 1_000)) {
188
+ return;
189
+ }
190
+ lastAlertHb = hb;
191
+ lastAlertMs = t;
192
+ captureBlocked(lag, hb).catch((err) => {
193
+ writeLog(`WATCHDOG: Unexpected collection failure: ${String(err)}`);
194
+ });
195
+ }
196
+ /**
197
+ * --- 响应主线程请求采集常规 CPU Profile ---
120
198
  * @param dir 主线程已创建的诊断目录
121
199
  * @param ts 唯一采集时间标识
122
- * @returns 无返回值,独立保存结果并通知主线程
123
200
  */
124
- async function collectProfile(dir, ts) {
201
+ async function runProfile(dir, ts) {
125
202
  const file = `cpu-${ts}.cpuprofile`;
126
- const result = { 'file': file, 'saved': false, 'errors': [] };
127
- if (Atomics.compareExchange(view, 2, 0n, 1n) !== 0n) {
128
- result.errors.push('Inspector is already collecting a profile.');
129
- const recorded = writeFile(dir, `profile-${ts}.json`, JSON.stringify(result, null, 2));
130
- workerThreads.parentPort?.postMessage({ 'type': 'profile', ...result, recorded });
203
+ const res = {
204
+ 'file': file,
205
+ 'saved': false,
206
+ 'errors': [],
207
+ };
208
+ // --- 尝试占用 Inspector 锁 ---
209
+ if (Atomics.compareExchange(shm, SLOT_LOCK, 0n, 1n) !== 0n) {
210
+ res.errors.push('Inspector is already collecting a profile.');
211
+ const recorded = saveFile(dir, `profile-${ts}.json`, JSON.stringify(res, null, 2));
212
+ workerThreads.parentPort?.postMessage({
213
+ 'type': 'profile',
214
+ ...res,
215
+ 'recorded': recorded,
216
+ });
131
217
  return;
132
218
  }
219
+ // --- 连接主线程并定时采集 ---
133
220
  const session = new inspector.Session();
134
221
  let timedOut = false;
135
- const timeout = setTimeout(() => {
222
+ const timer = setTimeout(() => {
136
223
  timedOut = true;
137
224
  session.disconnect();
138
- }, data.profileDuration + 10_000);
225
+ }, cfg.profileDuration + 10_000);
139
226
  try {
140
227
  session.connectToMainThread();
141
228
  await session.post('Profiler.enable');
142
229
  await session.post('Profiler.start');
143
- await new Promise(resolve => setTimeout(resolve, data.profileDuration));
230
+ await new Promise(resolve => setTimeout(resolve, cfg.profileDuration));
144
231
  const { profile } = await session.post('Profiler.stop');
145
- result.saved = writeFile(dir, file, JSON.stringify(profile));
146
- if (!result.saved) {
147
- result.errors.push('Failed to save CPU profile.');
232
+ res.saved = saveFile(dir, file, JSON.stringify(profile));
233
+ if (!res.saved) {
234
+ res.errors.push('Failed to save CPU profile.');
148
235
  }
149
236
  }
150
- catch (error) {
151
- result.errors.push(timedOut ? 'Inspector profile collection timed out.' : String(error));
237
+ catch (err) {
238
+ res.errors.push(timedOut ? 'Inspector profile collection timed out.' : String(err));
152
239
  }
153
240
  finally {
154
- clearTimeout(timeout);
241
+ // --- 释放锁并回传结果 ---
242
+ clearTimeout(timer);
155
243
  session.disconnect();
156
- Atomics.compareExchange(view, 2, 1n, 0n);
157
- const recorded = writeFile(dir, `profile-${ts}.json`, JSON.stringify(result, null, 2));
244
+ Atomics.compareExchange(shm, SLOT_LOCK, 1n, 0n);
245
+ const recorded = saveFile(dir, `profile-${ts}.json`, JSON.stringify(res, null, 2));
158
246
  if (!recorded) {
159
247
  writeLog('WATCHDOG: Failed to save CPU profile result.');
160
248
  }
161
- workerThreads.parentPort?.postMessage({ 'type': 'profile', ...result, recorded });
249
+ workerThreads.parentPort?.postMessage({
250
+ 'type': 'profile',
251
+ ...res,
252
+ 'recorded': recorded,
253
+ });
162
254
  }
163
255
  }
164
256
  /**
165
- * --- 保存阻塞现场;暂停后立即恢复,再写磁盘,整个会话有统一超时和释放出口 ---
166
- * @param blockMs 心跳中断时间 ms
167
- * @param heartbeat 这次阻塞前的心跳,用于区分连续阻塞和新事件
168
- * @returns 无返回值,采集结果保留在 blocked-event.json
257
+ * --- 暂停主线程抓取调用栈并立即恢复,再写入栈文件 ---
258
+ * @param session 已连接主线程的 Inspector 会话
259
+ * @param urls 脚本 ID 到 URL 的映射
260
+ * @param dir 诊断目录
261
+ * @param id 事件标识
262
+ * @param lag 阻塞时长(ms)
263
+ * @param now 发生时间
264
+ * @param hb 阻塞前心跳
265
+ * @param rec 事件记录对象
266
+ * @param isTimedOut 检查整体是否已超时
267
+ * @param setPause 注册暂停取消回调
169
268
  */
170
- async function captureDiag(blockMs, heartbeat) {
171
- if (capturing) {
269
+ async function captureStack(session, urls, dir, id, lag, now, hb, rec, isTimedOut, setPause) {
270
+ try {
271
+ await session.post('Debugger.enable');
272
+ const frames = await new Promise((resolve) => {
273
+ setPause(resolve);
274
+ session.once('Debugger.paused', (msg) => {
275
+ resolve(msg.params.callFrames);
276
+ });
277
+ void session.post('Debugger.pause').catch(() => {
278
+ resolve(false);
279
+ });
280
+ });
281
+ if (frames !== false && !isTimedOut()) {
282
+ const lines = frames.map((f, i) => {
283
+ const url = f.url || urls[f.location.scriptId] || '';
284
+ return `#${i} ${f.functionName || '(anonymous)'} (${url}:${f.location.lineNumber + 1}:${(f.location.columnNumber ?? 0) + 1})`;
285
+ });
286
+ await session.post('Debugger.resume');
287
+ const name = `blocked-stack-${id}.txt`;
288
+ const body = `Heartbeat delayed: ${lag}ms\nPID: ${cfg.pid}\nCaptured: ${now.toISOString()}\n\n${lines.join('\n')}\n`;
289
+ if (saveFile(dir, name, body)) {
290
+ rec.files.push(name);
291
+ Atomics.store(shm, SLOT_SAVED, hb);
292
+ }
293
+ else {
294
+ rec.errors.push('Failed to save blocking stack.');
295
+ }
296
+ }
297
+ else {
298
+ rec.errors.push('No blocking stack received before timeout.');
299
+ }
300
+ if (!isTimedOut()) {
301
+ await session.post('Debugger.disable');
302
+ }
303
+ }
304
+ catch (err) {
305
+ rec.errors.push(`Stack: ${String(err)}`);
306
+ // --- 栈采集失败仍恢复主线程,让 CPU Profile 继续完成 ---
307
+ if (!isTimedOut()) {
308
+ await session.post('Debugger.resume').catch(() => undefined);
309
+ await session.post('Debugger.disable').catch(() => undefined);
310
+ }
311
+ }
312
+ }
313
+ /**
314
+ * --- 保存主线程阻塞现场(摘要、调用栈、CPU Profile) ---
315
+ * @param lag 心跳中断时长(ms)
316
+ * @param hb 阻塞前的心跳值
317
+ */
318
+ async function captureBlocked(lag, hb) {
319
+ if (busy) {
172
320
  return;
173
321
  }
174
- capturing = true;
322
+ busy = true;
323
+ // --- 组装当前活跃请求与阻塞事件初始摘要 ---
175
324
  const now = new Date();
176
325
  const ts = fmtTs(now);
177
326
  const id = `${ts}-${now.getTime()}`;
178
- const dir = path.join(data.logDir, 'monitor', ts.slice(0, 4), ts.slice(4, 6), ts.slice(6, 8), `${ts.slice(8)}-pid-${data.pid}-${now.getTime()}-blocked`);
327
+ const dir = path.join(cfg.logDir, 'monitor', ts.slice(0, 4), ts.slice(4, 6), ts.slice(6, 8), `${ts.slice(8)}-pid-${cfg.pid}-${now.getTime()}-blocked`);
179
328
  const cpu = process.cpuUsage();
180
329
  const rss = process.memoryUsage.rss();
181
- const requests = [];
182
- for (const req of activeRequests.values()) {
183
- if (requests.length >= 100) {
330
+ const active = [];
331
+ for (const r of reqs.values()) {
332
+ if (active.length >= 100) {
184
333
  break;
185
334
  }
186
- requests.push({
187
- 'url': req.url, 'method': req.method, 'duration': now.getTime() - req.start,
188
- 'cpuUser': cpu.user - req.startCpu.user, 'cpuSystem': cpu.system - req.startCpu.system,
189
- 'memDelta': rss - req.startMem,
335
+ active.push({
336
+ 'url': r.url,
337
+ 'method': r.method,
338
+ 'duration': now.getTime() - r.start,
339
+ 'cpuUser': cpu.user - r.startCpu.user,
340
+ 'cpuSystem': cpu.system - r.startCpu.system,
341
+ 'memDelta': rss - r.startMem,
190
342
  });
191
343
  }
192
- const record = {
193
- 'pid': data.pid, 'time': now.getTime(), 'heartbeat': Number(heartbeat), 'blockMs': blockMs,
194
- 'samples': [...samples], 'lastMainSnapshot': snapshot, 'activeRequests': requests, 'activeCount': activeRequests.size,
195
- 'recentRequests': recentRequests.filter(req => now.getTime() - (req.completedAt ?? 0) <= 60_000),
196
- 'status': 'pending', 'files': [], 'errors': [],
344
+ const rec = {
345
+ 'pid': cfg.pid,
346
+ 'time': now.getTime(),
347
+ 'heartbeat': Number(hb),
348
+ 'blockMs': lag,
349
+ 'samples': [...samples],
350
+ 'lastMainSnapshot': lastSnap,
351
+ 'activeRequests': active,
352
+ 'activeCount': reqs.size,
353
+ 'recentRequests': recent.filter(r => now.getTime() - (r.completedAt ?? 0) <= 60_000),
354
+ 'status': 'pending',
355
+ 'files': [],
356
+ 'errors': [],
197
357
  };
358
+ // --- 创建目录并先保存初始事件摘要 ---
198
359
  try {
199
360
  fs.mkdirSync(dir, { 'recursive': true, 'mode': 0o700 });
200
361
  fs.chmodSync(dir, 0o700);
201
362
  }
202
- catch (error) {
203
- writeLog(`WATCHDOG: Failed to create diagnostic directory: ${String(error)}`);
204
- capturing = false;
363
+ catch (err) {
364
+ writeLog(`WATCHDOG: Failed to create diagnostic directory: ${String(err)}`);
365
+ busy = false;
205
366
  return;
206
367
  }
207
- if (!writeFile(dir, 'blocked-event.json', JSON.stringify(record, null, 2))) {
208
- capturing = false;
368
+ if (!saveFile(dir, 'blocked-event.json', JSON.stringify(rec, null, 2))) {
369
+ busy = false;
209
370
  return;
210
371
  }
211
- writeLog(`WATCHDOG: Main thread heartbeat delayed ${blockMs}ms, PID:${data.pid}, EVENT:${dir}`);
212
- if (Atomics.compareExchange(view, 2, 0n, 2n) !== 0n) {
213
- record.status = 'skipped-busy';
214
- lastAlertTime = Number(process.hrtime.bigint() / 1000000n) - data.cooldown * 1_000 + 5_000;
215
- record.errors.push('Inspector is already collecting a profile.');
216
- if (!writeFile(dir, 'blocked-event.json', JSON.stringify(record, null, 2))) {
372
+ writeLog(`WATCHDOG: Main thread heartbeat delayed ${lag}ms, PID:${cfg.pid}, EVENT:${dir}`);
373
+ // --- 抢占 Inspector 锁,若已有采集在跑则跳过 ---
374
+ if (Atomics.compareExchange(shm, SLOT_LOCK, 0n, 2n) !== 0n) {
375
+ rec.status = 'skipped-busy';
376
+ lastAlertMs = nowMs() - cfg.cooldown * 1_000 + 5_000;
377
+ rec.errors.push('Inspector is already collecting a profile.');
378
+ if (!saveFile(dir, 'blocked-event.json', JSON.stringify(rec, null, 2))) {
217
379
  writeLog('WATCHDOG: Failed to save Inspector busy result.');
218
380
  }
219
- capturing = false;
381
+ busy = false;
220
382
  return;
221
383
  }
384
+ // --- 建立 Inspector 会话并设置整体超时 ---
222
385
  const session = new inspector.Session();
223
- const scriptUrls = {};
386
+ const urls = {};
224
387
  let timedOut = false;
225
- let finishPause = null;
226
- const timeout = setTimeout(() => {
388
+ let cancelPause = null;
389
+ const timer = setTimeout(() => {
227
390
  timedOut = true;
228
- finishPause?.(false);
229
- // --- 断开会话会使挂起的 post 失败,并释放我们设置的暂停状态 ---
391
+ cancelPause?.(false);
230
392
  session.disconnect();
231
- }, data.profileDuration + 10_000);
232
- session.on('Debugger.scriptParsed', (message) => {
233
- scriptUrls[message.params.scriptId] = message.params.url;
393
+ }, cfg.profileDuration + 10_000);
394
+ session.on('Debugger.scriptParsed', (msg) => {
395
+ urls[msg.params.scriptId] = msg.params.url;
234
396
  });
235
397
  try {
236
398
  session.connectToMainThread();
237
- // --- 先启动 Profile,避免等待调用栈时错过仍在执行的热点 ---
399
+ // --- 先启动 Profile,避免等调用栈期间错过正在执行的热点 ---
238
400
  await session.post('Profiler.enable');
239
401
  await session.post('Profiler.start');
240
- const profileStarted = Number(process.hrtime.bigint() / 1000000n);
241
- try {
242
- await session.post('Debugger.enable');
243
- const frames = await new Promise((resolve) => {
244
- finishPause = resolve;
245
- session.once('Debugger.paused', (message) => { resolve(message.params.callFrames); });
246
- void session.post('Debugger.pause').catch(() => { resolve(false); });
247
- });
248
- if (frames !== false && !timedOut) {
249
- const lines = frames.map((frame, i) => {
250
- const url = frame.url || scriptUrls[frame.location.scriptId] || '';
251
- return `#${i} ${frame.functionName || '(anonymous)'} ` +
252
- `(${url}:${frame.location.lineNumber + 1}:${(frame.location.columnNumber ?? 0) + 1})`;
253
- });
254
- await session.post('Debugger.resume');
255
- const name = `blocked-stack-${id}.txt`;
256
- if (writeFile(dir, name, `Heartbeat delayed: ${blockMs}ms\nPID: ${data.pid}\nCaptured: ${now.toISOString()}\n\n${lines.join('\n')}\n`)) {
257
- record.files.push(name);
258
- Atomics.store(view, 4, heartbeat);
259
- }
260
- else {
261
- record.errors.push('Failed to save blocking stack.');
262
- }
263
- }
264
- else {
265
- record.errors.push('No blocking stack received before timeout.');
266
- }
267
- if (!timedOut) {
268
- await session.post('Debugger.disable');
269
- }
270
- }
271
- catch (error) {
272
- record.errors.push(`Stack: ${String(error)}`);
273
- // --- 栈采集失败仍尝试恢复主线程,CPU Profile 可以独立完成 ---
274
- if (!timedOut) {
275
- await session.post('Debugger.resume').catch(() => undefined);
276
- await session.post('Debugger.disable').catch(() => undefined);
277
- }
278
- }
279
- const remaining = data.profileDuration - (Number(process.hrtime.bigint() / 1000000n) - profileStarted);
280
- if (remaining > 0) {
281
- await new Promise(resolve => setTimeout(resolve, remaining));
402
+ const started = nowMs();
403
+ // --- 抓取阻塞调用栈 ---
404
+ await captureStack(session, urls, dir, id, lag, now, hb, rec, () => timedOut, (fn) => {
405
+ cancelPause = fn;
406
+ });
407
+ // --- 补足剩余 Profile 采集时长并落盘 ---
408
+ const left = cfg.profileDuration - (nowMs() - started);
409
+ if (left > 0) {
410
+ await new Promise(resolve => setTimeout(resolve, left));
282
411
  }
283
412
  const { profile } = await session.post('Profiler.stop');
284
413
  const name = `blocked-cpu-${id}.cpuprofile`;
285
- if (writeFile(dir, name, JSON.stringify(profile))) {
286
- record.files.push(name);
287
- Atomics.store(view, 4, heartbeat);
414
+ if (saveFile(dir, name, JSON.stringify(profile))) {
415
+ rec.files.push(name);
416
+ Atomics.store(shm, SLOT_SAVED, hb);
288
417
  }
289
418
  else {
290
- record.errors.push('Failed to save CPU profile.');
419
+ rec.errors.push('Failed to save CPU profile.');
291
420
  }
292
- record.status = record.errors.length ? 'partial' : 'complete';
421
+ rec.status = rec.errors.length ? 'partial' : 'complete';
293
422
  }
294
- catch (error) {
295
- record.status = record.files.length ? 'partial' : 'failed';
296
- record.errors.push(timedOut ? 'Inspector collection timed out.' : String(error));
423
+ catch (err) {
424
+ rec.status = rec.files.length ? 'partial' : 'failed';
425
+ rec.errors.push(timedOut ? 'Inspector collection timed out.' : String(err));
297
426
  }
298
427
  finally {
299
- clearTimeout(timeout);
428
+ // --- 释放锁、回写最终摘要并通知主线程 ---
429
+ clearTimeout(timer);
300
430
  session.disconnect();
301
- Atomics.compareExchange(view, 2, 2n, 0n);
302
- capturing = false;
303
- if (!writeFile(dir, 'blocked-event.json', JSON.stringify(record, null, 2))) {
304
- record.errors.push('Failed to update event summary.');
305
- record.status = 'partial';
431
+ Atomics.compareExchange(shm, SLOT_LOCK, 2n, 0n);
432
+ busy = false;
433
+ if (!saveFile(dir, 'blocked-event.json', JSON.stringify(rec, null, 2))) {
434
+ rec.errors.push('Failed to update event summary.');
435
+ rec.status = 'partial';
306
436
  }
307
- writeLog(`WATCHDOG: Diagnostic ${record.status}, PID:${data.pid}, EVENT:${dir}`);
308
- workerThreads.parentPort?.postMessage({ 'type': 'diagnostic', 'heartbeat': Number(heartbeat), dir,
309
- 'files': record.files.map(name => path.join(dir, name)), 'errors': record.errors, 'status': record.status });
437
+ writeLog(`WATCHDOG: Diagnostic ${rec.status}, PID:${cfg.pid}, EVENT:${dir}`);
438
+ workerThreads.parentPort?.postMessage({
439
+ 'type': 'diagnostic',
440
+ 'heartbeat': Number(hb),
441
+ 'dir': dir,
442
+ 'files': rec.files.map(name => path.join(dir, name)),
443
+ 'errors': rec.errors,
444
+ 'status': rec.status,
445
+ });
310
446
  }
311
447
  }
312
- // --- 每秒独立采样;新心跳代表新事件,不让上一事件的冷却吞掉下一次阻塞 ---
313
- setInterval(() => {
314
- const time = Number(process.hrtime.bigint() / 1000000n);
315
- const cpu = process.cpuUsage();
316
- const elapsed = time - lastTime;
317
- const heartbeat = Atomics.load(view, 0);
318
- const blockMs = time - Number(heartbeat);
319
- const cpuPercent = elapsed > 0
320
- ? (cpu.user - lastCpu.user + cpu.system - lastCpu.system) / (elapsed * 1_000) * 100 : 0;
321
- lastCpu = cpu;
322
- lastTime = time;
323
- samples.push({ 'time': Date.now(), elapsed, 'cpu': Math.round(cpuPercent * 100) / 100,
324
- 'rss': process.memoryUsage.rss(), 'heartbeatLag': blockMs });
325
- if (samples.length > 60) {
326
- samples.shift();
327
- }
328
- if (heartbeat <= 0n || blockMs < data.threshold || Atomics.load(view, 1) === 1n || Atomics.load(view, 3) === 1n) {
329
- return;
330
- }
331
- if (capturing || heartbeat === lastAlertHeartbeat && time - lastAlertTime < data.cooldown * 1_000) {
332
- return;
333
- }
334
- lastAlertHeartbeat = heartbeat;
335
- lastAlertTime = time;
336
- captureDiag(blockMs, heartbeat).catch((error) => {
337
- writeLog(`WATCHDOG: Unexpected collection failure: ${String(error)}`);
338
- });
339
- }, data.interval);