feat(vpc): add folded batch instance apply

go
codex 3 weeks ago
parent b80d723a14
commit 2489e04f42

@ -328,6 +328,19 @@ final class CloudVpcPortService
$spec = json_decode((string) $instance->spec_json, true);
$supported = is_array($spec) && !array_is_list($spec)
&& ($spec['os_source'] ?? null) === 'cloud_template';
$publicIpv4 = '';
if (is_array($spec) && !array_is_list($spec)) {
foreach (['public_ip_cidr', 'public_ip'] as $field) {
$candidate = explode('/', trim((string) (
$spec[$field] ?? ''
)), 2)[0];
if (filter_var($candidate, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4) !== false) {
$publicIpv4 = $candidate;
break;
}
}
}
// Keep a historical attached port visible for status and
// diagnosis even if its immutable source metadata is damaged.
if (!$supported && $port === null) {
@ -365,6 +378,7 @@ final class CloudVpcPortService
'id' => (string) $instance->id,
'name' => (string) $instance->name,
'region_id' => $regionId,
'public_ipv4' => $publicIpv4,
'instance_status' => (string) $instance->status,
'service_status' => (string) $instance->service_status,
'network_status' => (string) $instance->network_status,

@ -297,3 +297,39 @@ body.vu-body .ssh-key-picker-manage:hover {
.vm-upgrade-section{max-width:880px}.vm-upgrade-current-card{margin:0 0 25px;padding:18px;border:1px solid #e1e9ed;border-radius:10px;background:#fbfcfd}.vm-upgrade-current-card h4,.vm-upgrade-picker-heading h4{margin:0;color:#314a5f;font-size:13px}.vm-upgrade-spec-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;margin:14px 0 0;padding:1px;background:#e3eaee}.vm-upgrade-spec-grid>div{min-width:0;padding:11px 13px;background:#fff}.vm-upgrade-spec-grid dt{margin-bottom:4px;color:#8797a5;font-size:9px}.vm-upgrade-spec-grid dd{margin:0;color:#294257;font-size:11px;font-weight:800;overflow-wrap:anywhere}.vm-upgrade-picker-heading{display:flex;align-items:baseline;justify-content:space-between;gap:15px;margin-bottom:11px}.vm-upgrade-picker-heading span{color:#8a99a7;font-size:10px}.vm-upgrade-offers{display:grid;gap:10px;margin:0 0 22px}.vm-upgrade-offer{position:relative;display:grid;width:100%;gap:14px;padding:16px 18px;border:1px solid #dce7ec;border-radius:10px;background:#fff;color:#50677a;text-align:left;cursor:pointer}.vm-upgrade-offer:hover:not(:disabled){border-color:#8ecdd2;background:#f8fcfc}.vm-upgrade-offer:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.vm-upgrade-offer[aria-checked=true]{border-color:#2eabb4;background:#eef9fa;box-shadow:inset 0 0 0 1px #2eabb4}.vm-upgrade-offer[aria-checked=true]::after{content:"✓";position:absolute;top:10px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900}.vm-upgrade-offer:disabled{cursor:not-allowed;opacity:.66}.vm-upgrade-offer-heading{display:flex;align-items:center;justify-content:space-between;gap:35px;padding-right:21px}.vm-upgrade-offer-name{min-width:0;color:#293f53;font-size:13px;overflow-wrap:anywhere}.vm-upgrade-offer-price{flex:none;color:#0d929d;font-size:13px}.vm-upgrade-offer-facts{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}.vm-upgrade-offer-fact{display:grid;min-width:0;gap:3px}.vm-upgrade-offer-fact small{color:#8a99a7;font-size:9px}.vm-upgrade-offer-fact b{color:#445d70;font-size:10px;overflow-wrap:anywhere}.vm-upgrade-empty{margin:0;padding:24px;border:1px dashed #d7e1e6;border-radius:10px;color:#8494a2;font-size:11px;text-align:center}@media screen and (max-width:510px){.vm-upgrade-current-card{padding:14px}.vm-upgrade-spec-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.vm-upgrade-picker-heading{align-items:flex-start;flex-direction:column;gap:4px}.vm-upgrade-offer{gap:13px;padding:15px}.vm-upgrade-offer-heading{align-items:flex-start;flex-direction:column;gap:5px;padding-right:27px}.vm-upgrade-offer-facts{grid-template-columns:repeat(2,minmax(0,1fr));gap:11px 8px}.vm-upgrade-offer-fact:last-child{grid-column:1/-1}.vm-upgrade-offer-price{font-size:12px}}
.vm-automatic-backup-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-automatic-backup-grid>.vm-settings-field{align-content:start}.vm-automatic-backup-list-heading{display:flex;align-items:center;justify-content:space-between;gap:15px;margin:32px 0 12px;padding-top:24px;border-top:1px solid #e6ecef}.vm-automatic-backup-list-heading h4{margin:0 0 4px;color:#354c60;font-size:14px}.vm-automatic-backup-list-heading small{color:#8797a5;font-size:10px}.vm-automatic-backup-list{display:grid;gap:10px}.vm-automatic-backup-card{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:13px 18px;padding:15px;border:1px solid #dfe8ed;border-radius:9px;background:#fbfdfd}.vm-automatic-backup-card-main{display:grid;gap:5px;min-width:0}.vm-automatic-backup-card-main strong{color:#31495d;font-size:12px;overflow-wrap:anywhere}.vm-automatic-backup-card-main small{color:#8192a1;font-size:10px;line-height:1.55}.vm-automatic-backup-card-status{align-self:start}.vm-automatic-backup-card-actions{grid-column:1/-1;display:flex;justify-content:flex-end}.vm-automatic-backup-empty{display:grid;gap:5px;padding:25px 17px;border:1px dashed #cedce2;border-radius:9px;color:#8797a5;text-align:center}.vm-automatic-backup-empty strong{color:#506779;font-size:12px}.vm-automatic-backup-empty span{font-size:10px}@media screen and (max-width:740px){.vm-automatic-backup-grid{grid-template-columns:1fr}}@media screen and (max-width:510px){.vm-automatic-backup-list-heading{align-items:flex-start;flex-direction:column}.vm-automatic-backup-list-heading .button{width:100%}.vm-automatic-backup-card{grid-template-columns:1fr}.vm-automatic-backup-card-status,.vm-automatic-backup-card-actions{grid-column:1}.vm-automatic-backup-card-actions .button{width:100%}}
.vm-automatic-backup-service{display:grid;gap:15px;margin:0 0 24px;padding:18px;border:1px solid #dce7ec;border-radius:11px;background:#fbfdfd}.vm-automatic-backup-service-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:18px}.vm-automatic-backup-service-heading h4{margin:4px 0 0;color:#30495d;font-size:14px}.vm-automatic-backup-service-prices{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;padding:1px;background:#e2eaed}.vm-automatic-backup-service-prices>div{display:grid;min-width:0;gap:5px;padding:14px;background:#fff}.vm-automatic-backup-service-prices span{color:#7c8e9e;font-size:10px}.vm-automatic-backup-service-prices strong{color:#263f54;font-size:14px;overflow-wrap:anywhere}.vm-automatic-backup-service-prices small{color:#8999a6;font-size:9px;line-height:1.55}.vm-automatic-backup-service-note{margin:0;color:#64798b;font-size:10px;line-height:1.7}.vm-automatic-backup-service-actions{display:flex;justify-content:flex-end;gap:10px}.vm-automatic-backup-service-actions .button{min-width:138px}@media screen and (max-width:740px){.vm-automatic-backup-service-prices{grid-template-columns:1fr}.vm-automatic-backup-service-actions{flex-direction:column}.vm-automatic-backup-service-actions .button{width:100%}}
/* Collapsible VPC cards and sequential multi-instance apply. */
.cloud-vpc-disclosure{display:block;padding:0;overflow:hidden}
.cloud-vpc-card-summary{position:relative;display:block;padding:20px 50px 20px 20px;list-style:none;cursor:pointer;user-select:none}
.cloud-vpc-card-summary::-webkit-details-marker{display:none}
.cloud-vpc-card-summary::after{content:"⌄";position:absolute;top:50%;right:21px;color:#78909e;font-size:19px;font-weight:800;transform:translateY(-50%);transition:transform .18s ease}
.cloud-vpc-disclosure[open]>.cloud-vpc-card-summary::after{transform:translateY(-50%) rotate(180deg)}
.cloud-vpc-card-summary:focus-visible{outline:3px solid rgba(18,166,176,.2);outline-offset:-3px}
.cloud-vpc-card-body{display:grid;gap:18px;padding:0 20px 20px;border-top:1px solid #edf1f3}
.cloud-vpc-card-body>.cloud-vpc-card-facts{margin-top:18px}
.cloud-vpc-batch-status{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:12px 14px;border:1px solid #bfe4e6;border-radius:9px;background:#f0fbfb}
.cloud-vpc-batch-status>div{display:grid;gap:4px;min-width:0}
.cloud-vpc-batch-status strong{color:#28727a;font-size:10px}
.cloud-vpc-batch-status small{color:#64818a;font-size:9px;line-height:1.5}
.cloud-vpc-batch-status.failed{border-color:#f0d8dc;background:#fff6f7}
.cloud-vpc-batch-status.failed strong,.cloud-vpc-batch-status.failed small{color:#a64d59}
.cloud-vpc-batch-status.uncertain{border-color:#eed9ad;background:#fff9ed}
.cloud-vpc-batch-status.uncertain strong,.cloud-vpc-batch-status.uncertain small{color:#93681c}
.cloud-vpc-attach-form{grid-template-columns:1fr;align-items:stretch;gap:12px}
.cloud-vpc-candidate-picker{min-width:0;margin:0;padding:0;border:0}
.cloud-vpc-candidate-picker legend{margin:0 0 8px;color:#52697b;font-size:10px;font-weight:800}
.cloud-vpc-candidate-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
.cloud-vpc-candidate-row{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;gap:10px;min-width:0;padding:11px 12px;border:1px solid #e1e9ed;border-radius:9px;background:#fbfcfd;cursor:pointer}
.cloud-vpc-candidate-row:hover:not(.disabled){border-color:#a9d9dc;background:#f7fcfc}
.cloud-vpc-candidate-row.selected{border-color:#67c2c7;background:#effafa}
.cloud-vpc-candidate-row.disabled{cursor:not-allowed;opacity:.65}
.cloud-vpc-candidate-row input{width:17px;height:17px;margin:0;accent-color:#18a6b0}
.cloud-vpc-candidate-identity{display:grid;gap:4px;min-width:0}
.cloud-vpc-candidate-identity strong{color:#31495d;font-size:10px;overflow-wrap:anywhere}
.cloud-vpc-candidate-identity small{color:#8293a1;font:500 9px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
.cloud-vpc-candidate-identity small.warning{color:#a27226;font-family:inherit}
.cloud-vpc-batch-toolbar{display:flex;align-items:center;justify-content:flex-end;gap:9px;flex-wrap:wrap}
.cloud-vpc-batch-toolbar>span{margin-right:auto;color:#8192a0;font-size:10px}
.cloud-vpc-batch-toolbar .button{min-width:112px}
@media(max-width:740px){.cloud-vpc-candidate-list{grid-template-columns:1fr}}
@media(max-width:510px){.cloud-vpc-disclosure{padding:0}.cloud-vpc-card-summary{padding:15px 43px 15px 15px}.cloud-vpc-card-summary::after{right:16px}.cloud-vpc-card-body{gap:15px;padding:0 15px 15px}.cloud-vpc-batch-status{align-items:flex-start;flex-direction:column}.cloud-vpc-batch-status .button{width:100%}.cloud-vpc-batch-toolbar{align-items:stretch;flex-direction:column}.cloud-vpc-batch-toolbar>span{margin:0}.cloud-vpc-batch-toolbar .button{width:100%}}

@ -34,6 +34,8 @@ const state = {
createKey: '', createFingerprint: '', userKey: 'unknown',
mutatingVpcs: new Set(), mutatingInstances: new Set(),
observers: new Map(), terminalTasks: new Set(),
expandedVpcs: new Set(), selections: new Map(),
batchPlan: null, batchAdvancing: false, batchAdvanceScheduled: false,
};
function element(tag, className = '', content) {
@ -87,6 +89,7 @@ function apply(payload) {
state.used = Math.max(0, Number(payload?.used) || state.items.length);
render();
observeActiveTasks();
scheduleBatchAdvance();
}
function renderRegions() {
@ -98,8 +101,7 @@ function renderRegions() {
empty.value = '';
select.append(empty);
for (const region of state.regions) {
const option = element('option', '',
`${region.name} · 可分配 ${region.available} 个子网`);
const option = element('option', '', region.name || region.code || '未命名地区');
option.value = String(region.id);
option.selected = String(region.id) === selected;
select.append(option);
@ -161,6 +163,89 @@ function candidatesForVpc(vpc) {
&& Number(instance?.region_id || 0) === regionId);
}
function vpcKey(vpc) {
return String(vpc?.vpc_key || '');
}
function publicIpv4(instance) {
return String(instance?.public_ipv4 || '').trim() || '未分配';
}
function selectionForVpc(vpc) {
const key = vpcKey(vpc);
if (!state.selections.has(key)) state.selections.set(key, new Set());
return state.selections.get(key);
}
function batchStorageKey() {
return `virt-cloud:vpc-attach-batch:${state.userKey}`;
}
function persistBatchPlan() {
try {
if (state.batchPlan) {
sessionStorage.setItem(batchStorageKey(), JSON.stringify(state.batchPlan));
} else {
sessionStorage.removeItem(batchStorageKey());
}
} catch {}
}
function restoreBatchPlan() {
let saved = null;
try { saved = JSON.parse(sessionStorage.getItem(batchStorageKey()) || 'null'); }
catch {}
const key = String(saved?.vpcKey || '');
const ids = Array.isArray(saved?.ids)
? [...new Set(saved.ids.map(String).filter(id => /^[0-9]+$/.test(id)))] : [];
if (!/^[a-f0-9]{32}$/.test(key) || !ids.length
|| !['running', 'failed', 'uncertain'].includes(String(saved?.status || ''))) {
state.batchPlan = null;
persistBatchPlan();
return;
}
const completed = Array.isArray(saved?.completed)
? [...new Set(saved.completed.map(String).filter(id => ids.includes(id)))] : [];
const current = ids.includes(String(saved?.current || ''))
? String(saved.current) : '';
state.batchPlan = {
vpcKey: key,
ids,
completed,
current,
currentState: current ? String(saved?.currentState || 'submitting') : '',
status: String(saved.status),
failedMessage: String(saved?.failedMessage || ''),
};
state.expandedVpcs.add(key);
}
function clearBatchPlan() {
state.batchPlan = null;
persistBatchPlan();
setPageStatus();
render();
}
function failBatchPlan(status, message) {
if (!state.batchPlan) return;
state.batchPlan.status = status;
state.batchPlan.failedMessage = message;
persistBatchPlan();
setPageStatus(message, status === 'uncertain' ? 'warning' : 'error');
render();
}
function scheduleBatchAdvance() {
if (state.batchAdvanceScheduled || state.batchAdvancing || state.loading
|| state.batchPlan?.status !== 'running') return;
state.batchAdvanceScheduled = true;
queueMicrotask(() => {
state.batchAdvanceScheduled = false;
void advanceBatchPlan();
});
}
function renderInstanceRow(instance, vpc) {
const port = instance?.port || {};
const [label, className] = PORT_STATE_LABELS[String(port.state || '')]
@ -169,7 +254,9 @@ function renderInstanceRow(instance, vpc) {
const identity = element('div', 'cloud-vpc-instance-identity');
identity.append(element('strong', '', instance.name || `实例 #${instanceId(instance)}`));
identity.append(element('span', '',
`${port.private_ip || '私网 IP 待分配'} · ${port.mac_address || 'MAC 待生成'}`));
`公网 IPv4 ${publicIpv4(instance)}`));
identity.append(element('span', '',
`私网 ${port.private_ip || '待分配'} · ${port.mac_address || 'MAC 待生成'}`));
if (instance.action_unavailable_reason) {
identity.append(element('small', '', instance.action_unavailable_reason));
}
@ -194,22 +281,53 @@ function renderInstanceRow(instance, vpc) {
}
if (button) {
button.type = 'button';
button.disabled = mutating || Boolean(activeTask) || !action;
button.disabled = mutating || Boolean(activeTask) || !action
|| Boolean(state.batchPlan);
controls.append(button);
}
row.append(identity, status, controls);
return row;
}
function renderBatchStatus(vpc) {
const plan = state.batchPlan;
if (!plan || plan.vpcKey !== vpcKey(vpc)) return null;
const box = element('div', `cloud-vpc-batch-status ${plan.status}`);
const content = element('div');
const completed = plan.completed.length;
const current = state.instances.find(item => instanceId(item) === plan.current);
let title = `已完成 ${completed} / ${plan.ids.length} 台`;
let message = plan.failedMessage;
if (plan.status === 'running') {
title = `正在按顺序应用 ${completed} / ${plan.ids.length} 台`;
message = plan.current
? `当前处理:${current?.name || `实例 #${plan.current}`}。完成后会自动提交下一台。`
: '正在核对下一台实例的连接资格。';
}
content.append(element('strong', '', title), element('small', '', message));
box.append(content);
if (plan.status !== 'running') {
const clear = element('button', 'button button-outline small', '清除队列');
clear.type = 'button';
clear.addEventListener('click', clearBatchPlan);
box.append(clear);
}
return box;
}
function renderInstanceManager(vpc) {
const section = element('section', 'cloud-vpc-instance-manager');
const heading = element('div', 'cloud-vpc-instance-heading');
const title = element('div');
title.append(element('strong', '', '实例连接'),
element('small', '', '加入或移出都会自动正常关机并冷启动。'));
element('small', '',
'可一次选择多台;系统会逐台正常关机、应用网卡并冷启动,请在队列完成前保持页面打开。'));
heading.append(title);
section.append(heading);
const batchStatus = renderBatchStatus(vpc);
if (batchStatus) section.append(batchStatus);
const connected = instancesForVpc(vpc);
const rows = element('div', 'cloud-vpc-instance-list');
if (!connected.length) {
@ -220,41 +338,90 @@ function renderInstanceManager(vpc) {
section.append(rows);
const candidates = candidatesForVpc(vpc);
const eligibleCandidateIds = new Set(candidates
.filter(instance => instance.can_attach === true).map(instanceId));
const selection = selectionForVpc(vpc);
for (const id of [...selection]) {
if (!eligibleCandidateIds.has(id)) selection.delete(id);
}
const form = element('form', 'cloud-vpc-attach-form');
const field = element('div', 'field');
const label = element('label', '', '加入同地区实例');
const select = document.createElement('select');
const placeholder = element('option', '', candidates.length
? '请选择实例' : '当前地区没有可加入的实例');
placeholder.value = '';
select.append(placeholder);
const picker = element('fieldset', 'cloud-vpc-candidate-picker');
const legend = element('legend', '', '选择要加入的同地区实例');
picker.append(legend);
const list = element('div', 'cloud-vpc-candidate-list');
const checkboxes = [];
const batchBlocked = Boolean(state.batchPlan);
for (const instance of candidates) {
const reason = String(instance.action_unavailable_reason || '');
const option = element('option', '',
`${instance.name || `实例 #${instanceId(instance)}`}${reason ? ` · ${reason}` : ''}`);
option.value = instanceId(instance);
option.disabled = instance.can_attach !== true;
select.append(option);
const id = instanceId(instance);
const row = element('label', 'cloud-vpc-candidate-row');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = id;
checkbox.checked = selection.has(id);
checkbox.disabled = batchBlocked || instance.can_attach !== true
|| state.mutatingInstances.has(id);
const identity = element('span', 'cloud-vpc-candidate-identity');
identity.append(element('strong', '', instance.name || `实例 #${id}`),
element('small', '', `公网 IPv4 ${publicIpv4(instance)}`));
if (reason) identity.append(element('small', 'warning', reason));
row.classList.toggle('selected', checkbox.checked);
row.classList.toggle('disabled', checkbox.disabled);
row.append(checkbox, identity);
list.append(row);
checkboxes.push({ checkbox, id, row });
}
label.htmlFor = `cloud-vpc-instance-${vpc.vpc_key}`;
select.id = label.htmlFor;
select.disabled = !candidates.some(instance => instance.can_attach === true);
field.append(label, select);
if (!candidates.length) {
list.append(element('p', 'cloud-vpc-instance-empty',
'当前地区没有可加入的实例。'));
}
picker.append(list);
const submit = element('button', 'button button-primary small', '加入并重启');
const toolbar = element('div', 'cloud-vpc-batch-toolbar');
const selectionCount = element('span', '', '已选择 0 台');
const selectAll = element('button', 'button button-outline small', '全选可用');
selectAll.type = 'button';
const submit = element('button', 'button button-primary small', '应用所选实例');
submit.type = 'submit';
submit.disabled = true;
select.addEventListener('change', () => {
const selected = candidates.find(instance => instanceId(instance) === select.value);
submit.disabled = !selected || selected.can_attach !== true
|| state.mutatingInstances.has(instanceId(selected));
const updateControls = () => {
const count = [...selection].filter(id => eligibleCandidateIds.has(id)).length;
selectionCount.textContent = `已选择 ${count} 台`;
submit.textContent = count ? `应用 ${count} 台实例` : '应用所选实例';
submit.disabled = batchBlocked || count < 1;
const selectable = checkboxes.filter(item => !item.checkbox.disabled);
const allSelected = selectable.length > 0
&& selectable.every(item => selection.has(item.id));
selectAll.textContent = allSelected ? '取消全选' : '全选可用';
selectAll.disabled = batchBlocked || selectable.length < 1;
};
for (const item of checkboxes) {
item.checkbox.addEventListener('change', () => {
if (item.checkbox.checked) selection.add(item.id);
else selection.delete(item.id);
item.row.classList.toggle('selected', item.checkbox.checked);
updateControls();
});
}
selectAll.addEventListener('click', () => {
const selectable = checkboxes.filter(item => !item.checkbox.disabled);
const allSelected = selectable.length > 0
&& selectable.every(item => selection.has(item.id));
for (const item of selectable) {
item.checkbox.checked = !allSelected;
item.row.classList.toggle('selected', !allSelected);
if (allSelected) selection.delete(item.id);
else selection.add(item.id);
}
updateControls();
});
form.addEventListener('submit', event => {
event.preventDefault();
const selected = candidates.find(instance => instanceId(instance) === select.value);
if (selected?.can_attach === true) void mutatePort(selected, vpc, 'attach');
void startBatchAttach(vpc, candidates.filter(instance =>
selection.has(instanceId(instance)) && instance.can_attach === true));
});
form.append(field, submit);
toolbar.append(selectionCount, selectAll, submit);
form.append(picker, toolbar);
updateControls();
section.append(form);
return section;
}
@ -270,8 +437,11 @@ function render() {
list.append(empty);
}
for (const vpc of state.items) {
const key = vpcKey(vpc);
const [label, className] = vpcState(vpc.state);
const card = element('article', 'cloud-vpc-card');
const card = element('details', 'cloud-vpc-card cloud-vpc-disclosure');
card.open = state.expandedVpcs.has(key);
const summary = element('summary', 'cloud-vpc-card-summary');
const heading = element('div', 'cloud-vpc-card-heading');
const title = element('div', 'cloud-vpc-card-title');
title.append(element('span', 'cloud-vpc-card-icon', '◇'),
@ -279,7 +449,13 @@ function render() {
title.lastElementChild.append(element('small', '',
`${vpc.region_name} · ${vpc.port_count} 台实例`));
heading.append(title, element('span', `state-pill ${className}`, label));
summary.append(heading);
card.addEventListener('toggle', () => {
if (card.open) state.expandedVpcs.add(key);
else state.expandedVpcs.delete(key);
});
const body = element('div', 'cloud-vpc-card-body');
const facts = element('dl', 'cloud-vpc-card-facts');
for (const [factLabel, value] of [
['私网 CIDR', vpc.cidr],
@ -295,17 +471,19 @@ function render() {
const remove = element('button', 'button button-outline small danger', '删除 VPC');
remove.type = 'button';
remove.disabled = state.mutatingVpcs.has(String(vpc.vpc_key))
|| vpc.can_delete !== true;
|| vpc.can_delete !== true || Boolean(state.batchPlan);
remove.title = vpc.port_count > 0 ? '请先移出该 VPC 中的全部实例。' : '';
remove.addEventListener('click', () => void removeVpc(vpc));
actions.append(remove);
card.append(heading, facts, renderInstanceManager(vpc), actions);
body.append(facts, renderInstanceManager(vpc), actions);
card.append(summary, body);
list.append(card);
}
byId('cloud-vpcs-count').textContent = `${state.items.length} 个`;
byId('cloud-vpcs-quota').textContent = `${state.used} / ${state.maximum}`;
byId('cloud-vpcs-refresh').disabled = state.loading || state.creating
|| state.mutatingInstances.size > 0 || state.mutatingVpcs.size > 0;
|| state.mutatingInstances.size > 0 || state.mutatingVpcs.size > 0
|| state.batchPlan?.status === 'running';
}
function taskFailureMessage(task) {
@ -331,12 +509,24 @@ function observeReceipt(instance, receipt, accepted = false) {
state.observers.delete(id);
state.terminalTasks.add(id);
state.mutatingInstances.delete(instanceId(instance));
const batchPlanAtTerminal = state.batchPlan;
const belongsToBatch = batchPlanAtTerminal?.status === 'running'
&& batchPlanAtTerminal.current === 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 (belongsToBatch) {
if (state.batchPlan !== batchPlanAtTerminal
|| state.batchPlan?.status !== 'running') return;
setPageStatus(taskSucceededWithoutRecovery(task)
? '批量 VPC 队列正在核对当前实例,收敛后会自动处理下一台。'
: taskFailureMessage(task),
taskSucceededWithoutRecovery(task) ? '' : 'error');
return;
}
if (nextTask && nextTask !== id) {
setPageStatus(taskSucceededWithoutRecovery(task)
? 'VPC 编排正在继续执行下一阶段,请勿重复提交。'
@ -399,27 +589,164 @@ async function load(force = false) {
state.controller = null;
state.loading = false;
render();
scheduleBatchAdvance();
}
}
}
async function startBatchAttach(vpc, instances) {
if (state.batchPlan || !instances.length) return;
const confirmed = await requestUserConfirmation({
title: `确认将 ${instances.length} 台实例加入 VPC`,
message: `系统会按顺序将所选实例加入“${vpc.name}”。每台实例都会正常关机、应用私网网卡并冷启动;前一台完全收敛后才会提交下一台。`,
confirmText: `应用 ${instances.length} 台实例`,
tone: 'default',
});
if (!confirmed || state.batchPlan) return;
const key = vpcKey(vpc);
state.batchPlan = {
vpcKey: key,
ids: instances.map(instanceId),
completed: [],
current: '',
currentState: '',
status: 'running',
failedMessage: '',
};
state.selections.get(key)?.clear();
state.expandedVpcs.add(key);
persistBatchPlan();
setPageStatus(`已接收 ${instances.length} 台实例,将按顺序应用 VPC 私网。`);
render();
scheduleBatchAdvance();
}
async function advanceBatchPlan() {
const plan = state.batchPlan;
if (!plan || plan.status !== 'running' || state.batchAdvancing
|| state.loading) return;
state.batchAdvancing = true;
try {
const vpc = state.items.find(item => vpcKey(item) === plan.vpcKey);
if (!vpc) {
failBatchPlan('failed', '批量加入已停止:目标 VPC 不存在或已不可见。');
return;
}
while (state.batchPlan === plan && plan.status === 'running') {
if (plan.current) {
const current = state.instances.find(item => instanceId(item) === plan.current);
if (!current) {
failBatchPlan('failed', `批量加入已停止:实例 #${plan.current} 已不可见。`);
return;
}
const attached = vpcKey(current?.port) === plan.vpcKey
&& String(current?.port?.state || '') === 'attached';
if (attached) {
if (!plan.completed.includes(plan.current)) plan.completed.push(plan.current);
plan.current = '';
plan.currentState = '';
persistBatchPlan();
render();
continue;
}
if (taskId(current?.active_task)
|| state.mutatingInstances.has(instanceId(current))) return;
if (current?.port) {
const message = current.can_retry_attach === true
? `实例“${current.name}”的连接阶段需要人工重试,后续实例尚未提交。`
: `实例“${current.name}”未收敛到已连接状态,后续实例尚未提交。`;
failBatchPlan('failed', message);
return;
}
if (plan.currentState === 'submitting' || plan.currentState === 'accepted') {
failBatchPlan('uncertain',
`实例“${current.name}”的提交结果无法从服务端确认,已停止后续队列,请先在任务中心核对。`);
return;
}
failBatchPlan('failed', `实例“${current.name}”未能加入 VPC,后续实例尚未提交。`);
return;
}
const nextId = plan.ids.find(id => !plan.completed.includes(id));
if (!nextId) {
const total = plan.ids.length;
state.batchPlan = null;
persistBatchPlan();
render();
setPageStatus(`${total} 台实例已全部加入 VPC。`, 'success');
toast(`${total} 台实例已全部加入 VPC。`, 'success');
return;
}
const next = state.instances.find(item => instanceId(item) === nextId);
if (!next) {
failBatchPlan('failed', `批量加入已停止:实例 #${nextId} 已不可见。`);
return;
}
if (vpcKey(next?.port) === plan.vpcKey
&& String(next?.port?.state || '') === 'attached') {
plan.completed.push(nextId);
persistBatchPlan();
continue;
}
if (next.can_attach !== true) {
failBatchPlan('failed',
`实例“${next.name}”当前不可加入:${next.action_unavailable_reason || '实例状态已变化'}。`);
return;
}
plan.current = nextId;
plan.currentState = 'submitting';
persistBatchPlan();
render();
const outcome = await mutatePort(next, vpc, 'attach', {
confirmed: true,
quiet: true,
});
if (state.batchPlan !== plan) return;
if (outcome.status === 'accepted') {
plan.currentState = 'accepted';
persistBatchPlan();
render();
const refreshed = state.instances.find(item => instanceId(item) === nextId);
if (vpcKey(refreshed?.port) === plan.vpcKey
&& String(refreshed?.port?.state || '') === 'attached') continue;
return;
}
if (outcome.status === 'uncertain') {
failBatchPlan('uncertain', outcome.message
|| `实例“${next.name}”的提交结果暂时无法确认,已停止后续队列。`);
return;
}
failBatchPlan('failed', outcome.message
|| `实例“${next.name}”提交失败,后续实例尚未提交。`);
return;
}
} finally {
state.batchAdvancing = false;
}
}
async function mutatePort(instance, vpc, requestedAction) {
async function mutatePort(instance, vpc, requestedAction, options = {}) {
const id = instanceId(instance);
if (!id || state.mutatingInstances.has(id)) return;
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;
|| (!attach && !['detach', 'retry_detach'].includes(action))) {
return { status: 'ignored' };
}
const confirmed = await requestUserConfirmation({
title: attach ? '确认加入 VPC 私网' : '确认移出 VPC 私网',
message: attach
? `实例“${instance.name}”将自动正常关机,加入“${vpc.name}”后冷启动。期间服务会短暂中断。`
: `实例“${instance.name}”将自动正常关机,移除私网网卡后冷启动,并释放私网 IP。`,
confirmText: attach ? '加入并重启' : '移出并重启',
tone: attach ? 'default' : 'danger',
});
if (!confirmed) return;
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 || '')}`;
@ -444,16 +771,21 @@ async function mutatePort(instance, vpc, requestedAction) {
});
observeReceipt(instance, receipt, true);
setPageStatus('VPC 变更任务已接收,正在执行关机、网卡和路由阶段。');
toast('VPC 私网任务已接收。', 'success');
if (options.quiet !== true) toast('VPC 私网任务已接收。', 'success');
await load(true);
return { status: 'accepted' };
} catch (error) {
await load(true);
if (transportUncertain(error)) {
setPageStatus(error?.message
|| '请求结果暂时无法确认,已保留同一请求标识,请勿重复提交。', 'warning');
const message = error?.message
|| '请求结果暂时无法确认,已保留同一请求标识,请勿重复提交。';
setPageStatus(message, 'warning');
return { status: 'uncertain', message };
} else {
clearPendingMutationKey(instance);
setPageStatus(error?.message || 'VPC 私网操作提交失败。', 'error');
const message = error?.message || 'VPC 私网操作提交失败。';
setPageStatus(message, 'error');
return { status: 'failed', message };
}
} finally {
state.mutatingInstances.delete(id);
@ -531,6 +863,7 @@ export async function initialize() {
const bootstrap = readBootstrap('cloud-vpcs-bootstrap');
if (!await initializeSession('vpcs', bootstrap?.user)) return;
state.userKey = String(bootstrap?.user?.id || bootstrap?.user?.user_id || 'unknown');
restoreBatchPlan();
if (Array.isArray(bootstrap?.items) && Array.isArray(bootstrap?.instances)
&& Array.isArray(bootstrap?.regions)) {
apply(bootstrap);

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026102902' scope='global'}
{assign var=venix_asset_version value='2026102903' scope='global'}

@ -253,8 +253,12 @@ namespace {
$instance->resource_pool_id = 1; $instance->name = 'vm-' . $id;
$instance->status = 'active'; $instance->service_status = 'exempt';
$instance->network_status = 'active'; $instance->expires_at = null;
$instance->spec_json = json_encode(['os_source' => 'cloud_template'],
JSON_THROW_ON_ERROR);
$networkSpec = $id === 2
? ['public_ip' => '203.0.113.12']
: ['public_ip_cidr' => '203.0.113.11/24'];
$instance->spec_json = json_encode(array_merge([
'os_source' => 'cloud_template',
], $networkSpec), JSON_THROW_ON_ERROR);
$instance->created_at = $instance->updated_at = time();
$instance->save();
return $instance;
@ -301,12 +305,14 @@ namespace {
$targetManagement = collect($management)->firstWhere('id', '1');
$peerManagement = collect($management)->firstWhere('id', '2');
$assert(($targetManagement['region_id'] ?? null) === 1
&& ($targetManagement['public_ipv4'] ?? null) === '203.0.113.11'
&& array_key_exists('port', $targetManagement)
&& $targetManagement['port'] === null
&& ($targetManagement['can_attach'] ?? false) === true,
'The VPC page projection did not expose the eligible same-region instance.');
$assert(($peerManagement['port']['vpc_key'] ?? null)
=== (string) $vpc->vpc_key
&& ($peerManagement['public_ipv4'] ?? null) === '203.0.113.12'
&& ($peerManagement['can_detach'] ?? false) === true,
'The VPC page projection did not expose its attached instance action.');

@ -80,7 +80,15 @@ $assert(str_contains($template, 'class="cloud-vpcs-stack"')
&& str_contains($styles, '.cloud-vpc-create-form')
&& str_contains($styles, '.cloud-vpc-card')
&& str_contains($styles, '.cloud-vpc-instance-manager')
&& str_contains($javascript, 'function renderInstanceManager('),
&& str_contains($styles, '.cloud-vpc-candidate-list')
&& str_contains($javascript, 'function renderInstanceManager(')
&& str_contains($javascript, "element('details', 'cloud-vpc-card cloud-vpc-disclosure')")
&& str_contains($javascript, 'function startBatchAttach(')
&& str_contains($javascript, 'async function advanceBatchPlan(')
&& str_contains($javascript, 'sessionStorage.setItem(batchStorageKey()')
&& str_contains($javascript, 'public_ipv4')
&& str_contains($portService, "'public_ipv4' => \$publicIpv4")
&& !str_contains($javascript, '可分配 ${region.available} 个子网'),
'The VPC page must use one responsive stack with instance management.');
$assert(!str_contains($detailTemplate, 'id="vm-settings-nav-vpc"')
&& !str_contains($detailTemplate, 'id="vm-settings-section-vpc"')

Loading…
Cancel
Save