You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
283 lines
12 KiB
JavaScript
283 lines
12 KiB
JavaScript
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
function versionedModuleUrl(path) {
|
|
const url = new URL(path, import.meta.url);
|
|
url.search = '';
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
return url.href;
|
|
}
|
|
|
|
const {
|
|
api, byId, initializeSession, readBootstrap, showError,
|
|
} = await import(versionedModuleUrl('./runtime.js'));
|
|
|
|
const state = {
|
|
linePools: [], linePoolCount: 0,
|
|
loading: false, controller: null,
|
|
};
|
|
|
|
function element(tag, className = '', content) {
|
|
const node = document.createElement(tag);
|
|
if (className) node.className = className;
|
|
if (content !== undefined) node.textContent = String(content);
|
|
return node;
|
|
}
|
|
|
|
function poolIcon() {
|
|
const wrapper = element('span', 'cloud-traffic-icon');
|
|
const icon = element('i', 'mdi mdi-chart-donut-variant');
|
|
icon.setAttribute('aria-hidden', 'true');
|
|
wrapper.append(icon);
|
|
return wrapper;
|
|
}
|
|
|
|
function formatBytes(value) {
|
|
let amount = Number(value);
|
|
if (!Number.isFinite(amount) || amount < 0) return '暂未提供';
|
|
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
|
let index = 0;
|
|
while (amount >= 1024 && index < units.length - 1) {
|
|
amount /= 1024;
|
|
index += 1;
|
|
}
|
|
const precision = index === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2;
|
|
return `${amount.toFixed(precision)} ${units[index]}`;
|
|
}
|
|
|
|
function formatDate(value, fallback) {
|
|
const raw = Number(value);
|
|
if (!Number.isFinite(raw) || raw <= 0) return fallback;
|
|
return new Date(raw * 1000).toLocaleString('zh-CN', { hour12: false });
|
|
}
|
|
|
|
function poolState(value) {
|
|
return ({
|
|
available: ['可用', 'running'], exhausted: ['已用尽', 'stopped'],
|
|
attention: ['需要核查', 'stopped'], preparing: ['额度准备中', 'warning'],
|
|
})[String(value || '')] || ['状态未知', 'other'];
|
|
}
|
|
|
|
function restrictionState(value) {
|
|
return ({
|
|
clear: ['网络正常', 'running'], applying: ['网络策略应用中', 'warning'],
|
|
restricted: ['已因共享流量耗尽断网', 'stopped'],
|
|
attention: ['网络策略需要人工核查', 'stopped'],
|
|
})[String(value || '')] || ['网络状态未知', 'other'];
|
|
}
|
|
|
|
function linePoolState(value) {
|
|
return ({
|
|
available: ['状态正常', 'running'],
|
|
preparing: ['额度准备中', 'warning'],
|
|
applying: ['网络策略应用中', 'warning'],
|
|
exhausted: ['流量已用尽', 'stopped'],
|
|
restricted: ['线路池已断网', 'stopped'],
|
|
attention: ['需要核查', 'stopped'],
|
|
})[String(value || '')] || ['状态未知', 'other'];
|
|
}
|
|
|
|
function instanceNetwork(value) {
|
|
return ({
|
|
active: ['网络正常', 'running'], blocking: ['正在停用网络', 'warning'],
|
|
blocked_traffic: ['共享流量用尽,已断网', 'stopped'],
|
|
blocked_expired: ['服务到期,已断网', 'stopped'],
|
|
restoring: ['正在恢复网络', 'warning'], restore_pending: ['等待恢复网络', 'warning'],
|
|
})[String(value || '')] || ['状态未知', 'other'];
|
|
}
|
|
|
|
function fact(label, value, note = '') {
|
|
const row = document.createElement('div');
|
|
const dd = element('dd', '', value);
|
|
if (note) dd.append(element('small', '', note));
|
|
row.append(element('dt', '', label), dd);
|
|
return row;
|
|
}
|
|
|
|
function renderInstances(pool, section) {
|
|
const instances = Array.isArray(pool.instances) ? pool.instances : [];
|
|
const heading = element('div', 'cloud-traffic-instances-heading');
|
|
heading.append(element('h4', '', '当前实例采样'), element('span', '', `${instances.length} 台`));
|
|
const list = element('div', 'cloud-traffic-instance-list');
|
|
if (!instances.length) {
|
|
list.append(element('p', 'cloud-traffic-instance-empty',
|
|
'当前没有正在使用该线路池的有效实例;未到期额度仍按原服务周期保留。'));
|
|
}
|
|
for (const instance of instances) {
|
|
const link = element('a', 'cloud-traffic-instance');
|
|
link.href = `/user/cloud/instances/${encodeURIComponent(String(instance.id || ''))}`;
|
|
const identity = document.createElement('div');
|
|
const regionName = String(instance?.region?.name || '').trim() || '地区待核查';
|
|
identity.append(element('strong', '', instance.name || `实例 #${instance.id || ''}`),
|
|
element('small', '', `${regionName} · 到期 ${formatDate(instance.service_expires_at, '时间未记录')}`));
|
|
const facts = document.createElement('dl');
|
|
facts.append(fact('本周期总额度', formatBytes(instance.period_traffic_quota_bytes)),
|
|
fact('本实例已用', formatBytes(instance.traffic_used_bytes)),
|
|
fact('RX / TX', `${formatBytes(instance.traffic_download_bytes)} / ${formatBytes(instance.traffic_upload_bytes)}`));
|
|
const [networkLabel, networkClass] = instanceNetwork(instance.network_status);
|
|
const network = document.createElement('div');
|
|
const networkValue = document.createElement('dd');
|
|
networkValue.append(element('span', `state-pill ${networkClass}`, networkLabel));
|
|
network.append(element('dt', '', '网络'), networkValue);
|
|
facts.append(network);
|
|
link.append(identity, facts);
|
|
list.append(link);
|
|
}
|
|
section.append(heading, list);
|
|
}
|
|
|
|
function coverageLabel(pool) {
|
|
const names = [];
|
|
for (const region of Array.isArray(pool?.coverage_regions) ? pool.coverage_regions : []) {
|
|
const name = String(region?.name || '').trim();
|
|
if (name && !names.includes(name)) names.push(name);
|
|
}
|
|
return names.length ? `覆盖:${names.join('、')}` : '覆盖地区待核查';
|
|
}
|
|
|
|
function renderLineContent(pool) {
|
|
const projectionReady = pool.projection_ready === true;
|
|
const card = element('article', 'cloud-traffic-card cloud-traffic-line-content');
|
|
const intro = element('div', 'cloud-traffic-line-intro');
|
|
intro.append(element('p', '', '线路内全部地区共享额度,并按最早到期批次优先消耗。'));
|
|
const states = element('div', 'cloud-traffic-state-group');
|
|
const [stateLabel, stateClass] = poolState(pool.state);
|
|
const [networkLabel, networkClass] = restrictionState(pool.network_restriction_state);
|
|
states.append(element('span', `state-pill ${stateClass}`, stateLabel),
|
|
element('span', `state-pill ${networkClass}`, networkLabel));
|
|
intro.append(states);
|
|
const facts = element('dl', 'cloud-traffic-facts');
|
|
const pending = '正在准备';
|
|
facts.append(fact('当前有效额度', projectionReady
|
|
? formatBytes(pool.active_entitlement_bytes) : pending),
|
|
fact('有效额度已消耗', projectionReady
|
|
? formatBytes(pool.active_consumed_bytes) : pending),
|
|
fact('当前可用余额', projectionReady
|
|
? formatBytes(pool.available_bytes) : pending),
|
|
fact('采样超额债务', projectionReady
|
|
? formatBytes(pool.overage_bytes) : pending),
|
|
fact('下一批额度到期', projectionReady
|
|
? formatDate(pool.next_expiry_at, '暂无即将到期额度') : '额度准备中',
|
|
projectionReady ? `届时作废 ${formatBytes(pool.next_expiry_bytes)}` : '账本投影尚未生成'),
|
|
fact('最近可信采样', projectionReady
|
|
? formatDate(pool.last_observed_at, '暂未完成采样') : '等待首次核算'));
|
|
const instances = element('section', 'cloud-traffic-instances');
|
|
instances.setAttribute('aria-label', `${pool.name || '共享流量池'} 中的当前实例`);
|
|
renderInstances(pool, instances);
|
|
card.append(intro, facts, instances);
|
|
return card;
|
|
}
|
|
|
|
function existingLinePoolState(list) {
|
|
const result = new Map();
|
|
for (const details of list.querySelectorAll(
|
|
'details.cloud-traffic-line[data-line-key]',
|
|
)) {
|
|
result.set(details.getAttribute('data-line-key'), {
|
|
open: details.open === true,
|
|
requiresAttention: details.getAttribute('data-requires-attention') === '1',
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function renderLinePool(pool, previousState) {
|
|
const key = String(pool.key || `line-group:${Number(pool.group_id) || 0}`);
|
|
const details = element('details', 'cloud-traffic-line');
|
|
details.setAttribute('data-line-key', key);
|
|
const requiresAttention = pool.requires_attention === true;
|
|
details.setAttribute('data-requires-attention', requiresAttention ? '1' : '0');
|
|
const previous = previousState.get(key);
|
|
details.open = previous
|
|
? (requiresAttention && !previous.requiresAttention ? true : previous.open)
|
|
: pool.default_open === true;
|
|
const summary = element('summary', 'cloud-traffic-line-summary');
|
|
const identity = element('span', 'cloud-traffic-line-identity');
|
|
const icon = element('span', 'cloud-traffic-line-icon');
|
|
const marker = element('i', 'mdi mdi-lan-connect');
|
|
marker.setAttribute('aria-hidden', 'true');
|
|
icon.append(marker);
|
|
const title = element('span', 'cloud-traffic-line-title');
|
|
title.append(element('strong', '', pool.name || '线路流量池'),
|
|
element('small', '', coverageLabel(pool)));
|
|
identity.append(icon, title);
|
|
const meta = element('span', 'cloud-traffic-line-meta');
|
|
const counts = element('span', 'cloud-traffic-line-counts');
|
|
counts.append(element('span', '', `${Number(pool.coverage_region_count) || 0} 个地区`),
|
|
element('span', '', `${Number(pool.instance_count) || 0} 台实例`));
|
|
const [statusLabel, statusClass] = linePoolState(pool.summary_state);
|
|
const arrow = element('span', 'cloud-traffic-line-arrow', '⌄');
|
|
arrow.setAttribute('aria-hidden', 'true');
|
|
meta.append(counts, element('span', `state-pill ${statusClass}`, statusLabel), arrow);
|
|
summary.append(identity, meta);
|
|
const body = element('div', 'cloud-traffic-line-body');
|
|
body.append(renderLineContent(pool));
|
|
details.append(summary, body);
|
|
return details;
|
|
}
|
|
|
|
function render() {
|
|
const list = byId('cloud-traffic-list');
|
|
const previousState = existingLinePoolState(list);
|
|
list.replaceChildren();
|
|
if (!state.linePools.length) {
|
|
const empty = element('div', 'cloud-traffic-empty');
|
|
empty.append(poolIcon(), element('strong', '', '当前没有已启用的线路流量池'),
|
|
element('span', '', '管理员完成影子核算验收并启用后,将在这里显示线路共享额度。'));
|
|
list.append(empty);
|
|
}
|
|
for (const pool of state.linePools) {
|
|
list.append(renderLinePool(pool, previousState));
|
|
}
|
|
byId('cloud-traffic-count').textContent =
|
|
`${state.linePoolCount} 个线路流量池`;
|
|
byId('cloud-traffic-refresh').disabled = state.loading;
|
|
}
|
|
|
|
function applyPayload(payload) {
|
|
const values = Array.isArray(payload?.line_pools) ? payload.line_pools : [];
|
|
state.linePools = values.filter(pool => pool && typeof pool === 'object'
|
|
&& typeof pool.key === 'string' && pool.key !== ''
|
|
&& Array.isArray(pool.instances));
|
|
state.linePoolCount = Math.max(0, Number(payload?.line_pool_count) || 0);
|
|
render();
|
|
}
|
|
|
|
async function load() {
|
|
if (state.loading) return;
|
|
state.loading = true;
|
|
state.controller?.abort();
|
|
const controller = new AbortController();
|
|
state.controller = controller;
|
|
const status = byId('cloud-traffic-status');
|
|
status.hidden = false;
|
|
status.className = 'vm-settings-status';
|
|
status.textContent = '正在读取共享流量池…';
|
|
render();
|
|
try {
|
|
const payload = await api('/api/v1/traffic-pools', { signal: controller.signal });
|
|
if (controller.signal.aborted) return;
|
|
applyPayload(payload);
|
|
status.hidden = true;
|
|
} catch (error) {
|
|
if (controller.signal.aborted) return;
|
|
status.className = 'vm-settings-status error';
|
|
status.textContent = error?.message || '共享流量池读取失败,请稍后重试。';
|
|
} finally {
|
|
if (state.controller === controller) state.controller = null;
|
|
state.loading = false;
|
|
render();
|
|
}
|
|
}
|
|
|
|
export async function initialize() {
|
|
try {
|
|
const bootstrap = readBootstrap('cloud-traffic-bootstrap');
|
|
if (!await initializeSession('traffic', bootstrap?.user)) return;
|
|
applyPayload(bootstrap);
|
|
byId('cloud-traffic-refresh')?.addEventListener('click', () => void load());
|
|
window.addEventListener('pagehide', () => state.controller?.abort());
|
|
} catch (error) {
|
|
showError('cloud-page-error', error?.message || '流量池页面加载失败,请刷新后重试。');
|
|
}
|
|
}
|