|
|
import { toast } from './toast.js?v=2026100802';
|
|
|
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const state = {
|
|
|
csrfToken: '', userId: '', regions: [], instances: [], vpcs: [],
|
|
|
selectedKey: '', selected: null, busy: false, stopped: false, detailDirty: false,
|
|
|
listEpoch: 0, detailEpoch: 0, listController: null, detailController: null,
|
|
|
bootstrapEpoch: 0, refreshEpoch: 0, bootstrapController: null, pollTimer: 0,
|
|
|
deleteRequestKeys: new Map(), createFocusReturn: null,
|
|
|
};
|
|
|
|
|
|
const STATUS_LABELS = Object.freeze({
|
|
|
awaiting_members: '待添加实例',
|
|
|
applying: '应用中', waiting: '等待宿主机回读', uncertain: '结果待核对',
|
|
|
degraded: '部分失败', active: '已生效', suspended: '网络已暂停',
|
|
|
deleting: '清理中', succeeded: '已完成', failed: '失败', queued: '排队中',
|
|
|
running: '执行中', unknown: '状态未知',
|
|
|
});
|
|
|
|
|
|
const EMPTY_MEMBER_GATE_CODES = Object.freeze(new Set([
|
|
|
'vpc_no_members', 'vpc_no_participating_hosts',
|
|
|
]));
|
|
|
|
|
|
const OPERATION_LABELS = Object.freeze({
|
|
|
vpc_create: '创建 VPC', member_attach: '加入实例', member_detach: '移除实例',
|
|
|
routes_replace: '更新路由', acl_replace: '更新 ACL', vpc_delete: '删除 VPC',
|
|
|
subnet_remove: '移除子网', reconcile: '重新核对',
|
|
|
});
|
|
|
|
|
|
function element(tag, className = '', textContent = '') {
|
|
|
const node = document.createElement(tag);
|
|
|
if (className) node.className = className;
|
|
|
if (textContent !== '') node.textContent = String(textContent);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function field(label, value, className = '') {
|
|
|
const wrapper = element('div', `vpc-fact ${className}`.trim());
|
|
|
wrapper.append(element('dt', '', label), element('dd', '', value));
|
|
|
return wrapper;
|
|
|
}
|
|
|
|
|
|
function setError(message = '') {
|
|
|
const node = byId('vpc-page-error');
|
|
|
if (!node) return;
|
|
|
node.textContent = message;
|
|
|
node.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function setNotice(message = '', kind = '') {
|
|
|
const node = byId('vpc-page-notice');
|
|
|
if (!node) return;
|
|
|
node.textContent = message;
|
|
|
node.className = `vpc-notice ${kind}`.trim();
|
|
|
node.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function setFormError(id, message = '') {
|
|
|
const node = byId(id);
|
|
|
if (!node) return;
|
|
|
node.textContent = message;
|
|
|
node.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function secureTransportRequired() {
|
|
|
return location.protocol !== 'https:'
|
|
|
&& !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname);
|
|
|
}
|
|
|
|
|
|
async function api(path, options = {}) {
|
|
|
const method = String(options.method || 'GET').toUpperCase();
|
|
|
const headers = new Headers({ Accept: 'application/json', ...(options.headers || {}) });
|
|
|
if (!['GET', 'HEAD'].includes(method)) {
|
|
|
if (secureTransportRequired()) throw new Error('请通过 HTTPS 修改 VPC 私网配置。');
|
|
|
if (!state.csrfToken) throw new Error('会话安全令牌缺失,请刷新页面。');
|
|
|
headers.set('X-CSRF-Token', state.csrfToken);
|
|
|
headers.set('Content-Type', 'application/json');
|
|
|
}
|
|
|
const response = await fetch(path, {
|
|
|
method, headers, credentials: 'same-origin', cache: 'no-store',
|
|
|
signal: options.signal,
|
|
|
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
|
});
|
|
|
let payload = null;
|
|
|
try { payload = response.status === 204 ? null : await response.json(); }
|
|
|
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); }
|
|
|
if (response.status === 401) {
|
|
|
location.assign('/auth/login');
|
|
|
throw new Error('登录已过期。');
|
|
|
}
|
|
|
if (!response.ok || payload?.ret === 0) {
|
|
|
const detail = Array.isArray(payload?.detail)
|
|
|
? payload.detail.map(item => item?.msg || '输入错误').join(';') : payload?.detail;
|
|
|
const error = new Error(String(detail || payload?.message || payload?.error
|
|
|
|| `请求失败 (${response.status})`));
|
|
|
error.status = response.status;
|
|
|
throw error;
|
|
|
}
|
|
|
return payload;
|
|
|
}
|
|
|
|
|
|
function requestKey(prefix) {
|
|
|
const uuid = typeof crypto?.randomUUID === 'function'
|
|
|
? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
|
return `${prefix}-${uuid}`.slice(0, 128);
|
|
|
}
|
|
|
|
|
|
function entityKey() {
|
|
|
const value = typeof crypto?.randomUUID === 'function'
|
|
|
? crypto.randomUUID().replaceAll('-', '')
|
|
|
: `${Date.now()}${Math.random().toString(16).slice(2)}`;
|
|
|
return value.replace(/[^a-f0-9]/gi, '').toLowerCase().padEnd(32, '0').slice(0, 32);
|
|
|
}
|
|
|
|
|
|
function safeText(value, fallback = '—') {
|
|
|
const text = value === null || value === undefined ? '' : String(value).trim();
|
|
|
return text || fallback;
|
|
|
}
|
|
|
|
|
|
function memberCount(root) {
|
|
|
if (root?.member_count === null || root?.member_count === undefined
|
|
|
|| root?.member_count === '') return null;
|
|
|
const value = Number(root?.member_count);
|
|
|
return Number.isInteger(value) && value >= 0 ? value : null;
|
|
|
}
|
|
|
|
|
|
function projectionFieldKnown(root, field) {
|
|
|
const marker = `${field}_known`;
|
|
|
if (Object.prototype.hasOwnProperty.call(root || {}, marker)) return root[marker] === true;
|
|
|
return Object.prototype.hasOwnProperty.call(root || {}, field);
|
|
|
}
|
|
|
|
|
|
function awaitingMembers(root) {
|
|
|
const raw = String(root?.state || '').toLowerCase();
|
|
|
if (raw === 'deleting' || root?.usable === true) return false;
|
|
|
const count = memberCount(root);
|
|
|
if (String(root?.setup_state || '').toLowerCase() === 'awaiting_members'
|
|
|
&& (count === null || count === 0)) return true;
|
|
|
// Once the server exposes either explicit projection field, it owns the
|
|
|
// classification. In particular, setup_state=null must not be overwritten
|
|
|
// by a stale engine gate code from an unsafe or malformed ledger.
|
|
|
if (projectionFieldKnown(root, 'setup_state')
|
|
|
|| projectionFieldKnown(root, 'member_count')) return false;
|
|
|
const emptyGate = EMPTY_MEMBER_GATE_CODES.has(String(root?.last_error_code || ''));
|
|
|
// Older rows predate setup_state/member_count. These two engine gate codes
|
|
|
// are a closed-set proof that the current revision had no participating
|
|
|
// member host, so they remain a safe neutral projection until a new member
|
|
|
// mutation creates a later revision.
|
|
|
return emptyGate && (count === null || count === 0);
|
|
|
}
|
|
|
|
|
|
function rootStatus(root) {
|
|
|
const sync = String(root?.sync_state || '').toLowerCase();
|
|
|
const raw = String(root?.state || '').toLowerCase();
|
|
|
// Root deletion is a durable tombstone, even when the latest engine call
|
|
|
// is failed or uncertain. Never reopen mutation controls while teardown
|
|
|
// still owns the VPC.
|
|
|
if (raw === 'deleting') return 'deleting';
|
|
|
if (root?.usable === true) return 'active';
|
|
|
if (awaitingMembers(root)) return 'awaiting_members';
|
|
|
if (sync === 'waiting' || sync === 'waiting_observed') return 'waiting';
|
|
|
if (sync === 'uncertain' || raw === 'uncertain') return 'uncertain';
|
|
|
if (raw === 'degraded' || sync === 'failed') return 'degraded';
|
|
|
if (raw === 'applying' || ['pending', 'queued', 'running'].includes(sync)) return 'applying';
|
|
|
return raw === 'active' ? 'uncertain' : (raw || 'unknown');
|
|
|
}
|
|
|
|
|
|
function childStatus(value) {
|
|
|
const raw = String(value || '').toLowerCase();
|
|
|
return ['active', 'suspended', 'applying', 'waiting', 'uncertain', 'degraded',
|
|
|
'deleting', 'deleted'].includes(raw) ? raw : 'unknown';
|
|
|
}
|
|
|
|
|
|
function statusPill(status, extra = '') {
|
|
|
const normalized = status === 'waiting_observed' ? 'waiting' : String(status || 'unknown');
|
|
|
const pill = element('span', `vpc-state-pill ${normalized}`.trim(),
|
|
|
STATUS_LABELS[normalized] || normalized);
|
|
|
if (extra) pill.title = extra;
|
|
|
return pill;
|
|
|
}
|
|
|
|
|
|
function errorLabel(code) {
|
|
|
return {
|
|
|
vpc_no_members: 'VPC 已创建;加入至少一个实例后才会应用私网数据面。',
|
|
|
vpc_no_participating_hosts: 'VPC 已创建;加入至少一个同地区实例后才会配置私网。',
|
|
|
vpc_data_plane_deferred: 'Fabric 已就绪,正在等待私网数据面回读。',
|
|
|
vpc_observation_incomplete: '宿主机回读尚未完整,请稍后核对。',
|
|
|
}[String(code || '')] || '';
|
|
|
}
|
|
|
|
|
|
function operationLabel(kind) {
|
|
|
return OPERATION_LABELS[String(kind || '')] || safeText(kind, '未知操作');
|
|
|
}
|
|
|
|
|
|
function regionName(regionId) {
|
|
|
const row = state.regions.find(item => Number(item.id) === Number(regionId));
|
|
|
return row ? safeText(row.name, `地区 ${regionId}`) : `地区 ${regionId || '未知'}`;
|
|
|
}
|
|
|
|
|
|
function instanceName(instanceId) {
|
|
|
const row = state.instances.find(item => Number(item.id) === Number(instanceId));
|
|
|
return row ? safeText(row.name, `实例 #${instanceId}`) : `实例 #${instanceId}`;
|
|
|
}
|
|
|
|
|
|
function instanceRegion(instanceId) {
|
|
|
const row = state.instances.find(item => Number(item.id) === Number(instanceId));
|
|
|
return row ? safeText(row.region, '地区待核验') : '地区待核验';
|
|
|
}
|
|
|
|
|
|
function normalizeRoot(value) {
|
|
|
if (!value || typeof value !== 'object') return null;
|
|
|
const setupStateKnown = Object.prototype.hasOwnProperty.call(value, 'setup_state');
|
|
|
const memberCountKnown = Object.prototype.hasOwnProperty.call(value, 'member_count');
|
|
|
const count = value.member_count === null || value.member_count === undefined
|
|
|
|| value.member_count === '' ? null : Number(value.member_count);
|
|
|
return {
|
|
|
...value,
|
|
|
vpc_key: String(value.vpc_key || ''),
|
|
|
name: String(value.name || '未命名 VPC'),
|
|
|
cidr: String(value.cidr || ''),
|
|
|
region_id: Number(value.region_id || 0),
|
|
|
desired_revision: Number(value.desired_revision || 0),
|
|
|
observed_revision: Number(value.observed_revision || 0),
|
|
|
member_count: count !== null && Number.isInteger(count) && count >= 0 ? count : null,
|
|
|
setup_state: value.setup_state ? String(value.setup_state) : '',
|
|
|
setup_state_known: setupStateKnown,
|
|
|
member_count_known: memberCountKnown,
|
|
|
last_error_code: value.last_error_code ? String(value.last_error_code) : '',
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function normalizeDocument(value) {
|
|
|
if (!value || typeof value !== 'object') return null;
|
|
|
const root = normalizeRoot(value.vpc);
|
|
|
if (!root) return null;
|
|
|
const members = Array.isArray(value.members) ? value.members : [];
|
|
|
root.member_count = members.filter(item =>
|
|
|
String(item?.state || '').toLowerCase() !== 'deleted').length;
|
|
|
return {
|
|
|
vpc: root,
|
|
|
members,
|
|
|
routes: Array.isArray(value.routes) ? value.routes : [],
|
|
|
acl_rules: Array.isArray(value.acl_rules) ? value.acl_rules : [],
|
|
|
operations: Array.isArray(value.operations) ? value.operations : [],
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function needsPolling() {
|
|
|
const fastStatuses = new Set(['applying', 'waiting', 'uncertain', 'degraded', 'deleting']);
|
|
|
return Boolean(state.vpcs.some(vpc => fastStatuses.has(rootStatus(
|
|
|
state.selected?.vpc?.vpc_key === vpc.vpc_key ? state.selected.vpc : vpc
|
|
|
)))
|
|
|
|| (state.selected && fastStatuses.has(rootStatus(state.selected.vpc))));
|
|
|
}
|
|
|
|
|
|
function markDetailDirty() {
|
|
|
if (state.detailDirty) return;
|
|
|
state.detailDirty = true;
|
|
|
setNotice('详情中有未保存修改,自动状态核对已暂停。', 'warning');
|
|
|
}
|
|
|
|
|
|
function confirmDetailMutation() {
|
|
|
return !state.detailDirty
|
|
|
|| confirm('当前 VPC 有未保存修改,继续操作会丢失这些修改。继续吗?');
|
|
|
}
|
|
|
|
|
|
function clearDetailDirty() {
|
|
|
state.detailDirty = false;
|
|
|
}
|
|
|
|
|
|
function cancelReadbacks() {
|
|
|
state.refreshEpoch += 1;
|
|
|
state.bootstrapEpoch += 1;
|
|
|
state.listEpoch += 1;
|
|
|
state.detailEpoch += 1;
|
|
|
state.bootstrapController?.abort();
|
|
|
state.listController?.abort();
|
|
|
state.detailController?.abort();
|
|
|
state.bootstrapController = null;
|
|
|
state.listController = null;
|
|
|
state.detailController = null;
|
|
|
}
|
|
|
|
|
|
function hasPolicyMember(doc = state.selected) {
|
|
|
return Array.isArray(doc?.members) && doc.members.some(item =>
|
|
|
!['deleting', 'deleted'].includes(childStatus(item?.state))
|
|
|
);
|
|
|
}
|
|
|
|
|
|
function selectedRootDeleting() {
|
|
|
return rootStatus(state.selected?.vpc) === 'deleting';
|
|
|
}
|
|
|
|
|
|
function selectedDocumentCurrent() {
|
|
|
return Boolean(state.selectedKey && state.selected?.vpc?.vpc_key === state.selectedKey);
|
|
|
}
|
|
|
|
|
|
function allowSelectedMutation() {
|
|
|
if (!selectedDocumentCurrent()) {
|
|
|
setError('VPC 详情尚未读取完成,请等待刷新后再操作。');
|
|
|
return false;
|
|
|
}
|
|
|
if (!selectedRootDeleting()) return true;
|
|
|
setError('VPC 正在删除,完成所有宿主机清理前不能再修改成员、路由或 ACL。');
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
function finishVpcDeletion(message = 'VPC 已完成宿主机清理,私网 CIDR 已释放。') {
|
|
|
const deletedKey = state.selectedKey;
|
|
|
if (deletedKey) {
|
|
|
state.deleteRequestKeys.delete(deletedKey);
|
|
|
// Remove the exact completed root immediately. A best-effort list refresh
|
|
|
// follows, but a transient refresh failure must not leave a clickable
|
|
|
// stale row that the detail endpoint has already proved deleted.
|
|
|
state.vpcs = state.vpcs.filter(item => item?.vpc_key !== deletedKey);
|
|
|
}
|
|
|
state.detailController?.abort();
|
|
|
state.detailController = null;
|
|
|
state.detailEpoch += 1;
|
|
|
state.selectedKey = '';
|
|
|
state.selected = null;
|
|
|
clearDetailDirty();
|
|
|
byId('vpc-detail-panel').hidden = true;
|
|
|
byId('vpc-detail').replaceChildren();
|
|
|
renderList();
|
|
|
setError('');
|
|
|
if (message) { setNotice(message, 'success'); toast(message, 'success'); }
|
|
|
}
|
|
|
|
|
|
function lockDeletingDetail(container, reconcile) {
|
|
|
if (!selectedRootDeleting()) return;
|
|
|
container.dataset.rootDeleting = 'true';
|
|
|
for (const control of container.querySelectorAll('button, input, select, textarea')) {
|
|
|
control.disabled = true;
|
|
|
}
|
|
|
// Reconcile does not change desired state; it is the explicit retry path
|
|
|
// for a deletion whose host readback is incomplete or uncertain.
|
|
|
if (reconcile) reconcile.disabled = state.busy;
|
|
|
}
|
|
|
|
|
|
function refreshRouteEditorState() {
|
|
|
const editor = byId('vpc-route-editor');
|
|
|
if (!editor) return;
|
|
|
const allowed = new Set((state.selected?.members || [])
|
|
|
.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))
|
|
|
.map(item => String(item.private_ip || '')));
|
|
|
for (const row of editor.querySelectorAll('.vpc-editor-row')) {
|
|
|
const value = row.querySelector('[data-route-field="next_hop_ip"]')?.value || '';
|
|
|
if (!value || !allowed.has(String(value))) row.dataset.invalid = 'true';
|
|
|
else delete row.dataset.invalid;
|
|
|
}
|
|
|
const blocked = Boolean(editor.querySelector('[data-vpc-tombstone-state="deleting"]'));
|
|
|
const save = document.querySelector('[data-vpc-save="routes"]');
|
|
|
if (save) save.disabled = state.busy || blocked
|
|
|
|| Boolean(editor.querySelector('[data-invalid="true"]'));
|
|
|
}
|
|
|
|
|
|
function schedulePoll(delay = needsPolling() ? 8000 : 30000) {
|
|
|
clearTimeout(state.pollTimer);
|
|
|
if (state.stopped || document.visibilityState === 'hidden') return;
|
|
|
state.pollTimer = window.setTimeout(async () => {
|
|
|
if (state.stopped || document.visibilityState === 'hidden') return;
|
|
|
if (state.busy) { schedulePoll(1500); return; }
|
|
|
await loadList(true);
|
|
|
if (state.stopped || state.busy || document.visibilityState === 'hidden') {
|
|
|
if (!state.stopped) schedulePoll(1500);
|
|
|
return;
|
|
|
}
|
|
|
if (state.selectedKey && !state.detailDirty) {
|
|
|
await loadDetail(state.selectedKey, true);
|
|
|
}
|
|
|
if (state.busy) { schedulePoll(1500); return; }
|
|
|
schedulePoll();
|
|
|
}, delay);
|
|
|
}
|
|
|
|
|
|
function renderSummary() {
|
|
|
const projectedStatus = item => rootStatus(
|
|
|
state.selected?.vpc?.vpc_key === item.vpc_key ? state.selected.vpc : item
|
|
|
);
|
|
|
const active = state.vpcs.filter(item => projectedStatus(item) === 'active').length;
|
|
|
const attention = state.vpcs.filter(item =>
|
|
|
!['active', 'awaiting_members'].includes(projectedStatus(item))).length;
|
|
|
byId('vpc-stat-total').textContent = String(state.vpcs.length);
|
|
|
byId('vpc-stat-active').textContent = String(active);
|
|
|
byId('vpc-stat-attention').textContent = String(attention);
|
|
|
byId('vpc-list-caption').textContent = state.vpcs.length
|
|
|
? `${state.vpcs.length} 个 VPC · ${needsPolling() ? '正在每 8 秒核对变化' : '稳定状态每 30 秒刷新'}`
|
|
|
: '还没有已创建的 VPC';
|
|
|
}
|
|
|
|
|
|
function renderList() {
|
|
|
const container = byId('vpc-list');
|
|
|
container.replaceChildren();
|
|
|
const rows = state.vpcs.map(root => {
|
|
|
const selectedDocument = state.selected?.vpc?.vpc_key === root.vpc_key
|
|
|
? state.selected : null;
|
|
|
const displayRoot = selectedDocument?.vpc || root;
|
|
|
const status = rootStatus(displayRoot);
|
|
|
const row = element('button', `vpc-list-row${root.vpc_key === state.selectedKey ? ' selected' : ''}`);
|
|
|
row.type = 'button';
|
|
|
row.dataset.vpcKey = root.vpc_key;
|
|
|
const main = element('span', 'vpc-list-main');
|
|
|
const heading = element('span', 'vpc-list-heading');
|
|
|
heading.append(element('strong', '', displayRoot.name), statusPill(status));
|
|
|
main.append(heading, element('small', '', `${displayRoot.cidr} · ${regionName(displayRoot.region_id)}`));
|
|
|
const meta = element('span', 'vpc-list-meta');
|
|
|
const count = memberCount(displayRoot);
|
|
|
meta.append(element('small', '', count === null ? '成员数量待读取' : `${count} 个成员`),
|
|
|
element('small', '', status === 'awaiting_members' ? '下一步:添加实例'
|
|
|
: (displayRoot.usable === true ? '宿主机回读已确认' : '正在核对私网配置')));
|
|
|
row.append(main, meta);
|
|
|
return row;
|
|
|
});
|
|
|
container.append(...rows);
|
|
|
byId('vpc-list-empty').hidden = rows.length !== 0;
|
|
|
const reconcile = byId('vpc-list-reconcile');
|
|
|
const selectedStatus = rootStatus(selectedDocumentCurrent() ? state.selected.vpc : null);
|
|
|
const canReconcile = selectedDocumentCurrent()
|
|
|
&& !['active', 'awaiting_members'].includes(selectedStatus);
|
|
|
reconcile.hidden = !canReconcile;
|
|
|
reconcile.disabled = !canReconcile || state.busy;
|
|
|
renderSummary();
|
|
|
}
|
|
|
|
|
|
function section(title, description, className = '') {
|
|
|
const card = element('section', `vpc-subpanel ${className}`.trim());
|
|
|
const header = element('div', 'vpc-subpanel-heading');
|
|
|
header.append(element('div', '', ''), element('span', 'vpc-subpanel-count', ''));
|
|
|
header.firstChild.append(element('h3', '', title), element('p', '', description));
|
|
|
card.append(header);
|
|
|
return card;
|
|
|
}
|
|
|
|
|
|
function button(label, className = 'button button-outline small') {
|
|
|
const node = element('button', className, label);
|
|
|
node.type = 'button';
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function input(labelText, value = '', type = 'text', placeholder = '') {
|
|
|
const wrapper = element('div', 'field');
|
|
|
const id = `vpc-field-${Math.random().toString(16).slice(2)}`;
|
|
|
const label = element('label', '', labelText);
|
|
|
const control = document.createElement(type === 'select' ? 'select' : 'input');
|
|
|
control.id = id;
|
|
|
if (type !== 'select') {
|
|
|
control.type = type; control.value = value === null ? '' : String(value);
|
|
|
if (placeholder) control.placeholder = placeholder;
|
|
|
}
|
|
|
label.htmlFor = id;
|
|
|
wrapper.append(label, control);
|
|
|
return { wrapper, control };
|
|
|
}
|
|
|
|
|
|
function disclosure(title, description, className = '') {
|
|
|
const node = element('details', `vpc-disclosure ${className}`.trim());
|
|
|
const summary = element('summary', 'vpc-disclosure-summary');
|
|
|
const copy = element('span', 'vpc-disclosure-copy');
|
|
|
copy.append(element('strong', '', title), element('small', '', description));
|
|
|
summary.append(copy, element('span', 'vpc-disclosure-icon', '⌄'));
|
|
|
const body = element('div', 'vpc-disclosure-body');
|
|
|
node.append(summary, body);
|
|
|
return { node, body };
|
|
|
}
|
|
|
|
|
|
function renderSetupGuide() {
|
|
|
const guide = element('section', 'vpc-setup-guide');
|
|
|
const heading = element('div', 'vpc-setup-guide-heading');
|
|
|
heading.append(element('span', 'eyebrow', 'NEXT STEP'),
|
|
|
element('h3', '', '添加实例以启用私网'));
|
|
|
guide.append(heading,
|
|
|
element('p', 'vpc-setup-guide-copy', 'VPC 和独立网段已保留。加入同地区实例后,平台才会配置 WireGuard、私网路由和实例网卡。'));
|
|
|
const steps = element('ol', 'vpc-setup-steps');
|
|
|
for (const [stateName, title, description] of [
|
|
|
['complete', 'VPC 与 /24 网段已创建', '控制面资源已保留'],
|
|
|
['current', '添加同地区实例', '平台自动分配私网 IP'],
|
|
|
['pending', '等待宿主机与实例回读', '全部核对后标记为可用'],
|
|
|
]) {
|
|
|
const item = element('li', `vpc-setup-step ${stateName}`);
|
|
|
item.append(element('span', 'vpc-setup-step-mark', stateName === 'complete' ? '✓' : ''),
|
|
|
element('span', 'vpc-setup-step-copy'));
|
|
|
item.lastChild.append(element('strong', '', title), element('small', '', description));
|
|
|
steps.append(item);
|
|
|
}
|
|
|
guide.append(steps);
|
|
|
return guide;
|
|
|
}
|
|
|
|
|
|
function renderDetail() {
|
|
|
const container = byId('vpc-detail');
|
|
|
const doc = state.selected;
|
|
|
if (!doc) { container.replaceChildren(); return; }
|
|
|
const root = doc.vpc;
|
|
|
const sameVpc = container.dataset.vpcKey === root.vpc_key;
|
|
|
const previousView = sameVpc ? {
|
|
|
advancedOpen: container.querySelector('.vpc-advanced')?.open === true,
|
|
|
diagnosticsOpen: container.querySelector('.vpc-diagnostics')?.open === true,
|
|
|
memberInstance: container.querySelector('#vpc-member-instance')?.value || '',
|
|
|
} : { advancedOpen: false, diagnosticsOpen: false, memberInstance: '' };
|
|
|
container.replaceChildren();
|
|
|
container.dataset.vpcKey = root.vpc_key;
|
|
|
byId('vpc-detail-title').textContent = root.name;
|
|
|
byId('vpc-detail-caption').textContent = `${root.cidr} · ${regionName(root.region_id)}`;
|
|
|
|
|
|
const overview = element('section', 'vpc-detail-overview');
|
|
|
const overviewHeading = element('div', 'vpc-detail-overview-heading');
|
|
|
const status = rootStatus(root);
|
|
|
const rootHint = status !== 'awaiting_members'
|
|
|
&& EMPTY_MEMBER_GATE_CODES.has(String(root.last_error_code || ''))
|
|
|
? '当前私网台账未满足空 VPC 的安全条件,请展开“同步与诊断”核对。'
|
|
|
: errorLabel(root.last_error_code);
|
|
|
overviewHeading.append(statusPill(status),
|
|
|
element('span', 'vpc-readback-note', root.usable === true
|
|
|
? 'WireGuard、私网路由和实例网卡均已回读确认。'
|
|
|
: (status === 'deleting'
|
|
|
? '正在清理所有宿主机私网对象;精确回读完成前不会释放 VPC CIDR。'
|
|
|
: (status === 'awaiting_members'
|
|
|
? 'VPC 与网段已创建,添加同地区实例后才会配置私网。'
|
|
|
: (rootHint || '配置仍在宿主机应用或核对,期间不要重复创建同一成员。')))));
|
|
|
const actions = element('div', 'vpc-detail-actions');
|
|
|
let reconcile = null;
|
|
|
if (status === 'awaiting_members') {
|
|
|
const addMember = button('添加实例', 'button button-primary small');
|
|
|
addMember.dataset.vpcAction = 'add-member';
|
|
|
addMember.disabled = state.busy;
|
|
|
actions.append(addMember);
|
|
|
} else if (status !== 'active') {
|
|
|
reconcile = button('核对 / 重试', 'button button-primary small');
|
|
|
reconcile.dataset.vpcAction = 'reconcile';
|
|
|
reconcile.disabled = state.busy;
|
|
|
actions.append(reconcile);
|
|
|
}
|
|
|
const remove = button('删除 VPC', 'button button-outline small danger');
|
|
|
remove.dataset.vpcAction = 'delete'; remove.disabled = state.busy || status === 'deleting';
|
|
|
actions.append(remove);
|
|
|
overviewHeading.append(actions);
|
|
|
const count = memberCount(root) ?? doc.members.filter(item =>
|
|
|
childStatus(item.state) !== 'deleted').length;
|
|
|
const facts = element('dl', 'vpc-facts');
|
|
|
facts.append(field('VPC CIDR', root.cidr), field('地区', regionName(root.region_id)),
|
|
|
field('成员', `${count} / ${Number(root.max_members || 200)}`));
|
|
|
overview.append(overviewHeading, facts);
|
|
|
container.append(overview);
|
|
|
|
|
|
if (status === 'awaiting_members') container.append(renderSetupGuide());
|
|
|
container.append(renderMembers(doc));
|
|
|
const policyAvailable = hasPolicyMember(doc);
|
|
|
const advanced = disclosure('高级网络策略', !policyAvailable
|
|
|
? '添加首个实例并生成数据面后,才可配置 Route 与 VPC ACL。'
|
|
|
: '自定义 Route 与 VPC ACL;保存时会替换对应的整套策略。', 'vpc-advanced');
|
|
|
if (!policyAvailable) {
|
|
|
advanced.body.append(element('p', 'vpc-empty-inline',
|
|
|
status === 'awaiting_members'
|
|
|
? '当前 VPC 尚无成员。请先添加同地区实例;宿主机开始应用私网后将开放策略编辑。'
|
|
|
: '当前没有可承载策略的 VPC 成员。请先处理同步诊断或添加同地区实例。'));
|
|
|
} else {
|
|
|
advanced.body.append(renderRoutes(doc), renderAcl(doc));
|
|
|
}
|
|
|
advanced.node.open = previousView.advancedOpen;
|
|
|
container.append(advanced.node);
|
|
|
|
|
|
const diagnostics = disclosure('同步与诊断', '查看 revision、同步状态、错误代码和最近操作。', 'vpc-diagnostics');
|
|
|
const diagnosticFacts = element('dl', 'vpc-facts vpc-diagnostic-facts');
|
|
|
diagnosticFacts.append(field('目标 revision', root.desired_revision || 0),
|
|
|
field('已观测 revision', root.observed_revision || 0),
|
|
|
field('同步状态', safeText(root.sync_state)),
|
|
|
field('最近错误代码', root.last_error_code || '无'));
|
|
|
diagnostics.body.append(diagnosticFacts, renderOperations(doc));
|
|
|
diagnostics.node.open = previousView.diagnosticsOpen;
|
|
|
container.append(diagnostics.node);
|
|
|
const memberSelect = container.querySelector('#vpc-member-instance');
|
|
|
if (previousView.memberInstance && memberSelect
|
|
|
&& [...memberSelect.options].some(option => option.value === previousView.memberInstance
|
|
|
&& !option.disabled)) {
|
|
|
memberSelect.value = previousView.memberInstance;
|
|
|
}
|
|
|
clearDetailDirty();
|
|
|
lockDeletingDetail(container, reconcile);
|
|
|
}
|
|
|
|
|
|
function renderMembers(doc) {
|
|
|
const card = section('成员与私网 IP', '选择同一地区的实例即可加入;平台会使用唯一自动子网分配私网 IP,并在宿主机回读后生效。', 'vpc-members');
|
|
|
const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member';
|
|
|
const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true;
|
|
|
instance.control.id = 'vpc-member-instance';
|
|
|
instance.wrapper.querySelector('label').htmlFor = instance.control.id;
|
|
|
const placeholder = new Option('请选择同地区实例', '', true, true);
|
|
|
placeholder.disabled = true;
|
|
|
instance.control.append(placeholder);
|
|
|
const vpcRegionId = Number(doc.vpc.region_id || 0);
|
|
|
const attached = new Set(doc.members
|
|
|
.filter(item => childStatus(item.state) !== 'deleted')
|
|
|
.map(item => Number(item.instance_id)));
|
|
|
const eligible = [];
|
|
|
const unavailable = [];
|
|
|
for (const row of state.instances.filter(item => item.service_available !== false)) {
|
|
|
const rowRegionId = Number(row.region_id);
|
|
|
const regionVerified = Number.isInteger(rowRegionId) && rowRegionId > 0;
|
|
|
const sameRegion = regionVerified && rowRegionId === vpcRegionId;
|
|
|
const alreadyAttached = attached.has(Number(row.id));
|
|
|
const suffix = alreadyAttached ? ' · 已在当前 VPC'
|
|
|
: (!regionVerified ? ' · 地区待核验,暂不可加入'
|
|
|
: (!sameRegion ? ' · 地区不匹配' : ''));
|
|
|
const option = new Option(`${row.name} · ${safeText(row.region, '地区待核验')}${suffix}`, String(row.id));
|
|
|
option.dataset.regionId = row.region_id || '';
|
|
|
option.disabled = alreadyAttached || !sameRegion;
|
|
|
(option.disabled ? unavailable : eligible).push(option);
|
|
|
}
|
|
|
instance.control.append(...eligible, ...unavailable);
|
|
|
const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit';
|
|
|
save.disabled = state.busy || eligible.length === 0;
|
|
|
form.append(instance.wrapper, save); card.append(form);
|
|
|
if (!eligible.length) {
|
|
|
card.append(element('p', 'vpc-member-empty-hint',
|
|
|
'当前没有可加入的同地区实例。实例地区缺失或不一致时会保持禁用,请先创建或核验同地区实例。'));
|
|
|
}
|
|
|
const list = element('div', 'vpc-row-list');
|
|
|
for (const row of doc.members.filter(item => childStatus(item.state) !== 'deleted')) {
|
|
|
const item = element('div', 'vpc-data-row');
|
|
|
const copy = element('div', 'vpc-row-copy');
|
|
|
copy.append(element('strong', '', `${instanceName(row.instance_id)} · ${safeText(row.private_ip)}`),
|
|
|
element('small', '', `${instanceRegion(row.instance_id)} · 状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`));
|
|
|
if (row.last_error_code) copy.append(element('small', 'vpc-row-error',
|
|
|
errorLabel(row.last_error_code) || '成员状态需要核对,请展开“同步与诊断”查看详情。'));
|
|
|
const remove = button('退出 VPC', 'button button-outline small danger');
|
|
|
remove.dataset.vpcRemoveMember = row.member_key;
|
|
|
remove.disabled = state.busy || childStatus(row.state) === 'deleting';
|
|
|
item.append(copy, remove); list.append(item);
|
|
|
}
|
|
|
if (!doc.members.some(item => childStatus(item.state) !== 'deleted')) list.append(element('p', 'vpc-empty-inline', '暂无成员。'));
|
|
|
card.append(list); return card;
|
|
|
}
|
|
|
|
|
|
function routeRow(value = {}) {
|
|
|
const row = element('div', 'vpc-editor-row');
|
|
|
row.dataset.routeKey = value.route_key || entityKey();
|
|
|
const destination = input('目标 /32', value.destination_cidr || '', 'text', '10.40.2.7/32');
|
|
|
destination.control.dataset.routeField = 'destination_cidr';
|
|
|
const nextHop = input('下一跳成员 IP', value.next_hop_ip || '', 'select');
|
|
|
nextHop.control.dataset.routeField = 'next_hop_ip';
|
|
|
const members = (state.selected?.members || [])
|
|
|
.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)));
|
|
|
let foundNextHop = false;
|
|
|
for (const member of members) {
|
|
|
const memberIp = String(member.private_ip || '');
|
|
|
if (memberIp === String(value.next_hop_ip || '')) foundNextHop = true;
|
|
|
nextHop.control.append(new Option(`${safeText(member.private_ip)} · ${instanceName(member.instance_id)}`, memberIp));
|
|
|
}
|
|
|
nextHop.control.value = String(value.next_hop_ip || '');
|
|
|
if (!foundNextHop) {
|
|
|
row.dataset.invalid = 'true';
|
|
|
if (value.next_hop_ip) {
|
|
|
const missing = new Option(`${value.next_hop_ip} · 成员状态待核验`, value.next_hop_ip);
|
|
|
missing.disabled = true;
|
|
|
nextHop.control.append(missing);
|
|
|
nextHop.control.value = String(value.next_hop_ip);
|
|
|
}
|
|
|
}
|
|
|
const metric = input('Metric', value.metric || 100, 'number'); metric.control.min = '1'; metric.control.max = '65535'; metric.control.dataset.routeField = 'metric';
|
|
|
const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'route';
|
|
|
row.append(destination.wrapper, nextHop.wrapper, metric.wrapper, remove); return row;
|
|
|
}
|
|
|
|
|
|
function renderRoutes(doc) {
|
|
|
const card = section('Route', '路由目标当前限制为 VPC 内的精确 /32,下一跳必须是本 VPC 成员私网 IP。保存会替换整套路由。', 'vpc-routes');
|
|
|
const list = element('div', 'vpc-editor-list'); list.id = 'vpc-route-editor';
|
|
|
const tombstones = doc.routes.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
const editable = doc.routes.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
for (const row of editable) list.append(routeRow(row));
|
|
|
for (const row of tombstones) {
|
|
|
const item = element('div', 'vpc-tombstone-row');
|
|
|
item.dataset.vpcTombstone = 'true';
|
|
|
item.dataset.vpcTombstoneState = childStatus(row.state);
|
|
|
const pending = childStatus(row.state) === 'deleting';
|
|
|
item.append(element('strong', '', row.destination_cidr || '已删除路由'),
|
|
|
element('small', '', pending
|
|
|
? '状态:清理中;完成前不能覆盖整套路由'
|
|
|
: '状态:已清理;这是历史记录,可继续编辑其他路由'));
|
|
|
list.append(item);
|
|
|
}
|
|
|
if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义路由;同 VPC 成员的 /32 由数据面维护。'));
|
|
|
const toolbar = element('div', 'vpc-editor-toolbar');
|
|
|
const add = button('添加路由', 'button button-outline small'); add.dataset.editorAdd = 'route';
|
|
|
const save = button('保存路由', 'button button-primary small'); save.dataset.vpcSave = 'routes';
|
|
|
const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting');
|
|
|
add.disabled = state.busy || pendingTombstones;
|
|
|
save.disabled = state.busy || pendingTombstones || Boolean(list.querySelector('[data-invalid="true"]'));
|
|
|
toolbar.append(add, save); card.append(list, toolbar); return card;
|
|
|
}
|
|
|
|
|
|
function aclRow(value = {}) {
|
|
|
const row = element('div', 'vpc-editor-row vpc-acl-row');
|
|
|
row.dataset.aclKey = value.rule_key || entityKey();
|
|
|
const priority = input('优先级', value.priority || 100, 'number'); priority.control.min = '1'; priority.control.max = '1000000'; priority.control.dataset.aclField = 'priority';
|
|
|
const direction = input('方向', '', 'select'); direction.control.dataset.aclField = 'direction';
|
|
|
for (const option of [['ingress', '入站'], ['egress', '出站']]) direction.control.append(new Option(option[1], option[0]));
|
|
|
direction.control.value = value.direction || 'ingress';
|
|
|
const action = input('动作', '', 'select'); action.control.dataset.aclField = 'action';
|
|
|
for (const option of [['allow', '允许'], ['deny', '拒绝']]) action.control.append(new Option(option[1], option[0]));
|
|
|
action.control.value = value.action || 'deny';
|
|
|
const protocol = input('协议', '', 'select'); protocol.control.dataset.aclField = 'protocol';
|
|
|
for (const option of [['all', '全部'], ['tcp', 'TCP'], ['udp', 'UDP'], ['icmp', 'ICMP']]) protocol.control.append(new Option(option[1], option[0]));
|
|
|
protocol.control.value = value.protocol || 'all';
|
|
|
const source = input('源 CIDR', value.source_cidr || '', 'text', '10.40.0.0/16'); source.control.dataset.aclField = 'source_cidr';
|
|
|
const destination = input('目标 CIDR', value.destination_cidr || '', 'text', '10.40.0.0/16'); destination.control.dataset.aclField = 'destination_cidr';
|
|
|
const from = input('起始端口', value.port_from ?? '', 'number', 'TCP/UDP 可选'); from.control.min = '1'; from.control.max = '65535'; from.control.dataset.aclField = 'port_from';
|
|
|
const to = input('结束端口', value.port_to ?? '', 'number', 'TCP/UDP 可选'); to.control.min = '1'; to.control.max = '65535'; to.control.dataset.aclField = 'port_to';
|
|
|
const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'acl';
|
|
|
row.append(priority.wrapper, direction.wrapper, action.wrapper, protocol.wrapper, source.wrapper, destination.wrapper, from.wrapper, to.wrapper, remove); return row;
|
|
|
}
|
|
|
|
|
|
function renderAcl(doc) {
|
|
|
const card = section('VPC ACL', '默认策略由数据面保持拒绝;这里只提交结构化规则,不会修改实例公网防火墙。保存会替换整套 ACL。', 'vpc-acl');
|
|
|
const list = element('div', 'vpc-editor-list'); list.id = 'vpc-acl-editor';
|
|
|
const tombstones = doc.acl_rules.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
const editable = doc.acl_rules.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state)));
|
|
|
for (const row of editable) list.append(aclRow(row));
|
|
|
for (const row of tombstones) {
|
|
|
const item = element('div', 'vpc-tombstone-row');
|
|
|
item.dataset.vpcTombstone = 'true';
|
|
|
item.dataset.vpcTombstoneState = childStatus(row.state);
|
|
|
const pending = childStatus(row.state) === 'deleting';
|
|
|
item.append(element('strong', '', `规则 ${safeText(row.rule_key)}`),
|
|
|
element('small', '', pending
|
|
|
? '状态:清理中;完成前不能覆盖整套 ACL'
|
|
|
: '状态:已清理;这是历史记录,可继续编辑其他规则'));
|
|
|
list.append(item);
|
|
|
}
|
|
|
if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义 ACL 规则。'));
|
|
|
const toolbar = element('div', 'vpc-editor-toolbar');
|
|
|
const add = button('添加规则', 'button button-outline small'); add.dataset.editorAdd = 'acl';
|
|
|
const save = button('保存 ACL', 'button button-primary small'); save.dataset.vpcSave = 'acl';
|
|
|
const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting');
|
|
|
add.disabled = state.busy || pendingTombstones;
|
|
|
save.disabled = state.busy || pendingTombstones;
|
|
|
toolbar.append(add, save); card.append(list, toolbar); return card;
|
|
|
}
|
|
|
|
|
|
function renderOperations(doc) {
|
|
|
const card = section('最近操作', '每次修改都会生成独立的 VPC revision;只有宿主机精确回读后才会进入 active。', 'vpc-operations');
|
|
|
const list = element('div', 'vpc-operation-list');
|
|
|
for (const row of doc.operations.slice(0, 12)) {
|
|
|
const item = element('div', 'vpc-operation-row');
|
|
|
item.append(element('span', '', operationLabel(row.kind)), statusPill(row.status === 'waiting_observed' ? 'waiting' : row.status),
|
|
|
element('small', '', `revision ${row.desired_revision || 0}${row.error_code ? ` · ${row.error_code}` : ''}`));
|
|
|
list.append(item);
|
|
|
}
|
|
|
if (!doc.operations.length) list.append(element('p', 'vpc-empty-inline', '暂无操作记录。'));
|
|
|
card.append(list); return card;
|
|
|
}
|
|
|
|
|
|
function createRegionOptions() {
|
|
|
const select = byId('vpc-create-region');
|
|
|
const previousValue = select.value;
|
|
|
const open = byId('vpc-create-open');
|
|
|
const submit = byId('vpc-create-submit');
|
|
|
const availability = byId('vpc-create-availability');
|
|
|
select.replaceChildren();
|
|
|
if (!state.regions.length) {
|
|
|
select.append(new Option('暂无可用 Fabric 地区', ''));
|
|
|
select.disabled = true;
|
|
|
open.disabled = true;
|
|
|
submit.disabled = true;
|
|
|
availability.hidden = false;
|
|
|
open.title = '管理员尚未开放可用 Fabric 地区';
|
|
|
byId('vpc-create-region-hint').textContent = '管理员尚未完成可用 Fabric 映射,暂不能创建 VPC。';
|
|
|
return;
|
|
|
}
|
|
|
select.disabled = false;
|
|
|
open.disabled = state.busy;
|
|
|
submit.disabled = state.busy;
|
|
|
availability.hidden = true;
|
|
|
open.removeAttribute('title');
|
|
|
byId('vpc-create-region-hint').textContent = '只列出已完成 Fabric 映射的地区;网段、子网和成员地址均自动分配。';
|
|
|
const placeholder = new Option('请选择地区', '', true, true);
|
|
|
placeholder.disabled = true;
|
|
|
select.append(placeholder);
|
|
|
for (const row of state.regions) select.append(new Option(String(row.name), String(row.id)));
|
|
|
if (state.regions.some(row => String(row.id) === previousValue)) select.value = previousValue;
|
|
|
}
|
|
|
|
|
|
function hasPendingCreateIntent(form) {
|
|
|
return /^[A-Za-z0-9_.:-]{8,128}$/.test(form?.dataset?.requestKey || '')
|
|
|
&& Boolean(form?.dataset?.requestFingerprint);
|
|
|
}
|
|
|
|
|
|
function resetCreateIntent(form) {
|
|
|
delete form.dataset.requestKey;
|
|
|
delete form.dataset.requestFingerprint;
|
|
|
}
|
|
|
|
|
|
function openCreateModal() {
|
|
|
if (state.busy || !state.regions.length) return;
|
|
|
const form = byId('vpc-create-form');
|
|
|
state.createFocusReturn = document.activeElement;
|
|
|
// Preserve a submitted intent across close/reopen. A transport failure may
|
|
|
// have lost a successful 202 response, so retrying the same values must
|
|
|
// reuse the same request key instead of allocating a second VPC/CIDR.
|
|
|
if (!hasPendingCreateIntent(form)) {
|
|
|
form.reset();
|
|
|
setFormError('vpc-create-error', '');
|
|
|
}
|
|
|
createRegionOptions();
|
|
|
byId('vpc-create-modal').hidden = false;
|
|
|
document.body.classList.add('vpc-modal-open');
|
|
|
byId('vpc-create-name').focus();
|
|
|
}
|
|
|
|
|
|
function closeCreateModal(resetIntent = false, force = false) {
|
|
|
if (state.busy && !force) return;
|
|
|
const modal = byId('vpc-create-modal');
|
|
|
if (modal.hidden) return;
|
|
|
modal.hidden = true;
|
|
|
document.body.classList.remove('vpc-modal-open');
|
|
|
const form = byId('vpc-create-form');
|
|
|
if (resetIntent) {
|
|
|
resetCreateIntent(form);
|
|
|
setFormError('vpc-create-error', '');
|
|
|
}
|
|
|
const returnTarget = state.createFocusReturn;
|
|
|
state.createFocusReturn = null;
|
|
|
if (returnTarget instanceof HTMLElement && returnTarget.isConnected
|
|
|
&& !returnTarget.disabled) returnTarget.focus();
|
|
|
else byId('vpc-create-open')?.focus();
|
|
|
}
|
|
|
|
|
|
function handleCreateModalKeydown(event) {
|
|
|
const modal = byId('vpc-create-modal');
|
|
|
if (!modal || modal.hidden) return;
|
|
|
if (event.key === 'Escape') {
|
|
|
event.preventDefault();
|
|
|
closeCreateModal();
|
|
|
return;
|
|
|
}
|
|
|
if (event.key !== 'Tab') return;
|
|
|
const focusable = [...byId('vpc-create-panel').querySelectorAll(
|
|
|
'button:not(:disabled), input:not(:disabled), select:not(:disabled), [tabindex]:not([tabindex="-1"])'
|
|
|
)];
|
|
|
if (!focusable.length) return;
|
|
|
const first = focusable[0];
|
|
|
const last = focusable[focusable.length - 1];
|
|
|
if (event.shiftKey && document.activeElement === first) {
|
|
|
event.preventDefault();
|
|
|
last.focus();
|
|
|
} else if (!event.shiftKey && document.activeElement === last) {
|
|
|
event.preventDefault();
|
|
|
first.focus();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadList(silent = false) {
|
|
|
const epoch = ++state.listEpoch;
|
|
|
state.listController?.abort(); state.listController = new AbortController();
|
|
|
try {
|
|
|
const payload = await api('/api/v1/vpcs', { signal: state.listController.signal });
|
|
|
if (epoch !== state.listEpoch || state.stopped) return null;
|
|
|
state.vpcs = Array.isArray(payload?.vpcs) ? payload.vpcs.map(normalizeRoot)
|
|
|
.filter(item => item && rootStatus(item) !== 'deleted') : [];
|
|
|
// The list is bounded to the newest 200 rows. Absence from it is not a
|
|
|
// deletion receipt, so keep a selected tombstone until its detail read
|
|
|
// explicitly reports state=deleted.
|
|
|
renderList();
|
|
|
if (!silent) setError('');
|
|
|
return null;
|
|
|
} catch (error) {
|
|
|
if (error?.name === 'AbortError') return null;
|
|
|
if (!silent || !state.vpcs.length) setError(error.message);
|
|
|
return error;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadDetail(key, silent = false, allowDirty = false) {
|
|
|
if (!key) return;
|
|
|
if (state.detailDirty && !allowDirty) return;
|
|
|
const epoch = ++state.detailEpoch;
|
|
|
state.detailController?.abort(); state.detailController = new AbortController();
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, { signal: state.detailController.signal });
|
|
|
if (epoch !== state.detailEpoch || state.stopped || key !== state.selectedKey) return null;
|
|
|
state.selected = normalizeDocument(payload);
|
|
|
if (rootStatus(state.selected?.vpc) === 'deleted') {
|
|
|
finishVpcDeletion();
|
|
|
await loadList(true);
|
|
|
return null;
|
|
|
}
|
|
|
state.vpcs = state.vpcs.map(item => item.vpc_key === state.selected.vpc.vpc_key
|
|
|
? state.selected.vpc : item);
|
|
|
byId('vpc-detail-panel').hidden = !state.selected;
|
|
|
renderList();
|
|
|
renderDetail();
|
|
|
if (!silent) setError('');
|
|
|
return null;
|
|
|
} catch (error) {
|
|
|
if (error?.name === 'AbortError') return null;
|
|
|
if (!silent) setError(error.message);
|
|
|
return error;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function selectVpc(key) {
|
|
|
if (state.detailDirty
|
|
|
&& !confirm('当前 VPC 有未保存修改,切换后会丢失这些修改。继续吗?')) return;
|
|
|
clearDetailDirty();
|
|
|
state.selectedKey = String(key || '');
|
|
|
state.selected = null;
|
|
|
byId('vpc-detail-panel').hidden = true;
|
|
|
const detail = byId('vpc-detail');
|
|
|
detail.replaceChildren();
|
|
|
delete detail.dataset.vpcKey;
|
|
|
renderList();
|
|
|
await loadDetail(state.selectedKey);
|
|
|
schedulePoll(needsPolling() ? 5000 : 30000);
|
|
|
}
|
|
|
|
|
|
async function applyDocument(payload, message = '') {
|
|
|
const doc = normalizeDocument(payload);
|
|
|
if (doc) {
|
|
|
if (rootStatus(doc.vpc) === 'deleted') {
|
|
|
finishVpcDeletion();
|
|
|
await loadList(true);
|
|
|
return;
|
|
|
}
|
|
|
clearDetailDirty();
|
|
|
state.selected = doc;
|
|
|
state.selectedKey = doc.vpc.vpc_key;
|
|
|
if (!state.vpcs.some(item => item.vpc_key === doc.vpc.vpc_key)) state.vpcs.unshift(doc.vpc);
|
|
|
else state.vpcs = state.vpcs.map(item => item.vpc_key === doc.vpc.vpc_key ? doc.vpc : item);
|
|
|
byId('vpc-detail-panel').hidden = false;
|
|
|
renderList(); renderDetail();
|
|
|
}
|
|
|
if (message) { setNotice(message, 'success'); toast(message, 'success'); }
|
|
|
schedulePoll(needsPolling() ? 1500 : 30000);
|
|
|
}
|
|
|
|
|
|
async function mutate(path, method, body, message) {
|
|
|
if (state.busy) return null;
|
|
|
clearTimeout(state.pollTimer);
|
|
|
cancelReadbacks();
|
|
|
const controls = [...document.querySelectorAll('#vpc-workspace button, #vpc-workspace input, #vpc-workspace select')];
|
|
|
const previousDisabled = new Map(controls.map(node => [node, node.disabled]));
|
|
|
state.busy = true; controls.forEach(node => { node.disabled = true; });
|
|
|
let succeeded = false;
|
|
|
try {
|
|
|
const payload = await api(path, { method, body });
|
|
|
await applyDocument(payload, message);
|
|
|
succeeded = true;
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
setError(error.message); setNotice(''); return null;
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
previousDisabled.forEach((disabled, node) => {
|
|
|
if (node.isConnected) node.disabled = disabled;
|
|
|
});
|
|
|
createRegionOptions(); renderList();
|
|
|
if (succeeded && state.selected) renderDetail();
|
|
|
else refreshRouteEditorState();
|
|
|
schedulePoll(succeeded && needsPolling() ? 1500 : undefined);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function createVpc(event) {
|
|
|
event.preventDefault(); if (state.busy) return;
|
|
|
setFormError('vpc-create-error', ''); setError('');
|
|
|
const form = event.currentTarget;
|
|
|
if (!state.regions.length) {
|
|
|
setFormError('vpc-create-error', '管理员尚未开放可用 Fabric 地区,暂不能创建 VPC。');
|
|
|
return;
|
|
|
}
|
|
|
if (!form.checkValidity()) {
|
|
|
form.reportValidity();
|
|
|
return;
|
|
|
}
|
|
|
const body = {
|
|
|
name: form.name.value.trim(), region_id: Number(form.region_id.value),
|
|
|
};
|
|
|
if (!confirmDetailMutation()) return;
|
|
|
// Keep one idempotency key for the same form values until the server has
|
|
|
// acknowledged the create. A lost 202 response must be retryable without
|
|
|
// allocating a second VPC/CIDR; changing the values starts a new intent.
|
|
|
const fingerprint = JSON.stringify(body);
|
|
|
if (form.dataset.requestFingerprint !== fingerprint
|
|
|
|| !/^[A-Za-z0-9_.:-]{8,128}$/.test(form.dataset.requestKey || '')) {
|
|
|
form.dataset.requestKey = requestKey('vpc-create');
|
|
|
form.dataset.requestFingerprint = fingerprint;
|
|
|
}
|
|
|
body.request_key = form.dataset.requestKey;
|
|
|
clearTimeout(state.pollTimer);
|
|
|
cancelReadbacks();
|
|
|
const controls = [...document.querySelectorAll(
|
|
|
'#vpc-workspace button, #vpc-workspace input, #vpc-workspace select'
|
|
|
)];
|
|
|
const previousDisabled = new Map(controls.map(node => [node, node.disabled]));
|
|
|
state.busy = true;
|
|
|
controls.forEach(node => { node.disabled = true; });
|
|
|
byId('vpc-create-submit').disabled = true;
|
|
|
byId('vpc-create-close').disabled = true;
|
|
|
byId('vpc-create-cancel').disabled = true;
|
|
|
let acknowledged = false;
|
|
|
try {
|
|
|
const payload = await api('/api/v1/vpcs', { method: 'POST', body });
|
|
|
acknowledged = true;
|
|
|
resetCreateIntent(form);
|
|
|
form.reset();
|
|
|
await applyDocument(payload, 'VPC 已创建。请添加同地区实例以启用私网。');
|
|
|
} catch (error) { setFormError('vpc-create-error', error.message); }
|
|
|
finally {
|
|
|
state.busy = false;
|
|
|
previousDisabled.forEach((disabled, node) => {
|
|
|
if (node.isConnected) node.disabled = disabled;
|
|
|
});
|
|
|
byId('vpc-create-close').disabled = false;
|
|
|
byId('vpc-create-cancel').disabled = false;
|
|
|
if (acknowledged) closeCreateModal(true, true);
|
|
|
createRegionOptions(); renderList();
|
|
|
if (acknowledged && state.selected) renderDetail();
|
|
|
schedulePoll(needsPolling() ? 1500 : 30000);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function submitMember(form) {
|
|
|
if (!allowSelectedMutation() || !confirmDetailMutation()) return;
|
|
|
const instanceId = Number(form.instance_id.value);
|
|
|
if (!Number.isInteger(instanceId) || instanceId < 1) {
|
|
|
setError('请选择一个已核验为同地区的实例。');
|
|
|
return;
|
|
|
}
|
|
|
const body = { instance_id: instanceId, request_key: requestKey('member-add') };
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body,
|
|
|
'实例已加入 VPC 目标,私网 IP 已自动分配,网卡将在实际回读后显示为可用。');
|
|
|
}
|
|
|
|
|
|
function readRoutes() {
|
|
|
return [...document.querySelectorAll('#vpc-route-editor .vpc-editor-row')].map(row => ({
|
|
|
route_key: row.dataset.routeKey,
|
|
|
destination_cidr: row.querySelector('[data-route-field="destination_cidr"]').value.trim(),
|
|
|
next_hop_ip: row.querySelector('[data-route-field="next_hop_ip"]').value,
|
|
|
metric: Number(row.querySelector('[data-route-field="metric"]').value || 100),
|
|
|
}));
|
|
|
}
|
|
|
|
|
|
function readAcl() {
|
|
|
return [...document.querySelectorAll('#vpc-acl-editor .vpc-editor-row')].map(row => {
|
|
|
const value = fieldName => row.querySelector(`[data-acl-field="${fieldName}"]`).value.trim();
|
|
|
const item = {
|
|
|
rule_key: row.dataset.aclKey, priority: Number(value('priority') || 100),
|
|
|
direction: value('direction'), action: value('action'), protocol: value('protocol'),
|
|
|
source_cidr: value('source_cidr'), destination_cidr: value('destination_cidr'),
|
|
|
port_from: value('port_from') === '' ? null : Number(value('port_from')),
|
|
|
port_to: value('port_to') === '' ? null : Number(value('port_to')),
|
|
|
};
|
|
|
return item;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function saveEditor(kind) {
|
|
|
if (!allowSelectedMutation()) return;
|
|
|
if (!hasPolicyMember()) {
|
|
|
setError('请先添加同地区实例并处理现有同步诊断;有可用成员后才可保存 Route 或 ACL。');
|
|
|
return;
|
|
|
}
|
|
|
if (kind === 'routes') {
|
|
|
refreshRouteEditorState();
|
|
|
if (document.querySelector('#vpc-route-editor [data-vpc-tombstone-state="deleting"]')) {
|
|
|
setError('路由仍有删除中的记录,待宿主机回读完成后再保存整套路由。');
|
|
|
return;
|
|
|
}
|
|
|
if (document.querySelector('#vpc-route-editor [data-invalid="true"]')) {
|
|
|
setError('路由下一跳必须选择当前仍在 VPC 中的成员私网 IP。');
|
|
|
return;
|
|
|
}
|
|
|
}
|
|
|
if (kind === 'acl' && document.querySelector('#vpc-acl-editor [data-vpc-tombstone-state="deleting"]')) {
|
|
|
setError('ACL 仍有删除中的记录,待宿主机回读完成后再保存整套 ACL。');
|
|
|
return;
|
|
|
}
|
|
|
const body = kind === 'routes'
|
|
|
? { routes: readRoutes(), request_key: requestKey('routes') }
|
|
|
: { rules: readAcl(), request_key: requestKey('acl') };
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/${kind === 'routes' ? 'routes' : 'acl'}`,
|
|
|
'PUT', body, `${kind === 'routes' ? '路由' : 'ACL'} 目标已提交,等待宿主机回读。`);
|
|
|
}
|
|
|
|
|
|
async function reconcile() {
|
|
|
if (state.busy || !selectedDocumentCurrent()) {
|
|
|
if (!state.busy) setError('VPC 详情尚未读取完成,请等待刷新后再核对。');
|
|
|
return;
|
|
|
}
|
|
|
if (rootStatus(state.selected?.vpc) === 'awaiting_members') {
|
|
|
setNotice('VPC 正在等待实例;添加同地区实例后会自动生成新的配置版本。', 'warning');
|
|
|
return;
|
|
|
}
|
|
|
if (state.detailDirty
|
|
|
&& !confirm('当前 VPC 有未保存修改,核对后会丢失这些修改。继续吗?')) return;
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/reconcile`, 'POST', {}, '已请求重新核对 VPC 状态。');
|
|
|
}
|
|
|
|
|
|
async function removeMember(key) {
|
|
|
if (!state.selectedKey || state.busy || !allowSelectedMutation() || !confirmDetailMutation()
|
|
|
|| !confirm('确认让这个实例退出 VPC?宿主机回读确认前,私网 IP 不会重新分配。')) return;
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members/${encodeURIComponent(key)}`,
|
|
|
'DELETE', { request_key: requestKey('member-remove') }, '成员退出目标已提交,等待私网网卡移除回读。');
|
|
|
}
|
|
|
|
|
|
async function deleteVpc() {
|
|
|
if (!state.selectedKey || !state.selected || state.busy || selectedRootDeleting()) return;
|
|
|
if (!confirmDetailMutation()) return;
|
|
|
const root = state.selected.vpc;
|
|
|
const confirmation = prompt(`永久删除 VPC“${root.name}”并清理其私网网卡、路由和 ACL。宿主机回读完成后 CIDR 将被释放。请输入完整 VPC 名称确认:`);
|
|
|
if (confirmation === null) return;
|
|
|
if (confirmation !== root.name) {
|
|
|
toast('VPC 名称不匹配,未执行删除。', 'error');
|
|
|
return;
|
|
|
}
|
|
|
const key = state.deleteRequestKeys.get(root.vpc_key) || requestKey('vpc-delete');
|
|
|
state.deleteRequestKeys.set(root.vpc_key, key);
|
|
|
// A detail poll started before the destructive mutation must not overwrite
|
|
|
// the returned deleting state with its older active projection.
|
|
|
state.detailController?.abort();
|
|
|
state.detailController = null;
|
|
|
state.detailEpoch += 1;
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(root.vpc_key)}`, 'DELETE', {
|
|
|
confirmation_name: root.name,
|
|
|
request_key: key,
|
|
|
}, 'VPC 删除目标已提交;完成宿主机清理前不会释放 CIDR。');
|
|
|
}
|
|
|
|
|
|
function handleClick(event) {
|
|
|
const listRow = event.target.closest('[data-vpc-key]');
|
|
|
if (listRow && listRow.closest('#vpc-list')) { selectVpc(listRow.dataset.vpcKey); return; }
|
|
|
const removeMemberKey = event.target.closest('[data-vpc-remove-member]')?.dataset.vpcRemoveMember;
|
|
|
if (removeMemberKey) { removeMember(removeMemberKey); return; }
|
|
|
const action = event.target.closest('[data-vpc-action]')?.dataset.vpcAction;
|
|
|
if (action === 'add-member') {
|
|
|
const select = byId('vpc-member-instance');
|
|
|
select?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
|
select?.focus();
|
|
|
return;
|
|
|
}
|
|
|
if (action === 'reconcile') { reconcile(); return; }
|
|
|
if (action === 'delete') { deleteVpc(); return; }
|
|
|
const add = event.target.closest('[data-editor-add]')?.dataset.editorAdd;
|
|
|
if (add) {
|
|
|
if (!allowSelectedMutation()) return;
|
|
|
if (!hasPolicyMember()) {
|
|
|
setError('请先添加同地区实例并处理现有同步诊断;有可用成员后才可编辑 Route 或 ACL。');
|
|
|
return;
|
|
|
}
|
|
|
const list = byId(add === 'route' ? 'vpc-route-editor' : 'vpc-acl-editor');
|
|
|
if (list.querySelector('[data-vpc-tombstone-state="deleting"]')) return;
|
|
|
list.querySelector('.vpc-empty-inline')?.remove();
|
|
|
list.append(add === 'route' ? routeRow() : aclRow());
|
|
|
markDetailDirty();
|
|
|
refreshRouteEditorState();
|
|
|
return;
|
|
|
}
|
|
|
const remove = event.target.closest('[data-editor-remove]')?.dataset.editorRemove;
|
|
|
if (remove) {
|
|
|
if (!allowSelectedMutation()) return;
|
|
|
event.target.closest('.vpc-editor-row')?.remove(); markDetailDirty(); refreshRouteEditorState(); return;
|
|
|
}
|
|
|
const save = event.target.closest('[data-vpc-save]')?.dataset.vpcSave;
|
|
|
if (save) saveEditor(save);
|
|
|
}
|
|
|
|
|
|
function handleSubmit(event) {
|
|
|
const kind = event.target.dataset.vpcForm;
|
|
|
if (kind === 'member') { event.preventDefault(); submitMember(event.target); }
|
|
|
}
|
|
|
|
|
|
function handleDetailInput(event) {
|
|
|
if (!event.target.closest('#vpc-route-editor, #vpc-acl-editor')) return;
|
|
|
markDetailDirty();
|
|
|
if (event.target.matches('[data-route-field="next_hop_ip"]')) refreshRouteEditorState();
|
|
|
}
|
|
|
|
|
|
function applyBootstrapPayload(payload, includeVpcs = false) {
|
|
|
const user = payload?.user;
|
|
|
if (!user || !/^[a-f0-9]{64}$/.test(String(user.csrf_token || ''))
|
|
|
|| !/^[1-9]\d*$/.test(String(user.user_id || ''))) {
|
|
|
throw new Error('VPC 页面安全会话缺失,请刷新页面。');
|
|
|
}
|
|
|
if (state.userId && state.userId !== String(user.user_id)) {
|
|
|
throw new Error('当前登录账户已变化,请重新加载页面。');
|
|
|
}
|
|
|
state.csrfToken = String(user.csrf_token); state.userId = String(user.user_id);
|
|
|
state.regions = Array.isArray(payload.regions) ? payload.regions : [];
|
|
|
state.instances = Array.isArray(payload.instances) ? payload.instances : [];
|
|
|
if (includeVpcs) {
|
|
|
state.vpcs = Array.isArray(payload.vpcs) ? payload.vpcs.map(normalizeRoot)
|
|
|
.filter(item => item && rootStatus(item) !== 'deleted') : [];
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function readBootstrap() {
|
|
|
const node = byId('vpc-bootstrap');
|
|
|
let payload;
|
|
|
try { payload = JSON.parse(node?.textContent || '{}'); } catch { throw new Error('VPC 页面初始数据无效,请刷新页面。'); }
|
|
|
applyBootstrapPayload(payload, true);
|
|
|
}
|
|
|
|
|
|
async function refreshBootstrap(silent = false) {
|
|
|
const epoch = ++state.bootstrapEpoch;
|
|
|
state.bootstrapController?.abort();
|
|
|
state.bootstrapController = new AbortController();
|
|
|
try {
|
|
|
const response = await fetch(`${location.pathname}${location.search}`, {
|
|
|
method: 'GET',
|
|
|
headers: new Headers({ Accept: 'text/html' }),
|
|
|
credentials: 'same-origin',
|
|
|
cache: 'no-store',
|
|
|
signal: state.bootstrapController.signal,
|
|
|
});
|
|
|
if (!response.ok) throw new Error(`页面候选数据刷新失败 (${response.status})`);
|
|
|
const html = await response.text();
|
|
|
if (epoch !== state.bootstrapEpoch || state.stopped) return null;
|
|
|
const page = new DOMParser().parseFromString(html, 'text/html');
|
|
|
const node = page.getElementById('vpc-bootstrap');
|
|
|
if (!node) throw new Error('页面候选数据缺失,请重新登录后刷新。');
|
|
|
let payload;
|
|
|
try { payload = JSON.parse(node.textContent || '{}'); }
|
|
|
catch { throw new Error('页面候选数据无效,请重新加载页面。'); }
|
|
|
applyBootstrapPayload(payload, false);
|
|
|
createRegionOptions();
|
|
|
renderList();
|
|
|
if (state.selected) renderDetail();
|
|
|
return null;
|
|
|
} catch (error) {
|
|
|
if (error?.name === 'AbortError') return null;
|
|
|
if (!silent) setError(error.message);
|
|
|
return error;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function refreshWorkspace() {
|
|
|
if (state.busy) return;
|
|
|
const epoch = ++state.refreshEpoch;
|
|
|
clearTimeout(state.pollTimer);
|
|
|
const selectedKey = state.selectedKey;
|
|
|
const [bootstrapError, listError] = await Promise.all([
|
|
|
refreshBootstrap(true),
|
|
|
loadList(true),
|
|
|
]);
|
|
|
if (epoch !== state.refreshEpoch || state.stopped) return;
|
|
|
const detailError = selectedKey && selectedKey === state.selectedKey
|
|
|
? await loadDetail(selectedKey, true, true) : null;
|
|
|
if (epoch !== state.refreshEpoch || state.stopped) return;
|
|
|
const errors = [bootstrapError, listError, detailError]
|
|
|
.filter(error => error instanceof Error)
|
|
|
.map(error => error.message);
|
|
|
setError([...new Set(errors)].join(';'));
|
|
|
schedulePoll();
|
|
|
}
|
|
|
|
|
|
function bind() {
|
|
|
byId('vpc-create-open').addEventListener('click', openCreateModal);
|
|
|
byId('vpc-create-close').addEventListener('click', () => closeCreateModal());
|
|
|
byId('vpc-create-cancel').addEventListener('click', () => closeCreateModal());
|
|
|
byId('vpc-create-modal').addEventListener('click', event => {
|
|
|
if (event.target === byId('vpc-create-modal')) closeCreateModal();
|
|
|
});
|
|
|
byId('vpc-create-form').addEventListener('submit', createVpc);
|
|
|
byId('vpc-refresh').addEventListener('click', async () => {
|
|
|
if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return;
|
|
|
await refreshWorkspace();
|
|
|
});
|
|
|
byId('vpc-list-reconcile').addEventListener('click', reconcile);
|
|
|
byId('vpc-workspace').addEventListener('click', handleClick);
|
|
|
byId('vpc-workspace').addEventListener('submit', handleSubmit);
|
|
|
byId('vpc-workspace').addEventListener('input', handleDetailInput);
|
|
|
byId('vpc-workspace').addEventListener('change', handleDetailInput);
|
|
|
byId('vpc-detail-refresh').addEventListener('click', async () => {
|
|
|
if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return;
|
|
|
await refreshWorkspace();
|
|
|
});
|
|
|
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') schedulePoll(1000); else clearTimeout(state.pollTimer); });
|
|
|
document.addEventListener('keydown', handleCreateModalKeydown);
|
|
|
window.addEventListener('beforeunload', () => { state.stopped = true; state.bootstrapController?.abort(); state.listController?.abort(); state.detailController?.abort(); clearTimeout(state.pollTimer); }, { once: true });
|
|
|
}
|
|
|
|
|
|
export async function initialize() {
|
|
|
try {
|
|
|
readBootstrap(); bind(); createRegionOptions(); renderList();
|
|
|
await loadList();
|
|
|
if (state.vpcs.length) await selectVpc(state.selectedKey || state.vpcs[0].vpc_key);
|
|
|
schedulePoll(needsPolling() ? 3000 : 30000);
|
|
|
} catch (error) { setError(error.message); }
|
|
|
}
|