|
|
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: '执行中', paused: '已暂停', stopped: '回读时已关机', 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 configurationReady(root) {
|
|
|
if (projectionFieldKnown(root, 'configured')) return root?.configured === true;
|
|
|
// Compatibility for a rolling PHP/UI deployment. Older responses exposed
|
|
|
// only the stricter aggregate runtime signal.
|
|
|
return root?.usable === true;
|
|
|
}
|
|
|
|
|
|
function awaitingMembers(root) {
|
|
|
const raw = String(root?.state || '').toLowerCase();
|
|
|
if (raw === 'deleting' || configurationReady(root)) 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 (configurationReady(root)) 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', 'stopped', '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: '宿主机回读尚未完整,请稍后核对。',
|
|
|
vpc_private_guest_restart_required: '请先将实例完全关机,再点“核对 / 重试”写入私网配置;完成后启动实例,等待来宾网络核验。',
|
|
|
vpc_private_remove_requires_stopped: '实例仍有待清理的私网配置,请先完全关机,再点“核对 / 重试”移除;清理确认前私网 IP 会继续保留。',
|
|
|
vpc_private_guest_shutdown_pending: '正在等待实例完全关机;关机完成后请点“核对 / 重试”。',
|
|
|
vpc_private_guest_stopped: '私网配置已写入,上次回读时实例处于关机状态;开机后的来宾网络仍待核验。',
|
|
|
vpc_private_guest_agent_unavailable: '无法连接实例内的来宾代理,请确认实例已启动并联系管理员检查代理服务;私网尚未确认可用。',
|
|
|
vpc_private_guest_probe_permission_denied: '来宾系统权限策略拒绝读取私网路由,请联系管理员检查 SELinux 或执行权限;私网尚未确认可用。',
|
|
|
vpc_private_guest_probe_unsupported: '来宾代理未提供私网核验所需能力,请联系管理员检查代理配置;私网尚未确认可用。',
|
|
|
vpc_private_guest_probe_uncertain: '来宾网络核验结果未确认,请联系管理员核对原探测记录;不要重复加入实例。',
|
|
|
vpc_private_guest_probe_deadline_exceeded: '来宾网络核验超时,请稍后核对;若持续超时,请联系管理员检查来宾代理。',
|
|
|
vpc_private_guest_probe_reap_required: '上一次来宾探测尚未完成核销,请联系管理员核对原探测记录;不要重复加入实例。',
|
|
|
vpc_private_guest_address_mismatch: '实例内的私网地址与当前 VPC 配置不一致,请检查私网配置后重新核对。',
|
|
|
vpc_private_guest_route_mismatch: '实例内的私网路由与当前 VPC 配置不一致,请检查私网路由后重新核对。',
|
|
|
vpc_private_guest_link_mismatch: '实例内的私网网卡尚未正常连通,请检查网卡状态后重新核对。',
|
|
|
vpc_instance_operation_pending: '成员实例还有未完成或结果待核对的任务,请先在实例详情中核对任务,再修改 VPC。',
|
|
|
vpc_auto_power_retired: '新的 VPC 成员操作不再自动关机或开机;请先将实例完全关机再重试。',
|
|
|
vpc_member_requires_stopped: '加入、退出或删除 VPC 前必须先将相关实例完全关机;平台不会自动操作电源。',
|
|
|
vpc_member_power_unavailable: '尚未读到实例的最新关机状态;请在实例详情刷新电源状态后重试。',
|
|
|
vpc_vm_not_persistent: '实例缺少可核对的持久化定义,暂不能修改私网;请联系管理员。',
|
|
|
vpc_vm_managed_save_present: '实例存在 managed-save 状态,暂不能修改私网;请联系管理员核对并清理保存状态。',
|
|
|
vpc_vm_native_snapshot_present: '实例存在原生快照,暂不能修改私网;请联系管理员核对快照后重试。',
|
|
|
vpc_vm_native_snapshot_state_unknown: '宿主机无法确认实例原生快照状态,暂不能修改私网;请联系管理员检查 libvirt。',
|
|
|
vpc_private_remove_unsafe: '实例存在 managed-save 或原生快照,暂不能移除私网;请联系管理员核对保存状态和快照。',
|
|
|
vpc_power_shutdown_timeout: '正常关机等待超时,自动流程已暂停,平台未强制断电。可在实例详情检查电源,必要时手动强制断电,再点击“核对 / 重试”继续。',
|
|
|
vpc_power_start_timeout: '启动命令已接受,但等待实例开机超时,自动流程已暂停。请在实例详情核对当前电源状态,再点击“核对 / 重试”;平台不会重复发送启动命令。',
|
|
|
vpc_power_result_uncertain: '电源请求的执行结果未确认,请先在实例详情核对原操作;不要重复提交加入或退出。',
|
|
|
vpc_power_state_unavailable: '当前实例电源状态不支持自动处理。请在实例详情核对状态,处理后再点击“核对 / 重试”。',
|
|
|
vpc_power_instance_busy: '实例还有其他任务或服务暂不可用,自动流程已暂停。请先在实例详情处理,再点击“核对 / 重试”。',
|
|
|
vpc_power_manual_override: '检测到新的手动电源操作,自动流程已暂停。确认实例状态后可点击“核对 / 重试”;本次流程不再自动恢复开机。',
|
|
|
vpc_power_command_rejected: '电源命令已确认未执行,自动流程已暂停。请在实例详情手动完成所需的关机或开机,再点击“核对 / 重试”;该按钮不会重新发送已失败的电源命令,手动操作后也不会再自动恢复开机。',
|
|
|
vpc_power_configuration_unconfirmed: '私网配置尚未完整确认,自动流程已暂停。请联系管理员核对宿主机;如需先恢复业务,可在实例详情处理电源。修复后再点击“核对 / 重试”,不要重复加入或退出。',
|
|
|
vpc_apply_coordination_busy: 'VPC 应用的协调资源仍被占用,自动流程已暂停。请联系管理员核对 Engine coordination claim 和数据库状态;确认原操作结果后再点击“核对 / 重试”,不要重复加入或退出。',
|
|
|
vpc_apply_coordination_uncertain: 'VPC 应用的协调结果未确认,自动流程已暂停。请联系管理员核对 Engine coordination claim、原操作记录和数据库状态;不要重复加入或退出。',
|
|
|
vpc_apply_coordination_unavailable: 'VPC 应用的协调数据库暂不可用,自动流程已暂停。请联系管理员检查 Engine 数据库连接与 coordination claim 状态;恢复并核对原操作后再点击“核对 / 重试”。',
|
|
|
}[String(code || '')] || '';
|
|
|
}
|
|
|
|
|
|
function operationLabel(kind) {
|
|
|
return OPERATION_LABELS[String(kind || '')] || safeText(kind, '未知操作');
|
|
|
}
|
|
|
|
|
|
function powerWorkflow(doc = state.selected) {
|
|
|
const operationId = String(doc?.vpc?.last_operation_id || '');
|
|
|
if (!operationId) return null;
|
|
|
const operation = doc?.operations?.find(row => row.operation_id === operationId
|
|
|
&& ['member_attach', 'member_detach'].includes(row.kind));
|
|
|
const value = operation?.power_workflow;
|
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
|
const removing = operation.kind === 'member_detach';
|
|
|
const phases = {
|
|
|
preflight: ['准备自动处理', '正在核对实例电源状态和本次私网操作。'],
|
|
|
shutting_down: ['正在请求正常关机', '只发送正常关机请求,不会自动强制断电。'],
|
|
|
waiting_stopped: ['等待实例完全关机', '关机请求已提交;确认实例停止后才会修改私网配置。'],
|
|
|
applying: [removing ? '正在移除私网配置' : '正在写入私网配置',
|
|
|
'正在应用并核对实例私网网卡和网络配置。'],
|
|
|
configured: ['私网配置已确认', '正在处理本次操作后的电源状态。'],
|
|
|
starting: ['正在恢复开机', '私网配置已确认,正在恢复原本运行的实例。'],
|
|
|
paused: ['自动流程已暂停', '请核对实例和最近操作,处理后点击“核对 / 重试”继续。'],
|
|
|
completed: ['自动流程已完成', removing
|
|
|
? '退出和电源处理已完成;私网地址以清理回读结果为准。'
|
|
|
: '加入和电源处理已完成;来宾网络可用性将单独核验。'],
|
|
|
};
|
|
|
const phase = String(value.phase || '');
|
|
|
if (!Object.prototype.hasOwnProperty.call(phases, phase)) return null;
|
|
|
const instanceId = Number(value.instance_id);
|
|
|
return {
|
|
|
phase, title: phases[phase][0], description: phases[phase][1],
|
|
|
operationLabel: operationLabel(operation.kind),
|
|
|
instanceId: Number.isSafeInteger(instanceId) && instanceId > 0 ? instanceId : null,
|
|
|
originalRunning: typeof value.original_running === 'boolean' ? value.original_running : null,
|
|
|
resumeCancelled: value.resume_cancelled === true,
|
|
|
error: errorLabel(value.error_code),
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function renderPowerWorkflow(doc) {
|
|
|
const workflow = powerWorkflow(doc);
|
|
|
if (!workflow) return null;
|
|
|
const title = `${workflow.operationLabel}进度${workflow.instanceId
|
|
|
? ` · ${instanceName(workflow.instanceId)}` : ''}`;
|
|
|
const card = section(title, workflow.description, `vpc-power-workflow ${workflow.phase}`);
|
|
|
card.append(element('strong', 'vpc-power-phase', workflow.title));
|
|
|
if (workflow.error) card.append(element('p', 'vpc-power-guidance', workflow.error));
|
|
|
if (workflow.resumeCancelled) {
|
|
|
card.append(element('p', 'vpc-power-guidance',
|
|
|
'已检测到新的手动电源操作,本次流程不再自动恢复开机;后续电源状态由你控制。'));
|
|
|
} else if (workflow.originalRunning === false) {
|
|
|
card.append(element('p', 'vpc-power-guidance', '实例原本已关机,本次操作会保持关机。'));
|
|
|
}
|
|
|
return card;
|
|
|
}
|
|
|
|
|
|
function hasPendingPowerWorkflow(doc = state.selected) {
|
|
|
const workflow = powerWorkflow(doc);
|
|
|
return Boolean(workflow && workflow.phase !== 'completed');
|
|
|
}
|
|
|
|
|
|
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 configuredKnown = Object.prototype.hasOwnProperty.call(value, 'configured');
|
|
|
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,
|
|
|
configured: value.configured === true,
|
|
|
configured_known: configuredKnown,
|
|
|
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']);
|
|
|
const workflow = powerWorkflow();
|
|
|
const selectedKey = state.selected?.vpc?.vpc_key;
|
|
|
const selectedPaused = workflow?.phase === 'paused';
|
|
|
return Boolean(state.vpcs.some(vpc => {
|
|
|
const selected = selectedKey === vpc.vpc_key;
|
|
|
return (!selected || !selectedPaused)
|
|
|
&& fastStatuses.has(rootStatus(selected ? state.selected.vpc : vpc));
|
|
|
})
|
|
|
|| (state.selected && !selectedPaused && fastStatuses.has(rootStatus(state.selected.vpc)))
|
|
|
|| (workflow && !['paused', 'completed'].includes(workflow.phase)));
|
|
|
}
|
|
|
|
|
|
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 Promise.all([loadList(true), refreshBootstrap(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 paused = selectedDocument && powerWorkflow(selectedDocument)?.phase === 'paused';
|
|
|
const row = element('button', `vpc-list-row${root.vpc_key === state.selectedKey ? ' selected' : ''}`);
|
|
|
row.type = 'button';
|
|
|
row.dataset.vpcKey = root.vpc_key;
|
|
|
row.setAttribute('aria-pressed', String(root.vpc_key === state.selectedKey));
|
|
|
row.setAttribute('aria-controls', 'vpc-detail-panel');
|
|
|
const main = element('span', 'vpc-list-main');
|
|
|
const heading = element('span', 'vpc-list-heading');
|
|
|
heading.append(element('strong', '', displayRoot.name), statusPill(paused ? 'paused' : 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', '', paused ? '自动流程已暂停,请核对 / 重试'
|
|
|
: (status === 'awaiting_members' ? '下一步:添加实例'
|
|
|
: (configurationReady(displayRoot)
|
|
|
? (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) || hasMemberCleanup()
|
|
|
|| hasPendingPowerWorkflow());
|
|
|
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 power = powerWorkflow(doc);
|
|
|
const paused = power?.phase === 'paused';
|
|
|
const rootHint = status !== 'awaiting_members'
|
|
|
&& EMPTY_MEMBER_GATE_CODES.has(String(root.last_error_code || ''))
|
|
|
? '当前私网台账未满足空 VPC 的安全条件,请展开“同步与诊断”核对。'
|
|
|
: errorLabel(root.last_error_code);
|
|
|
overviewHeading.append(statusPill(paused ? 'paused' : status),
|
|
|
element('span', 'vpc-readback-note', paused ? (power.error || power.description)
|
|
|
: (configurationReady(root)
|
|
|
? (root.usable === true
|
|
|
? 'WireGuard、私网路由、实例网卡和成员运行状态均已确认。'
|
|
|
: '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);
|
|
|
}
|
|
|
if (!['active', 'awaiting_members'].includes(status) || hasMemberCleanup(doc)
|
|
|
|| hasPendingPowerWorkflow(doc)) {
|
|
|
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);
|
|
|
|
|
|
const workflow = renderPowerWorkflow(doc);
|
|
|
if (workflow) container.append(workflow);
|
|
|
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('配置状态', configurationReady(root) ? '已应用' : '待回读'),
|
|
|
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 hasMemberCleanup(doc = state.selected) {
|
|
|
return Boolean(doc?.members?.some(item => childStatus(item.state) === 'deleted'));
|
|
|
}
|
|
|
|
|
|
function memberChoice(row, doc) {
|
|
|
const current = doc?.members?.find(item => Number(item.instance_id) === Number(row?.id));
|
|
|
const attachment = row?.vpc_attachment;
|
|
|
if (current && ['deleting', 'deleted'].includes(childStatus(current.state))) {
|
|
|
return { disabled: true, reason: '旧 VPC 私网仍在清理' };
|
|
|
}
|
|
|
if (attachment?.state === 'cleanup_pending') {
|
|
|
const name = String(attachment.vpc_name || '').trim();
|
|
|
return { disabled: true, reason: name
|
|
|
? `旧 VPC:${name} 仍在清理,请先核对` : '旧 VPC 私网仍在清理' };
|
|
|
}
|
|
|
if (current) return { disabled: true, reason: '已在当前 VPC' };
|
|
|
if (attachment?.state === 'attached') {
|
|
|
const name = String(attachment.vpc_name || '').trim();
|
|
|
return { disabled: true, reason: attachment.vpc_key === doc?.vpc?.vpc_key
|
|
|
? '已在当前 VPC' : (name ? `已加入 VPC:${name}` : '已加入其他 VPC') };
|
|
|
}
|
|
|
// Only an explicit, current server projection proves that both the member
|
|
|
// and its independent private-IP reservation have been released.
|
|
|
if (attachment?.state !== 'available') {
|
|
|
return { disabled: true, reason: '私网归属待核验,请刷新' };
|
|
|
}
|
|
|
if (row.service_available === false) return { disabled: true, reason: '服务当前不可用' };
|
|
|
const regionId = Number(row.region_id);
|
|
|
if (!Number.isInteger(regionId) || regionId <= 0) {
|
|
|
return { disabled: true, reason: '地区待核验,暂不可加入' };
|
|
|
}
|
|
|
return regionId === Number(doc?.vpc?.region_id)
|
|
|
? { disabled: false, reason: '' } : { disabled: true, reason: '地区不匹配' };
|
|
|
}
|
|
|
|
|
|
function populateMemberChoices(select, doc) {
|
|
|
const previous = select.value;
|
|
|
const placeholder = new Option('请选择同地区实例', '', true, true);
|
|
|
placeholder.disabled = true;
|
|
|
const eligible = [];
|
|
|
const unavailable = [];
|
|
|
for (const row of state.instances.filter(item => item.service_available !== false)) {
|
|
|
const choice = memberChoice(row, doc);
|
|
|
const suffix = choice.reason ? ` · ${choice.reason}` : '';
|
|
|
const option = new Option(`${row.name} · ${safeText(row.region, '地区待核验')}${suffix}`, String(row.id));
|
|
|
option.dataset.regionId = row.region_id || '';
|
|
|
option.disabled = choice.disabled;
|
|
|
(option.disabled ? unavailable : eligible).push(option);
|
|
|
}
|
|
|
select.replaceChildren(placeholder, ...eligible, ...unavailable);
|
|
|
select.value = eligible.some(option => option.value === previous) ? previous : '';
|
|
|
return eligible.length;
|
|
|
}
|
|
|
|
|
|
function refreshMemberChoices() {
|
|
|
const select = byId('vpc-member-instance');
|
|
|
if (!select || !selectedDocumentCurrent()) return;
|
|
|
const count = populateMemberChoices(select, state.selected);
|
|
|
const save = document.querySelector('[data-vpc-member-submit]');
|
|
|
if (save) save.disabled = state.busy || selectedRootDeleting() || count === 0;
|
|
|
const hint = document.querySelector('[data-vpc-member-empty]');
|
|
|
if (hint) hint.hidden = count > 0;
|
|
|
}
|
|
|
|
|
|
function renderMembers(doc) {
|
|
|
const card = section('成员与私网 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 eligibleCount = populateMemberChoices(instance.control, doc);
|
|
|
const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit';
|
|
|
save.dataset.vpcMemberSubmit = 'true';
|
|
|
save.disabled = state.busy || eligibleCount === 0;
|
|
|
form.append(instance.wrapper, save); card.append(form);
|
|
|
const hint = element('p', 'vpc-member-empty-hint',
|
|
|
'当前没有可加入的同地区实例。已加入其他 VPC、私网仍在清理或归属待核验的实例暂不可加入。');
|
|
|
hint.dataset.vpcMemberEmpty = 'true';
|
|
|
hint.hidden = eligibleCount > 0;
|
|
|
card.append(hint);
|
|
|
if (hasMemberCleanup(doc)) {
|
|
|
card.append(element('p', 'vpc-member-empty-hint',
|
|
|
'存在尚未释放的旧成员记录。请点击“核对 / 重试”,完成清理核验后实例才可加入其他 VPC。'));
|
|
|
}
|
|
|
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');
|
|
|
const identity = element('div', 'vpc-member-identity');
|
|
|
identity.append(element('strong', '', instanceName(row.instance_id)),
|
|
|
element('code', 'vpc-member-ip', safeText(row.private_ip)));
|
|
|
const meta = element('div', 'vpc-member-meta');
|
|
|
meta.append(element('small', '', instanceRegion(row.instance_id)),
|
|
|
statusPill(childStatus(row.state)));
|
|
|
copy.append(identity, meta);
|
|
|
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', '新建 VPC 自动添加本 VPC /24 网段入站、出站允许规则,让组内实例互通;不匹配规则的通信仍默认拒绝。规则可编辑或删除,保存会替换整套 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
|
|
|
|| (state.detailDirty && !allowDirty)) 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();
|
|
|
const selectedKey = state.selectedKey;
|
|
|
await refreshBootstrap(true);
|
|
|
if (selectedKey !== state.selectedKey || state.stopped || state.busy) return;
|
|
|
await loadDetail(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 {
|
|
|
await refreshBootstrap(true);
|
|
|
state.busy = false;
|
|
|
previousDisabled.forEach((disabled, node) => {
|
|
|
if (node.isConnected) node.disabled = disabled;
|
|
|
});
|
|
|
createRegionOptions(); renderList();
|
|
|
if (succeeded && state.selected) renderDetail();
|
|
|
else refreshRouteEditorState();
|
|
|
refreshMemberChoices();
|
|
|
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 {
|
|
|
await refreshBootstrap(true);
|
|
|
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();
|
|
|
refreshMemberChoices();
|
|
|
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 row = state.instances.find(item => Number(item.id) === instanceId);
|
|
|
const choice = memberChoice(row, state.selected);
|
|
|
if (choice.disabled) {
|
|
|
setError(choice.reason);
|
|
|
refreshMemberChoices();
|
|
|
return;
|
|
|
}
|
|
|
if (!confirm(`确认将“${instanceName(instanceId)}”加入 VPC?请先确认实例已完全关机。平台不会自动关机或开机;写入和核对私网配置后,实例仍保持关机。`)) return;
|
|
|
const body = { instance_id: instanceId, request_key: requestKey('member-add') };
|
|
|
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body,
|
|
|
'已提交加入 VPC,正在写入并核对私网配置;实例会保持关机。');
|
|
|
}
|
|
|
|
|
|
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' && !hasMemberCleanup()
|
|
|
&& !hasPendingPowerWorkflow()) {
|
|
|
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') }, '已提交退出 VPC,正在移除并核对私网配置;实例会保持关机,清理确认前私网 IP 会继续保留。');
|
|
|
}
|
|
|
|
|
|
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。请先将 VPC 内全部实例完全关机;平台不会自动操作电源,实例会保持关机。宿主机回读完成后 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();
|
|
|
const controller = new AbortController();
|
|
|
state.bootstrapController = controller;
|
|
|
let timedOut = false;
|
|
|
const timeout = window.setTimeout(() => {
|
|
|
timedOut = true;
|
|
|
controller.abort();
|
|
|
}, 10000);
|
|
|
try {
|
|
|
const response = await fetch(`${location.pathname}${location.search}`, {
|
|
|
method: 'GET',
|
|
|
headers: new Headers({ Accept: 'text/html' }),
|
|
|
credentials: 'same-origin',
|
|
|
cache: 'no-store',
|
|
|
signal: controller.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();
|
|
|
// A candidate refresh must not rebuild an in-progress ACL/route editor.
|
|
|
refreshMemberChoices();
|
|
|
return null;
|
|
|
} catch (error) {
|
|
|
if (error?.name === 'AbortError' && !timedOut) return null;
|
|
|
if (epoch !== state.bootstrapEpoch || state.stopped) return null;
|
|
|
if (timedOut) error = new Error('实例归属读取超时,请稍后刷新。');
|
|
|
state.instances = state.instances.map(row => ({ ...row,
|
|
|
vpc_attachment: { state: 'unavailable', vpc_key: null, vpc_name: null },
|
|
|
}));
|
|
|
refreshMemberChoices();
|
|
|
if (!silent) setError(error.message);
|
|
|
return error;
|
|
|
} finally {
|
|
|
clearTimeout(timeout);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
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); }
|
|
|
}
|