From 8efd0d91cdcf9c7ac795acbdbd6eda7833e61a89 Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 17 Oct 2026 02:42:22 +0800 Subject: [PATCH] Fix instance transition status updates --- web/app/Controllers/CloudApiController.php | 39 +++++- .../Cloud/CloudInstancePageService.php | 111 ++++++++++++++- web/public/cloud/instances.js | 65 ++++++++- web/public/cloud/runtime.js | 2 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/CloudInstancePageServiceTest.php | 128 +++++++++++++++++- .../CloudInstancePageSsrContractTest.php | 23 +++- .../CloudInstanceReadPerformanceTest.php | 48 ++++++- 8 files changed, 399 insertions(+), 19 deletions(-) diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 3ed5aa63..7deb91db 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -749,8 +749,8 @@ final class CloudApiController $ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw)))); $snapshots = CloudInstancePageService::forActorIds($actor, $ids); // Normal list refreshes are cache-only and therefore return without - // waiting on any host. An explicit live=1 request retains the - // synchronous Agent probe for diagnostics/manual refresh. + // waiting on any host. An explicit live=1 request is reserved for a + // bounded convergence check or diagnostics. $liveRequested = ($request->getQueryParams()['live'] ?? '') === '1'; if (!$liveRequested) { $statuses = []; @@ -769,15 +769,48 @@ final class CloudApiController ); foreach ($group as $snapshot) { $uuid = strtolower((string) $snapshot['uuid']); + $runtimeRevision = null; + try { + $runtimeRevision = + CloudInstanceRuntimeService::beginCurrentObservation( + (int) $snapshot['id'], + (int) $hostId, + $uuid + ); + } catch (\Throwable $error) { + // A live response remains useful during a rolling + // schema update, but an unclaimed result cannot write. + } try { $item = $agent->request( 'GET', '/v1/vms/' . rawurlencode($uuid) . '/state', $actor ); + $observedState = is_array($item) + ? CloudInstanceRuntimeService::normalizeState( + $item['state'] ?? ($item['power_state'] ?? null) + ) : 'unknown'; if (is_string($item['uuid'] ?? null) && hash_equals($uuid, - strtolower(trim($item['uuid'])))) { + strtolower(trim($item['uuid']))) + && $observedState !== 'unknown') { + $item['state'] = $observedState; + try { + if ($runtimeRevision !== null) { + CloudInstanceRuntimeService::markObserved( + (int) $snapshot['id'], + (int) $hostId, + $uuid, + $observedState, + null, + $runtimeRevision + ); + } + } catch (\Throwable $error) { + error_log('cloud list live runtime write unavailable: ' + . get_class($error)); + } $live[(int) $hostId . ':' . $uuid] = $item; } } catch (CloudError $error) { diff --git a/web/app/Services/Cloud/CloudInstancePageService.php b/web/app/Services/Cloud/CloudInstancePageService.php index 0fc6b87d..4719a615 100644 --- a/web/app/Services/Cloud/CloudInstancePageService.php +++ b/web/app/Services/Cloud/CloudInstancePageService.php @@ -3,6 +3,7 @@ namespace App\Services\Cloud; use App\Models\CloudInstance; +use App\Models\CloudJob; use App\Models\CloudServicePeriod; use App\Services\Config; @@ -12,11 +13,13 @@ use App\Services\Config; * This service must never contact the host Agent. It gives the browser a * useful first paint from the last known runtime observation even when one or * more libvirt hosts are slow or unavailable; the dedicated status endpoint - * reads the same cache by default and only layers a live observation when an - * explicit browser refresh asks for it. + * reads the same cache by default and only layers a live observation for an + * explicit bounded convergence request. */ final class CloudInstancePageService { + private const SHUTDOWN_CONVERGENCE_SECONDS = 60; + public static function forActor(array $actor, int $page = 1, int $perPage = 20): array { $page = max(1, $page); @@ -169,6 +172,7 @@ final class CloudInstancePageService $records = self::visibleQuery($actor) ->whereIn('id', array_keys($ordered)) ->get(['id', 'uuid', 'host_id', 'name']); + $transitions = self::operationTransitions($records); $runtime = []; try { // Resolve the cache against the current authorized DB identity. @@ -196,6 +200,10 @@ final class CloudInstancePageService 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, 'name' => (string) $instance->name, + 'operation_transition' => + $transitions[(int) $instance->id]['transition'] ?? null, + 'shutdown_convergence_until' => + $transitions[(int) $instance->id]['shutdown_until'] ?? null, ] + array_intersect_key($cached, array_flip([ 'state', 'state_transitioning', 'state_transition', 'state_fresh', 'state_observed_at', @@ -277,7 +285,19 @@ final class CloudInstancePageService $available = $liveAvailable || (($snapshot['state_fresh'] ?? false) === true); $state = $liveAvailable ? CloudInstanceMetadata::state($live['state']) : $cachedState; - $transition = $state === 'shutdown' ? 'shutdown' : null; + $operationTransition = self::operationTransition( + $snapshot['operation_transition'] ?? null + ); + $shutdownUntil = filter_var( + $snapshot['shutdown_convergence_until'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $shutdownConverging = $shutdownUntil !== false + && $shutdownUntil >= time() + && !self::stoppedState($state); + $transition = $operationTransition ?? (($shutdownConverging + || $state === 'shutdown') ? 'shutdown' : null); return [ 'id' => (string) $snapshot['id'], 'api_id' => (string) $snapshot['api_id'], @@ -286,6 +306,9 @@ final class CloudInstancePageService 'state' => $state, 'state_transitioning' => $transition !== null, 'state_transition' => $transition, + 'operation_transition' => $operationTransition, + 'shutdown_convergence_until' => $shutdownConverging + ? $shutdownUntil : null, 'live_state_available' => $available, 'state_fresh' => $liveAvailable || (bool) ($snapshot['state_fresh'] ?? false), 'state_observed_at' => $liveAvailable @@ -296,6 +319,88 @@ final class CloudInstancePageService ]; } + /** + * Project user-visible active operations plus a bounded graceful-shutdown + * convergence window for actor-scoped rows. The encrypted task body, job + * identifiers and host placement never leave this service; power actions + * are decoded through the canonical allow-list. + */ + private static function operationTransitions($instances): array + { + if ($instances->isEmpty()) { + return []; + } + $instanceIds = $instances->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $shutdownCutoff = time() - self::SHUTDOWN_CONVERGENCE_SECONDS; + try { + $jobs = CloudJob::whereIn('instance_id', $instanceIds) + ->whereIn('kind', ['action', 'reinstall']) + ->where(static function ($query) use ($shutdownCutoff): void { + $query->whereIn('status', ['queued', 'running']) + ->orWhere('updated_at', '>=', $shutdownCutoff); + }) + ->orderByDesc('id') + ->get(['id', 'instance_id', 'kind', 'status', 'sealed_payload', + 'updated_at']); + } catch (\Throwable $error) { + // Keep status polling available during a rolling schema upgrade. + return []; + } + $result = []; + $seen = []; + foreach ($jobs as $job) { + $instanceId = (int) $job->instance_id; + if ($instanceId < 1 || isset($seen[$instanceId])) { + continue; + } + // Instance mutations share one job lane. Any newer recent + // terminal row must therefore suppress an older successful + // shutdown window, even when the newer result is uncertain or + // failed. + $seen[$instanceId] = true; + $status = (string) $job->status; + if (in_array($status, ['queued', 'running'], true)) { + $transition = (string) $job->kind === 'reinstall' + ? 'reinstall' : self::operationTransition( + CloudJobService::action($job) + ); + if ($transition !== null) { + $result[$instanceId] = ['transition' => $transition, + 'shutdown_until' => null]; + } + continue; + } + if ($status === 'succeeded' + && (string) $job->kind === 'action' + && CloudJobService::action($job) === 'shutdown') { + $until = max(0, (int) $job->updated_at) + + self::SHUTDOWN_CONVERGENCE_SECONDS; + if ($until >= time()) { + $result[$instanceId] = ['transition' => null, + 'shutdown_until' => $until]; + } + } + } + return $result; + } + + /** Bound browser-visible transition values independently of job data. */ + private static function operationTransition($value): ?string + { + return is_string($value) && in_array( + $value, + ['start', 'shutdown', 'reinstall'], + true + ) ? $value : null; + } + + private static function stoppedState(string $state): bool + { + return in_array($state, ['shutoff', 'stopped', 'crashed'], true); + } + /** Keep the paginated list bootstrap intentionally smaller than detail. */ private static function listItem(array $snapshot): array { diff --git a/web/public/cloud/instances.js b/web/public/cloud/instances.js index cd77fe33..d0fd3bbf 100644 --- a/web/public/cloud/instances.js +++ b/web/public/cloud/instances.js @@ -4,7 +4,9 @@ import { toast } from './toast.js?v=2026100206'; // handles local filtering, pagination and batched live-state refreshes. const byId = id => document.getElementById(id); const POLL_INTERVAL = 15000; +const TRANSITION_POLL_INTERVAL = 3000; const MAX_POLL_INTERVAL = 120000; +const MAX_CONVERGENCE_PROBES = 4; const state = { vms: [], stats: { total: 0, running: 0, stopped: 0 }, @@ -20,6 +22,7 @@ const state = { pageActive: true, pollTimer: null, pollFailures: 0, + convergenceCursor: 0, }; function showError(message = '') { @@ -103,11 +106,31 @@ function stateLabel(value) { } function runtimeStateReady(vm) { - return hasKnownState(vm) + return !operationTransition(vm) && hasKnownState(vm) && (String(vm?.state_sync_status || '').toLowerCase() === '' || String(vm?.state_sync_status || '').toLowerCase() === 'fresh'); } +function activeOperationTransition(vm) { + const transition = String(vm?.operation_transition || '').toLowerCase(); + return ['start', 'shutdown', 'reinstall'].includes(transition) ? transition : ''; +} + +function operationTransition(vm) { + const active = activeOperationTransition(vm); + if (active) return active; + if (vm?.state_transitioning !== true) return ''; + const transition = String(vm?.state_transition || '').toLowerCase(); + return transition === 'shutdown' ? transition : ''; +} + +function shutdownConverging(vm) { + const deadline = Number(vm?.shutdown_convergence_until); + return operationTransition(vm) === 'shutdown' + && !activeOperationTransition(vm) + && deadline >= Math.floor(Date.now() / 1000); +} + function hasKnownState(vm) { const state = String(vm?.state || '').toLowerCase(); const sync = String(vm?.state_sync_status || '').toLowerCase(); @@ -117,6 +140,7 @@ function hasKnownState(vm) { } function stateCategoryForVm(vm) { + if (operationTransition(vm)) return 'other'; const sync = String(vm?.state_sync_status || '').toLowerCase(); if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) { return 'other'; @@ -126,6 +150,11 @@ function stateCategoryForVm(vm) { } function stateDisplay(vm) { + const transition = operationTransition(vm); + if (transition) { + const labels = { start: '开机中', shutdown: '关机中', reinstall: '重装中' }; + return { label: labels[transition], category: 'other', note: '', noteClass: '' }; + } const sync = String(vm?.state_sync_status || '').toLowerCase(); if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) { return { label: '暂时无法同步', category: 'other', note: '', noteClass: 'offline' }; @@ -386,8 +415,11 @@ function stopPolling() { } function nextPollDelay() { - if (!state.pollFailures) return POLL_INTERVAL; - return Math.min(MAX_POLL_INTERVAL, POLL_INTERVAL * (2 ** Math.min(state.pollFailures, 3))); + const base = state.vms.some(vm => activeOperationTransition(vm) + || shutdownConverging(vm)) + ? TRANSITION_POLL_INTERVAL : POLL_INTERVAL; + if (!state.pollFailures) return base; + return Math.min(MAX_POLL_INTERVAL, base * (2 ** Math.min(state.pollFailures, 3))); } function schedulePolling(delay = nextPollDelay()) { @@ -543,6 +575,28 @@ function applyStatuses(payload) { } } +async function refreshConvergingStatuses() { + const candidates = state.vms.filter(shutdownConverging) + .map(vm => vm.api_id).filter(Boolean); + if (!candidates.length) { + state.convergenceCursor = 0; + return; + } + const start = state.convergenceCursor % candidates.length; + const ids = []; + for (let offset = 0; offset < Math.min(MAX_CONVERGENCE_PROBES, candidates.length); offset++) { + ids.push(candidates[(start + offset) % candidates.length]); + } + state.convergenceCursor = (start + ids.length) % candidates.length; + try { + const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}&live=1`); + applyStatuses(payload); + } catch { + // Preserve the last identity-checked state and retry while the transition + // remains active; a host outage must not become a fabricated shutdown. + } +} + async function refreshStatuses(scheduleNext = true) { if (!state.pageActive || state.statusLoading || document.hidden || !state.vms.length) { if (scheduleNext) schedulePolling(); @@ -555,6 +609,7 @@ async function refreshStatuses(scheduleNext = true) { try { const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}`); applyStatuses(payload); + await refreshConvergingStatuses(); state.pollFailures = 0; showError(); } catch (error) { @@ -623,7 +678,9 @@ function hydrate() { function bindEvents() { byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); - byId('refresh-button')?.addEventListener('click', () => { void loadPage(state.pagination.page, false); }); + byId('refresh-button')?.addEventListener('click', () => { + void loadPage(state.pagination.page, false); + }); byId('search-input')?.addEventListener('input', renderVms); byId('state-filter')?.addEventListener('change', renderVms); byId('instances-previous')?.addEventListener('click', () => { diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 14d90ff0..4c0cecc2 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -1062,7 +1062,7 @@ function detailStateDisplay(vm) { const transition = powerTransition(vm); if (transition === 'shutdown') { return { - label: '关机中', category: 'other', note: '正在确认宿主机电源状态', noteClass: 'stale', + label: '关机中', category: 'other', note: '', noteClass: '', }; } const sync = String(vm?.state_sync_status || '').toLowerCase(); diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index cc6c2f3b..3ce58a9c 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026101702' scope='global'} +{assign var=venix_asset_version value='2026101703' scope='global'} diff --git a/web/tests/CloudInstancePageServiceTest.php b/web/tests/CloudInstancePageServiceTest.php index 6177cb78..a91f7ac4 100644 --- a/web/tests/CloudInstancePageServiceTest.php +++ b/web/tests/CloudInstancePageServiceTest.php @@ -5,7 +5,13 @@ namespace App\Services { { public static function get($name, $default = null) { - return $name === 'cloud_max_renewal_periods_ahead' ? 24 : $default; + if ($name === 'cloud_max_renewal_periods_ahead') { + return 24; + } + if ($name === 'cloud_data_key') { + return base64_encode(str_repeat('k', 32)); + } + return $default; } } } @@ -15,6 +21,7 @@ namespace { use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudInstanceRuntimeService; + use App\Services\Cloud\CloudSecrets; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -89,6 +96,14 @@ namespace { $table->integer('created_at')->default(0); $table->integer('updated_at')->default(0); }); + $schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id')->nullable(); + $table->string('kind'); + $table->string('status'); + $table->text('sealed_payload'); + $table->integer('updated_at')->default(0); + }); Capsule::table('cloud_hosts')->insert([ 'id' => 7, 'region' => 'internal-host-location', 'country_code' => 'ZZ', @@ -216,6 +231,117 @@ namespace { $assertNoPlacement($ownedStatuses, 'Instance batch status identity exposed internal placement.'); + Capsule::table('cloud_jobs')->insert([ + 'id' => 101, 'instance_id' => 1, 'kind' => 'action', 'status' => 'queued', + 'sealed_payload' => CloudSecrets::encrypt([ + 'body' => ['action' => 'start'], + ], 'job-payload'), + ]); + Capsule::table('cloud_jobs')->insert([ + 'id' => 102, 'instance_id' => 2, 'kind' => 'reinstall', 'status' => 'running', + 'sealed_payload' => 'must-not-expose-foreign-job', + ]); + $startingSnapshots = CloudInstancePageService::forActorIds($owner, [1, 2]); + $starting = CloudInstancePageService::powerStatus($startingSnapshots[0], [ + 'uuid' => $startingSnapshots[0]['uuid'], 'state' => 'running', + ]); + $assert(count($startingSnapshots) === 1 + && $starting['state_transitioning'] === true + && $starting['state_transition'] === 'start' + && $starting['operation_transition'] === 'start' + && !array_key_exists('sealed_payload', $starting) + && !array_key_exists('host_id', $starting), + 'Owner-scoped polling did not expose a queued start transition safely.'); + + Capsule::table('cloud_jobs')->where('id', 101)->update(['status' => 'succeeded']); + Capsule::table('cloud_jobs')->insert([ + 'id' => 103, 'instance_id' => 1, 'kind' => 'reinstall', 'status' => 'running', + 'sealed_payload' => 'must-not-expose-reinstall-job', + ]); + $reinstallSnapshot = CloudInstancePageService::forActorIds($owner, [1])[0]; + $reinstalling = CloudInstancePageService::powerStatus($reinstallSnapshot, [ + 'uuid' => $reinstallSnapshot['uuid'], 'state' => 'running', + ]); + $assert($reinstalling['state_transitioning'] === true + && $reinstalling['state_transition'] === 'reinstall' + && $reinstalling['operation_transition'] === 'reinstall', + 'A running reinstall was not projected into the instance list.'); + + Capsule::table('cloud_jobs')->where('id', 103)->update(['status' => 'uncertain']); + Capsule::table('cloud_jobs')->insert([ + 'id' => 104, 'instance_id' => 1, 'kind' => 'action', 'status' => 'running', + 'sealed_payload' => CloudSecrets::encrypt([ + 'body' => ['action' => 'shutdown'], + ], 'job-payload'), + ]); + $shutdownSnapshot = CloudInstancePageService::forActorIds($owner, [1])[0]; + $shuttingDown = CloudInstancePageService::powerStatus($shutdownSnapshot, [ + 'uuid' => $shutdownSnapshot['uuid'], 'state' => 'shutoff', + ]); + $assert($shuttingDown['state_transitioning'] === true + && $shuttingDown['state_transition'] === 'shutdown' + && $shuttingDown['operation_transition'] === 'shutdown', + 'A running shutdown was not projected into the instance list.'); + Capsule::table('cloud_jobs')->where('id', 104)->update([ + 'status' => 'succeeded', 'updated_at' => time(), + ]); + $convergenceSnapshot = CloudInstancePageService::forActorIds($owner, [1])[0]; + $converging = CloudInstancePageService::powerStatus($convergenceSnapshot, [ + 'uuid' => $convergenceSnapshot['uuid'], 'state' => 'running', + ]); + $assert($converging['state_transitioning'] === true + && $converging['state_transition'] === 'shutdown' + && $converging['operation_transition'] === null + && is_int($converging['shutdown_convergence_until']), + 'A recently succeeded shutdown stopped converging on a transient running observation.'); + $stopped = CloudInstancePageService::powerStatus($convergenceSnapshot, [ + 'uuid' => $convergenceSnapshot['uuid'], 'state' => 'shutoff', + ]); + $assert($stopped['state_transitioning'] === false + && $stopped['state_transition'] === null + && $stopped['shutdown_convergence_until'] === null, + 'A confirmed stopped state did not finish shutdown convergence.'); + Capsule::table('cloud_jobs')->where('id', 104)->update([ + 'updated_at' => time() - 61, + ]); + $terminal = CloudInstancePageService::powerStatus( + CloudInstancePageService::forActorIds($owner, [1])[0] + ); + $assert($terminal['state_transitioning'] === false + && $terminal['state_transition'] === null + && $terminal['operation_transition'] === null + && $terminal['shutdown_convergence_until'] === null, + 'Expired or uncertain jobs were presented as active instance transitions.'); + Capsule::table('cloud_jobs')->where('id', 104)->update([ + 'updated_at' => time(), + ]); + Capsule::table('cloud_jobs')->insert([ + 'id' => 105, 'instance_id' => 1, 'kind' => 'action', + 'status' => 'uncertain', 'updated_at' => time(), + 'sealed_payload' => CloudSecrets::encrypt([ + 'body' => ['action' => 'start'], + ], 'job-payload'), + ]); + $superseded = CloudInstancePageService::powerStatus( + CloudInstancePageService::forActorIds($owner, [1])[0] + ); + $assert($superseded['state_transitioning'] === false + && $superseded['shutdown_convergence_until'] === null, + 'A newer uncertain start inherited an older shutdown convergence window.'); + Capsule::table('cloud_jobs')->insert([ + 'id' => 106, 'instance_id' => 1, 'kind' => 'action', + 'status' => 'failed', 'updated_at' => time(), + 'sealed_payload' => CloudSecrets::encrypt([ + 'body' => ['action' => 'shutdown'], + ], 'job-payload'), + ]); + $failedShutdown = CloudInstancePageService::powerStatus( + CloudInstancePageService::forActorIds($owner, [1])[0] + ); + $assert($failedShutdown['state_transitioning'] === false + && $failedShutdown['shutdown_convergence_until'] === null, + 'A failed shutdown incorrectly opened a convergence window.'); + $adminPage = CloudInstancePageService::forActor($admin, 1, 20); $assert($adminPage['stats']['total'] === 2, 'Read-only administrator lost the historical all-instance view.'); diff --git a/web/tests/CloudInstancePageSsrContractTest.php b/web/tests/CloudInstancePageSsrContractTest.php index 869afba0..29fcbc76 100644 --- a/web/tests/CloudInstancePageSsrContractTest.php +++ b/web/tests/CloudInstancePageSsrContractTest.php @@ -56,6 +56,18 @@ $assert(str_contains($service, 'private static function listItem(') && str_contains($service, "'live_state_available'") && str_contains($service, "array_intersect_key"), 'Instance list bootstrap and polling payloads must remain detail-free and bounded.'); +$assert(str_contains($service, 'private static function operationTransitions(') + && str_contains($service, "->whereIn('status', ['queued', 'running'])") + && str_contains($service, "->orWhere('updated_at', '>=', \$shutdownCutoff)") + && str_contains($service, "->whereIn('kind', ['action', 'reinstall'])") + && str_contains($service, "\$status === 'succeeded'") + && str_contains($service, 'CloudJobService::action($job)') + && str_contains($service, "['start', 'shutdown', 'reinstall']") + && str_contains($service, 'SHUTDOWN_CONVERGENCE_SECONDS = 60') + && str_contains($service, "'shutdown_convergence_until' =>") + && !str_contains($section($service, 'public static function powerStatus(', + 'private static function operationTransitions('), 'sealed_payload'), + 'List polling must project only allow-listed active operations without exposing job payloads.'); $assert(str_contains($service, 'public static function statusForActor(') && str_contains($service, 'CloudInstanceRuntimeService::forInstances([$instance])') && str_contains($service, "'state_sync_status' =>") @@ -126,9 +138,18 @@ $assert(str_contains($statusesApi, 'CloudInstancePageService::forActorIds') && str_contains($statusesApi, 'CloudAgentSettingsService::clientForHost(') && str_contains($statusesApi, "'/v1/vms/' . rawurlencode(\$uuid) . '/state'") && str_contains($statusesApi, 'hash_equals($uuid,') + && str_contains($statusesApi, + 'CloudInstanceRuntimeService::beginCurrentObservation(') + && str_contains($statusesApi, 'CloudInstanceRuntimeService::normalizeState(') + && str_contains($statusesApi, 'CloudInstanceRuntimeService::markObserved(') + && str_contains($statusesApi, '$runtimeRevision') + && strpos($statusesApi, 'CloudInstanceRuntimeService::beginCurrentObservation(') + < strpos($statusesApi, '$agent->request(') + && strrpos($statusesApi, 'hash_equals(') + < strpos($statusesApi, 'CloudInstanceRuntimeService::markObserved(') && str_contains($statusesApi, ". ':' . \$uuid") && !str_contains($statusesApi, "request('GET', '/v1/vms'"), - 'Batch VM status must intersect owner UUIDs, preserve host identity and use only per-VM Agent state resources.'); + 'Batch VM status must intersect owner UUIDs and safely write through bounded live observations.'); $assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor') && str_contains($statusApi, "['live'] ?? '') === '1'") && str_contains($statusApi, 'CloudAgentSettingsService::clientForHost(') diff --git a/web/tests/CloudInstanceReadPerformanceTest.php b/web/tests/CloudInstanceReadPerformanceTest.php index 66be9b30..60a3a9a0 100644 --- a/web/tests/CloudInstanceReadPerformanceTest.php +++ b/web/tests/CloudInstanceReadPerformanceTest.php @@ -67,8 +67,23 @@ $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(') @@ -121,7 +136,9 @@ $assert(str_contains($powerAction, 'state.powerMutation = mutation') && str_contains($runtime, 'const deadline = Date.now() + POWER_STATE_CONVERGENCE_TIMEOUT_MS') && str_contains($runtime, 'while (Date.now() < deadline)') - && str_contains($runtime, "label: '关机中'") + && 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'") @@ -134,11 +151,32 @@ $assert(str_contains($instances, && str_contains($instances, 'if (state.loading || state.metadataLoading) return;') && str_contains($instances, 'const busy = state.loading || state.metadataLoading || state.statusLoading;') - && substr_count($instances, - 'await Promise.all([refreshMetadata(), refreshStatuses(true)]);') === 2 - && str_contains($instances, 'async function refreshStatuses(') + && 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 fetch only its static metadata once, then retain lightweight status polling.'); + '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";