Fix admin instance detail rendering

go
codex 1 month ago
parent 402ee0e128
commit 913f0fadff

@ -153,12 +153,20 @@ final class CloudAdminInstanceService
$dns = array_values(array_filter(array_slice($dns, 0, 8),
static fn ($value): bool => is_string($value)
&& filter_var($value, FILTER_VALIDATE_IP) !== false));
$publicIpCidr = self::text($spec['public_ip_cidr'] ?? null, 64);
$managedCloudTemplate = ($spec['managed'] ?? false) === true
&& ($spec['os_source'] ?? null) === 'cloud_template';
$canMutate = $row['instance_status'] === 'active';
$row += [
'public_ip_cidr' => self::text($spec['public_ip_cidr'] ?? null, 64),
'public_ip_cidr' => $publicIpCidr,
'gateway' => self::ip($spec['gateway'] ?? null), 'dns_servers' => $dns,
'bandwidth_mbps' => self::positiveOrNull($spec['bandwidth_mbps'] ?? null),
'os_source' => self::text($spec['os_source'] ?? null, 32),
'login_name' => self::text($spec['login_name'] ?? null, 32),
'network_change_supported' => $canMutate && $managedCloudTemplate
&& $publicIpCidr !== null,
'instance_settings_supported' => $canMutate && $managedCloudTemplate
&& ($publicIpCidr !== null || $row['public_ip'] !== ''),
// The Agent can extend its UUID-derived name on collisions. Do
// not invent that name from a UUID when it was never persisted.
'agent_name' => self::resourceName($spec['agent_name'] ?? null),

@ -689,6 +689,17 @@ function settingsEditor(vm) {
const current = section.querySelector('[data-settings-current-hostname]');
if (current) current.textContent = `当前主机名:${text(vm.guest_hostname, vm.hostname, '未记录')}`;
if (!form) return section;
if (vm.instance_settings_supported !== true) {
form.remove();
const description = section.querySelector('.admin-instance-settings-heading p');
if (description) {
description.className = 'text-warning fs-13 mb-0';
description.textContent = vm.instance_status && vm.instance_status !== 'active'
? `当前实例处于“${text(vm.display?.lifecycle, vm.instance_status)}”状态,暂不能修改主机名、密码或 SSH 公钥。`
: '当前实例缺少已验证的面板云镜像元数据,暂不能修改主机名、密码或 SSH 公钥。请先核对实例元数据。';
}
return section;
}
const activeJob = Boolean(vm.active_job && ['queued', 'running', 'uncertain'].includes(String(vm.active_job.status)));
if (activeJob) {
unlockSettingsForm(form, true);
@ -755,14 +766,12 @@ function networkJobState(job) {
return String(job?.status || job?.job?.status || '').toLowerCase();
}
function networkOptionsView(section, options, fallback = false, fallbackMessage = '') {
function networkOptionsView(section, options) {
const summary = networkOptionSummary(options);
const status = section.querySelector('[data-network-options-status]');
if (status) {
status.textContent = fallback
? (fallbackMessage || '地址池详情暂不可用,暂不能选择新的公网 IP。')
: (options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。');
status.className = `text-muted fs-12 mb-0${fallback ? ' text-warning' : ''}`;
status.textContent = options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。';
status.className = 'text-muted fs-12 mb-0';
}
const values = section.querySelector('[data-network-options-values]');
if (!values) return;
@ -815,32 +824,46 @@ function networkOptionsView(section, options, fallback = false, fallbackMessage
}
}
function networkOptionsErrorView(section, message) {
section._networkOptions = null;
section.querySelector('[data-network-options-values]')?.replaceChildren();
const status = section.querySelector('[data-network-options-status]');
if (status) {
status.textContent = message;
status.className = 'text-warning fs-12 mb-0';
}
const edit = section.querySelector('[data-network-edit="open"]');
if (edit instanceof HTMLButtonElement) {
edit.disabled = true;
edit.setAttribute('aria-expanded', 'false');
edit.title = message;
}
const form = section.querySelector('.admin-instance-network-form');
if (form) form.hidden = true;
}
async function loadNetworkOptions(vm, section) {
const serial = state.networkSerial;
const controller = new AbortController();
state.networkOptionsRequest = controller;
let options = networkOptionsFromVm(vm);
let fallback = true;
let fallbackMessage = '';
let options;
try {
const payload = await api(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network-options`, controller);
if (serial !== state.networkSerial || controller.signal.aborted) return;
options = networkOptionsPayload(payload, vm);
fallback = false;
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (serial !== state.networkSerial) return;
// The options endpoint is additive. Older deployments can still use the
// existing detail fields while the Agent remains the final validator.
options = networkOptionsFromVm(vm);
fallbackMessage = error.status === 409
const message = error.status === 409
? error.message : '无法读取宿主机地址池,暂不能选择新的公网 IP。';
if (state.detailId === String(vm.id)) networkOptionsErrorView(section, message);
return;
} finally {
if (state.networkOptionsRequest === controller) state.networkOptionsRequest = null;
}
if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return;
section._networkOptions = options;
networkOptionsView(section, options, fallback, fallbackMessage);
networkOptionsView(section, options);
}
function targetNetworkValue(section, vm) {
@ -1016,7 +1039,7 @@ function networkEditor(vm) {
const template = byId('admin-instance-network-controls');
const controls = template?.content?.cloneNode(true);
const edit = controls?.querySelector('[data-network-edit="open"]');
if (edit) heading.append(edit);
if (edit && vm.network_change_supported === true) heading.append(edit);
section.append(heading);
const current = el('div', 'admin-instance-network-current mt-3');
@ -1026,6 +1049,18 @@ function networkEditor(vm) {
current.append(el('span', 'text-muted fs-13', '当前公网地址'), currentValue);
section.append(current);
if (!edit) {
if (controls) section.append(controls);
return section;
}
if (vm.network_change_supported !== true) {
section.append(el('p', 'text-warning fs-13 mt-3 mb-0',
vm.instance_status && vm.instance_status !== 'active'
? `当前实例处于“${text(vm.display?.lifecycle, vm.instance_status)}”状态,暂不能更换公网 IP。`
: '当前实例缺少已验证的面板云镜像元数据,暂不能更换公网 IP。请先核对实例元数据。'));
return section;
}
const optionsBox = el('div', 'admin-instance-network-options-box mt-3');
optionsBox.append(el('p', 'text-muted fs-13 mb-2', '宿主机网络约束'));
const optionsValues = el('dl', 'admin-instance-network-options');
@ -1248,6 +1283,9 @@ async function openDetail(id, opener) {
cancelSettingsActivity('detail-switch');
state.detailId = id;
state.opener = opener;
const dialog = byId('instance-detail');
const drawerBody = dialog.querySelector('.admin-instance-drawer-body');
if (drawerBody) drawerBody.scrollTop = 0;
const controller = new AbortController();
state.detailRequest = controller;
byId('instance-detail-title').textContent = `实例 #${id}`;
@ -1256,9 +1294,9 @@ async function openDetail(id, opener) {
tabs.forEach(tab => byId(`instance-panel-${tab}`).replaceChildren());
chooseTab('basic');
detailNotice('正在读取详情…');
if (!byId('instance-detail').open) {
if (!dialog.open) {
lockDetailScroll();
window.VenixDrawerMotion.openDrawerWithMotion(byId('instance-detail'));
window.VenixDrawerMotion.openDrawerWithMotion(dialog);
}
try {
const payload = await api(`/api/v1/admin/instances/${id}`, controller);

@ -56,7 +56,9 @@ $detail = [
'instance' => array_replace($items[0], [
'public_ip_cidr' => '192.0.2.101/24', 'gateway' => '192.0.2.1',
'dns_servers' => ['1.1.1.1', '8.8.8.8'], 'engine_name' => 'vc-1111111111114111',
'bandwidth_mbps' => 100, 'os_source' => 'cloud', 'login_name' => 'root',
'bandwidth_mbps' => 100, 'os_source' => 'cloud_template',
'network_change_supported' => true, 'instance_settings_supported' => true,
'login_name' => 'root',
'current_period_started_at' => $now - 26 * 86400,
'current_period_ends_at' => $now + 4 * 86400, 'renewal_price' => '10.00',
'renewal_days' => 30, 'renewal_traffic_bytes' => 107374182400,
@ -95,6 +97,28 @@ $assert = static function (bool $ok, string $message): void {
if (!$ok) throw new RuntimeException($message);
};
$html = $render($page);
$clientScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instances.js');
$openDetailStart = strpos($clientScript, 'async function openDetail(id, opener)');
$openDetailEnd = $openDetailStart === false ? false
: strpos($clientScript, 'async function copy(value)', $openDetailStart);
$openDetailSource = $openDetailStart === false || $openDetailEnd === false
? '' : substr($clientScript, $openDetailStart,
$openDetailEnd - $openDetailStart);
$scrollReset = strpos($openDetailSource, 'drawerBody.scrollTop = 0;');
$drawerOpen = strpos($openDetailSource,
'window.VenixDrawerMotion.openDrawerWithMotion(dialog)');
$assert($scrollReset !== false && $drawerOpen !== false
&& $scrollReset < $drawerOpen,
'Opening or switching instance detail must reset the reusable drawer body to the top.');
$assert(str_contains($clientScript,
'if (vm.network_change_supported !== true)')
&& str_contains($clientScript,
'if (vm.instance_settings_supported !== true)')
&& str_contains($clientScript, "vm.instance_status !== 'active'")
&& str_contains($clientScript, 'function networkOptionsErrorView(')
&& !str_contains($clientScript,
'Older deployments can still use the existing detail fields'),
'Unsupported, inactive or failed administrator controls must not render guessed network constraints or actionable settings.');
if (in_array('--fixture', $argv ?? [], true)) {
$smarty->assign('billing_page', null);
$smarty->assign('billing_view', 'invoices');

@ -217,6 +217,7 @@ namespace {
'spec_json' => json_encode([
'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10',
'managed' => true,
'public_ip_cidr' => '198.51.100.10/24',
'state' => 'running', 'console_port' => 5900,
'password' => 'must-not-expose-spec-password',
@ -383,8 +384,20 @@ namespace {
'Administrator detail lost the physical placement needed for operations.');
$assert((int) $detail['instance']['active_job']['id'] === 26
&& $detail['instance']['active_job']['status'] === 'running'
&& $detail['instance']['can_manage'] === true,
&& $detail['instance']['can_manage'] === true
&& $detail['instance']['network_change_supported'] === true
&& $detail['instance']['instance_settings_supported'] === true,
'An operation submitted by a super-admin was lost because the job actor differs from the instance owner.');
$unsupported = CloudAdminInstanceService::detail($admin, '214');
$assert($unsupported['instance']['network_change_supported'] === false
&& $unsupported['instance']['instance_settings_supported'] === false,
'Incomplete legacy metadata exposed administrator mutation controls.');
Capsule::table('cloud_instances')->where('id', 205)->update(['status' => 'deleting']);
$inactive = CloudAdminInstanceService::detail($admin, '205');
$assert($inactive['instance']['network_change_supported'] === false
&& $inactive['instance']['instance_settings_supported'] === false,
'A non-active instance exposed controls that both mutation endpoints reject.');
Capsule::table('cloud_instances')->where('id', 205)->update(['status' => 'active']);
$assert(count($detail['jobs']) === 20 && $detail['jobs_truncated'] === true
&& $ids($detail['jobs']) === range(26, 7),
'Instance tasks must be newest-first, bounded to 20, and explicitly marked truncated.');

Loading…
Cancel
Save