'use strict'; jQuery(function ($) { const $metrics = $('[data-about-metrics]'); if (!$metrics.length) return; const $cpu = $metrics.find('[data-about-cpu]'); const $memory = $metrics.find('[data-about-memory]'); const percent = new Intl.NumberFormat('zh-CN', {style: 'percent', maximumFractionDigits: 1}); let previous = null; let timer = null; let pending = null; let sessionExpired = false; function active() { return $metrics[0].open && !document.hidden && !sessionExpired; } function poll() { timer = null; if (!active()) return; let delay = 5000; pending = $.ajax({url: '/admin/about/metrics', dataType: 'json', timeout: 4000}); pending .done(({cpu, memory}) => { if (!cpu || !previous || cpu.total <= previous.total) { $cpu.text(cpu ? '采样中…' : '暂不可用'); if (cpu) delay = 1000; } else { const total = cpu.total - previous.total; const idle = cpu.idle - previous.idle; $cpu.text(percent.format(Math.max(0, Math.min(1, 1 - idle / total)))); } previous = cpu; $memory.text(memory ?? '暂不可用'); }) .fail(({status}, reason) => { if (reason === 'abort') return; previous = null; sessionExpired = status === 401; const message = sessionExpired ? '登录已过期' : '暂不可用'; $cpu.text(message); $memory.text(message); }) .always(() => { pending = null; if (active()) timer = window.setTimeout(poll, delay); }); } function sync() { if (active()) { if (timer === null && pending === null) { $cpu.text('采样中…'); poll(); } return; } window.clearTimeout(timer); timer = null; previous = null; pending?.abort(); } $metrics.on('toggle', sync); $(document).on('visibilitychange', sync); sync(); });