You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudInstanceReadPerformanc...

179 lines
9.8 KiB
PHTML

<?php
// Static regression checks for the instance read path. These protect the
// security boundary that the database collection is authoritative and the
// Agent is queried only for known UUIDs; detail pages never refresh a host
// inventory or the full list.
$root = dirname(__DIR__);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$section = static function (string $source, string $start, string $end): string {
$offset = strpos($source, $start);
if ($offset === false) {
return '';
}
$limit = strpos($source, $end, $offset + strlen($start));
return $limit === false ? substr($source, $offset)
: substr($source, $offset, $limit - $offset);
};
$controller = file_get_contents($root . '/app/Controllers/CloudApiController.php');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$detail = file_get_contents($root . '/public/cloud/detail.js');
$instances = file_get_contents($root . '/public/cloud/instances.js');
$detailTemplate = file_get_contents(
$root . '/resources/views/venix/cloud/pages/detail.tpl'
);
$contexts = $section($controller, 'private function vmListContexts(',
'private function vmData(');
$list = $section($controller, 'public function vms(', 'public function vm(');
$detailApi = $section($controller, 'public function vm(', 'public function metrics(');
$assert(str_contains($contexts,
"foreach (\$instances as \$instance)")
&& str_contains($contexts,
"'GET', '/v1/vms/' . \$uuid, \$actor")
&& !str_contains($contexts, "'GET', '/v1/vms', \$actor"),
'Instance reads must target known UUIDs and never enumerate a host.');
$assert(str_contains($contexts, 'CloudServicePeriod::whereIn')
&& str_contains($contexts, "->groupBy('instance_id')"),
'Instance host and service-period dependencies are no longer bulk loaded.');
$assert(str_contains($contexts, "rawurlencode((string) \$instance->uuid)")
&& str_contains($contexts, 'hash_equals(strtolower((string) $instance->uuid)')
&& str_contains($contexts, 'Preserve a useful database-backed row'),
'Targeted Agent rows must match the actor-visible database UUID and fail closed.');
$assert(str_contains($list, '$contexts = $this->vmListContexts($instances, $actor)')
&& str_contains($list, '$contexts[(int) $instance->id] ?? []'),
'The VM list bypasses its bulk contexts and may reintroduce per-row reads.');
$assert(str_contains($detailApi,
'$this->vmData(CloudAccess::instance($args[\'id\'], $actor), $actor)'),
'The single-instance API no longer starts from the owner-scoped access check.');
$loadVm = $section($runtime, 'async function loadVm(',
'function renderVmDetail(');
$selection = $section($runtime, 'async function selectVmByApiId(',
'function bindPageCleanup(');
$assert(str_contains($loadVm, "api(`/api/v1/vms/\${encodeURIComponent(id)}`)")
&& str_contains($loadVm, 'state.vms = [vm]'),
'The detail loader does not use the single-instance API.');
$assert(str_contains($selection, 'await loadVm(apiId, true)')
&& !str_contains($selection, 'loadVms('),
'Detail selection still fetches the full VM list.');
$statusLoader = $section($runtime, 'async function loadVmStatus(',
'function renderVmDetail(');
$powerAction = $section($runtime, 'async function powerAction(',
'async function deleteVm(');
$detailStateDisplay = $section($runtime, 'function detailStateDisplay(',
'function diskLabel(');
$detailPolling = $section($detail, 'const poll = async () => {',
'const startPolling = () => {');
$listStateDisplay = $section($instances, 'function stateDisplay(',
'function vmRegion(');
$listSchedulePolling = $section($instances, 'function schedulePolling(',
'function statusItems(');
$listConvergingRefresh = $section($instances,
'async function refreshConvergingStatuses(',
'async function refreshStatuses(');
$listStatusRefresh = $section($instances, 'async function refreshStatuses(',
'async function loadPage(');
$listPageLoad = $section($instances, 'async function loadPage(',
'function hydrate(');
$listEvents = $section($instances, 'function bindEvents(',
'export async function initialize(');
$assert(str_contains($detail, 'hydrateVmDetailBootstrap(detailBootstrap())')
&& str_contains($detailTemplate, 'id="vm-detail-bootstrap"')
&& !str_contains($detail, 'initializeSession(')
&& !str_contains($detail, 'selectVmByApiId(')
&& str_contains($detail,
'api(`/api/v1/vms/${encodeURIComponent(vmId)}/metadata`)')
&& str_contains($detail, 'loadVmMetadata(vmId, forceMetadata).catch(')
&& str_contains($detail,
'loadVmStatus(vmId, liveStatus ? { live: true, force: true } : {})')
&& str_contains($detail,
'if (!force && !needsVmMetadata(selectedVm())) return selectedVm();')
&& str_contains($detail,
'refreshMetadataAndStatus(vmId, true, true, true)')
&& str_contains($detail, 'await Promise.all([')
&& str_contains($detail, 'Object.prototype.hasOwnProperty.call(update, field)')
&& !str_contains($detail, 'loadVm('),
'Detail must keep SSR first paint, then safely merge one metadata response before status polling.');
$assert(str_contains($statusLoader,
'api(`/api/v1/vms/${encodeURIComponent(id)}/status${liveQuery}`')
&& str_contains($statusLoader, "const liveQuery = live ? '?live=1' : ''")
&& str_contains($statusLoader, 'new AbortController()')
&& str_contains($statusLoader, 'active?.controller.abort()')
&& str_contains($statusLoader, 'generation !== vmStatusGeneration')
&& str_contains($statusLoader,
'if (controller.signal.aborted || generation !== vmStatusGeneration) return null;')
&& !str_contains($statusLoader, 'state.loadingVMs')
&& str_contains($statusLoader, 'const current = selectedVm()')
&& str_contains($detailPolling, 'await loadVmStatus(vmId)')
&& !str_contains($detailPolling, 'live: true')
&& str_contains($detail, 'window.setTimeout(poll, 20000)')
&& !str_contains($detail, 'setInterval(')
&& !str_contains($detail, 'loadVms'),
'Detail refresh and non-overlapping polling must use only the lightweight status endpoint.');
$assert(str_contains($detail,
'void refreshMetadataAndStatus(vmId, false, false, true)')
&& str_contains($detail,
'await refreshMetadataAndStatus(vmId, true, true, true)')
&& substr_count($detail,
'loadVmStatus(vmId, { live: true, force: true })') >= 2,
'Initial, manual, BFCache and visible-page refreshes must bypass the runtime cache.');
$assert(str_contains($powerAction, 'state.powerMutation = mutation')
&& str_contains($powerAction, 'renderVmDetail(vm)')
&& str_contains($powerAction, 'observeAcceptedTask(result')
&& str_contains($powerAction, "task.status === 'failed'")
&& str_contains($powerAction, '任务已接收,可在任务中心查看结果。')
&& !str_contains($powerAction, 'waitForShutdownState')
&& !str_contains($powerAction, 'state.mutationBusy = true')
&& !str_contains($powerAction, 'setDetailBusy(true)')
&& str_contains($detailStateDisplay, "label: '关机中'")
&& str_contains($detailStateDisplay, "note: '', noteClass: ''")
&& !str_contains($detailStateDisplay, '正在确认宿主机电源状态')
&& str_contains($runtime,
'const powerBusy = localPowerMutation(vm) !== null')
&& str_contains($runtime, "const consoleAvailable = running || transition === 'shutdown'")
&& str_contains($runtime, 'disabled: powerBusy || !running'),
'Power actions must accept one durable task and release local controls without foreground convergence loops.');
$assert(str_contains($instances,
'api(`/api/v1/vms/metadata?ids=${encodeURIComponent(ids.join(\',\'))}`)')
&& str_contains($instances, 'async function refreshMetadata()')
&& str_contains($instances, 'state.vms.filter(needsVmMetadata)')
&& str_contains($instances, 'if (state.loading || state.metadataLoading) return;')
&& str_contains($instances,
'const busy = state.loading || state.metadataLoading || state.statusLoading;')
&& str_contains($listPageLoad,
'await Promise.all([refreshMetadata(), refreshStatuses(true)]);')
&& str_contains($instances,
'await Promise.all([refreshMetadata(), refreshStatuses(true)]);')
&& str_contains($listStatusRefresh,
'async function refreshStatuses(scheduleNext = true)')
&& str_contains($listStatusRefresh, 'await refreshConvergingStatuses()')
&& !str_contains($listStatusRefresh, 'live=1')
&& str_contains($instances, 'function shutdownConverging(vm)')
&& str_contains($instances,
'deadline >= Math.floor(Date.now() / 1000)')
&& str_contains($listConvergingRefresh, 'state.vms.filter(shutdownConverging)')
&& str_contains($listConvergingRefresh, '&live=1')
&& str_contains($instances, 'MAX_CONVERGENCE_PROBES = 4')
&& str_contains($listConvergingRefresh,
'Math.min(MAX_CONVERGENCE_PROBES, candidates.length)')
&& str_contains($listConvergingRefresh, 'state.convergenceCursor')
&& str_contains($listEvents, 'loadPage(state.pagination.page, false)')
&& !str_contains($listEvents, 'loadPage(state.pagination.page, false, true)')
&& str_contains($listSchedulePolling, 'void refreshStatuses(true);')
&& str_contains($listStateDisplay, "start: '开机中'")
&& str_contains($listStateDisplay, "shutdown: '关机中'")
&& str_contains($listStateDisplay, "reinstall: '重装中'")
&& str_contains($instances, 'TRANSITION_POLL_INTERVAL = 3000')
&& str_contains($instances, 'Object.prototype.hasOwnProperty.call(update, field)')
&& !str_contains($instances, "api('/api/v1/vms')"),
'Each instance page must retain cache-only polling and bound live probes to shutdown convergence.');
echo "Cloud instance bulk-list and single-detail read paths passed.\n";