trace.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. // trace.js — Phase 2 Full-Detail Frontend Trace Recorder & Offline IndexedDB Spool
  2. // Loaded FIRST before all other scripts. Enabled by default; dynamically synced with backend config.
  3. (() => {
  4. const nativeFetch = window.fetch ? window.fetch.bind(window) : null;
  5. const nativeSendBeacon = navigator.sendBeacon ? navigator.sendBeacon.bind(navigator) : null;
  6. const nativeConsoleError = console.error ? console.error.bind(console) : () => {};
  7. const nativeConsoleWarn = console.warn ? console.warn.bind(console) : () => {};
  8. const SESSION_ID = `fe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
  9. const FLUSH_INTERVAL_MS = 2000;
  10. const FLUSH_MAX_EVENTS = 50;
  11. const FLUSH_MAX_BYTES = 65536;
  12. const DB_NAME = 'xjkj_stl_trace_spool';
  13. const DB_STORE = 'batches';
  14. let config = {
  15. enabled: true,
  16. backend_state_diff: true,
  17. backend_rpc_http: true,
  18. backend_serial_stream: true,
  19. backend_hardware_io: true,
  20. frontend_trace: true,
  21. compress_rotated: true,
  22. volume_mb: 50,
  23. retention_days: 30,
  24. min_free_gb: 2,
  25. };
  26. let diskLowPaused = false;
  27. let seq = 0;
  28. let buffer = [];
  29. let bufferBytes = 0;
  30. let flushTimer = null;
  31. let flushing = false;
  32. let idbPromise = null;
  33. let spooledCount = 0;
  34. let recentRing = [];
  35. const RECENT_RING_MAX = 500;
  36. const SECRET_KEY_RE = /^(password|passwd|secret|token|api_token|authorization|cookie|current_password|new_password|bmc_password)$/i;
  37. const SECRET_ELEM_RE = /(password|passwd|secret|token|pw-)/i;
  38. function isActive() {
  39. return !!config.enabled && !!config.frontend_trace && !diskLowPaused;
  40. }
  41. function sanitize(value, depth = 0) {
  42. if (depth > 5) return '[DEPTH_LIMIT]';
  43. if (value === null || value === undefined) return value;
  44. if (typeof value === 'string') {
  45. return value.length > 512 ? value.slice(0, 512) + `...[+${value.length - 512}B]` : value;
  46. }
  47. if (typeof value === 'number' || typeof value === 'boolean') return value;
  48. if (Array.isArray(value)) {
  49. if (value.length > 32) {
  50. return { _type: 'array', length: value.length, sample: value.slice(0, 6).map(v => sanitize(v, depth + 1)) };
  51. }
  52. return value.map(v => sanitize(v, depth + 1));
  53. }
  54. if (typeof value === 'object') {
  55. const out = {};
  56. const entries = Object.entries(value);
  57. for (let i = 0; i < Math.min(entries.length, 40); i++) {
  58. const [k, v] = entries[i];
  59. out[k] = SECRET_KEY_RE.test(k) ? '[REDACTED]' : sanitize(v, depth + 1);
  60. }
  61. if (entries.length > 40) out._truncated_keys = entries.length - 40;
  62. return out;
  63. }
  64. return String(value);
  65. }
  66. function elementDescriptor(el) {
  67. if (!el || el.nodeType !== 1) return '';
  68. const tag = (el.tagName || '').toLowerCase();
  69. const id = el.id ? `#${el.id}` : '';
  70. const name = el.getAttribute?.('name') ? `[name=${el.getAttribute('name')}]` : '';
  71. const dataPage = el.dataset?.page ? `[data-page=${el.dataset.page}]` : '';
  72. const dataAct = el.dataset?.prodAction ? `[data-prod-action=${el.dataset.prodAction}]` : '';
  73. return `${tag}${id}${name}${dataPage}${dataAct}`;
  74. }
  75. function safeElementValue(el) {
  76. if (!el) return undefined;
  77. const type = (el.type || '').toLowerCase();
  78. if (type === 'password' || SECRET_ELEM_RE.test(el.id || '') || SECRET_ELEM_RE.test(el.name || '')) {
  79. return '[REDACTED]';
  80. }
  81. if (type === 'checkbox' || type === 'radio') return !!el.checked;
  82. if (typeof el.value === 'string') {
  83. return el.value.length > 200 ? el.value.slice(0, 200) + '...' : el.value;
  84. }
  85. return undefined;
  86. }
  87. // ---- Dynamic IndexedDB Offline Spool (zero hardcoded 20MB cap) ----
  88. function openIdb() {
  89. if (idbPromise) return idbPromise;
  90. if (!window.indexedDB) return Promise.resolve(null);
  91. idbPromise = new Promise(resolve => {
  92. try {
  93. const req = indexedDB.open(DB_NAME, 1);
  94. req.onupgradeneeded = () => {
  95. const db = req.result;
  96. if (!db.objectStoreNames.contains(DB_STORE)) {
  97. db.createObjectStore(DB_STORE, { keyPath: 'id', autoIncrement: true });
  98. }
  99. };
  100. req.onsuccess = () => resolve(req.result);
  101. req.onerror = () => resolve(null);
  102. } catch (_) {
  103. resolve(null);
  104. }
  105. });
  106. return idbPromise;
  107. }
  108. async function spoolBatchToIdb(events) {
  109. if (!events.length) return;
  110. const db = await openIdb();
  111. if (!db) return;
  112. try {
  113. // Dynamic browser origin quota check (retain up to 25% of available browser storage)
  114. let maxBytes = 64 * 1024 * 1024;
  115. if (navigator.storage?.estimate) {
  116. const est = await navigator.storage.estimate();
  117. if (est && typeof est.quota === 'number' && typeof est.usage === 'number') {
  118. const avail = Math.max(0, est.quota - est.usage);
  119. maxBytes = Math.max(4 * 1024 * 1024, Math.floor(avail * 0.25));
  120. }
  121. }
  122. const payloadStr = JSON.stringify(events);
  123. if (payloadStr.length > maxBytes) return;
  124. await new Promise(resolve => {
  125. const tx = db.transaction(DB_STORE, 'readwrite');
  126. tx.objectStore(DB_STORE).add({ ts_ms: Date.now(), bytes: payloadStr.length, events });
  127. tx.oncomplete = () => { spooledCount += 1; resolve(); };
  128. tx.onerror = () => resolve();
  129. });
  130. } catch (_) {}
  131. }
  132. async function syncSpooledCount() {
  133. const db = await openIdb();
  134. if (!db) return;
  135. try {
  136. spooledCount = await new Promise(resolve => {
  137. const tx = db.transaction(DB_STORE, 'readonly');
  138. const req = tx.objectStore(DB_STORE).count();
  139. req.onsuccess = () => resolve(Number(req.result || 0));
  140. req.onerror = () => resolve(0);
  141. });
  142. } catch (_) {}
  143. }
  144. async function drainIdbSpool() {
  145. if (!isActive() || !nativeFetch) return;
  146. const db = await openIdb();
  147. if (!db) return;
  148. try {
  149. while (true) {
  150. const records = await new Promise(resolve => {
  151. const tx = db.transaction(DB_STORE, 'readonly');
  152. const req = tx.objectStore(DB_STORE).getAll(null, 10);
  153. req.onsuccess = () => resolve(req.result || []);
  154. req.onerror = () => resolve([]);
  155. });
  156. if (!records.length) {
  157. spooledCount = 0;
  158. return;
  159. }
  160. let stopped = false;
  161. for (const rec of records) {
  162. const res = await nativeFetch('/api/trace/frontend', {
  163. method: 'POST',
  164. credentials: 'same-origin',
  165. headers: { 'Content-Type': 'application/json' },
  166. body: JSON.stringify({ events: rec.events }),
  167. });
  168. if (!res.ok) { stopped = true; break; }
  169. await new Promise(resolve => {
  170. const tx = db.transaction(DB_STORE, 'readwrite');
  171. tx.objectStore(DB_STORE).delete(rec.id);
  172. tx.oncomplete = () => resolve();
  173. tx.onerror = () => resolve();
  174. });
  175. spooledCount = Math.max(0, spooledCount - 1);
  176. }
  177. if (stopped || records.length < 10) break;
  178. }
  179. } catch (_) {}
  180. }
  181. async function exportOfflineJsonl() {
  182. const all = [];
  183. const seen = new Set();
  184. const pushUnique = ev => {
  185. if (!ev || typeof ev !== 'object') return;
  186. const key = `${ev.session_id || ''}:${ev.seq || ''}:${ev.ts_ms || ''}`;
  187. if (seen.has(key)) return;
  188. seen.add(key);
  189. all.push(ev);
  190. };
  191. const db = await openIdb();
  192. if (db) {
  193. const records = await new Promise(resolve => {
  194. try {
  195. const tx = db.transaction(DB_STORE, 'readonly');
  196. const req = tx.objectStore(DB_STORE).getAll();
  197. req.onsuccess = () => resolve(req.result || []);
  198. req.onerror = () => resolve([]);
  199. } catch (_) {
  200. resolve([]);
  201. }
  202. });
  203. for (const rec of records) {
  204. if (Array.isArray(rec.events)) rec.events.forEach(pushUnique);
  205. }
  206. }
  207. recentRing.forEach(pushUnique);
  208. const text = all.map(e => JSON.stringify(e)).join('\n') + '\n';
  209. const url = URL.createObjectURL(new Blob([text], { type: 'application/x-ndjson' }));
  210. const a = document.createElement('a');
  211. a.href = url;
  212. a.download = `stl_frontend_offline_${SESSION_ID}.jsonl`;
  213. a.click();
  214. setTimeout(() => URL.revokeObjectURL(url), 10000);
  215. }
  216. // ---- Event Recorder & Batch Uploader ----
  217. function record(kind, payload = {}) {
  218. if (!isActive()) return;
  219. const ev = {
  220. kind,
  221. session_id: SESSION_ID,
  222. seq: ++seq,
  223. ts_ms: Date.now(),
  224. mono_ms: Math.round((performance.now?.() || 0) * 100) / 100,
  225. page: document.body?.dataset?.currentPage || '',
  226. ui_mode: document.body?.dataset?.uiMode || '',
  227. ...sanitize(payload),
  228. };
  229. recentRing.push(ev);
  230. if (recentRing.length > RECENT_RING_MAX) recentRing.shift();
  231. let approxLen = 128;
  232. try { approxLen = JSON.stringify(ev).length; } catch (_) {}
  233. buffer.push(ev);
  234. bufferBytes += approxLen;
  235. if (buffer.length >= FLUSH_MAX_EVENTS || bufferBytes >= FLUSH_MAX_BYTES) {
  236. void flush(false);
  237. } else if (!flushTimer) {
  238. flushTimer = setTimeout(() => {
  239. flushTimer = null;
  240. void flush(false);
  241. }, FLUSH_INTERVAL_MS);
  242. }
  243. }
  244. async function flush(useBeacon = false) {
  245. if (!buffer.length) return;
  246. if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; }
  247. const batch = buffer;
  248. buffer = [];
  249. bufferBytes = 0;
  250. if (!isActive()) return;
  251. const body = JSON.stringify({ events: batch });
  252. if (useBeacon && nativeSendBeacon) {
  253. try {
  254. const blob = new Blob([body], { type: 'application/json' });
  255. if (nativeSendBeacon('/api/trace/frontend', blob)) return;
  256. } catch (_) {}
  257. }
  258. if (!nativeFetch) return;
  259. if (flushing) {
  260. await spoolBatchToIdb(batch);
  261. return;
  262. }
  263. flushing = true;
  264. try {
  265. const res = await nativeFetch('/api/trace/frontend', {
  266. method: 'POST',
  267. credentials: 'same-origin',
  268. headers: { 'Content-Type': 'application/json' },
  269. body,
  270. });
  271. if (!res.ok) {
  272. if (res.status !== 401 && res.status !== 403) {
  273. await spoolBatchToIdb(batch);
  274. }
  275. } else {
  276. const data = await res.json().catch(() => null);
  277. if (data && typeof data.enabled === 'boolean') config.enabled = data.enabled;
  278. if (data && typeof data.disk_low_paused === 'boolean') setDiskLowBanner(data.disk_low_paused);
  279. if (spooledCount > 0) void drainIdbSpool();
  280. }
  281. } catch (_) {
  282. await spoolBatchToIdb(batch);
  283. } finally {
  284. flushing = false;
  285. }
  286. }
  287. // ---- 1. Wrap window.fetch with strict anti-recursion ----
  288. if (nativeFetch) {
  289. window.fetch = async function wrappedFetch(input, init) {
  290. const urlStr = typeof input === 'string' ? input : (input?.url || '');
  291. const skip = !isActive() || urlStr.includes('/api/trace/frontend') || init?.__stlTraceInternal;
  292. if (skip) return nativeFetch(input, init);
  293. const t0 = performance.now();
  294. const method = (init?.method || (typeof input === 'object' && input?.method) || 'GET').toUpperCase();
  295. try {
  296. const res = await nativeFetch(input, init);
  297. record('fe_http', {
  298. method,
  299. url: urlStr,
  300. status: res.status,
  301. ok: res.ok,
  302. duration_ms: Math.round((performance.now() - t0) * 100) / 100,
  303. });
  304. return res;
  305. } catch (err) {
  306. record('fe_http', {
  307. method,
  308. url: urlStr,
  309. status: 0,
  310. ok: false,
  311. error: err?.message || String(err),
  312. duration_ms: Math.round((performance.now() - t0) * 100) / 100,
  313. });
  314. throw err;
  315. }
  316. };
  317. }
  318. // ---- 2. Global Error & Console Interceptors ----
  319. window.addEventListener('error', ev => {
  320. record('fe_error', {
  321. source: 'window.error',
  322. message: ev.message || '',
  323. filename: ev.filename || '',
  324. lineno: ev.lineno || 0,
  325. colno: ev.colno || 0,
  326. });
  327. }, true);
  328. window.addEventListener('unhandledrejection', ev => {
  329. const r = ev.reason;
  330. record('fe_error', {
  331. source: 'unhandledrejection',
  332. message: r?.message || String(r || ''),
  333. });
  334. });
  335. console.error = (...args) => {
  336. nativeConsoleError(...args);
  337. record('fe_error', { source: 'console.error', args: args.map(a => String(a)).slice(0, 6) });
  338. };
  339. console.warn = (...args) => {
  340. nativeConsoleWarn(...args);
  341. record('fe_error', { source: 'console.warn', args: args.map(a => String(a)).slice(0, 6) });
  342. };
  343. // ---- 3. Capture-Phase UI Action Listeners ----
  344. document.addEventListener('click', ev => {
  345. const t = ev.target?.closest?.('button,a,input,select,[role="button"],summary') || ev.target;
  346. record('ui_action', {
  347. event: 'click',
  348. target: elementDescriptor(t),
  349. text: (t?.textContent || '').trim().slice(0, 80),
  350. value: safeElementValue(t),
  351. });
  352. }, true);
  353. document.addEventListener('change', ev => {
  354. const t = ev.target;
  355. record('ui_action', {
  356. event: 'change',
  357. target: elementDescriptor(t),
  358. value: safeElementValue(t),
  359. });
  360. }, true);
  361. document.addEventListener('submit', ev => {
  362. record('ui_action', {
  363. event: 'submit',
  364. target: elementDescriptor(ev.target),
  365. });
  366. }, true);
  367. document.addEventListener('keydown', ev => {
  368. if (ev.key === 'Enter' || ev.key === 'Escape') {
  369. record('ui_action', {
  370. event: 'keydown',
  371. key: ev.key,
  372. target: elementDescriptor(ev.target),
  373. });
  374. }
  375. }, true);
  376. window.addEventListener('hashchange', () => {
  377. record('ui_action', { event: 'hashchange', hash: location.hash });
  378. });
  379. document.addEventListener('visibilitychange', () => {
  380. record('ui_action', { event: 'visibilitychange', state: document.visibilityState });
  381. if (document.visibilityState === 'hidden') void flush(true);
  382. });
  383. window.addEventListener('pagehide', () => {
  384. record('ui_action', { event: 'pagehide' });
  385. void flush(true);
  386. });
  387. // ---- 4. Disk-Low Alert Banner & Trace Config UI Manager ----
  388. function setDiskLowBanner(paused, message = '') {
  389. diskLowPaused = !!paused;
  390. const banner = document.getElementById('trace-disk-low-banner');
  391. if (!banner) return;
  392. if (diskLowPaused) {
  393. banner.textContent = message || `磁盘剩余空间低于 ${config.min_free_gb || 2} GiB,全细节本地日志已自动暂停写入(不影响正常内存测试),清理磁盘空间后自动恢复。`;
  394. banner.classList.remove('hidden');
  395. } else {
  396. banner.classList.add('hidden');
  397. }
  398. }
  399. function applyConfig(nextCfg) {
  400. if (!nextCfg || typeof nextCfg !== 'object') return;
  401. config = { ...config, ...nextCfg };
  402. syncConfigForm();
  403. }
  404. function syncConfigForm() {
  405. const $ = id => document.getElementById(id);
  406. if (!$('trace-enabled-toggle')) return;
  407. $('trace-enabled-toggle').checked = !!config.enabled;
  408. if ($('trace-sub-state')) $('trace-sub-state').checked = !!config.backend_state_diff;
  409. if ($('trace-sub-rpc')) $('trace-sub-rpc').checked = !!config.backend_rpc_http;
  410. if ($('trace-sub-serial')) $('trace-sub-serial').checked = !!config.backend_serial_stream;
  411. if ($('trace-sub-hw')) $('trace-sub-hw').checked = !!config.backend_hardware_io;
  412. if ($('trace-sub-fe')) $('trace-sub-fe').checked = !!config.frontend_trace;
  413. if ($('trace-sub-compress')) $('trace-sub-compress').checked = !!config.compress_rotated;
  414. if ($('trace-vol-mb')) $('trace-vol-mb').value = String(config.volume_mb ?? 50);
  415. if ($('trace-ret-days')) $('trace-ret-days').value = String(config.retention_days ?? 30);
  416. if ($('trace-min-free-gb')) $('trace-min-free-gb').value = String(config.min_free_gb ?? 2);
  417. const badge = $('trace-status-badge');
  418. if (badge) {
  419. badge.textContent = diskLowPaused ? '空间不足暂停' : (config.enabled ? '全细节落盘运行中' : '已关闭');
  420. badge.classList.toggle('connected', !!config.enabled && !diskLowPaused);
  421. badge.classList.toggle('error', diskLowPaused);
  422. }
  423. }
  424. async function refreshTraceStatus() {
  425. if (!nativeFetch) return;
  426. try {
  427. const res = await nativeFetch('/api/trace/status', { credentials: 'same-origin', cache: 'no-store' });
  428. if (!res.ok) return;
  429. const st = await res.json();
  430. if (st.config) applyConfig(st.config);
  431. setDiskLowBanner(!!st.disk_low_paused);
  432. const line = document.getElementById('trace-metrics-line');
  433. if (line) {
  434. const mb = ((Number(st.written_bytes || 0)) / (1024 * 1024)).toFixed(2);
  435. const serMb = ((Number(st.serial_bytes_written || 0)) / (1024 * 1024)).toFixed(2);
  436. line.textContent = `当日目录: ${st.today || '-'} · 累计事件 ${st.written_events || 0} 条 · 已落盘 ${mb} MiB (原始串口 ${serMb} MiB) · 前端入库 ${st.frontend_events_ingested || 0} 条 · 丢弃 ${st.dropped_events || 0} · 分区可用 ${st.free_disk_gib ?? '--'} GiB · 浏览器离线队列 ${spooledCount} 批`;
  437. }
  438. const hwRes = await nativeFetch('/api/hw/info', { credentials: 'same-origin', cache: 'no-store' });
  439. if (hwRes.ok) {
  440. const hw = await hwRes.json();
  441. window.stlStore?.set?.('hwInfo', hw, 'hw_poll');
  442. const badge = document.getElementById('hw-tier-badge');
  443. if (badge) badge.textContent = hw.tier_name || `Tier ${hw.isa_tier ?? 0}`;
  444. const cpuEl = document.getElementById('hw-cpu-line');
  445. if (cpuEl) {
  446. const flags = [
  447. hw.has_ssse3 && 'SSSE3',
  448. hw.has_sse42 && 'SSE4.2',
  449. hw.has_popcnt && 'POPCNT',
  450. hw.has_pclmul && 'PCLMULQDQ',
  451. hw.has_aesni && 'AES-NI',
  452. hw.has_shani && 'SHA-NI',
  453. hw.has_avx2 && 'AVX2',
  454. hw.has_bmi2 && 'BMI2',
  455. hw.has_vpclmul && 'VPCLMULQDQ',
  456. hw.has_gfni && 'GFNI',
  457. hw.has_avx512 && 'AVX-512',
  458. ].filter(Boolean).join(' · ') || 'SSE2';
  459. cpuEl.textContent = `CPU: ${hw.cpu_brand || 'x86_64'} (${hw.physical_cores || '?'} 线程) · 激活档位: ${hw.tier_name || hw.isa_tier} · 硬件指令集: ${flags}`;
  460. }
  461. const gpuEl = document.getElementById('hw-gpu-line');
  462. if (gpuEl) {
  463. const g = hw.opencl_igpu || {};
  464. const sKb = Math.round(Number(g.break_even_bytes || 524288) / 1024);
  465. gpuEl.textContent = g.available
  466. ? `OpenCL 核显: ${g.device_name} (${g.compute_units || 0} EU · 零拷贝LLC=${g.zero_copy_llc ? '是' : '否'}) · 标定阈值 S*=${sKb} KiB (GPU ${g.calibrated_gpu_us || 0}us vs CPU ${g.calibrated_cpu_us || 0}us) · GPU 分流 ${g.gpu_offload_count || 0} 次 / CPU SIMD ${g.cpu_fallback_count || 0} 次`
  467. : `OpenCL 核显: 未检测到 OpenCL GPU ICD,大批量任务自动走 CPU 多档 SIMD 兜底 (S*=${sKb} KiB · CPU SIMD 执行 ${g.cpu_fallback_count || 0} 次)`;
  468. }
  469. }
  470. } catch (_) {}
  471. }
  472. async function saveTraceConfigFromUi() {
  473. if (!nativeFetch) return;
  474. const $ = id => document.getElementById(id);
  475. const patch = {
  476. enabled: !!$('trace-enabled-toggle')?.checked,
  477. backend_state_diff: !!$('trace-sub-state')?.checked,
  478. backend_rpc_http: !!$('trace-sub-rpc')?.checked,
  479. backend_serial_stream: !!$('trace-sub-serial')?.checked,
  480. backend_hardware_io: !!$('trace-sub-hw')?.checked,
  481. frontend_trace: !!$('trace-sub-fe')?.checked,
  482. compress_rotated: !!$('trace-sub-compress')?.checked,
  483. volume_mb: Math.max(1, Number($('trace-vol-mb')?.value || 50)),
  484. retention_days: Math.max(1, Number($('trace-ret-days')?.value || 30)),
  485. min_free_gb: Math.max(0, Number($('trace-min-free-gb')?.value ?? 2)),
  486. };
  487. const res = await nativeFetch('/api/trace/config', {
  488. method: 'POST',
  489. credentials: 'same-origin',
  490. headers: { 'Content-Type': 'application/json' },
  491. body: JSON.stringify(patch),
  492. });
  493. if (res.ok) {
  494. const st = await res.json().catch(() => null);
  495. if (st?.config) applyConfig(st.config);
  496. setDiskLowBanner(!!st?.disk_low_paused);
  497. await refreshTraceStatus();
  498. const note = $('trace-save-note');
  499. if (note) note.textContent = `已生效(${patch.enabled ? '开启' : '已关闭'} · 无需重启)`;
  500. }
  501. }
  502. // ---- 5. Hook Store, WebSocket Transport, UI Alert MutationObserver & Periodic Perf ----
  503. function wireRuntimeHooks() {
  504. // Store state_diff + initial state_snapshot
  505. if (window.stlStore?.subscribe) {
  506. let diffCount = 0;
  507. record('fe_state_snapshot', {
  508. trigger: 'init',
  509. uiMode: window.stlStore.get('uiMode'),
  510. page: window.stlStore.get('page'),
  511. stationId: window.stlStore.get('stationId'),
  512. connected: window.stlStore.get('connected'),
  513. });
  514. window.stlStore.subscribe(({ path, prev, next, trigger }) => {
  515. if (!isActive()) return;
  516. const summarizeVal = (p, v) => {
  517. if (p === 'stations' && Array.isArray(v)) {
  518. return v.map(s => `${s.station_id}:${s.task_status}:${s.verdict}:${s.fault_code || ''}`).join('|');
  519. }
  520. if (p.startsWith('controlByStation.')) {
  521. return v ? `${v.task_status || ''}:${v.verdict || ''}:${v.firmware?.observed_phase || ''}:${v.watchdog?.fault_code || ''}` : '';
  522. }
  523. if (p.startsWith('diagnosticsByStation.')) {
  524. return v ? `${v.state || ''}:${v.bytes_received || 0}` : '';
  525. }
  526. return sanitize(v);
  527. };
  528. const oldS = summarizeVal(path, prev);
  529. const newS = summarizeVal(path, next);
  530. if (JSON.stringify(oldS) === JSON.stringify(newS)) return;
  531. diffCount += 1;
  532. record('fe_state_diff', { path, old: oldS, new: newS, trigger });
  533. if (diffCount % 200 === 0) {
  534. record('fe_state_snapshot', {
  535. trigger: 'periodic',
  536. uiMode: window.stlStore.get('uiMode'),
  537. page: window.stlStore.get('page'),
  538. stationId: window.stlStore.get('stationId'),
  539. connected: window.stlStore.get('connected'),
  540. stationCount: (window.stlStore.get('stations') || []).length,
  541. });
  542. }
  543. });
  544. }
  545. // Wrap WebSocket RPC calls
  546. if (window.stlTransport?.call && !window.stlTransport.__traceWrapped) {
  547. const origCall = window.stlTransport.call;
  548. window.stlTransport.__traceWrapped = true;
  549. window.stlTransport.call = async function tracedCall(method, params, timeoutMs) {
  550. const isNoisyPoll = method === 'ReadCleanedUart' || method === 'GetThermalConsole';
  551. const t0 = performance.now();
  552. try {
  553. const res = await origCall(method, params, timeoutMs);
  554. if (!isNoisyPoll) {
  555. record('fe_ws', {
  556. method,
  557. ok: true,
  558. duration_ms: Math.round((performance.now() - t0) * 100) / 100,
  559. params: sanitize(params),
  560. });
  561. }
  562. return res;
  563. } catch (err) {
  564. record('fe_ws', {
  565. method,
  566. ok: false,
  567. code: err?.code || 'ERR',
  568. error: err?.message || String(err),
  569. duration_ms: Math.round((performance.now() - t0) * 100) / 100,
  570. params: sanitize(params),
  571. });
  572. throw err;
  573. }
  574. };
  575. }
  576. window.addEventListener('stl:transport-state', ev => {
  577. const d = ev.detail || {};
  578. record('fe_ws', { event: 'transport_state', state: d.state, generation: d.generation, pending: d.pending });
  579. if (d.state === 'open') {
  580. void refreshTraceStatus();
  581. void drainIdbSpool();
  582. }
  583. });
  584. window.addEventListener('stl:server-event', ev => {
  585. const msg = ev.detail || {};
  586. if (msg.event === 'trace_config_changed' && msg.result) {
  587. applyConfig(msg.result);
  588. return;
  589. }
  590. if (msg.event === 'trace_disk_low' && msg.result) {
  591. setDiskLowBanner(!!msg.result.paused, msg.result.message || '');
  592. return;
  593. }
  594. if (msg.event === 'task_complete') {
  595. record('fe_ws', { event: 'task_complete', result: sanitize(msg.result) });
  596. }
  597. });
  598. // UI Alert MutationObserver
  599. const obsTargets = ['action-status', 'watchdog-alert-banner', 'dimm-replacement-banner'];
  600. const mo = new MutationObserver(muts => {
  601. for (const m of muts) {
  602. const el = m.target.nodeType === 1 ? m.target : m.target.parentElement;
  603. if (!el) continue;
  604. const txt = (el.textContent || '').trim().slice(0, 240);
  605. record('fe_ui_alert', {
  606. target: elementDescriptor(el),
  607. hidden: el.classList?.contains('hidden') || false,
  608. alert_kind: el.dataset?.alertKind || '',
  609. text: txt,
  610. });
  611. }
  612. });
  613. for (const tid of obsTargets) {
  614. const node = document.getElementById(tid);
  615. if (node) mo.observe(node, { childList: true, characterData: true, subtree: true, attributes: true, attributeFilter: ['class', 'data-alert-kind'] });
  616. }
  617. // Bind Trace Management Panel buttons in Engineering Records page
  618. document.getElementById('btn-trace-save')?.addEventListener('click', () => { void saveTraceConfigFromUi(); });
  619. document.getElementById('btn-trace-refresh')?.addEventListener('click', () => { void refreshTraceStatus(); });
  620. document.getElementById('btn-trace-export-offline')?.addEventListener('click', () => { void exportOfflineJsonl(); });
  621. document.getElementById('btn-trace-download-bundle')?.addEventListener('click', () => {
  622. const sid = document.getElementById('trace-bundle-station')?.value || '';
  623. const url = `/api/trace/bundle${sid ? '?station_id=' + encodeURIComponent(sid) : ''}`;
  624. const a = document.createElement('a');
  625. a.href = url;
  626. a.download = '';
  627. a.click();
  628. });
  629. // Periodic 30s fe_perf snapshot
  630. setInterval(() => {
  631. if (!isActive()) return;
  632. const mem = performance.memory ? {
  633. used_mb: Math.round(performance.memory.usedJSHeapSize / 1048576),
  634. total_mb: Math.round(performance.memory.totalJSHeapSize / 1048576),
  635. } : null;
  636. record('fe_perf', {
  637. dom_nodes: document.getElementsByTagName('*').length,
  638. heap: mem,
  639. spooled_batches: spooledCount,
  640. station_id: window.stlStore?.get('stationId') || '',
  641. });
  642. }, 30000);
  643. void syncSpooledCount().then(() => refreshTraceStatus());
  644. }
  645. window.stlTrace = {
  646. record,
  647. flush,
  648. refreshStatus: refreshTraceStatus,
  649. exportOfflineJsonl,
  650. getConfig: () => ({ ...config }),
  651. isActive,
  652. };
  653. if (document.readyState === 'loading') {
  654. document.addEventListener('DOMContentLoaded', wireRuntimeHooks);
  655. } else {
  656. wireRuntimeHooks();
  657. }
  658. })();