|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
|
|
function versionedModuleUrl(path) {
|
|
|
const url = new URL(path, import.meta.url);
|
|
|
url.search = '';
|
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
|
return url.href;
|
|
|
}
|
|
|
|
|
|
const [taskObserver, runtime] = await Promise.all([
|
|
|
import(versionedModuleUrl('./task-observer.js')),
|
|
|
import(versionedModuleUrl('./runtime.js')),
|
|
|
]);
|
|
|
const {
|
|
|
announceTaskAccepted, observeTask, recoveryTaskFailureNotice,
|
|
|
resolvedTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl,
|
|
|
} = taskObserver;
|
|
|
const {
|
|
|
api, byId, initializeSession, readBootstrap, showError, toast,
|
|
|
} = runtime;
|
|
|
|
|
|
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options)
|
|
|
?? Promise.resolve(false);
|
|
|
|
|
|
const PORT_STATE_LABELS = Object.freeze({
|
|
|
preparing: ['正在连接', 'other'], attached: ['已连接', 'running'],
|
|
|
detaching: ['正在断开', 'other'], release_pending: ['等待清理', 'other'],
|
|
|
released: ['已断开', 'other'], migrating: ['正在迁移', 'other'],
|
|
|
});
|
|
|
|
|
|
const BATCH_ITEM_STATE_LABELS = Object.freeze({
|
|
|
waiting_route: ['等待中', 'other'],
|
|
|
queued: ['执行中', 'other'],
|
|
|
succeeded: ['已完成', 'running'],
|
|
|
failed: ['失败', 'failed'],
|
|
|
unknown: ['失败', 'failed'],
|
|
|
});
|
|
|
|
|
|
const state = {
|
|
|
items: [], instances: [], regions: [], maximum: 16, used: 0,
|
|
|
loading: false, controller: null, creating: false, initialized: false,
|
|
|
createKey: '', createFingerprint: '', userKey: 'unknown',
|
|
|
mutatingVpcs: new Set(), mutatingInstances: new Set(),
|
|
|
mutatingBatches: new Set(), membershipBatches: [],
|
|
|
batchRefreshAt: 0,
|
|
|
observers: new Map(), terminalTasks: new Set(),
|
|
|
expandedMacs: new Set(), selections: new Map(), memberQueries: new Map(),
|
|
|
regionOptions: '',
|
|
|
};
|
|
|
|
|
|
function element(tag, className = '', content) {
|
|
|
const node = document.createElement(tag);
|
|
|
if (className) node.className = className;
|
|
|
if (content !== undefined) node.textContent = String(content);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function idempotencyKey() {
|
|
|
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replaceAll('-', '');
|
|
|
if (globalThis.crypto?.getRandomValues) {
|
|
|
const bytes = new Uint8Array(16);
|
|
|
globalThis.crypto.getRandomValues(bytes);
|
|
|
return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
|
|
}
|
|
|
return `${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`
|
|
|
.padEnd(32, '0').slice(0, 32);
|
|
|
}
|
|
|
|
|
|
function transportUncertain(error) {
|
|
|
const status = Number(error?.status);
|
|
|
return error?.mutationMayHaveApplied === true
|
|
|
|| (Number.isFinite(status) && status >= 500)
|
|
|
|| /failed to fetch|network|load failed|timeout|timed out|abort/i
|
|
|
.test(String(error?.message || ''));
|
|
|
}
|
|
|
|
|
|
function setPageStatus(message = '', type = '') {
|
|
|
const target = byId('cloud-vpcs-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-settings-status${type ? ` ${type}` : ''}`;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function apply(payload) {
|
|
|
state.items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
state.instances = Array.isArray(payload?.instances) ? payload.instances : [];
|
|
|
state.membershipBatches = Array.isArray(payload?.membership_batches)
|
|
|
? payload.membership_batches : [];
|
|
|
state.regions = Array.isArray(payload?.regions) ? payload.regions : [];
|
|
|
state.maximum = Math.max(1, Number(payload?.maximum) || 16);
|
|
|
state.used = Math.max(0, Number(payload?.used) || state.items.length);
|
|
|
render();
|
|
|
observeActiveTasks();
|
|
|
observeActiveBatches();
|
|
|
}
|
|
|
|
|
|
function renderRegions() {
|
|
|
const select = byId('cloud-vpc-region');
|
|
|
const options = JSON.stringify(state.regions.map(region => [region.id, region.name, region.code]));
|
|
|
if (options !== state.regionOptions) {
|
|
|
state.regionOptions = options;
|
|
|
const selected = select.value;
|
|
|
select.replaceChildren();
|
|
|
const empty = element('option', '', state.regions.length
|
|
|
? '请选择地区' : '暂无可用地区');
|
|
|
empty.value = '';
|
|
|
select.append(empty);
|
|
|
for (const region of state.regions) {
|
|
|
const option = element('option', '', region.name || region.code || '未命名地区');
|
|
|
option.value = String(region.id);
|
|
|
option.selected = String(region.id) === selected;
|
|
|
select.append(option);
|
|
|
}
|
|
|
}
|
|
|
select.disabled = state.creating;
|
|
|
byId('cloud-vpc-name').disabled = state.creating;
|
|
|
byId('cloud-vpc-create-submit').disabled = state.creating
|
|
|
|| state.used >= state.maximum || !state.regions.length;
|
|
|
byId('cloud-vpc-create-submit').textContent = state.creating
|
|
|
? '正在创建…' : '创建并管理实例 →';
|
|
|
const availability = byId('cloud-vpc-create-availability');
|
|
|
availability.textContent = state.used >= state.maximum
|
|
|
? `已达到 ${state.maximum} 个 VPC 的配额,请先删除不再使用的空闲网络。`
|
|
|
: !state.regions.length ? '暂无可用地区,请稍后重试或联系管理员。' : '';
|
|
|
availability.hidden = !availability.textContent;
|
|
|
}
|
|
|
|
|
|
function vpcState(value) {
|
|
|
return String(value || '').toLowerCase() === 'active'
|
|
|
? ['运行正常', 'running'] : [String(value || '状态未知'), 'other'];
|
|
|
}
|
|
|
|
|
|
function instanceId(instance) {
|
|
|
return String(instance?.id || '');
|
|
|
}
|
|
|
|
|
|
function portAction(instance) {
|
|
|
if (instance?.can_attach === true) return 'attach';
|
|
|
if (instance?.can_retry_attach === true) return 'retry_attach';
|
|
|
if (instance?.can_detach === true) return 'detach';
|
|
|
if (instance?.can_retry_detach === true) return 'retry_detach';
|
|
|
return '';
|
|
|
}
|
|
|
|
|
|
function taskId(receipt) {
|
|
|
return taskUrl(receipt) ? String(receipt.task_id || '') : '';
|
|
|
}
|
|
|
|
|
|
function pendingStorageKey(instance) {
|
|
|
return `virt-cloud:pending-vpc-port:${state.userKey}:${instanceId(instance)}`;
|
|
|
}
|
|
|
|
|
|
function pendingMutationKey(instance, fingerprint) {
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(pendingStorageKey(instance)) || 'null'); }
|
|
|
catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : idempotencyKey();
|
|
|
try {
|
|
|
sessionStorage.setItem(pendingStorageKey(instance), JSON.stringify({ fingerprint, key }));
|
|
|
} catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingMutationKey(instance) {
|
|
|
try { sessionStorage.removeItem(pendingStorageKey(instance)); } catch {}
|
|
|
}
|
|
|
|
|
|
function instancesForVpc(vpc) {
|
|
|
const key = String(vpc?.vpc_key || '');
|
|
|
return state.instances.filter(instance => String(instance?.port?.vpc_key || '') === key);
|
|
|
}
|
|
|
|
|
|
function candidatesForVpc(vpc) {
|
|
|
const regionId = Number(vpc?.region_id || 0);
|
|
|
return state.instances.filter(instance => !instance?.port
|
|
|
&& Number(instance?.region_id || 0) === regionId);
|
|
|
}
|
|
|
|
|
|
function vpcKey(vpc) {
|
|
|
return String(vpc?.vpc_key || '');
|
|
|
}
|
|
|
|
|
|
function publicIpv4(instance) {
|
|
|
return String(instance?.public_ipv4 || '').trim() || '未分配';
|
|
|
}
|
|
|
|
|
|
function normalizedMemberQuery(value) {
|
|
|
return String(value || '').trim().toLocaleLowerCase();
|
|
|
}
|
|
|
|
|
|
function instanceMatchesMemberQuery(instance, query) {
|
|
|
if (!query) return true;
|
|
|
return [instance?.name, instanceId(instance), publicIpv4(instance)]
|
|
|
.some(value => String(value || '').toLocaleLowerCase().includes(query));
|
|
|
}
|
|
|
|
|
|
function pageRoute() {
|
|
|
const hash = window.location.hash;
|
|
|
if (!hash || hash === '#') {
|
|
|
const query = new URL(window.location.href).searchParams;
|
|
|
const key = query.getAll('vpc').at(-1) ?? null;
|
|
|
const view = query.getAll('view').at(-1) ?? null;
|
|
|
if ((key !== null && !/^[a-f0-9]{32}$/.test(key))
|
|
|
|| [...query.keys()].some(name => /^(?:vpc|view)\[/.test(name))
|
|
|
|| (view !== null && !['create', 'members', 'join'].includes(view))
|
|
|
|| (!key && ['members', 'join'].includes(view))) return { page: 'missing' };
|
|
|
if (key) return { page: 'members', key, joining: view === 'join' };
|
|
|
return { page: view === 'create' ? 'create' : 'home' };
|
|
|
}
|
|
|
if (hash === '#/') return { page: 'home' };
|
|
|
if (hash === '#/create') return { page: 'create' };
|
|
|
const match = /^#\/([a-f0-9]{32})\/instances(\/join)?$/.exec(hash);
|
|
|
return match ? { page: 'members', key: match[1], joining: Boolean(match[2]) }
|
|
|
: { page: 'missing' };
|
|
|
}
|
|
|
|
|
|
function membersHref(vpc, joining = false) {
|
|
|
return `/user/cloud/vpcs?vpc=${encodeURIComponent(vpcKey(vpc))}${joining ? '&view=join' : ''}`;
|
|
|
}
|
|
|
|
|
|
function currentVpc() {
|
|
|
const route = pageRoute();
|
|
|
return state.items.find(vpc => vpcKey(vpc) === route.key) || null;
|
|
|
}
|
|
|
|
|
|
function routeChanged() {
|
|
|
closeBatchConfirmation(false);
|
|
|
render();
|
|
|
const route = pageRoute();
|
|
|
const heading = route.page === 'home' ? 'cloud-vpcs-title'
|
|
|
: route.page === 'create' ? 'cloud-vpc-create-title'
|
|
|
: currentVpc() ? 'cloud-vpc-members-title' : 'cloud-vpc-missing-title';
|
|
|
byId(heading)?.focus({ preventScroll: true });
|
|
|
byId('cloud-vpcs-workspace')?.scrollIntoView({ block: 'start' });
|
|
|
}
|
|
|
|
|
|
function tableCell(className, label, content) {
|
|
|
const cell = element('td', className, content);
|
|
|
cell.dataset.label = label;
|
|
|
return cell;
|
|
|
}
|
|
|
|
|
|
function tableHeader(labels) {
|
|
|
const head = element('thead');
|
|
|
const row = element('tr');
|
|
|
for (const label of labels) {
|
|
|
const cell = element('th', '', label);
|
|
|
cell.scope = 'col';
|
|
|
row.append(cell);
|
|
|
}
|
|
|
head.append(row);
|
|
|
return head;
|
|
|
}
|
|
|
|
|
|
function selectionForVpc(vpc, action) {
|
|
|
const key = `${vpcKey(vpc)}:${action}`;
|
|
|
if (!state.selections.has(key)) state.selections.set(key, new Set());
|
|
|
return state.selections.get(key);
|
|
|
}
|
|
|
|
|
|
function activeBatchForVpc(vpc) {
|
|
|
const key = vpcKey(vpc);
|
|
|
return state.membershipBatches.find(batch => String(batch?.vpc_key || '') === key)
|
|
|
|| null;
|
|
|
}
|
|
|
|
|
|
function activeBatchItemForInstance(vpc, instance) {
|
|
|
const batch = activeBatchForVpc(vpc);
|
|
|
if (!batch || !Array.isArray(batch.items)) return null;
|
|
|
const id = instanceId(instance);
|
|
|
return batch.items.find(item => String(item?.instance_id || '') === id) || null;
|
|
|
}
|
|
|
|
|
|
function batchPendingStorageKey(vpc, action) {
|
|
|
return `virt-cloud:pending-vpc-batch:${state.userKey}:${vpcKey(vpc)}:${action}`;
|
|
|
}
|
|
|
|
|
|
function pendingBatchKey(vpc, action, ids) {
|
|
|
const fingerprint = `${action}:${[...ids].map(String).sort((a, b) => Number(a) - Number(b)).join(',')}`;
|
|
|
const storageKey = batchPendingStorageKey(vpc, action);
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(storageKey) || 'null'); } catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : idempotencyKey();
|
|
|
try { sessionStorage.setItem(storageKey, JSON.stringify({ fingerprint, key })); } catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingBatchKey(vpc, action) {
|
|
|
try { sessionStorage.removeItem(batchPendingStorageKey(vpc, action)); } catch {}
|
|
|
}
|
|
|
|
|
|
function taskCenterButton() {
|
|
|
const button = element('button', 'cloud-vpc-text-button', '查看任务');
|
|
|
button.type = 'button';
|
|
|
button.setAttribute('data-task-center-open', '');
|
|
|
button.setAttribute('aria-haspopup', 'dialog');
|
|
|
button.setAttribute('aria-controls', 'panel-task-drawer');
|
|
|
button.setAttribute('aria-expanded', 'false');
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function renderBatchStatus(vpc) {
|
|
|
const batch = activeBatchForVpc(vpc);
|
|
|
if (!batch) return null;
|
|
|
const batchState = String(batch.state || '');
|
|
|
const box = element('div', `cloud-vpc-batch-status${batchState === 'blocked' ? ' uncertain' : ''}`);
|
|
|
const content = element('div');
|
|
|
const total = Math.max(0, Number(batch.total) || 0);
|
|
|
const succeeded = Math.max(0, Number(batch.succeeded) || 0);
|
|
|
const failed = Math.max(0, Number(batch.failed) || 0);
|
|
|
const unknown = Math.max(0, Number(batch.unknown) || 0);
|
|
|
const action = batch.action === 'detach' ? '移出' : '加入';
|
|
|
const phase = {
|
|
|
routing: '正在准备私网连接',
|
|
|
ports: '正在应用网卡并重启实例',
|
|
|
cleanup: '正在清理并核对网络状态',
|
|
|
blocked: batch.can_cancel === true ? '清理未完成,可继续撤销'
|
|
|
: '部分结果待核对,请在任务中心查看并联系管理员',
|
|
|
}[batchState] || '正在核对执行结果';
|
|
|
const progress = [
|
|
|
`共 ${total} 台`, `${succeeded} 台成功`,
|
|
|
failed > 0 ? `${failed} 台失败` : '',
|
|
|
unknown > 0 ? `${unknown} 台待核对` : '',
|
|
|
].filter(Boolean).join(' · ');
|
|
|
content.append(element('strong', '', `${action}实例 · ${phase}`),
|
|
|
element('small', '', `${progress}。离开页面不会中断任务。`));
|
|
|
const actions = element('div', 'cloud-vpc-batch-actions');
|
|
|
actions.append(taskCenterButton());
|
|
|
if (batch.can_cancel === true) {
|
|
|
const cancel = element('button', 'cloud-vpc-text-button danger', '继续撤销并清理');
|
|
|
cancel.type = 'button';
|
|
|
cancel.dataset.vpcFocus = 'cancel-batch';
|
|
|
cancel.disabled = state.mutatingBatches.has(vpcKey(vpc));
|
|
|
cancel.addEventListener('click', () => void cancelMembershipBatch(vpc, batch));
|
|
|
actions.append(cancel);
|
|
|
}
|
|
|
box.append(content, actions);
|
|
|
return box;
|
|
|
}
|
|
|
|
|
|
function emptyState(title, description, href = '', action = '') {
|
|
|
const box = element('div', 'cloud-vpc-empty');
|
|
|
box.append(element('strong', '', title), element('p', '', description));
|
|
|
if (href) {
|
|
|
const link = element('a', 'button button-outline', action);
|
|
|
link.href = href;
|
|
|
box.append(link);
|
|
|
}
|
|
|
return box;
|
|
|
}
|
|
|
|
|
|
function renderHome() {
|
|
|
const list = byId('cloud-vpcs-list');
|
|
|
list.replaceChildren();
|
|
|
if (!state.items.length) {
|
|
|
list.append(emptyState('还没有 VPC', '选择一个地区,建立你的第一张私有网络。',
|
|
|
'/user/cloud/vpcs?view=create', '创建 VPC'));
|
|
|
return;
|
|
|
}
|
|
|
const table = element('table', 'cloud-vpc-table cloud-vpc-network-table');
|
|
|
table.setAttribute('aria-label', 'VPC 网络列表');
|
|
|
table.append(tableHeader(['网络名称 / 地区', '私网网段', '实例', '状态']));
|
|
|
const body = element('tbody');
|
|
|
for (const vpc of state.items) {
|
|
|
const row = element('tr');
|
|
|
const identity = tableCell('cloud-vpc-network-name', '网络');
|
|
|
const link = element('a', 'cloud-vpc-name-link', vpc.name);
|
|
|
link.href = membersHref(vpc);
|
|
|
identity.append(link, element('small', '', vpc.region_name));
|
|
|
const address = tableCell('cloud-vpc-table-address', '私网网段');
|
|
|
address.append(element('code', '', vpc.cidr));
|
|
|
const [label, type] = activeBatchForVpc(vpc) ? ['变更中', 'other'] : vpcState(vpc.state);
|
|
|
const status = tableCell('cloud-vpc-network-status', '状态');
|
|
|
status.append(element('span', `state-pill ${type}`, label));
|
|
|
row.append(identity, address,
|
|
|
tableCell('cloud-vpc-network-count', '实例', `${vpc.port_count || 0} 台`),
|
|
|
status);
|
|
|
body.append(row);
|
|
|
}
|
|
|
table.append(body);
|
|
|
list.append(table);
|
|
|
}
|
|
|
|
|
|
function canSelectInstance(instance, action, batchBlocked) {
|
|
|
return !batchBlocked && instance[action === 'attach' ? 'can_attach' : 'can_detach'] === true
|
|
|
&& !state.mutatingInstances.has(instanceId(instance)) && !taskId(instance.active_task);
|
|
|
}
|
|
|
|
|
|
function renderInstanceRow(instance, vpc, joining, checkbox) {
|
|
|
const id = instanceId(instance);
|
|
|
const port = instance.port || {};
|
|
|
const row = element('tr', 'cloud-vpc-instance-row');
|
|
|
row.classList.toggle('selected', checkbox.checked);
|
|
|
const select = tableCell('cloud-vpc-table-select', '选择');
|
|
|
select.append(checkbox);
|
|
|
const identity = tableCell('cloud-vpc-instance-identity', '实例');
|
|
|
const link = element('a', 'cloud-vpc-name-link', instance.name || `实例 #${id}`);
|
|
|
link.href = `/user/cloud/instances/${encodeURIComponent(id)}`;
|
|
|
identity.append(link);
|
|
|
const publicAddress = tableCell('cloud-vpc-table-address', '公网 IPv4');
|
|
|
publicAddress.append(element('code', '', publicIpv4(instance)));
|
|
|
const privateAddress = tableCell('cloud-vpc-table-address cloud-vpc-private-address',
|
|
|
joining ? '私网分配' : '私网 IPv4');
|
|
|
privateAddress.append(element(joining ? 'span' : 'code', '', joining
|
|
|
? '自动分配' : port.private_ip || '待分配'));
|
|
|
if (!joining && port.mac_address) {
|
|
|
const details = element('details', 'cloud-vpc-mac');
|
|
|
details.open = state.expandedMacs.has(id);
|
|
|
details.append(element('summary', '', 'MAC 地址'), element('code', '', port.mac_address));
|
|
|
details.addEventListener('toggle', () => {
|
|
|
if (details.open) state.expandedMacs.add(id);
|
|
|
else state.expandedMacs.delete(id);
|
|
|
});
|
|
|
privateAddress.append(details);
|
|
|
}
|
|
|
|
|
|
const batchItem = activeBatchItemForInstance(vpc, instance);
|
|
|
const [label, type] = batchItem
|
|
|
? BATCH_ITEM_STATE_LABELS[String(batchItem.state || '')] || ['等待中', 'other']
|
|
|
: joining
|
|
|
? (instance.can_attach === true ? ['可加入', 'running'] : ['暂不可加入', 'other'])
|
|
|
: PORT_STATE_LABELS[String(port.state || '')] || ['状态待确认', 'other'];
|
|
|
const status = tableCell('cloud-vpc-instance-status', '状态');
|
|
|
status.append(element('span', `state-pill ${type}`, label));
|
|
|
if (!batchItem && instance.action_unavailable_reason) {
|
|
|
status.append(element('small', '', instance.action_unavailable_reason));
|
|
|
}
|
|
|
const action = portAction(instance);
|
|
|
if (!batchItem && taskId(instance.active_task)) {
|
|
|
status.append(taskCenterButton());
|
|
|
} else if (!batchItem && (action === 'retry_attach' || action === 'retry_detach')) {
|
|
|
const retry = element('button', 'cloud-vpc-text-button',
|
|
|
action === 'retry_attach' ? '重试连接' : '重试清理');
|
|
|
retry.type = 'button';
|
|
|
retry.dataset.vpcFocus = `retry-${id}`;
|
|
|
retry.disabled = Boolean(activeBatchForVpc(vpc))
|
|
|
|| state.mutatingBatches.has(vpcKey(vpc)) || state.mutatingInstances.has(id);
|
|
|
retry.addEventListener('click', () =>
|
|
|
void mutatePort(instance, vpc, action === 'retry_attach' ? 'attach' : 'detach'));
|
|
|
status.append(retry);
|
|
|
}
|
|
|
row.append(select, identity, publicAddress, privateAddress, status);
|
|
|
return row;
|
|
|
}
|
|
|
|
|
|
function renderInstanceManager(vpc, joining) {
|
|
|
const action = joining ? 'attach' : 'detach';
|
|
|
const instances = joining ? candidatesForVpc(vpc) : instancesForVpc(vpc);
|
|
|
const queryKey = vpcKey(vpc);
|
|
|
const batchBlocked = Boolean(activeBatchForVpc(vpc))
|
|
|
|| state.mutatingBatches.has(vpcKey(vpc));
|
|
|
const selection = selectionForVpc(vpc, action);
|
|
|
const eligibleIds = new Set(instances.filter(item =>
|
|
|
canSelectInstance(item, action, batchBlocked)).map(instanceId));
|
|
|
for (const id of [...selection]) {
|
|
|
if (!eligibleIds.has(id)) selection.delete(id);
|
|
|
}
|
|
|
const section = element('section', 'cloud-vpc-instance-manager');
|
|
|
section.classList.toggle('joining', joining);
|
|
|
section.setAttribute('aria-label', joining ? '加入实例' : '已加入实例');
|
|
|
section.append(element('p', 'cloud-vpc-list-hint', joining
|
|
|
? '选择同地区实例,一次提交加入;私网 IP 自动分配。'
|
|
|
: '勾选实例可批量移出当前 VPC。'));
|
|
|
if (!instances.length) {
|
|
|
section.append(joining
|
|
|
? emptyState('暂无可加入的实例', '只显示同地区且尚未加入 VPC 的实例。')
|
|
|
: emptyState('尚未加入实例', '将同地区实例连接到这张私网。',
|
|
|
membersHref(vpc, true), '加入实例 →'));
|
|
|
return section;
|
|
|
}
|
|
|
let search = null;
|
|
|
if (joining) {
|
|
|
const searchField = element('label', 'cloud-vpc-instance-search');
|
|
|
searchField.append(element('span', 'sr-only', '搜索实例或公网 IP'));
|
|
|
search = element('input', 'cloud-vpc-instance-search-input');
|
|
|
search.type = 'search';
|
|
|
search.placeholder = '搜索实例或公网 IP';
|
|
|
search.value = String(state.memberQueries.get(queryKey) || '');
|
|
|
search.dataset.vpcFocus = 'instance-search';
|
|
|
search.setAttribute('aria-label', '搜索实例或公网 IP');
|
|
|
searchField.append(search);
|
|
|
section.append(searchField);
|
|
|
}
|
|
|
const table = element('table', 'cloud-vpc-table cloud-vpc-member-table');
|
|
|
table.setAttribute('aria-label', joining ? '可加入实例' : '已加入实例');
|
|
|
const header = tableHeader(['', '实例', '公网 IPv4', joining ? '私网分配' : '私网 IPv4', '状态']);
|
|
|
const selectAll = element('input');
|
|
|
selectAll.type = 'checkbox';
|
|
|
selectAll.dataset.vpcFocus = 'select-all';
|
|
|
selectAll.setAttribute('aria-label', joining ? '全选可加入实例' : '全选可移出实例');
|
|
|
selectAll.disabled = eligibleIds.size === 0;
|
|
|
const selectAllLabel = element('label', 'cloud-vpc-select-all');
|
|
|
selectAllLabel.append(selectAll, element('span', '', joining ? '全选可加入实例' : '全选可移出实例'));
|
|
|
header.querySelector('th').append(selectAllLabel);
|
|
|
table.append(header);
|
|
|
const body = element('tbody');
|
|
|
const checks = [];
|
|
|
const countLabel = element('span');
|
|
|
countLabel.setAttribute('role', 'status');
|
|
|
const clear = element('button', 'cloud-vpc-text-button', '取消选择');
|
|
|
clear.type = 'button';
|
|
|
clear.dataset.vpcFocus = 'clear-selection';
|
|
|
const submit = element('button', 'button button-primary');
|
|
|
submit.type = 'button';
|
|
|
submit.dataset.vpcFocus = 'submit-selection';
|
|
|
const updateControls = () => {
|
|
|
const visibleEligibleIds = new Set(checks.filter(({ id, row }) =>
|
|
|
!row.hidden && eligibleIds.has(id)).map(({ id }) => id));
|
|
|
const selectedVisible = [...visibleEligibleIds].filter(id => selection.has(id)).length;
|
|
|
section.classList.toggle('has-selection', selection.size > 0);
|
|
|
countLabel.textContent = `已选择 ${selection.size} 台`;
|
|
|
clear.hidden = selection.size === 0;
|
|
|
submit.disabled = batchBlocked || selection.size === 0;
|
|
|
submit.textContent = selection.size
|
|
|
? `${joining ? '加入' : '移出'} ${selection.size} 台实例`
|
|
|
: `${joining ? '加入' : '移出'}所选实例`;
|
|
|
selectAll.disabled = visibleEligibleIds.size === 0;
|
|
|
selectAll.checked = visibleEligibleIds.size > 0
|
|
|
&& selectedVisible === visibleEligibleIds.size;
|
|
|
selectAll.indeterminate = selectedVisible > 0
|
|
|
&& selectedVisible < visibleEligibleIds.size;
|
|
|
for (const { checkbox, row, id } of checks) {
|
|
|
checkbox.checked = selection.has(id);
|
|
|
row.classList.toggle('selected', checkbox.checked);
|
|
|
}
|
|
|
};
|
|
|
for (const instance of instances) {
|
|
|
const id = instanceId(instance);
|
|
|
const checkbox = element('input');
|
|
|
checkbox.type = 'checkbox';
|
|
|
checkbox.value = id;
|
|
|
checkbox.dataset.vpcFocus = `select-${id}`;
|
|
|
checkbox.checked = selection.has(id);
|
|
|
checkbox.disabled = !eligibleIds.has(id);
|
|
|
checkbox.setAttribute('aria-label', `选择${joining ? '加入' : '移出'} ${instance.name || id}`);
|
|
|
const row = renderInstanceRow(instance, vpc, joining, checkbox);
|
|
|
checkbox.addEventListener('change', () => {
|
|
|
if (checkbox.checked && !checkbox.disabled) selection.add(id);
|
|
|
else selection.delete(id);
|
|
|
updateControls();
|
|
|
});
|
|
|
checks.push({ id, checkbox, row, instance });
|
|
|
body.append(row);
|
|
|
}
|
|
|
selectAll.addEventListener('change', () => {
|
|
|
for (const { id, row } of checks) {
|
|
|
if (row.hidden || !eligibleIds.has(id)) continue;
|
|
|
if (selectAll.checked) selection.add(id);
|
|
|
else selection.delete(id);
|
|
|
}
|
|
|
updateControls();
|
|
|
});
|
|
|
clear.addEventListener('click', () => { selection.clear(); updateControls(); });
|
|
|
submit.addEventListener('click', () => void submitMembershipBatch(vpc, action,
|
|
|
instances.filter(item => selection.has(instanceId(item)) && eligibleIds.has(instanceId(item)))));
|
|
|
table.append(body);
|
|
|
const noMatches = emptyState('没有匹配的实例', '请尝试其他实例名称或公网 IP。');
|
|
|
noMatches.classList.add('cloud-vpc-search-empty');
|
|
|
noMatches.hidden = true;
|
|
|
const applySearch = () => {
|
|
|
const query = normalizedMemberQuery(search?.value);
|
|
|
if (joining) {
|
|
|
if (query) state.memberQueries.set(queryKey, search.value);
|
|
|
else state.memberQueries.delete(queryKey);
|
|
|
}
|
|
|
let visible = 0;
|
|
|
for (const { instance, row } of checks) {
|
|
|
const matched = !joining || instanceMatchesMemberQuery(instance, query);
|
|
|
row.hidden = !matched;
|
|
|
if (matched) visible += 1;
|
|
|
}
|
|
|
noMatches.hidden = visible > 0;
|
|
|
updateControls();
|
|
|
};
|
|
|
search?.addEventListener('input', applySearch);
|
|
|
const toolbar = element('div', 'cloud-vpc-batch-toolbar');
|
|
|
toolbar.append(countLabel, clear, submit);
|
|
|
section.append(table, noMatches, toolbar);
|
|
|
applySearch();
|
|
|
return section;
|
|
|
}
|
|
|
|
|
|
function renderMembers(vpc, joining) {
|
|
|
byId('cloud-vpc-members-title').textContent = vpc.name;
|
|
|
const [label, type] = vpcState(vpc.state);
|
|
|
const status = byId('cloud-vpc-members-state');
|
|
|
status.textContent = label;
|
|
|
status.className = `state-pill ${type}`;
|
|
|
const summary = byId('cloud-vpc-network-summary');
|
|
|
summary.replaceChildren();
|
|
|
for (const [label, value] of [
|
|
|
['地区', vpc.region_name], ['私网网段', vpc.cidr], ['默认网关', vpc.gateway],
|
|
|
]) {
|
|
|
const item = element('div');
|
|
|
item.append(element('dt', '', label), element('dd', '', value));
|
|
|
summary.append(item);
|
|
|
}
|
|
|
const batch = byId('cloud-vpc-batch-status');
|
|
|
batch.replaceChildren();
|
|
|
const batchStatus = renderBatchStatus(vpc);
|
|
|
if (batchStatus) batch.append(batchStatus);
|
|
|
const members = byId('cloud-vpc-members-link');
|
|
|
members.replaceChildren(element('span', '', '已加入实例'),
|
|
|
element('span', 'cloud-vpc-tab-count', instancesForVpc(vpc).length));
|
|
|
members.href = membersHref(vpc);
|
|
|
const join = byId('cloud-vpc-join-link');
|
|
|
const joinable = candidatesForVpc(vpc).filter(instance => instance.can_attach === true).length;
|
|
|
join.replaceChildren(element('span', '', '加入实例'),
|
|
|
element('span', 'cloud-vpc-tab-count', joinable));
|
|
|
join.href = membersHref(vpc, true);
|
|
|
for (const [link, active] of [[members, !joining], [join, joining]]) {
|
|
|
if (active) link.setAttribute('aria-current', 'page');
|
|
|
else link.removeAttribute('aria-current');
|
|
|
}
|
|
|
byId('cloud-vpc-instance-manager').replaceChildren(renderInstanceManager(vpc, joining));
|
|
|
byId('cloud-vpc-members-note').textContent = joining
|
|
|
? '加入后,同一 VPC 内的实例默认互通。'
|
|
|
: '移出仅解除私网连接,实例和磁盘保留。';
|
|
|
const remove = byId('cloud-vpc-delete');
|
|
|
remove.disabled = vpc.can_delete !== true || Boolean(activeBatchForVpc(vpc))
|
|
|
|| state.mutatingVpcs.has(vpcKey(vpc)) || state.mutatingBatches.has(vpcKey(vpc));
|
|
|
remove.title = remove.disabled ? '请先移出全部实例,并等待相关任务完成。' : '删除空闲 VPC';
|
|
|
}
|
|
|
|
|
|
function render() {
|
|
|
const focused = document.activeElement?.dataset?.vpcFocus;
|
|
|
renderRegions();
|
|
|
const route = pageRoute();
|
|
|
const vpc = currentVpc();
|
|
|
const page = route.page === 'members' && !vpc ? 'missing' : route.page;
|
|
|
for (const name of ['home', 'create', 'members', 'missing']) {
|
|
|
byId(`cloud-vpcs-${name}`).hidden = page !== name;
|
|
|
}
|
|
|
byId('cloud-vpcs-back').hidden = page === 'home';
|
|
|
byId('cloud-vpcs-quota').textContent = `${state.used} / ${state.maximum} 个`;
|
|
|
if (page === 'home') renderHome();
|
|
|
if (page === 'members') renderMembers(vpc, route.joining);
|
|
|
if (focused) {
|
|
|
[...byId('cloud-vpcs-workspace').querySelectorAll('[data-vpc-focus]')]
|
|
|
.find(node => node.dataset.vpcFocus === focused && !node.disabled)
|
|
|
?.focus({ preventScroll: true });
|
|
|
}
|
|
|
}
|
|
|
|
|
|
let pendingConfirmation = null;
|
|
|
|
|
|
function closeBatchConfirmation(confirmed) {
|
|
|
if (!pendingConfirmation) return;
|
|
|
const { resolve, opener } = pendingConfirmation;
|
|
|
pendingConfirmation = null;
|
|
|
byId('cloud-vpc-confirm').close();
|
|
|
document.documentElement.classList.remove('cloud-vpc-confirm-open');
|
|
|
if (opener?.isConnected) opener.focus({ preventScroll: true });
|
|
|
resolve(confirmed);
|
|
|
}
|
|
|
|
|
|
function confirmMembership(vpc, action, instances) {
|
|
|
const dialog = byId('cloud-vpc-confirm');
|
|
|
if (pendingConfirmation || typeof dialog?.showModal !== 'function') {
|
|
|
setPageStatus('无法打开操作确认,请使用支持对话框的浏览器重试。', 'error');
|
|
|
return Promise.resolve(false);
|
|
|
}
|
|
|
const word = action === 'attach' ? '加入' : '移出';
|
|
|
byId('cloud-vpc-confirm-title').textContent = `确认${word} ${instances.length} 台实例`;
|
|
|
byId('cloud-vpc-confirm-note').textContent =
|
|
|
`${word} VPC:${vpc.name}。公网配置保持不变。`;
|
|
|
const list = byId('cloud-vpc-confirm-instances');
|
|
|
list.replaceChildren();
|
|
|
for (const instance of instances) {
|
|
|
const row = element('li');
|
|
|
row.append(element('span', '', instance.name), element('code', '', publicIpv4(instance)));
|
|
|
list.append(row);
|
|
|
}
|
|
|
byId('cloud-vpc-confirm-restart').checked = false;
|
|
|
const submit = byId('cloud-vpc-confirm-submit');
|
|
|
submit.disabled = true;
|
|
|
submit.textContent = `确认${word}并重启`;
|
|
|
submit.className = action === 'detach' ? 'button button-outline danger' : 'button button-primary';
|
|
|
return new Promise(resolve => {
|
|
|
pendingConfirmation = { resolve, opener: document.activeElement };
|
|
|
dialog.showModal();
|
|
|
document.documentElement.classList.add('cloud-vpc-confirm-open');
|
|
|
byId('cloud-vpc-confirm-cancel').focus();
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function bindBatchConfirmation() {
|
|
|
for (const id of ['cloud-vpc-confirm-close', 'cloud-vpc-confirm-cancel']) {
|
|
|
byId(id).addEventListener('click', () => closeBatchConfirmation(false));
|
|
|
}
|
|
|
byId('cloud-vpc-confirm-restart').addEventListener('change', event => {
|
|
|
byId('cloud-vpc-confirm-submit').disabled = !event.target.checked;
|
|
|
});
|
|
|
byId('cloud-vpc-confirm-form').addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
if (byId('cloud-vpc-confirm-restart').checked) closeBatchConfirmation(true);
|
|
|
});
|
|
|
const dialog = byId('cloud-vpc-confirm');
|
|
|
dialog.addEventListener('cancel', event => {
|
|
|
event.preventDefault();
|
|
|
closeBatchConfirmation(false);
|
|
|
});
|
|
|
dialog.addEventListener('close', () => {
|
|
|
if (!dialog.open) closeBatchConfirmation(false);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function taskFailureMessage(task) {
|
|
|
const resolved = resolvedTaskFailureNotice(task);
|
|
|
if (resolved) return resolved;
|
|
|
const recovery = recoveryTaskFailureNotice(task);
|
|
|
if (recovery) return recovery;
|
|
|
const message = task?.error || 'VPC 私网任务失败。';
|
|
|
if (task?.effect_may_have_applied === true) {
|
|
|
return `${message} 操作效果暂时无法确认,请勿重复提交,并在任务中心核查。`;
|
|
|
}
|
|
|
return task?.safe_to_resubmit === false
|
|
|
? `${message} 相关资源仍被锁定,请勿重复提交。` : message;
|
|
|
}
|
|
|
|
|
|
function observeReceipt(instance, receipt, accepted = false) {
|
|
|
const id = taskId(receipt);
|
|
|
if (!id || state.observers.has(id) || state.terminalTasks.has(id)) return null;
|
|
|
if (accepted) announceTaskAccepted(receipt, { title: 'VPC 私网' });
|
|
|
const handle = observeTask(receipt, {
|
|
|
onUpdate: () => setPageStatus('VPC 变更任务正在后台执行,请勿重复提交。'),
|
|
|
onTerminal: task => {
|
|
|
state.observers.delete(id);
|
|
|
state.terminalTasks.add(id);
|
|
|
state.mutatingInstances.delete(instanceId(instance));
|
|
|
void load(true).then(() => {
|
|
|
const refreshed = state.instances.find(item =>
|
|
|
instanceId(item) === instanceId(instance));
|
|
|
const nextTask = taskId(refreshed?.active_task);
|
|
|
const portState = String(refreshed?.port?.state || '');
|
|
|
const settled = !refreshed?.port || portState === 'attached';
|
|
|
if (nextTask && nextTask !== id) {
|
|
|
setPageStatus(taskSucceededWithoutRecovery(task)
|
|
|
? 'VPC 编排正在继续执行下一阶段,请勿重复提交。'
|
|
|
: '一个 VPC 阶段未完成,其他已接收阶段仍在收敛;完成前请勿重试。',
|
|
|
taskSucceededWithoutRecovery(task) ? '' : 'warning');
|
|
|
} else if (taskSucceededWithoutRecovery(task) && settled) {
|
|
|
setPageStatus('VPC 实例连接状态已更新。', 'success');
|
|
|
toast('VPC 私网操作完成。', 'success');
|
|
|
} else if (taskSucceededWithoutRecovery(task)) {
|
|
|
setPageStatus('当前阶段已完成,VPC 编排状态仍在收敛,请刷新核对后再操作。');
|
|
|
} else {
|
|
|
setPageStatus(taskFailureMessage(task), 'error');
|
|
|
}
|
|
|
});
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
state.observers.delete(id);
|
|
|
state.mutatingInstances.delete(instanceId(instance));
|
|
|
if (reason !== 'pagehide') {
|
|
|
setPageStatus('自动观察已停止,请在任务中心核对结果后再执行其他操作。', 'warning');
|
|
|
void load(true);
|
|
|
}
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) return null;
|
|
|
state.observers.set(id, handle);
|
|
|
void handle.done.finally(() => state.observers.delete(id));
|
|
|
return handle;
|
|
|
}
|
|
|
|
|
|
function observeActiveTasks() {
|
|
|
const batchVpcKeys = new Set(state.membershipBatches
|
|
|
.map(batch => String(batch?.vpc_key || '')).filter(Boolean));
|
|
|
for (const instance of state.instances) {
|
|
|
if (instance?.active_task
|
|
|
&& !batchVpcKeys.has(String(instance?.port?.vpc_key || ''))) {
|
|
|
observeReceipt(instance, instance.active_task, false);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function observeBatch(batch, accepted = false) {
|
|
|
const receipt = {
|
|
|
task_id: String(batch?.task_id || ''),
|
|
|
status_url: String(batch?.status_url || ''),
|
|
|
};
|
|
|
const id = taskId(receipt);
|
|
|
const key = String(batch?.vpc_key || '');
|
|
|
if (!id || !key || String(batch?.state || '') === 'blocked'
|
|
|
|| state.observers.has(id) || state.terminalTasks.has(id)) return null;
|
|
|
if (accepted) announceTaskAccepted(receipt, { title: '批量调整 VPC 实例' });
|
|
|
const handle = observeTask(receipt, {
|
|
|
onUpdate: () => {
|
|
|
setPageStatus('VPC 批次正在服务端执行;关闭页面不会中断任务。');
|
|
|
const now = Date.now();
|
|
|
if (!state.loading && now - state.batchRefreshAt >= 2000) {
|
|
|
state.batchRefreshAt = now;
|
|
|
void load(true);
|
|
|
}
|
|
|
},
|
|
|
onTerminal: task => {
|
|
|
state.observers.delete(id);
|
|
|
state.terminalTasks.add(id);
|
|
|
state.mutatingBatches.delete(key);
|
|
|
void load(true).then(() => {
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
setPageStatus('所选实例的 VPC 批量变更已完成。', 'success');
|
|
|
toast('VPC 批量操作已完成。', 'success');
|
|
|
} else {
|
|
|
setPageStatus(taskFailureMessage(task), 'error');
|
|
|
}
|
|
|
});
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
state.observers.delete(id);
|
|
|
state.mutatingBatches.delete(key);
|
|
|
if (reason !== 'pagehide') {
|
|
|
setPageStatus('批次观察已停止,请在任务中心核对结果。', 'warning');
|
|
|
void load(true);
|
|
|
}
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) return null;
|
|
|
state.observers.set(id, handle);
|
|
|
void handle.done.finally(() => state.observers.delete(id));
|
|
|
return handle;
|
|
|
}
|
|
|
|
|
|
function observeActiveBatches() {
|
|
|
for (const batch of state.membershipBatches) observeBatch(batch, false);
|
|
|
}
|
|
|
|
|
|
function stopObservers(reason = 'pagehide') {
|
|
|
for (const observer of state.observers.values()) observer.stop(reason);
|
|
|
state.observers.clear();
|
|
|
}
|
|
|
|
|
|
async function load(force = false) {
|
|
|
if (state.loading && !force) return;
|
|
|
state.controller?.abort();
|
|
|
state.loading = true;
|
|
|
const controller = new AbortController();
|
|
|
state.controller = controller;
|
|
|
setPageStatus('正在读取 VPC 和实例连接状态…');
|
|
|
render();
|
|
|
try {
|
|
|
const payload = await api('/api/v1/vpcs', { signal: controller.signal });
|
|
|
if (controller.signal.aborted) return;
|
|
|
apply(payload);
|
|
|
setPageStatus();
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted) return;
|
|
|
setPageStatus(error?.message || 'VPC 读取失败。', 'error');
|
|
|
} finally {
|
|
|
if (state.controller === controller) {
|
|
|
state.controller = null;
|
|
|
state.loading = false;
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function submitMembershipBatch(vpc, action, instances) {
|
|
|
const key = vpcKey(vpc);
|
|
|
if (!key || !instances.length || activeBatchForVpc(vpc)
|
|
|
|| state.mutatingBatches.has(key)) return;
|
|
|
const attach = action === 'attach';
|
|
|
const ids = [...new Set(instances.map(instance => Number(instanceId(instance))))]
|
|
|
.filter(id => Number.isInteger(id) && id > 0);
|
|
|
if (!ids.length) return;
|
|
|
const confirmed = await confirmMembership(vpc, action, instances);
|
|
|
if (!confirmed || activeBatchForVpc(vpc) || state.mutatingBatches.has(key)) return;
|
|
|
// Eligibility may change while the confirmation dialog is open.
|
|
|
const current = state.items.find(item => vpcKey(item) === key);
|
|
|
const available = current && (attach ? candidatesForVpc(current) : instancesForVpc(current));
|
|
|
if (!available || ids.some(id => !available.some(instance =>
|
|
|
Number(instanceId(instance)) === id && canSelectInstance(instance, action, false)))) {
|
|
|
setPageStatus('所选实例状态已变化,请重新选择可操作的实例。', 'warning');
|
|
|
render();
|
|
|
return;
|
|
|
}
|
|
|
const requestKey = pendingBatchKey(vpc, action, ids);
|
|
|
state.mutatingBatches.add(key);
|
|
|
setPageStatus(`正在提交 ${ids.length} 台实例的 VPC 批次…`);
|
|
|
render();
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vpcs/${encodeURIComponent(key)}/ports/batch`, {
|
|
|
method: 'POST',
|
|
|
headers: { 'Idempotency-Key': requestKey },
|
|
|
body: { action, instance_ids: ids, confirm_restart: true },
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
});
|
|
|
clearPendingBatchKey(vpc, action);
|
|
|
const batch = receipt?.batch || {
|
|
|
task_id: receipt.task_id,
|
|
|
status_url: receipt.status_url,
|
|
|
vpc_key: key,
|
|
|
action,
|
|
|
state: attach ? 'routing' : 'ports',
|
|
|
total: ids.length,
|
|
|
succeeded: 0,
|
|
|
failed: 0,
|
|
|
};
|
|
|
state.membershipBatches = state.membershipBatches
|
|
|
.filter(item => String(item?.vpc_key || '') !== key);
|
|
|
state.membershipBatches.push(batch);
|
|
|
selectionForVpc(vpc, action).clear();
|
|
|
observeBatch(batch, true);
|
|
|
if (currentVpc() && vpcKey(currentVpc()) === key) {
|
|
|
window.location.href = new URL(membersHref(vpc), window.location.href).href;
|
|
|
}
|
|
|
setPageStatus(`已接收 ${ids.length} 台实例;任务将在服务端并发处理。`);
|
|
|
toast('VPC 批量任务已接收。', 'success');
|
|
|
await load(true);
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
if (transportUncertain(error)) {
|
|
|
setPageStatus(error?.message
|
|
|
|| '批次提交结果暂时无法确认,已保留同一请求标识,请勿重复提交。', 'warning');
|
|
|
} else {
|
|
|
clearPendingBatchKey(vpc, action);
|
|
|
setPageStatus(error?.message || 'VPC 批次提交失败。', 'error');
|
|
|
}
|
|
|
} finally {
|
|
|
state.mutatingBatches.delete(key);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function cancelMembershipBatch(vpc, batch) {
|
|
|
const key = vpcKey(vpc);
|
|
|
const batchKey = String(batch?.batch_key || '');
|
|
|
if (!key || !/^[a-f0-9]{32}$/.test(batchKey)
|
|
|
|| batch?.can_cancel !== true || state.mutatingBatches.has(key)) return;
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: '继续撤销 VPC 加入操作',
|
|
|
message: '系统只会重试已确认未生效的宿主机清理,不会重放结果未知的操作。清理完成后将释放预留私网地址和实例操作锁。',
|
|
|
confirmText: '继续安全清理',
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed || state.mutatingBatches.has(key)) return;
|
|
|
state.mutatingBatches.add(key);
|
|
|
setPageStatus('正在继续撤销 VPC 加入操作…');
|
|
|
render();
|
|
|
try {
|
|
|
const receipt = await api(
|
|
|
`/api/v1/vpcs/${encodeURIComponent(key)}/ports/batches/${encodeURIComponent(batchKey)}/cancel`,
|
|
|
{ method: 'POST', expectedStatus: 202, requireTaskReceipt: true }
|
|
|
);
|
|
|
const next = receipt?.batch || { ...batch, state: 'cleanup', can_cancel: false };
|
|
|
state.membershipBatches = state.membershipBatches
|
|
|
.filter(item => String(item?.batch_key || '') !== batchKey);
|
|
|
state.membershipBatches.push(next);
|
|
|
observeBatch(next, false);
|
|
|
setPageStatus('已继续安全清理;完成前实例仍保持操作锁。');
|
|
|
await load(true);
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
setPageStatus(error?.message || '继续撤销 VPC 加入操作失败。', 'error');
|
|
|
} finally {
|
|
|
state.mutatingBatches.delete(key);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function mutatePort(instance, vpc, requestedAction, options = {}) {
|
|
|
const id = instanceId(instance);
|
|
|
if (!id || state.mutatingInstances.has(id)) return { status: 'ignored' };
|
|
|
const action = portAction(instance);
|
|
|
const attach = requestedAction === 'attach';
|
|
|
if (attach !== ['attach', 'retry_attach'].includes(action)
|
|
|
|| (!attach && !['detach', 'retry_detach'].includes(action))) {
|
|
|
return { status: 'ignored' };
|
|
|
}
|
|
|
|
|
|
const confirmed = options.confirmed === true
|
|
|
|| await requestUserConfirmation({
|
|
|
title: attach ? '确认加入 VPC 私网' : '确认移出 VPC 私网',
|
|
|
message: attach
|
|
|
? `实例“${instance.name}”将自动正常关机,加入“${vpc.name}”后冷启动。期间服务会短暂中断。`
|
|
|
: `实例“${instance.name}”将自动正常关机,移除私网网卡后冷启动,并释放私网 IP。`,
|
|
|
confirmText: attach ? '加入并重启' : '移出并重启',
|
|
|
tone: attach ? 'default' : 'danger',
|
|
|
});
|
|
|
if (!confirmed) return { status: 'cancelled' };
|
|
|
|
|
|
const fingerprint = attach ? `attach:${vpc.vpc_key}`
|
|
|
: `detach:${String(instance?.port?.port_key || '')}`;
|
|
|
const key = pendingMutationKey(instance, fingerprint);
|
|
|
state.mutatingInstances.add(id);
|
|
|
setPageStatus('正在提交 VPC 实例变更…');
|
|
|
render();
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vms/${encodeURIComponent(id)}/vpc`, {
|
|
|
method: attach ? 'PUT' : 'DELETE',
|
|
|
headers: { 'Idempotency-Key': key },
|
|
|
body: attach ? { vpc_key: vpc.vpc_key, confirm_restart: true }
|
|
|
: { confirm_restart: true },
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
});
|
|
|
clearPendingMutationKey(instance);
|
|
|
Object.assign(instance, {
|
|
|
active_task: receipt,
|
|
|
can_attach: false, can_detach: false,
|
|
|
can_retry_attach: false, can_retry_detach: false,
|
|
|
});
|
|
|
observeReceipt(instance, receipt, true);
|
|
|
setPageStatus('VPC 变更任务已接收,正在执行关机、网卡和路由阶段。');
|
|
|
if (options.quiet !== true) toast('VPC 私网任务已接收。', 'success');
|
|
|
await load(true);
|
|
|
return { status: 'accepted' };
|
|
|
} catch (error) {
|
|
|
await load(true);
|
|
|
if (transportUncertain(error)) {
|
|
|
const message = error?.message
|
|
|
|| '请求结果暂时无法确认,已保留同一请求标识,请勿重复提交。';
|
|
|
setPageStatus(message, 'warning');
|
|
|
return { status: 'uncertain', message };
|
|
|
} else {
|
|
|
clearPendingMutationKey(instance);
|
|
|
const message = error?.message || 'VPC 私网操作提交失败。';
|
|
|
setPageStatus(message, 'error');
|
|
|
return { status: 'failed', message };
|
|
|
}
|
|
|
} finally {
|
|
|
state.mutatingInstances.delete(id);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function createVpc(event) {
|
|
|
event.preventDefault();
|
|
|
if (state.creating) return;
|
|
|
const name = byId('cloud-vpc-name').value.trim();
|
|
|
const regionId = Number(byId('cloud-vpc-region').value);
|
|
|
const fingerprint = `${name}\0${regionId}`;
|
|
|
if (!name || !Number.isInteger(regionId) || regionId < 1) {
|
|
|
showError('cloud-vpc-create-error', '请填写名称并选择地区。');
|
|
|
return;
|
|
|
}
|
|
|
if (!state.createKey || state.createFingerprint !== fingerprint) {
|
|
|
state.createKey = idempotencyKey();
|
|
|
state.createFingerprint = fingerprint;
|
|
|
}
|
|
|
state.creating = true;
|
|
|
showError('cloud-vpc-create-error', '');
|
|
|
render();
|
|
|
try {
|
|
|
const result = await api('/api/v1/vpcs', {
|
|
|
method: 'POST', expectedStatus: 201,
|
|
|
headers: { 'Idempotency-Key': state.createKey },
|
|
|
body: { name, region_id: regionId },
|
|
|
});
|
|
|
state.createKey = '';
|
|
|
state.createFingerprint = '';
|
|
|
byId('cloud-vpc-name').value = '';
|
|
|
const created = result?.vpc;
|
|
|
if (/^[a-f0-9]{32}$/.test(vpcKey(created))) {
|
|
|
if (!state.items.some(item => vpcKey(item) === vpcKey(created))) {
|
|
|
state.items.push(created);
|
|
|
state.used += 1;
|
|
|
}
|
|
|
// Keep the confirmed creation visible even if the following refresh fails.
|
|
|
if (pageRoute().page === 'create') window.location.href = new URL(membersHref(created, true), window.location.href).href;
|
|
|
}
|
|
|
await load(true);
|
|
|
toast('VPC 已创建,可选择需要加入的实例。', 'success');
|
|
|
} catch (error) {
|
|
|
showError('cloud-vpc-create-error',
|
|
|
error?.message || 'VPC 创建失败,请使用相同内容重试。');
|
|
|
await load(true);
|
|
|
} finally {
|
|
|
state.creating = false;
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function removeVpc(vpc) {
|
|
|
const key = String(vpc?.vpc_key || '');
|
|
|
if (!key || state.mutatingVpcs.has(key) || vpc?.can_delete !== true) return;
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: '删除 VPC',
|
|
|
message: `确定删除“${vpc.name}”(${vpc.cidr})?释放后的 CIDR 可以重新分配,删除不可撤销。`,
|
|
|
confirmText: '删除 VPC', tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
state.mutatingVpcs.add(key);
|
|
|
render();
|
|
|
try {
|
|
|
await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, {
|
|
|
method: 'DELETE', expectedStatus: 200,
|
|
|
});
|
|
|
state.items = state.items.filter(item => vpcKey(item) !== key);
|
|
|
state.used = Math.max(0, state.used - 1);
|
|
|
if (pageRoute().key === key) window.location.href = new URL('/user/cloud/vpcs', window.location.href).href;
|
|
|
await load(true);
|
|
|
toast('VPC 已删除。', 'success');
|
|
|
} catch (error) {
|
|
|
setPageStatus(error?.message || 'VPC 删除失败。', 'error');
|
|
|
} finally {
|
|
|
state.mutatingVpcs.delete(key);
|
|
|
render();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
export async function initialize() {
|
|
|
if (state.initialized) return;
|
|
|
state.initialized = true;
|
|
|
try {
|
|
|
const bootstrap = readBootstrap('cloud-vpcs-bootstrap');
|
|
|
if (!await initializeSession('vpcs', bootstrap?.user)) return;
|
|
|
state.userKey = String(bootstrap?.user?.id || bootstrap?.user?.user_id || 'unknown');
|
|
|
if (Array.isArray(bootstrap?.items) && Array.isArray(bootstrap?.instances)
|
|
|
&& Array.isArray(bootstrap?.regions)) {
|
|
|
apply(bootstrap);
|
|
|
setPageStatus();
|
|
|
} else {
|
|
|
await load();
|
|
|
}
|
|
|
byId('cloud-vpc-create-form')?.addEventListener('submit', createVpc);
|
|
|
byId('cloud-vpc-delete')?.addEventListener('click', () => {
|
|
|
const vpc = currentVpc();
|
|
|
if (vpc) void removeVpc(vpc);
|
|
|
});
|
|
|
bindBatchConfirmation();
|
|
|
window.addEventListener('hashchange', routeChanged);
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
closeBatchConfirmation(false);
|
|
|
state.controller?.abort();
|
|
|
stopObservers('pagehide');
|
|
|
});
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
if (event.persisted) void load(true);
|
|
|
});
|
|
|
} catch (error) {
|
|
|
showError('cloud-page-error', error?.message || 'VPC 页面加载失败,请刷新后重试。');
|
|
|
}
|
|
|
}
|