From ea84d9519e299f0b7a3d0b8aaeb4b8b0f5a522ff Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 28 Sep 2026 04:11:58 +0800 Subject: [PATCH] perf: server-render instance pages --- engine/tests/test_app.py | 25 +- engine/tests/test_engine_boundary.py | 18 + engine/tests/test_libvirt_service.py | 6 + engine/virsh_panel/app.py | 17 + engine/virsh_panel/internal.py | 3 +- engine/virsh_panel/libvirt_service.py | 28 + web/app/Controllers/CloudApiController.php | 101 ++++ web/app/Controllers/CloudPageController.php | 292 +++++++++- web/app/Middleware/CloudApi.php | 11 +- .../Cloud/CloudInstancePageService.php | 460 +++++++++++++++ web/config/routes_cloud.php | 5 + web/public/cloud/detail.js | 54 +- web/public/cloud/instances.js | 544 +++++++++++++++++- web/public/cloud/runtime.js | 78 ++- .../views/venix/cloud/pages/detail.tpl | 39 +- .../views/venix/cloud/pages/instances.tpl | 37 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/CloudInstancePageServiceTest.php | 161 ++++++ .../CloudInstancePageSsrContractTest.php | 111 ++++ .../CloudInstanceReadPerformanceTest.php | 22 +- web/tests/CloudSessionSecurityTest.php | 13 + 21 files changed, 1923 insertions(+), 104 deletions(-) create mode 100644 web/app/Services/Cloud/CloudInstancePageService.php create mode 100644 web/tests/CloudInstancePageServiceTest.php create mode 100644 web/tests/CloudInstancePageSsrContractTest.php diff --git a/engine/tests/test_app.py b/engine/tests/test_app.py index 7f5b316f..8fc81006 100644 --- a/engine/tests/test_app.py +++ b/engine/tests/test_app.py @@ -119,12 +119,28 @@ class FakeVMService: raise VMError("libvirt API 不可用", 502) return [self.vm, *self.other_vms] + def list_vm_states(self): + self.calls.append(("list_vm_states",)) + if self.list_error: + raise VMError("libvirt API 不可用", 502) + return [ + {"uuid": vm["uuid"], "name": vm["name"], "state": vm["state"]} + for vm in [self.vm, *self.other_vms] + ] + def get_vm(self, vm_id): self.calls.append(("get_vm", vm_id)) if vm_id != self.vm["uuid"]: raise VMError("虚拟机不存在", 404) return self.vm + def get_vm_state(self, vm_id): + self.calls.append(("get_vm_state", vm_id)) + if vm_id != self.vm["uuid"]: + raise VMError("虚拟机不存在", 404) + return {"uuid": self.vm["uuid"], "name": self.vm["name"], + "state": self.vm["state"]} + def create_vm(self, spec): self.calls.append(("create_vm", spec)) return self.vm @@ -835,6 +851,12 @@ def test_vm_crud_actions_and_error_mapping(web): headers = {"X-CSRF-Token": csrf} assert client.get("/api/v1/resources").json()["isos"] == ["AlmaLinux-10.iso"] assert client.get("/api/v1/vms").json()["items"][0]["uuid"] == VM_ID + assert client.get("/api/v1/vm-states").json() == {"items": [{ + "uuid": VM_ID, "name": "alma-test", "state": "running", + }]} + assert client.get(f"/api/v1/vms/{VM_ID}/state").json() == { + "uuid": VM_ID, "name": "alma-test", "state": "running", + } assert client.get(f"/api/v1/vms/{VM_ID}").json()["name"] == "alma-test" missing = client.get("/api/v1/vms/missing") assert missing.status_code == 404 and missing.json() == {"error": "虚拟机不存在"} @@ -847,7 +869,8 @@ def test_vm_crud_actions_and_error_mapping(web): deleted = client.delete(f"/api/v1/vms/{VM_ID}?delete_disks=true", headers=headers) assert deleted.status_code == 200 and deleted.json()["deleted"] is True assert service.calls == [ - ("resources",), ("list_vms",), ("get_vm", VM_ID), ("get_vm", "missing"), + ("resources",), ("list_vms",), ("list_vm_states",), + ("get_vm_state", VM_ID), ("get_vm", VM_ID), ("get_vm", "missing"), ("create_vm", CREATE_BODY), ("get_vm", VM_ID), ("action", VM_ID, "reboot"), ("get_vm", VM_ID), ("delete_vm", VM_ID, True), diff --git a/engine/tests/test_engine_boundary.py b/engine/tests/test_engine_boundary.py index fa71b2d2..75fea0f4 100644 --- a/engine/tests/test_engine_boundary.py +++ b/engine/tests/test_engine_boundary.py @@ -1051,6 +1051,24 @@ def test_stable_host_identity_and_namespaces(): assert LogStore.METRIC_TABLE == "engine_vm_metric_samples" +def test_lightweight_vm_state_reads_are_allowlisted(boundary): + client, _engine, _store, _logs, services = boundary + listed = call(client, "GET", "/internal/v1/hosts/hk/vm-states", SUPER) + assert listed.status_code == 200, listed.text + assert listed.json()["items"] == [{ + "uuid": VM_ID, "name": "alma-test", "state": "running", + }] + single = call( + client, "GET", f"/internal/v1/hosts/hk/vms/{VM_ID}/state", SUPER, + ) + assert single.status_code == 200, single.text + assert single.json() == { + "uuid": VM_ID, "name": "alma-test", "state": "running", + } + assert ("list_vm_states",) in services["hk"].calls + assert ("get_vm_state", VM_ID) in services["hk"].calls + + def test_only_paid_operations_can_create_and_retry_never_duplicates(boundary): client, engine, store, _, services = boundary path = "/internal/v1/hosts/hk/vms" diff --git a/engine/tests/test_libvirt_service.py b/engine/tests/test_libvirt_service.py index 793dd9ee..b4564fe6 100644 --- a/engine/tests/test_libvirt_service.py +++ b/engine/tests/test_libvirt_service.py @@ -799,6 +799,12 @@ class VMServiceTests(unittest.TestCase): self.assertEqual(self.service.console_port(vm["uuid"]), 5907) self.assertEqual(self.service.list_vms()[0]["uuid"], vm["uuid"]) self.assertEqual(self.service.get_vm(vm["uuid"])["name"], "alma-test") + self.assertEqual(self.service.list_vm_states(), [{ + "uuid": vm["uuid"], "name": "alma-test", "state": "running", + }]) + self.assertEqual(self.service.get_vm_state(vm["uuid"]), { + "uuid": vm["uuid"], "name": "alma-test", "state": "running", + }) disk_name = "alma-test.qcow2" self.assertIn(disk_name, self.backend.pools["images"].volumes) root = self.backend.domains[0].root diff --git a/engine/virsh_panel/app.py b/engine/virsh_panel/app.py index 48771b6e..f219639d 100644 --- a/engine/virsh_panel/app.py +++ b/engine/virsh_panel/app.py @@ -2173,6 +2173,23 @@ def create_app( vm, parse_credential(records.get(credential_key(profile, vm["uuid"]))), profile, ) for vm in vms]} + @app.get("/api/v1/vm-states") + def list_vm_states(_session: Session = Depends(require_approved)): + profile = current_profile() + vms = new_service(profile).list_vm_states() + if database_mode: + account = account_for_session(_session) + if not account["admin"]: + owned_ids = state.users.list_owned_vm_ids(host_scope(profile), account["id"]) + vms = [vm for vm in vms if vm["uuid"] in owned_ids] + return {"items": vms} + + @app.get("/api/v1/vms/{vm_id}/state") + def get_vm_state(vm_id: str, _session: Session = Depends(require_approved)): + profile = current_profile() + require_vm_access(_session, profile, vm_id) + return new_service(profile).get_vm_state(vm_id) + @app.get("/api/v1/vms/{vm_id}") def get_vm(vm_id: str, _session: Session = Depends(require_approved)): profile = current_profile() diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index 535578d0..c9de54e8 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -42,8 +42,9 @@ VM_ID = r"[0-9a-fA-F-]{36}" JSON_LIMIT = 1024 * 1024 READ_PATHS = ( r"host", r"resources", r"vm-templates", r"rescue-templates", r"user-isos", r"vms", + r"vm-states", r"user-isos/[0-9a-f]{32}", - rf"vms/{VM_ID}(?:/metrics|/traffic/daily|/rescue)?", + rf"vms/{VM_ID}(?:/state|/metrics|/traffic/daily|/rescue)?", r"(?:reinstall-jobs|rescue-jobs|vm-templates/import-jobs|rescue-templates/import-jobs|user-isos/import-jobs)/[A-Za-z0-9_-]+", ) WRITE_PATHS = { diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py index 069792d9..598b7001 100644 --- a/engine/virsh_panel/libvirt_service.py +++ b/engine/virsh_panel/libvirt_service.py @@ -498,6 +498,29 @@ class VMService: key=lambda row: row["name"].casefold(), ) + @staticmethod + def _vm_state_dict(domain: Any) -> dict[str, Any]: + """Return the live power fields without parsing domain XML or disks.""" + info = domain.info() + return { + "uuid": domain.UUIDString(), + "name": domain.name(), + "state": STATES.get(info[0], "unknown"), + } + + def list_vm_states(self) -> list[dict[str, Any]]: + """Fetch lightweight power state for every persistent domain.""" + with self._connect() as conn: + rows: list[dict[str, Any]] = [] + for domain in conn.listAllDomains(0): + try: + rows.append(self._vm_state_dict(domain)) + except libvirt.libvirtError: + # A domain can disappear between listAllDomains() and + # info(). Preserve the rest of the host inventory. + continue + return sorted(rows, key=lambda row: row["name"].casefold()) + def provisioning_absent(self, vm_uuid: str, name: str) -> bool: """Only certify refund safety after a fresh host/volume inventory. @@ -519,6 +542,11 @@ class VMService: with self._connect() as conn: return self._vm_dict(self._domain(conn, uuid)) + def get_vm_state(self, uuid: str) -> dict[str, Any]: + """Fetch one domain's power state without loading its XML metadata.""" + with self._connect() as conn: + return self._vm_state_dict(self._domain(conn, uuid)) + def metric_counters(self) -> list[RawVMStats]: """Fetch running-domain counters in one libvirt API round trip. diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 216d8e6a..f1450980 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -17,6 +17,7 @@ use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInput; +use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudJobService; use App\Services\Cloud\CloudInvoicePageService; use App\Services\Cloud\CloudInvoicePaymentService; @@ -504,12 +505,112 @@ final class CloudApiController $contexts[(int) $instance->id] ?? []))->all()]); } + /** Database-only paginated instance rows used after the SSR first page. */ + public function vmPage($request, $response) + { + $actor = $this->billingActor($request); + $value = $request->getQueryParams()['page'] ?? '1'; + if (is_array($value) + || preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) !== 1) { + throw new CloudError('实例页码无效'); + } + return $this->json($response, CloudInstancePageService::forActor( + $actor, (int) $value, 20 + )); + } + + /** + * Lightweight live state for the visible list page. Database ownership is + * resolved before any engine response is considered, and engine UUIDs are + * intersected with that owner-scoped set before being returned. + */ + public function vmStatuses($request, $response) + { + $actor = $this->actor($request); + $raw = $request->getQueryParams()['ids'] ?? ''; + if (is_array($raw) || preg_match('/^[1-9][0-9]*(?:,[1-9][0-9]*){0,99}$/D', + (string) $raw) !== 1) { + throw new CloudError('实例编号列表无效'); + } + $ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw)))); + $snapshots = CloudInstancePageService::forActorIds($actor, $ids); + $live = []; + $engine = new CloudEngineClient(); + foreach ($this->vmSnapshotsByHost($snapshots) as $hostId => $group) { + $allowed = []; + foreach ($group as $snapshot) { + $allowed[strtolower((string) $snapshot['uuid'])] = true; + } + try { + $payload = $engine->host((int) $hostId, 'GET', 'vm-states', $actor); + foreach (is_array($payload['items'] ?? null) ? $payload['items'] : [] as $item) { + if (!is_array($item) || !is_string($item['uuid'] ?? null)) { + continue; + } + $uuid = strtolower(trim($item['uuid'])); + if (isset($allowed[$uuid])) { + $live[$uuid] = $item; + } + } + } catch (CloudError $error) { + // The database rows remain visible with an unknown state; one + // offline host must not hide instances from another host. + } + } + $statuses = []; + foreach ($snapshots as $snapshot) { + $uuid = strtolower((string) $snapshot['uuid']); + $statuses[] = CloudInstancePageService::powerStatus( + $snapshot, $live[$uuid] ?? [] + ); + } + return $this->json($response, ['vms' => $statuses]); + } + + /** Lightweight live state for one owner-scoped detail page. */ + public function vmStatus($request, $response, $args) + { + $actor = $this->actor($request); + $snapshot = CloudInstancePageService::statusForActor($actor, $args['id']); + $live = []; + try { + $candidate = (new CloudEngineClient())->host( + (int) $snapshot['host_id'], + 'GET', + 'vms/' . rawurlencode((string) $snapshot['uuid']) . '/state', + $actor + ); + if (is_array($candidate) + && is_string($candidate['uuid'] ?? null) + && hash_equals(strtolower((string) $snapshot['uuid']), + strtolower(trim($candidate['uuid'])))) { + $live = $candidate; + } + } catch (CloudError $error) { + // Preserve the database snapshot when the host is unavailable. + } + return $this->json($response, + CloudInstancePageService::status($snapshot, $live)); + } + public function vm($request, $response, $args) { $actor = $this->actor($request); return $this->json($response, $this->vmData(CloudAccess::instance($args['id'], $actor), $actor)); } + private function vmSnapshotsByHost(array $snapshots): array + { + $groups = []; + foreach ($snapshots as $snapshot) { + $hostId = max(0, (int) ($snapshot['host_id'] ?? 0)); + if ($hostId > 0) { + $groups[$hostId][] = $snapshot; + } + } + return $groups; + } + public function metrics($request, $response, $args) { $actor = $this->actor($request); diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 0eef47c5..318164d0 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -2,8 +2,11 @@ namespace App\Controllers; +use App\Services\AdminCsrf; use App\Services\Auth; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudError; +use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudInvoicePageService; use App\Services\Cloud\CloudUserIsoFeature; use App\Services\View; @@ -23,12 +26,48 @@ final class CloudPageController public function instances($request, $response, $args) { - return $this->render($response, 'instances', '实例管理'); + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + $page = $this->pageNumber($request->getQueryParams()['page'] ?? '1'); + $payload = CloudInstancePageService::forActor($actor, $page, 20); + $payload['user'] = $this->userBootstrap($user, $actor); + + return $this->render($response, 'instances', '实例管理', '', '', [ + 'cloud_vm_rows' => array_map( + fn (array $vm): array => $this->vmListRow($vm), + $payload['vms'] + ), + 'cloud_vm_stats' => $payload['stats'], + 'cloud_vm_pagination' => $payload['pagination'], + 'cloud_vm_scope_label' => ($actor['is_admin'] ?? false) + ? '全部可见实例' : '我的实例', + 'cloud_vm_bootstrap_json' => $this->safeJson($payload), + ]); } public function detail($request, $response, $args) { - return $this->renderVmPage($response, $args, 'detail', '实例详情'); + $vmId = isset($args['id']) ? (string) $args['id'] : ''; + if (preg_match('/^[1-9][0-9]*$/D', $vmId) !== 1) { + return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); + } + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + try { + $vm = CloudInstancePageService::detailForActor($actor, $vmId); + } catch (CloudError $error) { + if ($error->httpStatus === 404) { + return $response->withHeader('Location', '/user/cloud/instances') + ->withStatus(302); + } + throw $error; + } + $payload = ['vm' => $vm, 'user' => $this->userBootstrap($user, $actor)]; + + return $this->render($response, 'detail', '实例详情', $vmId, '', [ + 'cloud_vm_view' => $this->vmDetailView($vm), + 'cloud_vm_bootstrap_json' => $this->safeJson($payload), + ]); } public function deploy($request, $response, $args) @@ -122,6 +161,18 @@ final class CloudPageController ]); $smarty->assign('cloud_invoice_balance', '$—'); $smarty->assign('cloud_invoice_bootstrap_json', '{}'); + $smarty->assign('cloud_vm_rows', []); + $smarty->assign('cloud_vm_stats', [ + 'total' => 0, 'running' => 0, 'stopped' => 0, 'other' => 0, + ]); + $smarty->assign('cloud_vm_pagination', [ + 'page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1, + 'page_count' => 0, 'has_previous' => false, 'has_next' => false, + 'from' => 0, 'to' => 0, + ]); + $smarty->assign('cloud_vm_view', []); + $smarty->assign('cloud_vm_scope_label', '我的实例'); + $smarty->assign('cloud_vm_bootstrap_json', '{}'); foreach ($values as $name => $value) { $smarty->assign($name, $value); } @@ -183,4 +234,241 @@ final class CloudPageController } return '$' . number_format((float) $value, 2, '.', ','); } + + private function pageNumber($value): int + { + return !is_array($value) + && preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) === 1 + ? (int) $value : 1; + } + + private function userBootstrap($user, array $actor): array + { + return [ + 'csrf_token' => AdminCsrf::token(), + 'user_id' => (string) $user->id, + 'username' => (string) ($user->user_name ?: $user->email), + 'admin' => (bool) $actor['is_admin'], + ]; + } + + private function safeJson(array $value): string + { + $json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG + | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT + | JSON_INVALID_UTF8_SUBSTITUTE); + return $json === false ? '{}' : $json; + } + + private function vmListRow(array $vm): array + { + [$stateLabel, $stateClass] = $this->vmState((string) ($vm['state'] ?? 'unknown')); + [$systemLabel, $systemValue] = $this->vmSystem($vm); + return [ + 'api_id' => (string) ($vm['api_id'] ?? $vm['id'] ?? ''), + 'uuid' => (string) ($vm['uuid'] ?? ''), + 'name' => (string) ($vm['name'] ?? '未命名虚拟机'), + 'state_label' => $stateLabel, + 'state_class' => $stateClass, + 'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置', + 'system_label' => $systemLabel, + 'system_value' => $systemValue, + 'ip' => $this->vmIp($vm), + 'has_ip' => $this->vmIp($vm) !== '未获取', + 'vcpu' => isset($vm['vcpu']) ? (int) $vm['vcpu'] + : (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null), + 'memory_mib' => isset($vm['memory_mib']) ? (int) $vm['memory_mib'] + : (isset($vm['ram_mib']) ? (int) $vm['ram_mib'] : null), + 'disk_label' => $this->vmDisk($vm), + ]; + } + + private function vmDetailView(array $vm): array + { + [$stateLabel, $stateClass] = $this->vmState((string) ($vm['state'] ?? 'unknown')); + [$systemLabel, $systemValue] = $this->vmSystem($vm); + [$serviceLabel, $serviceClass] = $this->serviceStatus( + (string) ($vm['service_status'] ?? '') + ); + [$networkLabel, $networkClass] = $this->networkStatus( + (string) ($vm['network_status'] ?? '') + ); + $quota = max(0, (int) ($vm['traffic_quota_bytes'] ?? 0)); + $download = max(0, (int) ($vm['traffic_download_bytes'] ?? 0)); + $upload = max(0, (int) ($vm['traffic_upload_bytes'] ?? 0)); + $used = max(0, (int) ($vm['traffic_used_bytes'] ?? ($download + $upload))); + $remaining = $quota === 0 ? 0 : max(0, $quota - $used); + $passwordAvailable = (bool) ($vm['password_available'] ?? false); + $vcpu = isset($vm['vcpu']) ? (int) $vm['vcpu'] + : (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null); + $memory = isset($vm['memory_mib']) ? (int) $vm['memory_mib'] + : (isset($vm['ram_mib']) ? (int) $vm['ram_mib'] : null); + + return [ + 'name' => (string) ($vm['name'] ?? '虚拟机'), + 'state_label' => $stateLabel, + 'state_class' => $stateClass, + 'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置', + 'ip' => $this->vmIp($vm), + 'created_display' => $this->createdAgo($vm['created_at'] ?? null), + 'system_label' => $systemLabel, + 'system_value' => $systemValue, + 'spec_display' => ($vcpu ?? '—') . ' vCPU · ' . ($memory ?? '—') . ' MiB', + 'disk_display' => $this->vmDisk($vm), + 'ssh_user' => trim((string) ($vm['login_name'] ?? '')) ?: '未记录', + 'password_label' => $passwordAvailable ? '********' : '未记录', + 'password_available' => $passwordAvailable, + 'can_operate' => (bool) ($vm['can_operate'] ?? false), + 'can_delete' => (bool) ($vm['can_delete'] ?? false), + 'service_status_label' => $serviceLabel, + 'service_status_class' => $serviceClass, + 'network_status_label' => $networkLabel, + 'network_status_class' => $networkClass, + 'period_end_display' => $this->dateTime($vm['current_period_ends_at'] ?? null), + 'traffic_rx_display' => $this->formatBytes($download), + 'traffic_tx_display' => $this->formatBytes($upload), + 'traffic_used_display' => $this->formatBytes($used), + 'traffic_total_remaining_display' => $quota === 0 + ? '不限流量 / 不限流量' + : $this->formatBytes($quota) . ' / ' . $this->formatBytes($remaining), + 'traffic_ratio' => $quota === 0 ? '' : number_format( + min(100, max(0, ($used / $quota) * 100)), 1, '.', '' + ), + ]; + } + + private function vmState(string $value): array + { + $normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $value)); + if (in_array($normalized, ['running', 'blocked'], true)) { + return ['运行中', 'running']; + } + if (in_array($normalized, ['shutoff', 'stopped'], true)) { + return ['已关机', 'stopped']; + } + return match ($normalized) { + 'shutdown' => ['关机中', 'other'], + 'crashed' => ['已崩溃', 'stopped'], + 'paused' => ['已暂停', 'other'], + 'pmsuspended' => ['已挂起', 'other'], + default => ['未知', 'other'], + }; + } + + private function vmSystem(array $vm): array + { + $source = (string) ($vm['os_source'] ?? ''); + if ($source === 'iso') { + return ['安装镜像', trim((string) ($vm['install_iso'] ?? '')) ?: '未识别']; + } + if ($source === 'cloud_template') { + return ['系统镜像', trim((string) ($vm['os_name'] ?? '')) ?: '未识别']; + } + $value = trim((string) ($vm['os_name'] ?? '')); + if ($value === '') { + $value = trim((string) ($vm['install_iso'] ?? '')); + } + return ['系统', $value !== '' ? $value : '未识别']; + } + + private function vmIp(array $vm): string + { + $value = trim((string) ($vm['public_ip_cidr'] ?? '')); + if ($value === '') { + $value = trim((string) ($vm['public_ip'] ?? '')); + } + return $value === '' ? '未获取' : (explode('/', $value, 2)[0] ?: '未获取'); + } + + private function vmDisk(array $vm): string + { + $size = 0.0; + foreach (is_array($vm['disks'] ?? null) ? $vm['disks'] : [] as $disk) { + if (!is_array($disk)) { + continue; + } + $value = $disk['capacity_gib'] ?? $disk['size_gib'] ?? 0; + if (is_numeric($value) && (float) $value > 0) { + $size += (float) $value; + } + } + if ($size <= 0 && is_numeric($vm['disk_gib'] ?? null)) { + $size = max(0, (float) $vm['disk_gib']); + } + if ($size <= 0) { + return '—'; + } + return rtrim(rtrim(number_format($size, 2, '.', ''), '0'), '.') . ' GiB'; + } + + private function createdAgo($value): string + { + $timestamp = is_string($value) ? strtotime($value) : false; + if ($timestamp === false || $timestamp <= 0) { + return '未记录'; + } + $elapsed = max(0, time() - $timestamp); + if ($elapsed < 60) { + return '创建于刚刚'; + } + if ($elapsed < 3600) { + return '创建于 ' . intdiv($elapsed, 60) . ' 分钟前'; + } + if ($elapsed < 86400) { + return '创建于 ' . intdiv($elapsed, 3600) . ' 小时前'; + } + if ($elapsed < 2592000) { + return '创建于 ' . intdiv($elapsed, 86400) . ' 天前'; + } + return '创建于 ' . intdiv($elapsed, 2592000) . ' 个月前'; + } + + private function serviceStatus(string $value): array + { + $labels = [ + 'active' => ['服务有效', 'active'], 'pending' => ['待生效', 'warning'], + 'renewing' => ['续费处理中', 'warning'], 'exempt' => ['不受套餐限制', 'active'], + 'suspended_expired' => ['已因到期停机', 'stopped'], + 'suspended_traffic' => ['已因流量用尽暂停', 'stopped'], + 'expired' => ['已到期', 'stopped'], 'deleting' => ['正在永久删除', 'warning'], + 'purge_deleting' => ['正在永久删除', 'warning'], + 'delete_failed' => ['自动删除失败,请联系管理员', 'stopped'], + ]; + return $labels[strtolower(str_replace('-', '_', trim($value)))] + ?? [$value !== '' ? $value : '暂未提供', 'unknown']; + } + + private function networkStatus(string $value): array + { + $labels = [ + 'active' => ['网络正常', 'active'], 'blocking' => ['正在暂停网络', 'warning'], + 'blocked_traffic' => ['本期流量用尽,已断网', 'stopped'], + 'blocked_expired' => ['实例已到期,网络已停用', 'stopped'], + 'restoring' => ['正在恢复网络', 'warning'], + 'restore_pending' => ['等待恢复网络', 'warning'], + 'restore_failed' => ['网络恢复失败,请联系管理员', 'stopped'], + 'exempt' => ['网络不受套餐限制', 'active'], + ]; + return $labels[strtolower(str_replace('-', '_', trim($value)))] + ?? [$value !== '' ? $value : '暂未提供', 'unknown']; + } + + private function dateTime($value): string + { + return is_numeric($value) && (int) $value > 0 + ? date('Y/m/d H:i:s', (int) $value) : '暂未提供'; + } + + private function formatBytes(int $value): string + { + $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; + $amount = max(0, $value); + $unit = 0; + while ($amount >= 1024 && $unit < count($units) - 1) { + $amount /= 1024; + $unit++; + } + $precision = $unit === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2)); + return number_format($amount, $precision, '.', '') . ' ' . $units[$unit]; + } } diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php index 89f9e3c0..0a6e9254 100644 --- a/web/app/Middleware/CloudApi.php +++ b/web/app/Middleware/CloudApi.php @@ -12,11 +12,12 @@ final class CloudApi { try { $path = (string) $request->getUri()->getPath(); - // Billing is owned entirely by PHP and never calls the private - // libvirt engine. Authenticating these routes must therefore not - // create or look up a cloud_sessions row. - $invoiceOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1; - $actor = CloudAccess::actor(!$invoiceOnly); + // Billing and paginated instance snapshots are owned entirely by + // PHP and never call the private libvirt engine. Authenticating + // these routes must therefore not create a cloud_sessions row. + $databaseOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1 + || $path === '/api/v1/vms/page'; + $actor = CloudAccess::actor(!$databaseOnly); if (AdminCsrf::requiresProtection($request->getMethod())) { if ($request->getHeaderLine('X-CSRF-Token') !== '') { $request = $request->withHeader(AdminCsrf::HEADER_NAME, $request->getHeaderLine('X-CSRF-Token')); diff --git a/web/app/Services/Cloud/CloudInstancePageService.php b/web/app/Services/Cloud/CloudInstancePageService.php new file mode 100644 index 00000000..33c6ec0f --- /dev/null +++ b/web/app/Services/Cloud/CloudInstancePageService.php @@ -0,0 +1,460 @@ +count(); + $totalPages = max(1, (int) ceil($total / $perPage)); + $page = min($page, $totalPages); + $records = (clone $base)->orderByDesc('id') + ->offset(($page - 1) * $perPage) + ->limit($perPage) + ->get(self::listColumns()); + $snapshots = self::listSnapshots($records); + $counts = ['running' => 0, 'stopped' => 0, 'other' => 0]; + foreach ($snapshots as $vm) { + $counts[self::stateCategory((string) ($vm['state'] ?? 'unknown'))]++; + } + // Power state is not persisted in cloud_instances. Any records outside + // the visible page are therefore unknown until the lightweight live + // status request completes; never invent a running/stopped count. + $counts['other'] += max(0, $total - count($snapshots)); + $vms = $snapshots; + + return [ + 'vms' => $vms, + 'stats' => [ + 'total' => $total, + 'running' => $counts['running'], + 'stopped' => $counts['stopped'], + 'other' => $counts['other'], + ], + 'pagination' => self::pagination($page, $perPage, $total, count($vms)), + ]; + } + + public static function detailForActor(array $actor, $id): array + { + $instance = self::visibleInstanceQuery($actor, $id)->first(self::columns()); + if ($instance === null) { + throw new CloudError('虚拟机不存在或无权访问', 404); + } + return self::snapshots( + new \Illuminate\Database\Eloquent\Collection([$instance]), $actor + )[0]; + } + + /** Mutable database state for the detail poll, without static VM metadata. */ + public static function statusForActor(array $actor, $id): array + { + $instance = self::visibleInstanceQuery($actor, $id)->first([ + 'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name', + 'status', 'service_status', 'network_status', 'expires_at', + 'traffic_quota_bytes', 'traffic_download_bytes', + 'traffic_upload_bytes', + ]); + if ($instance === null) { + throw new CloudError('虚拟机不存在或无权访问', 404); + } + $period = null; + if ($instance->current_period_id !== null) { + $period = CloudServicePeriod::where('id', $instance->current_period_id) + ->where('instance_id', $instance->id) + ->first(['starts_at', 'ends_at']); + } + $owner = (int) $instance->user_id === (int) $actor['user_id']; + $global = ($actor['is_admin'] ?? false) + && ($actor['is_super_admin'] ?? false) + && ($actor['can_manage'] ?? false); + $lifecycleActive = (string) $instance->status === 'active'; + $canDelete = $lifecycleActive && ($owner || $global); + $download = max(0, (int) $instance->traffic_download_bytes); + $upload = max(0, (int) $instance->traffic_upload_bytes); + $used = $download + $upload; + $quota = max(0, (int) $instance->traffic_quota_bytes); + return [ + 'id' => (string) $instance->id, + 'api_id' => (string) $instance->id, + 'uuid' => (string) $instance->uuid, + 'host_id' => (int) $instance->host_id, + 'name' => (string) $instance->name, + 'state' => 'unknown', + 'instance_status' => (string) $instance->status, + 'service_status' => (string) $instance->service_status, + 'network_status' => (string) $instance->network_status, + 'service_expires_at' => $instance->expires_at === null + ? null : (int) $instance->expires_at, + 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, + 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, + 'traffic_download_bytes' => $download, + 'traffic_upload_bytes' => $upload, + 'traffic_used_bytes' => $used, + 'traffic_quota_bytes' => $quota, + 'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used), + 'is_owner' => $owner, + 'can_operate' => $canDelete && $instance->serviceAvailable(), + 'can_delete' => $canDelete, + ]; + } + + /** + * Return actor-visible snapshots in the caller's requested id order. + * Ordinary users stay owner scoped; read-only administrators retain the + * historical all-instance view without inheriting mutation permissions. + */ + public static function forActorIds(array $actor, array $ids): array + { + $ordered = []; + foreach ($ids as $id) { + $number = filter_var($id, FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]]); + if ($number !== false) { + if (!isset($ordered[(int) $number])) { + $ordered[(int) $number] = count($ordered); + } + } + } + if ($ordered === []) { + return []; + } + $records = self::visibleQuery($actor) + ->whereIn('id', array_keys($ordered)) + ->get(['id', 'uuid', 'host_id', 'name']); + $vms = []; + foreach ($records as $instance) { + $vms[] = [ + 'id' => (string) $instance->id, + 'api_id' => (string) $instance->id, + 'uuid' => (string) $instance->uuid, + 'host_id' => (int) $instance->host_id, + 'name' => (string) $instance->name, + 'state' => 'unknown', + ]; + } + usort($vms, static fn (array $left, array $right): int => + ($ordered[(int) $left['id']] ?? PHP_INT_MAX) + <=> ($ordered[(int) $right['id']] ?? PHP_INT_MAX)); + return $vms; + } + + /** A deliberately small mutable status view merged with live engine data. */ + public static function status(array $snapshot, array $live = []): array + { + $liveUuid = is_string($live['uuid'] ?? null) + ? strtolower(trim($live['uuid'])) : ''; + $liveMatches = $liveUuid !== '' && hash_equals( + strtolower((string) $snapshot['uuid']), $liveUuid + ); + if (!$liveMatches) { + $live = []; + } + $liveStateAvailable = $liveMatches + && is_string($live['state'] ?? null) + && trim($live['state']) !== ''; + $state = is_string($live['state'] ?? null) && trim($live['state']) !== '' + ? trim($live['state']) : (string) ($snapshot['state'] ?? 'unknown'); + $name = is_string($live['name'] ?? null) && trim($live['name']) !== '' + ? trim($live['name']) : (string) ($snapshot['name'] ?? ''); + return [ + 'id' => (string) $snapshot['id'], + 'api_id' => (string) $snapshot['api_id'], + 'uuid' => (string) $snapshot['uuid'], + 'name' => $name, + 'state' => $state, + 'live_state_available' => $liveStateAvailable, + 'instance_status' => (string) $snapshot['instance_status'], + 'service_status' => (string) $snapshot['service_status'], + 'network_status' => (string) $snapshot['network_status'], + 'service_expires_at' => $snapshot['service_expires_at'], + 'current_period_started_at' => $snapshot['current_period_started_at'], + 'current_period_ends_at' => $snapshot['current_period_ends_at'], + 'traffic_download_bytes' => (int) $snapshot['traffic_download_bytes'], + 'traffic_upload_bytes' => (int) $snapshot['traffic_upload_bytes'], + 'traffic_used_bytes' => (int) $snapshot['traffic_used_bytes'], + 'traffic_quota_bytes' => (int) $snapshot['traffic_quota_bytes'], + 'traffic_remaining_bytes' => (int) $snapshot['traffic_remaining_bytes'], + 'is_owner' => (bool) $snapshot['is_owner'], + 'can_operate' => (bool) $snapshot['can_operate'], + 'can_delete' => (bool) $snapshot['can_delete'], + ]; + } + + /** Minimal list-poll payload; billing and permissions belong to detail. */ + public static function powerStatus(array $snapshot, array $live = []): array + { + $liveUuid = is_string($live['uuid'] ?? null) + ? strtolower(trim($live['uuid'])) : ''; + $matches = $liveUuid !== '' && hash_equals( + strtolower((string) $snapshot['uuid']), $liveUuid + ); + $available = $matches && is_string($live['state'] ?? null) + && trim($live['state']) !== ''; + return [ + 'id' => (string) $snapshot['id'], + 'api_id' => (string) $snapshot['api_id'], + 'uuid' => (string) $snapshot['uuid'], + 'name' => $matches && is_string($live['name'] ?? null) + && trim($live['name']) !== '' + ? trim($live['name']) : (string) $snapshot['name'], + 'state' => $available ? trim($live['state']) : 'unknown', + 'live_state_available' => $available, + ]; + } + + /** Keep the paginated list bootstrap intentionally smaller than detail. */ + private static function listItem(array $snapshot): array + { + $keys = [ + 'id', 'api_id', 'uuid', 'name', 'state', 'region', 'location', + 'os_source', 'os_name', 'install_iso', 'public_ip_cidr', 'public_ip', + 'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib', + ]; + return array_intersect_key($snapshot, array_flip($keys)); + } + + private static function listSnapshots($instances): array + { + if ($instances->isEmpty()) { + return []; + } + $hosts = self::hostMap($instances); + $result = []; + foreach ($instances as $instance) { + $decoded = json_decode((string) $instance->spec_json, true); + $spec = CloudInput::safeResult(is_array($decoded) ? $decoded : []); + $host = $hosts[(int) $instance->host_id] ?? null; + $region = trim((string) ($host?->region ?? '')); + if ($region === '') { + $region = trim((string) ($spec['region'] ?? $spec['location'] ?? '')); + } + $result[] = self::listItem(array_merge($spec, [ + 'id' => (string) $instance->id, + 'api_id' => (string) $instance->id, + 'uuid' => (string) $instance->uuid, + 'name' => (string) $instance->name, + 'state' => 'unknown', + 'region' => $region, + ])); + } + return $result; + } + + private static function hostMap($instances): array + { + $hostIds = $instances->pluck('host_id')->map( + static fn ($id): int => (int) $id + )->unique()->values()->all(); + $hosts = []; + if ($hostIds !== []) { + foreach (CloudHost::whereIn('id', $hostIds) + ->get(['id', 'region', 'country_code']) as $host) { + $hosts[(int) $host->id] = $host; + } + } + return $hosts; + } + + private static function snapshots($instances, array $actor): array + { + if ($instances->isEmpty()) { + return []; + } + $instanceIds = $instances->pluck('id')->map(static fn ($id): int => (int) $id)->all(); + $periodIds = $instances->pluck('current_period_id')->filter( + static fn ($id): bool => $id !== null + )->map(static fn ($id): int => (int) $id)->unique()->values()->all(); + + $hosts = self::hostMap($instances); + $periods = []; + if ($periodIds !== []) { + foreach (CloudServicePeriod::whereIn('id', $periodIds) + ->whereIn('instance_id', $instanceIds) + ->get(['id', 'instance_id', 'starts_at', 'ends_at', 'status']) as $period) { + $periods[(int) $period->id] = $period; + } + } + $futurePeriods = []; + foreach (CloudServicePeriod::whereIn('instance_id', $instanceIds) + ->where('status', 'scheduled') + ->selectRaw('instance_id, COUNT(*) AS period_count') + ->groupBy('instance_id')->get() as $row) { + $futurePeriods[(int) $row->instance_id] = (int) $row->period_count; + } + + $result = []; + foreach ($instances as $instance) { + $period = $instance->current_period_id === null ? null + : ($periods[(int) $instance->current_period_id] ?? null); + if ($period !== null && (int) $period->instance_id !== (int) $instance->id) { + $period = null; + } + $result[] = self::snapshot( + $instance, + $actor, + $hosts[(int) $instance->host_id] ?? null, + $period, + (int) ($futurePeriods[(int) $instance->id] ?? 0) + ); + } + return $result; + } + + private static function snapshot(CloudInstance $instance, array $actor, + ?CloudHost $host, ?CloudServicePeriod $period, int $futurePeriods): array + { + $decoded = json_decode((string) $instance->spec_json, true); + $spec = CloudInput::safeResult(is_array($decoded) ? $decoded : []); + $owner = (int) $instance->user_id === (int) $actor['user_id']; + $global = ($actor['is_admin'] ?? false) + && ($actor['is_super_admin'] ?? false) + && ($actor['can_manage'] ?? false); + $lifecycleActive = (string) $instance->status === 'active'; + $canDelete = $lifecycleActive && ($owner || $global); + $canOperate = $canDelete && $instance->serviceAvailable(); + $quota = max(0, (int) $instance->traffic_quota_bytes); + $download = max(0, (int) $instance->traffic_download_bytes); + $upload = max(0, (int) $instance->traffic_upload_bytes); + $used = $download + $upload; + $region = trim((string) ($host?->region ?? '')); + if ($region === '') { + $region = trim((string) ($spec['region'] ?? $spec['location'] ?? '')); + } + $createdAt = (int) $instance->created_at > 0 + ? gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at) : null; + + $maximumFuturePeriods = max(1, min(120, + (int) Config::get('cloud_max_renewal_periods_ahead', 24))); + return array_merge($spec, [ + 'id' => (string) $instance->id, + 'api_id' => (string) $instance->id, + 'uuid' => (string) $instance->uuid, + 'display_uuid' => (string) $instance->uuid, + 'name' => (string) $instance->name, + // Power state is intentionally never trusted from the persisted + // specification. Operations remain disabled until a fresh, + // UUID-checked engine status response is merged by the browser. + 'state' => 'unknown', + 'host_id' => (int) $instance->host_id, + 'user_id' => (int) $instance->user_id, + 'owner_user_id' => (int) $instance->user_id, + 'region' => $region, + 'country_code' => strtoupper(trim((string) ($host?->country_code + ?? ($spec['country_code'] ?? '')))), + 'created_at' => $createdAt, + 'instance_status' => (string) $instance->status, + 'service_status' => (string) $instance->service_status, + 'network_status' => (string) $instance->network_status, + 'service_expires_at' => $instance->expires_at === null + ? null : (int) $instance->expires_at, + 'current_period_started_at' => $period === null ? null : (int) $period->starts_at, + 'current_period_ends_at' => $period === null ? null : (int) $period->ends_at, + 'prepaid_periods' => max(0, $futurePeriods), + 'traffic_download_bytes' => $download, + 'traffic_upload_bytes' => $upload, + 'traffic_used_bytes' => $used, + 'traffic_quota_bytes' => $quota, + 'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used), + 'renewal_price' => $instance->renewal_price === null + ? null : (string) $instance->renewal_price, + 'renewal_days' => max(0, (int) $instance->renewal_days), + 'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes), + 'login_name' => (string) ($spec['login_name'] + ?? (($spec['os_source'] ?? '') === 'cloud_template' ? 'root' : '')), + 'is_owner' => $owner, + 'can_operate' => $canOperate, + 'can_delete' => $canDelete, + 'can_view_credential' => $owner || $global, + 'can_renew' => $lifecycleActive && $owner + && $instance->expires_at !== null + && (int) $instance->renewal_days > 0 + && $instance->renewal_price !== null + && $futurePeriods < $maximumFuturePeriods, + 'has_initial_root_password' => ($owner || $global) + && $instance->credential_cipher !== null, + 'password_available' => ($owner || $global) + && $instance->credential_cipher !== null, + ]); + } + + private static function visibleQuery(array $actor) + { + $query = CloudInstance::where('status', '<>', 'deleted'); + if (!($actor['is_admin'] ?? false)) { + $query->where('user_id', (int) $actor['user_id']); + } + return $query; + } + + private static function visibleInstanceQuery(array $actor, $id) + { + $query = self::visibleQuery($actor); + if (ctype_digit((string) $id)) { + return $query->where('id', (int) $id); + } + return $query->where('uuid', (string) $id); + } + + private static function columns(): array + { + return [ + 'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name', + 'status', 'service_status', 'network_status', 'expires_at', + 'renewal_price', 'renewal_days', 'renewal_traffic_bytes', + 'traffic_quota_bytes', 'traffic_download_bytes', + 'traffic_upload_bytes', 'spec_json', 'credential_cipher', + 'created_at', 'updated_at', + ]; + } + + private static function listColumns(): array + { + return ['id', 'uuid', 'host_id', 'name', 'spec_json']; + } + + private static function pagination(int $page, int $perPage, int $total, int $count): array + { + $pages = max(1, (int) ceil($total / $perPage)); + return [ + 'page' => $page, + 'per_page' => $perPage, + 'page_count' => $count, + 'total' => $total, + 'total_pages' => $pages, + 'has_previous' => $page > 1, + 'has_next' => $page < $pages, + 'from' => $count === 0 ? 0 : (($page - 1) * $perPage) + 1, + 'to' => $count === 0 ? 0 : (($page - 1) * $perPage) + $count, + ]; + } + + private static function stateCategory(string $state): string + { + $normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $state)); + if (in_array($normalized, ['running', 'blocked'], true)) { + return 'running'; + } + if (in_array($normalized, ['shutoff', 'stopped', 'crashed'], true)) { + return 'stopped'; + } + return 'other'; + } +} diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index 6bcc8050..f68c0270 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -25,6 +25,11 @@ $app->group('/api/v1', function () { 'App\Controllers\CloudApiController:userIsoJob'); $this->delete('/user-isos/{id:[0-9a-f]{32}}', 'App\Controllers\CloudApiController:deleteUserIso'); + // Fixed lightweight read routes must be registered before the historical + // dynamic /vms/{id} compatibility endpoint. + $this->get('/vms/page', 'App\Controllers\CloudApiController:vmPage'); + $this->get('/vms/statuses', 'App\Controllers\CloudApiController:vmStatuses'); + $this->get('/vms/{id:[0-9]+}/status', 'App\Controllers\CloudApiController:vmStatus'); $this->get('/vms', 'App\Controllers\CloudApiController:vms'); $this->get('/vms/{id}', 'App\Controllers\CloudApiController:vm'); $this->get('/vms/{id}/metrics', 'App\Controllers\CloudApiController:metrics'); diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index 5a0e537f..44ba0f5f 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -4,12 +4,22 @@ if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { VM_DETAIL_TABS, bindPageCleanup, byId, clearCredential, clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential, - drawVmTrafficDaily, initializeSession, loadVm, loadVmMetrics, loadVmTrafficDaily, - renderVmDetail, renderVmMetrics, selectVmByApiId, + drawVmTrafficDaily, hydrateVmDetailBootstrap, loadVmMetrics, loadVmStatus, + loadVmTrafficDaily, renderVmDetail, renderVmMetrics, selectedVm, setVmDetailTab, showError, state, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, } = await import(runtimeUrl.href); +function detailBootstrap() { + const source = byId('vm-detail-bootstrap'); + if (!source) throw new Error('实例详情初始数据缺失,请刷新后重试。'); + try { + return JSON.parse(source.textContent || '{}'); + } catch { + throw new Error('实例详情初始数据无法解析,请刷新后重试。'); + } +} + function bindDetailTabs() { document.querySelectorAll('[data-detail-tab]').forEach(button => { button.addEventListener('click', () => { @@ -51,19 +61,19 @@ function bindConsole() { export async function initialize() { try { - if (!await initializeSession('detail')) return; + const vm = hydrateVmDetailBootstrap(detailBootstrap()); bindPageCleanup(); - const vmId = document.body.dataset.vmId || ''; - const vm = await selectVmByApiId(vmId); + const vmId = vm.api_id; state.detailTab = VM_DETAIL_TABS.includes(new URLSearchParams(location.search).get('tab')) ? new URLSearchParams(location.search).get('tab') : 'operations'; clearVmMetrics('打开“性能监控”页签后加载监控数据。'); clearVmTrafficDaily('打开“流量信息”页签后加载最近 30 天数据。'); renderVmDetail(vm); setVmDetailTab(state.detailTab); + byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); byId('vm-detail-refresh-button')?.addEventListener('click', async () => { - await loadVm(vmId); + await loadVmStatus(vmId); if (trafficDailyViewVisible()) await loadVmTrafficDaily(true); }); byId('vm-detail-ip-copy')?.addEventListener('click', async () => { @@ -93,29 +103,37 @@ export async function initialize() { }, 150); }); let timer = null; + let stopped = false; + const poll = async () => { + timer = null; + if (stopped || document.hidden) return; + await loadVmStatus(vmId); + if (!stopped && !document.hidden) timer = window.setTimeout(poll, 20000); + }; const startPolling = () => { - if (timer !== null) window.clearInterval(timer); - timer = window.setInterval(() => { - if (!document.hidden) { - void loadVm(vmId); - if (trafficDailyViewVisible()) void loadVmTrafficDaily(); - } - }, 15000); + stopped = false; + if (timer !== null) window.clearTimeout(timer); + timer = window.setTimeout(poll, 20000); + }; + const stopPolling = () => { + stopped = true; + if (timer !== null) window.clearTimeout(timer); + timer = null; }; startPolling(); + void loadVmStatus(vmId); window.addEventListener('pagehide', () => { - if (timer !== null) window.clearInterval(timer); - timer = null; + stopPolling(); }); window.addEventListener('pageshow', event => { if (!event.persisted) return; - void loadVm(vmId); + void loadVmStatus(vmId); setVmDetailTab(state.detailTab); startPolling(); }); document.addEventListener('visibilitychange', () => { - if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); } - else { void loadVm(vmId); setVmDetailTab(state.detailTab); } + if (document.hidden) { stopPolling(); clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); } + else { void loadVmStatus(vmId); setVmDetailTab(state.detailTab); startPolling(); } }); } catch (error) { showError('cloud-page-error', error.message); } } diff --git a/web/public/cloud/instances.js b/web/public/cloud/instances.js index 1636ec99..bab311bf 100644 --- a/web/public/cloud/instances.js +++ b/web/public/cloud/instances.js @@ -1,33 +1,517 @@ -const runtimeUrl = new URL('/cloud/runtime.js', location.origin); -const assetVersion = new URL(import.meta.url).searchParams.get('v'); -if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); -const { - bindPageCleanup, byId, initializeSession, loadVms, renderVMs, showError, -} = await import(runtimeUrl.href); +// The first twenty instances are rendered by PHP. This lightweight module only +// handles local filtering, pagination and batched live-state refreshes. +const byId = id => document.getElementById(id); +const POLL_INTERVAL = 15000; +const MAX_POLL_INTERVAL = 120000; +const state = { + vms: [], + stats: { total: 0, running: 0, stopped: 0 }, + pagination: { + page: 1, per_page: 20, total: 0, total_pages: 1, + page_count: 0, has_previous: false, has_next: false, from: 0, to: 0, + }, + user: {}, + loading: false, + statusLoading: false, + liveStatsReady: false, + pageActive: true, + pollTimer: null, + pollFailures: 0, +}; -export async function initialize() { +function showError(message = '') { + const target = byId('cloud-page-error'); + if (!target) return; + target.textContent = message; + target.hidden = !message; +} + +async function api(path) { + const response = await fetch(path, { + method: 'GET', headers: { Accept: 'application/json' }, + credentials: 'same-origin', cache: 'no-store', + }); + let payload; + try { payload = await response.json(); } + catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); } + if (response.status === 401) { + location.assign('/auth/login'); + throw new Error('登录已过期。'); + } + if (!response.ok || payload?.ret === 0) { + const detail = Array.isArray(payload?.detail) + ? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail; + throw new Error(String(detail || payload?.message || payload?.msg || payload?.error + || `请求失败 (${response.status})`)); + } + return payload; +} + +function makeElement(tag, className = '', content) { + const element = document.createElement(tag); + if (className) element.className = className; + if (content !== undefined) element.textContent = String(content); + return element; +} + +function firstText(...values) { + for (const value of values) { + if (value !== null && value !== undefined && String(value).trim() !== '') { + return String(value).trim(); + } + } + return ''; +} + +function normalizeVm(vm) { + const source = vm && typeof vm === 'object' ? vm : {}; + return { + ...source, + uuid: String(source.uuid || source.id || ''), + api_id: String(source.api_id || source.id || source.uuid || ''), + vcpu: source.vcpu ?? source.cpu_cores, + memory_mib: source.memory_mib ?? source.ram_mib, + public_ip_cidr: source.public_ip_cidr || source.public_ip || '', + }; +} + +function stateCategory(value) { + const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, ''); + if (normalized === 'running' || normalized === 'blocked') return 'running'; + if (['shutoff', 'stopped', 'crashed'].includes(normalized)) return 'stopped'; + return 'other'; +} + +function stateLabel(value) { + const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, ''); + const labels = { + running: '运行中', blocked: '运行中', shutoff: '已关机', stopped: '已关机', + shutdown: '关机中', crashed: '已崩溃', paused: '已暂停', pmsuspended: '已挂起', + nostate: '未知', unknown: '未知', + }; + return labels[normalized] || String(value || '未知'); +} + +function vmRegion(vm) { + return firstText(vm.region, vm.location, '未设置'); +} + +function vmIp(vm) { + return firstText(vm.public_ip_cidr, vm.public_ip).split('/')[0] || '未获取'; +} + +function vmSystemInfo(vm) { + if (vm.os_source === 'iso') return { label: '安装镜像', value: firstText(vm.install_iso, '未识别') }; + if (vm.os_source === 'cloud_template') return { label: '系统镜像', value: firstText(vm.os_name, '未识别') }; + return { label: '系统', value: firstText(vm.os_name, vm.install_iso, '未识别') }; +} + +function diskLabel(vm) { + if (Array.isArray(vm.disks) && vm.disks.length) { + const size = vm.disks.reduce((total, disk) => { + const capacity = Number(disk?.capacity_gib ?? disk?.size_gib ?? 0); + return total + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0); + }, 0); + if (size > 0) return `${Math.round(size * 100) / 100} GiB`; + } + const size = Number(vm.disk_gib); + return Number.isFinite(size) && size > 0 ? `${size} GiB` : '—'; +} + +function normalizeStats(value, vms = []) { + const source = value && typeof value === 'object' ? value : {}; + const pageRunning = vms.filter(vm => stateCategory(vm.state) === 'running').length; + const pageStopped = vms.filter(vm => stateCategory(vm.state) === 'stopped').length; + const number = (candidate, fallback) => { + const parsed = Number(candidate); + return Number.isFinite(parsed) && parsed >= 0 ? Math.trunc(parsed) : fallback; + }; + return { + total: number(source.total, vms.length), + running: number(source.running, pageRunning), + stopped: number(source.stopped, pageStopped), + }; +} + +function normalizePagination(value, fallbackPage = 1, fallbackTotal = 0) { + const source = value && typeof value === 'object' ? value : {}; + const page = Math.max(1, Math.trunc(Number(source.page) || fallbackPage)); + const totalPages = Math.max(1, Math.trunc(Number(source.total_pages) || 1)); + const total = Math.max(0, Math.trunc(Number(source.total) || fallbackTotal)); + return { + page, + per_page: Math.max(1, Math.trunc(Number(source.per_page) || 20)), + total, + page_count: Math.max(0, Math.trunc(Number(source.page_count) || 0)), + total_pages: totalPages, + has_previous: source.has_previous === true || page > 1, + has_next: source.has_next === true || page < totalPages, + from: Math.max(0, Math.trunc(Number(source.from) || 0)), + to: Math.max(0, Math.trunc(Number(source.to) || 0)), + }; +} + +function renderStats() { + if (byId('stat-total')) byId('stat-total').textContent = String(state.stats.total); + const liveValue = value => state.pagination.total === 0 || state.liveStatsReady + ? String(value) : '—'; + if (byId('stat-running')) byId('stat-running').textContent = liveValue(state.stats.running); + if (byId('stat-stopped')) byId('stat-stopped').textContent = liveValue(state.stats.stopped); +} + +function toast(message, kind = '') { + const element = byId('toast'); + if (!element) return; + element.textContent = message; + element.className = `toast ${kind}`; + element.hidden = false; + window.setTimeout(() => { element.hidden = true; }, 3000); +} + +async function copyText(value) { + if (navigator.clipboard?.writeText) { + try { await navigator.clipboard.writeText(value); return; } catch {} + } + const area = document.createElement('textarea'); + area.value = value; + area.style.position = 'fixed'; + area.style.opacity = '0'; + document.body.append(area); + area.select(); + try { + if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。'); + } finally { area.value = ''; area.remove(); } +} + +function copyIconButton(value, label) { + const button = makeElement('button', 'vm-copy-icon'); + button.type = 'button'; + button.dataset.copyValue = value; + button.dataset.copyLabel = label; + button.title = `复制${label}`; + button.setAttribute('aria-label', `复制${label}`); + const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + icon.setAttribute('viewBox', '0 0 24 24'); + icon.setAttribute('aria-hidden', 'true'); + const back = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); + for (const [name, valuePart] of Object.entries({ x: '8', y: '8', width: '12', height: '12', rx: '2' })) { + back.setAttribute(name, valuePart); + } + const front = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + front.setAttribute('d', 'M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2'); + icon.append(back, front); + button.append(icon); + return button; +} + +function makeCell(row, label) { + const cell = document.createElement('td'); + cell.dataset.label = label; + row.append(cell); + return cell; +} + +function matchingVms() { + const query = (byId('search-input')?.value || '').trim().toLocaleLowerCase(); + const filter = byId('state-filter')?.value || 'all'; + return state.vms.filter(vm => { + const textMatches = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.public_ip, + vm.region, vm.location, vm.os_name, vm.install_iso] + .some(value => String(value || '').toLocaleLowerCase().includes(query)); + const statusMatches = filter === 'all' || stateCategory(vm.state) === filter; + return textMatches && statusMatches; + }); +} + +function renderCount(filteredCount = state.vms.length) { + const target = byId('inventory-count'); + if (!target) return; + const filtering = Boolean((byId('search-input')?.value || '').trim()) + || (byId('state-filter')?.value || 'all') !== 'all'; + target.textContent = filtering + ? `匹配 ${filteredCount} 台 · 当前页 ${state.vms.length} 台 · 共 ${state.pagination.total} 台` + : `当前页 ${state.vms.length} 台 · 共 ${state.pagination.total} 台`; +} + +function renderVms(connectionError = false) { + const filtered = matchingVms(); + renderCount(filtered.length); + const tbody = byId('vm-table-body'); + const empty = byId('empty-state'); + if (!tbody || !empty) return; + tbody.replaceChildren(); + empty.hidden = filtered.length !== 0; + if (!filtered.length) { + if (connectionError) { + byId('empty-title').textContent = '无法加载实例'; + byId('empty-description').textContent = '请稍后重试,或联系管理员检查服务状态。'; + } else if (state.vms.length) { + byId('empty-title').textContent = '没有匹配的实例'; + byId('empty-description').textContent = '尝试更换搜索词或状态筛选。'; + } else { + byId('empty-title').textContent = '还没有实例'; + byId('empty-description').textContent = '点击右上角“部署实例”开始。'; + } + return; + } + + const fragment = document.createDocumentFragment(); + for (const vm of filtered) { + const row = document.createElement('tr'); + row.dataset.vmId = vm.api_id; + row.dataset.vmUuid = vm.uuid; + + const identity = makeElement('div', 'vm-identity'); + identity.append(makeElement('div', 'vm-icon', '▣')); + const identityText = document.createElement('div'); + const name = makeElement('a', 'vm-name-link', vm.name || '未命名实例'); + name.href = `/user/cloud/instances/${encodeURIComponent(vm.api_id)}`; + name.dataset.vmUuid = vm.uuid; + name.setAttribute('aria-label', `管理实例 ${vm.name || vm.uuid}`); + const uuidRow = makeElement('span', 'vm-uuid-row'); + const uuid = makeElement('span', 'vm-id', vm.uuid || 'UUID 未知'); + if (vm.uuid) uuid.title = vm.uuid; + uuidRow.append(uuid); + if (vm.uuid) uuidRow.append(copyIconButton(vm.uuid, 'UUID')); + identityText.append(name, uuidRow); + identity.append(identityText); + makeCell(row, '实例').append(identity); + + const category = stateCategory(vm.state); + const status = makeElement('span', `state-pill ${category} vm-state-pill`, stateLabel(vm.state)); + makeCell(row, '状态').append(status); + makeCell(row, '地区').append(makeElement('span', 'vm-metadata', vmRegion(vm))); + const system = vmSystemInfo(vm); + makeCell(row, system.label).append(makeElement('span', 'vm-metadata', system.value)); + + const ip = vmIp(vm); + const ipRow = makeElement('span', 'vm-ip-copy-row'); + ipRow.append(makeElement('span', 'vm-metadata vm-ip', ip)); + if (ip !== '未获取') ipRow.append(copyIconButton(ip, '公网 IP')); + makeCell(row, '已配置公网 IP').append(ipRow); + + const spec = makeElement('div', 'vm-spec'); + spec.append(makeElement('strong', '', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`), + makeElement('small', '', '计算资源')); + makeCell(row, '规格').append(spec); + makeCell(row, '磁盘').append(makeElement('span', 'vm-spec', diskLabel(vm))); + fragment.append(row); + } + tbody.append(fragment); +} + +function renderPagination() { + const navigation = byId('instances-pagination'); + if (!navigation) return; + const { page, total_pages: totalPages, total, has_previous: previous, has_next: next } = state.pagination; + navigation.hidden = total === 0; + navigation.setAttribute('aria-busy', String(state.loading)); + if (byId('instances-page-label')) { + byId('instances-page-label').textContent = `第 ${page} / ${totalPages} 页 · 共 ${total} 台`; + } + if (byId('instances-previous')) { + byId('instances-previous').disabled = state.loading || state.statusLoading || !previous; + } + if (byId('instances-next')) { + byId('instances-next').disabled = state.loading || state.statusLoading || !next; + } + if (byId('refresh-button')) { + byId('refresh-button').disabled = state.loading || state.statusLoading; + byId('refresh-button').setAttribute('aria-busy', String(state.loading || state.statusLoading)); + } +} + +function updatePageUrl(page) { + const url = new URL(location.href); + if (page > 1) url.searchParams.set('page', String(page)); + else url.searchParams.delete('page'); + history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`); +} + +function stopPolling() { + if (state.pollTimer !== null) window.clearTimeout(state.pollTimer); + state.pollTimer = null; +} + +function nextPollDelay() { + if (!state.pollFailures) return POLL_INTERVAL; + return Math.min(MAX_POLL_INTERVAL, POLL_INTERVAL * (2 ** Math.min(state.pollFailures, 3))); +} + +function schedulePolling(delay = nextPollDelay()) { + stopPolling(); + if (!state.pageActive || document.hidden || !state.vms.length) return; + state.pollTimer = window.setTimeout(() => { + state.pollTimer = null; + void refreshStatuses(true); + }, delay); +} + +function statusItems(payload) { + if (Array.isArray(payload?.vms)) return payload.vms; + if (Array.isArray(payload?.statuses)) return payload.statuses; + if (Array.isArray(payload?.items)) return payload.items; + if (payload?.statuses && typeof payload.statuses === 'object') { + return Object.entries(payload.statuses).map(([id, value]) => ( + value && typeof value === 'object' ? { id, ...value } : { id, state: value } + )); + } + return []; +} + +function vmMatchesUpdate(vm, update) { + const candidates = [update?.api_id, update?.id, update?.uuid].map(value => String(value || '')); + return candidates.includes(vm.api_id) || candidates.includes(vm.uuid); +} + +function applyStatuses(payload) { + const updates = statusItems(payload); + let statusFilterChanged = false; + for (const update of updates) { + const vm = state.vms.find(item => vmMatchesUpdate(item, update)); + if (!vm || !firstText(update.state, update.status)) continue; + const previousCategory = stateCategory(vm.state); + const nextState = firstText(update.state, update.status); + const nextCategory = stateCategory(nextState); + Object.assign(vm, update, { state: nextState }); + if (previousCategory !== nextCategory) { + if (previousCategory === 'running') state.stats.running = Math.max(0, state.stats.running - 1); + if (previousCategory === 'stopped') state.stats.stopped = Math.max(0, state.stats.stopped - 1); + if (nextCategory === 'running') state.stats.running += 1; + if (nextCategory === 'stopped') state.stats.stopped += 1; + statusFilterChanged = true; + } + const row = Array.from(document.querySelectorAll('#vm-table-body tr[data-vm-id]')) + .find(item => item.dataset.vmId === vm.api_id || item.dataset.vmUuid === vm.uuid); + const pill = row?.querySelector('.vm-state-pill'); + if (pill) { + pill.className = `state-pill ${nextCategory} vm-state-pill`; + pill.textContent = stateLabel(nextState); + } + } + if (payload?.stats && typeof payload.stats === 'object') { + state.stats = normalizeStats(payload.stats, state.vms); + } + state.liveStatsReady = state.vms.length === 0 + || state.vms.every(vm => vm.live_state_available === true); + renderStats(); + if (statusFilterChanged && (byId('state-filter')?.value || 'all') !== 'all') renderVms(); +} + +async function refreshStatuses(scheduleNext = true) { + if (!state.pageActive || state.statusLoading || document.hidden || !state.vms.length) { + if (scheduleNext) schedulePolling(); + return; + } + const ids = state.vms.map(vm => vm.api_id).filter(Boolean); + if (!ids.length) return; + state.statusLoading = true; + renderPagination(); try { - if (!await initializeSession('list')) return; - bindPageCleanup(); - byId('refresh-button')?.addEventListener('click', loadVms); - byId('search-input')?.addEventListener('input', () => renderVMs()); - byId('state-filter')?.addEventListener('change', () => renderVMs()); - await loadVms(); - let timer = null; - const startPolling = () => { - if (timer !== null) window.clearInterval(timer); - timer = window.setInterval(() => { if (!document.hidden) void loadVms(); }, 15000); - }; - startPolling(); - window.addEventListener('pagehide', () => { - if (timer !== null) window.clearInterval(timer); - timer = null; - }); - window.addEventListener('pageshow', event => { - if (!event.persisted) return; - void loadVms(); - startPolling(); - }); - document.addEventListener('visibilitychange', () => { if (!document.hidden) void loadVms(); }); - } catch (error) { showError('cloud-page-error', error.message); } + const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}`); + applyStatuses(payload); + state.pollFailures = 0; + showError(); + } catch (error) { + state.pollFailures += 1; + if (state.pollFailures >= 2) { + showError(`${error?.message || '实例实时状态更新失败。'} 页面将自动重试。`); + } + } finally { + state.statusLoading = false; + renderPagination(); + if (scheduleNext) schedulePolling(); + } +} + +async function loadPage(page = state.pagination.page, updateUrl = true) { + if (state.loading) return; + const requestedPage = Math.max(1, Math.trunc(Number(page) || 1)); + state.loading = true; + state.liveStatsReady = false; + stopPolling(); + renderPagination(); + let pageLoaded = false; + try { + const payload = await api(`/api/v1/vms/page?page=${encodeURIComponent(requestedPage)}`); + state.vms = (Array.isArray(payload?.vms) ? payload.vms : []).map(normalizeVm); + state.pagination = normalizePagination(payload?.pagination, requestedPage, state.vms.length); + state.stats = normalizeStats(payload?.stats, state.vms); + state.pollFailures = 0; + renderStats(); + renderVms(); + renderPagination(); + if (updateUrl) updatePageUrl(state.pagination.page); + showError(); + pageLoaded = true; + } catch (error) { + showError(error?.message || '实例加载失败,请稍后重试。'); + if (!state.vms.length) renderVms(true); + } finally { + state.loading = false; + renderPagination(); + } + if (pageLoaded) await refreshStatuses(true); +} + +function hydrate() { + const source = byId('instances-bootstrap'); + if (!source) return false; + try { + const payload = JSON.parse(source.textContent || '{}'); + if (!Array.isArray(payload?.vms)) return false; + state.vms = payload.vms.map(normalizeVm); + state.pagination = normalizePagination(payload.pagination, 1, state.vms.length); + state.stats = normalizeStats(payload.stats, state.vms); + state.liveStatsReady = state.vms.length === 0; + state.user = payload.user && typeof payload.user === 'object' ? payload.user : {}; + renderStats(); + renderPagination(); + renderCount(state.vms.length); + updatePageUrl(state.pagination.page); + return true; + } catch { return false; } +} + +function bindEvents() { + byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); + 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', () => { + if (!state.loading && !state.statusLoading && state.pagination.has_previous) { + void loadPage(state.pagination.page - 1); + } + }); + byId('instances-next')?.addEventListener('click', () => { + if (!state.loading && !state.statusLoading && state.pagination.has_next) { + void loadPage(state.pagination.page + 1); + } + }); + byId('vm-table-body')?.addEventListener('click', event => { + const button = event.target.closest?.('[data-copy-value]'); + if (!button) return; + void copyText(button.dataset.copyValue || '') + .then(() => toast(`${button.dataset.copyLabel || '内容'}已复制。`, 'success')) + .catch(error => toast(error?.message || '复制失败。', 'error')); + }); + window.addEventListener('pagehide', () => { + state.pageActive = false; + stopPolling(); + }); + window.addEventListener('pageshow', event => { + state.pageActive = true; + if (event.persisted) void refreshStatuses(true); + }); + document.addEventListener('visibilitychange', () => { + if (document.hidden) stopPolling(); + else void refreshStatuses(true); + }); +} + +export async function initialize() { + const hydrated = hydrate(); + bindEvents(); + if (!hydrated) await loadPage(1, false); + else void refreshStatuses(true); } diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index be5a39c5..253f2e95 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -199,6 +199,61 @@ async function loadVm(apiId = selectedVm()?.api_id || document.body.dataset.vmId state.loadingVMs = false; } } +function applyCloudUser(user = {}) { + state.csrfToken = String(user.csrf_token || ''); + if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); + state.userId = String(user.user_id || ''); + if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); + state.username = user.username || user.user_name || user.email || '用户'; + state.admin = user.admin === true || user.is_admin === true || Number(user.is_admin) === 1; + if (byId('current-username')) text('current-username', state.username); + for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { + const link = byId(id); + if (link) link.hidden = !state.admin; + } +} +function hydrateVmDetailBootstrap(payload) { + if (!payload || typeof payload !== 'object' || !payload.vm || typeof payload.vm !== 'object') { + throw new Error('实例详情初始数据缺失,请刷新后重试。'); + } + state.view = 'detail'; + applyCloudUser(payload.user || {}); + const vm = normalizeVm(payload.vm); + if (!vm.api_id || !vm.uuid) throw new Error('实例标识缺失,请返回实例列表。'); + state.vms = [vm]; + state.selectedVmId = vm.uuid; + return vm; +} +async function loadVmStatus(apiId = selectedVm()?.api_id || document.body.dataset.vmId, raise = false) { + const id = String(apiId || ''); + if (!id) { + const error = new Error('实例标识缺失。'); + showError('cloud-page-error', error.message); + if (raise) throw error; + return null; + } + if (state.loadingVMs) return selectedVm() || null; + state.loadingVMs = true; + try { + const payload = await api(`/api/v1/vms/${encodeURIComponent(id)}/status`); + const current = selectedVm(); + if (!current) throw new Error('实例初始数据已失效,请刷新页面。'); + const update = payload?.vm && typeof payload.vm === 'object' ? payload.vm : payload; + if (!update || typeof update !== 'object') throw new Error('实例实时状态格式无效。'); + const vm = normalizeVm({ ...current, ...update, id: current.api_id, uuid: current.uuid }); + state.vms = [vm]; + state.selectedVmId = vm.uuid; + showError('cloud-page-error', ''); + if (state.view === 'detail') renderVmDetail(vm); + return vm; + } catch (error) { + showError('cloud-page-error', error.message); + if (raise) throw error; + return null; + } finally { + state.loadingVMs = false; + } +} function renderVmDetail(vm) { text('vm-detail-name', vm.name); text('vm-detail-state', stateLabel(vm.state)); byId('vm-detail-state').className = `state-pill ${stateCategory(vm.state)}`; for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm)); @@ -209,12 +264,13 @@ function renderVmDetail(vm) { text('vm-detail-root-password', !vm.can_view_credential ? '无权查看' : vm.password_available ? (state.credentialVisible ? state.credentialPassword : '********') : '未记录'); for (const id of ['vm-detail-password-reveal', 'vm-detail-password-copy']) byId(id).hidden = !vm.password_available; renderVmService(vm); - const running = stateCategory(vm.state) === 'running'; const stopped = stateCategory(vm.state) === 'stopped'; + const category = stateCategory(vm.state); const running = category === 'running'; const stopped = category === 'stopped'; + const stateKnown = !['', 'unknown', 'nostate'].includes(String(vm.state || '').toLowerCase().replace(/[_\s-]+/g, '')); const primary = byId('vm-detail-primary-actions'); const danger = byId('vm-detail-danger-actions'); primary.replaceChildren(); danger.replaceChildren(); danger.closest('section').hidden = !vm.can_operate && !vm.can_delete; if (vm.can_operate) { primary.append(actionButton('控制台', () => openConsole(vm), { disabled: !running }), actionButton('开机', () => powerAction('start'), { disabled: !stopped }), actionButton('正常关机', () => powerAction('shutdown'), { disabled: !running }), actionButton('重启', () => powerAction('reboot'), { disabled: !running })); - danger.append(actionButton('重装系统', () => navigate(vmPagePath(vm.api_id, 'reinstall')), { variant: 'danger', disabled: vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => navigate(vmPagePath(vm.api_id, 'rescue')), { variant: 'danger' }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: stopped })); + danger.append(actionButton('重装系统', () => navigate(vmPagePath(vm.api_id, 'reinstall')), { variant: 'danger', disabled: !stateKnown || vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => navigate(vmPagePath(vm.api_id, 'rescue')), { variant: 'danger', disabled: !stateKnown }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: !stateKnown || stopped })); } else { primary.append(makeElement('p', 'muted', vm.is_owner || vm.can_delete ? '实例服务已到期或正在执行策略;日常操作暂不可用。' @@ -251,7 +307,7 @@ function renderVmService(vm) { progress.classList.remove('is-exhausted'); } } -async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVm(vm.api_id); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } +async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVmStatus(vm.api_id); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } async function deleteVm() { const vm = selectedVm(); if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error'); if (state.mutationBusy) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true } }); toast('删除任务已提交,正在执行…'); if (result.job_id) await pollJob('delete', result.job_id); navigate(CLOUD_PATHS.instances); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); } async function credential(copy = false) { @@ -1883,17 +1939,7 @@ async function initializeSession(view) { state.view = view; const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return false; } - state.csrfToken = session.csrf_token || ''; - if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); - state.userId = String(session.user_id || ''); - if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); - state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; - state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; - if (byId('current-username')) text('current-username', state.username); - for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { - const link = byId(id); - if (link) link.hidden = !state.admin; - } + applyCloudUser(session); byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); return true; } @@ -1918,9 +1964,9 @@ function bindPageCleanup() { export { CLOUD_PATHS, VM_DETAIL_TABS, api, bindPageCleanup, buy, byId, clearCredential, clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential, - drawVmTrafficDaily, initializeSession, invoicePagePath, + drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, invoicePagePath, loadInvoiceDetail, loadInvoices, loadKeys, loadPlanResources, loadVmMetrics, loadVmTrafficDaily, - loadVm, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall, + loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm, scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, diff --git a/web/resources/views/venix/cloud/pages/detail.tpl b/web/resources/views/venix/cloud/pages/detail.tpl index 5a43e316..b32a0fbc 100644 --- a/web/resources/views/venix/cloud/pages/detail.tpl +++ b/web/resources/views/venix/cloud/pages/detail.tpl @@ -1,7 +1,7 @@
← 返回实例列表 -
VIRTUAL MACHINE DETAILS

虚拟机

服务器 IP:未获取区域:未设置未记录

未知
+
VIRTUAL MACHINE DETAILS

{$cloud_vm_view.name|default:'虚拟机'|escape:"html"}

服务器 IP:{$cloud_vm_view.ip|default:'未获取'|escape:"html"}区域:{$cloud_vm_view.region|default:'未设置'|escape:"html"}{$cloud_vm_view.created_display|default:'未记录'|escape:"html"}

{$cloud_vm_view.state_label|default:'正在读取'|escape:"html"}
@@ -10,21 +10,21 @@
-

虚拟机信息

状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。

+

虚拟机信息

实时状态每 20 秒自动更新;IP 是面板记录的配置,不代表系统已联网。

-
地区
未设置
系统
未识别
-
已配置公网 IP
未获取
计算规格
—
-
硬盘大小
—
-
SSH 登录名
未记录
-
面板记录的初始 root 密码
未记录 - - +
地区
{$cloud_vm_view.region|default:'未设置'|escape:"html"}
{$cloud_vm_view.system_label|default:'系统'|escape:"html"}
{$cloud_vm_view.system_value|default:'未识别'|escape:"html"}
+
已配置公网 IP
{$cloud_vm_view.ip|default:'未获取'|escape:"html"}
计算规格
{$cloud_vm_view.spec_display|default:'—'|escape:"html"}
+
硬盘大小
{$cloud_vm_view.disk_display|default:'—'|escape:"html"}
+
SSH 登录名
{$cloud_vm_view.ssh_user|default:'未记录'|escape:"html"}
+
面板记录的初始 root 密码
{$cloud_vm_view.password_label|default:'未记录'|escape:"html"} + +
-

日常操作

在这里管理这台虚拟机的电源和控制台。

-

维护与危险操作

救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。

+

日常操作

在这里管理这台虚拟机的电源和控制台。

正在读取实时状态…

+

维护与危险操作

救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。

实时状态确认后才会启用操作。

@@ -32,15 +32,15 @@

服务周期与流量

查看当前服务、网络状态和本期流量使用情况。

-
服务状态
暂未提供
-
网络状态
暂未提供
-
当前账期结束
暂未提供
-
本期下载(RX)
暂未提供
-
本期上传(TX)
暂未提供
-
本期合计已用
暂未提供
-
总流量 / 剩余流量
暂未提供
+
服务状态
{$cloud_vm_view.service_status_label|default:'暂未提供'|escape:"html"}
+
网络状态
{$cloud_vm_view.network_status_label|default:'暂未提供'|escape:"html"}
+
当前账期结束
{$cloud_vm_view.period_end_display|default:'暂未提供'|escape:"html"}
+
本期下载(RX)
{$cloud_vm_view.traffic_rx_display|default:'暂未提供'|escape:"html"}
+
本期上传(TX)
{$cloud_vm_view.traffic_tx_display|default:'暂未提供'|escape:"html"}
+
本期合计已用
{$cloud_vm_view.traffic_used_display|default:'暂未提供'|escape:"html"}
+
总流量 / 剩余流量
{$cloud_vm_view.traffic_total_remaining_display|default:'暂未提供'|escape:"html"}
- +

最近 30 天每日流量

按天统计虚拟机的下载和上传流量。

@@ -62,3 +62,4 @@
+ diff --git a/web/resources/views/venix/cloud/pages/instances.tpl b/web/resources/views/venix/cloud/pages/instances.tpl index 67ddf3b6..5c5322eb 100644 --- a/web/resources/views/venix/cloud/pages/instances.tpl +++ b/web/resources/views/venix/cloud/pages/instances.tpl @@ -1,20 +1,41 @@
-
VIRTUAL MACHINES

实例管理

查看虚拟机信息;点击名称进入管理页面执行操作。

+
VIRTUAL MACHINES

实例管理

查看实例信息;点击名称进入管理页面执行操作。

-
-
虚拟机总数
—我的实例
-
运行中
— 正在提供服务
-
已关机
—可随时启动
+
+
实例总数
{$cloud_vm_stats.total|default:0|escape:"html"}{$cloud_vm_scope_label|default:'我的实例'|escape:"html"}
+
当前页运行中
{if $cloud_vm_pagination.total > 0}—{else}0{/if} 实时电源状态
+
当前页已关机
{if $cloud_vm_pagination.total > 0}—{else}0{/if}实时电源状态
-

虚拟机列表

正在加载…

-
虚拟机状态地区系统 / 安装镜像已配置公网 IP规格磁盘
- +
+

实例列表

当前页 {$cloud_vm_pagination.page_count|default:0|escape:"html"} 台 · 共 {$cloud_vm_pagination.total|escape:"html"} 台

+
+
+
+ {foreach $cloud_vm_rows as $vm} + + + + + + + + + + {/foreach} +
实例状态地区系统 / 安装镜像已配置公网 IP规格磁盘
{$vm.name|escape:"html"}{$vm.uuid|escape:"html"}{if $vm.uuid != ''}{/if}
{$vm.state_label|escape:"html"}{if $vm.has_ip}{/if}
{$vm.vcpu|default:'—'|escape:"html"} vCPU · {$vm.memory_mib|default:'—'|escape:"html"} MiB计算资源
{$vm.disk_label|escape:"html"}
+

还没有实例

点击右上角“部署实例”开始。

+ +
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 50ccb59d..1c3de25a 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1 +1 @@ -{assign var=venix_asset_version value='2026092804' scope='global'} +{assign var=venix_asset_version value='2026092805' scope='global'} diff --git a/web/tests/CloudInstancePageServiceTest.php b/web/tests/CloudInstancePageServiceTest.php new file mode 100644 index 00000000..68770325 --- /dev/null +++ b/web/tests/CloudInstancePageServiceTest.php @@ -0,0 +1,161 @@ +addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + $schema = $capsule->schema('default'); + $schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('region')->default(''); + $table->string('country_code')->default(''); + }); + $schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('uuid'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->integer('current_period_id')->nullable(); + $table->string('name'); + $table->string('status'); + $table->string('service_status'); + $table->string('network_status'); + $table->integer('expires_at')->nullable(); + $table->string('renewal_price')->nullable(); + $table->integer('renewal_days')->default(0); + $table->integer('renewal_traffic_bytes')->default(0); + $table->integer('traffic_quota_bytes')->default(0); + $table->integer('traffic_download_bytes')->default(0); + $table->integer('traffic_upload_bytes')->default(0); + $table->text('spec_json'); + $table->text('credential_cipher')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + }); + $schema->create('cloud_service_periods', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('starts_at'); + $table->integer('ends_at'); + $table->string('status'); + }); + + Capsule::table('cloud_hosts')->insert([ + 'id' => 7, 'region' => 'HongKong', 'country_code' => 'HK', + ]); + $now = time(); + $common = [ + 'host_id' => 7, 'current_period_id' => null, 'status' => 'active', + 'service_status' => 'active', 'network_status' => 'active', + 'expires_at' => $now + 86400, 'renewal_price' => '10.00', + 'renewal_days' => 30, 'renewal_traffic_bytes' => 2000, + 'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300, + 'traffic_upload_bytes' => 200, + 'spec_json' => json_encode(['vcpu' => 2, 'memory_mib' => 2048, 'state' => 'running', + 'disk_gib' => 40, 'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10']), + 'credential_cipher' => 'test-cipher', 'created_at' => $now - 60, + 'updated_at' => $now, + ]; + Capsule::table('cloud_instances')->insert($common + [ + 'id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111', + 'user_id' => 1, 'name' => 'owner-vm', + ]); + Capsule::table('cloud_instances')->insert($common + [ + 'id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222', + 'user_id' => 2, 'name' => 'foreign-vm', + ]); + + $owner = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, + 'can_manage' => false]; + $admin = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => false, + 'can_manage' => false]; + $global = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => true, + 'can_manage' => true]; + + Capsule::connection('default')->flushQueryLog(); + Capsule::connection('default')->enableQueryLog(); + $page = CloudInstancePageService::forActor($owner, 1, 20); + $pageQueryCount = count(Capsule::connection('default')->getQueryLog()); + Capsule::connection('default')->disableQueryLog(); + $assert($page['stats']['total'] === 1 && count($page['vms']) === 1 + && $page['pagination']['page_count'] === 1 + && $page['vms'][0]['name'] === 'owner-vm', + 'Ordinary user instance first page crossed the owner boundary.'); + $assert($pageQueryCount <= 3, + 'Instance first page regressed beyond count, rows and host batch queries.'); + $assert($page['vms'][0]['state'] === 'unknown', + 'Persisted specification power state was trusted before a live UUID check.'); + $assert(!array_key_exists('traffic_quota_bytes', $page['vms'][0]) + && !array_key_exists('password_available', $page['vms'][0]), + 'Paginated instance rows leaked detail-only billing or credential metadata.'); + $ownedDetail = CloudInstancePageService::detailForActor($owner, 1); + $assert($ownedDetail['can_operate'] && $ownedDetail['can_delete'] + && $ownedDetail['password_available'] && $ownedDetail['can_renew'], + 'Owner lost expected instance capabilities.'); + $assert(count(CloudInstancePageService::forActorIds($owner, [1, 2])) === 1, + 'Ordinary user batch status scope disclosed a foreign instance.'); + + $adminPage = CloudInstancePageService::forActor($admin, 1, 20); + $assert($adminPage['stats']['total'] === 2, + 'Read-only administrator lost the historical all-instance view.'); + $foreign = CloudInstancePageService::detailForActor($admin, 2); + $assert(!$foreign['is_owner'] && !$foreign['can_operate'] + && !$foreign['can_delete'] && !$foreign['can_view_credential'] + && !$foreign['password_available'] && !$foreign['can_renew'], + 'Read-only administrator inherited foreign instance mutation or credential access.'); + + $managed = CloudInstancePageService::detailForActor($global, 2); + $assert(!$managed['is_owner'] && $managed['can_operate'] + && $managed['can_delete'] && $managed['can_view_credential'] + && $managed['password_available'] && !$managed['can_renew'], + 'Super administrator capabilities no longer match the legacy VM boundary.'); + Capsule::connection('default')->flushQueryLog(); + Capsule::connection('default')->enableQueryLog(); + $mutable = CloudInstancePageService::statusForActor($global, 2); + $statusQueryCount = count(Capsule::connection('default')->getQueryLog()); + Capsule::connection('default')->disableQueryLog(); + $assert($statusQueryCount <= 1 && $mutable['host_id'] === 7 + && !array_key_exists('credential_cipher', $mutable) + && !array_key_exists('renewal_price', $mutable), + 'Detail status poll loaded static host, credential or renewal metadata.'); + $status = CloudInstancePageService::status($managed, + ['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']); + $assert($status['state'] === 'running' && $status['traffic_used_bytes'] === 500 + && $status['traffic_remaining_bytes'] === 1500 + && $status['live_state_available'] === true, + 'Lightweight status did not merge live state with the database billing snapshot.'); + $unavailable = CloudInstancePageService::status($managed); + $assert($unavailable['state'] === 'unknown' + && $unavailable['live_state_available'] === false, + 'Unavailable hosts were presented as confirmed live power state.'); + $power = CloudInstancePageService::powerStatus($managed, + ['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']); + $assert($power['state'] === 'running' && $power['live_state_available'] === true + && !array_key_exists('traffic_quota_bytes', $power) + && !array_key_exists('can_delete', $power), + 'List polling returned detail-only billing or permission fields.'); + + echo "Cloud instance page service ownership and administrator permissions passed.\n"; +} diff --git a/web/tests/CloudInstancePageSsrContractTest.php b/web/tests/CloudInstancePageSsrContractTest.php new file mode 100644 index 00000000..35d3c54d --- /dev/null +++ b/web/tests/CloudInstancePageSsrContractTest.php @@ -0,0 +1,111 @@ +', 'deleted')") + && str_contains($service, "if (!(\$actor['is_admin'] ?? false))") + && str_contains($service, "->where('user_id', (int) \$actor['user_id'])") + && str_contains($service, '->limit($perPage)') + && str_contains($service, '->get(self::listColumns())') + && str_contains($service, "'per_page' => \$perPage") + && str_contains($service, "'page_count' => \$count") + && !str_contains($service, 'CloudEngineClient'), + 'Instance first-paint service must remain actor scoped, bounded and engine free.'); +$assert(str_contains($pageService, 'self::listSnapshots($records)') + && !str_contains($pageService, 'self::snapshots($records, $actor)'), + 'Instance list first paint must not load detail-only billing and credential data.'); +$assert(str_contains($service, "\$canDelete = \$lifecycleActive && (\$owner || \$global)") + && str_contains($service, "'can_view_credential' => \$owner || \$global") + && str_contains($service, "'can_renew' => \$lifecycleActive && \$owner") + && str_contains($service, "'state' => 'unknown'"), + 'Read-only administrators must not inherit owner or super-admin instance operations.'); +$assert(str_contains($service, 'CloudHost::whereIn') + && str_contains($service, 'CloudServicePeriod::whereIn') + && str_contains($service, "->groupBy('instance_id')"), + 'Instance page dependencies must remain bulk loaded instead of queried per row.'); +$assert(str_contains($service, 'private static function listItem(') + && str_contains($service, 'private static function listSnapshots(') + && str_contains($service, "->get(['id', 'uuid', 'host_id', 'name'])") + && str_contains($service, 'public static function powerStatus(') + && 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, 'public static function statusForActor(') + && str_contains($service, "'traffic_upload_bytes',") + && !str_contains($section($service, 'public static function statusForActor(', + 'public static function forActorIds('), 'credential_cipher'), + 'Detail status polling must load only mutable database state.'); + +$instances = $section($page, 'public function instances(', 'public function detail('); +$detail = $section($page, 'public function detail(', 'public function deploy('); +$assert(str_contains($instances, 'CloudAccess::actor(false)') + && str_contains($instances, 'CloudInstancePageService::forActor') + && str_contains($instances, "'cloud_vm_rows'") + && str_contains($instances, "'cloud_vm_bootstrap_json'"), + 'Instance list HTML must embed its owner-scoped database first page without a cloud session.'); +$assert(str_contains($detail, 'CloudAccess::actor(false)') + && str_contains($detail, 'CloudInstancePageService::detailForActor') + && str_contains($detail, "'cloud_vm_view'") + && str_contains($detail, "'cloud_vm_bootstrap_json'"), + 'Instance detail HTML must embed a useful owner-scoped database snapshot.'); +$assert(str_contains($page, 'JSON_HEX_TAG') + && str_contains($page, "'csrf_token' => AdminCsrf::token()") + && str_contains($page, "withHeader('Cache-Control', 'private, no-store')"), + 'Embedded instance state must be script-safe, authenticated and non-cacheable.'); + +$pageRoute = strpos($routes, "'/vms/page'"); +$statusesRoute = strpos($routes, "'/vms/statuses'"); +$statusRoute = strpos($routes, "'/vms/{id:[0-9]+}/status'"); +$legacyRoute = strpos($routes, "'/vms/{id}'"); +$assert($pageRoute !== false && $statusesRoute !== false && $statusRoute !== false + && $legacyRoute !== false && $pageRoute < $legacyRoute + && $statusesRoute < $legacyRoute && $statusRoute < $legacyRoute, + 'Lightweight fixed VM routes must precede the legacy dynamic VM route.'); + +$pageApi = $section($api, 'public function vmPage(', 'public function vmStatuses('); +$statusesApi = $section($api, 'public function vmStatuses(', 'public function vmStatus('); +$statusApi = $section($api, 'public function vmStatus(', 'public function vm('); +$assert(str_contains($pageApi, '$this->billingActor($request)') + && str_contains($pageApi, 'CloudInstancePageService::forActor') + && !str_contains($pageApi, 'CloudEngineClient'), + 'Paginated VM rows must not create an engine session or contact libvirt.'); +$assert(str_contains($statusesApi, 'CloudInstancePageService::forActorIds') + && str_contains($statusesApi, 'CloudInstancePageService::powerStatus') + && str_contains($statusesApi, "'GET', 'vm-states'") + && str_contains($statusesApi, 'isset($allowed[$uuid])') + && !str_contains($statusesApi, "'GET', 'vms'"), + 'Batch VM status must intersect owner UUIDs and use only the lightweight engine resource.'); +$assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor') + && str_contains($statusApi, ". '/state'") + && str_contains($statusApi, 'hash_equals('), + 'Single VM status must be owner scoped, UUID checked and avoid the full VM detail resource.'); +$assert(str_contains($middleware, "\$path === '/api/v1/vms/page'") + && str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'), + 'Database-only VM pagination must not allocate a private-engine cloud session.'); + +echo "Instance list/detail SSR and lightweight live-status contract passed.\n"; diff --git a/web/tests/CloudInstanceReadPerformanceTest.php b/web/tests/CloudInstanceReadPerformanceTest.php index 9f58b0d8..b6a83614 100644 --- a/web/tests/CloudInstanceReadPerformanceTest.php +++ b/web/tests/CloudInstanceReadPerformanceTest.php @@ -23,6 +23,9 @@ $section = static function (string $source, string $start, string $end): string $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'); +$detailTemplate = file_get_contents( + $root . '/resources/views/venix/cloud/pages/detail.tpl' +); $contexts = $section($controller, 'private function vmListContexts(', 'private function vmData('); @@ -60,8 +63,21 @@ $assert(str_contains($loadVm, "api(`/api/v1/vms/\${encodeURIComponent(id)}`)") $assert(str_contains($selection, 'await loadVm(apiId, true)') && !str_contains($selection, 'loadVms('), 'Detail selection still fetches the full VM list.'); -$assert(!str_contains($detail, 'loadVms') - && substr_count($detail, 'loadVm(vmId)') >= 4, - 'Detail refresh or polling still loads every instance.'); +$statusLoader = $section($runtime, 'async function loadVmStatus(', + 'function renderVmDetail('); +$assert(str_contains($detail, 'hydrateVmDetailBootstrap(detailBootstrap())') + && str_contains($detailTemplate, 'id="vm-detail-bootstrap"') + && !str_contains($detail, 'initializeSession(') + && !str_contains($detail, 'selectVmByApiId(') + && !str_contains($detail, 'loadVm('), + 'Detail first paint must hydrate the SSR bootstrap without session or full-VM requests.'); +$assert(str_contains($statusLoader, + 'api(`/api/v1/vms/${encodeURIComponent(id)}/status`)') + && str_contains($statusLoader, 'const current = selectedVm()') + && substr_count($detail, 'loadVmStatus(vmId)') >= 4 + && 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.'); echo "Cloud instance bulk-list and single-detail read paths passed.\n"; diff --git a/web/tests/CloudSessionSecurityTest.php b/web/tests/CloudSessionSecurityTest.php index 5ce3f481..c8843674 100644 --- a/web/tests/CloudSessionSecurityTest.php +++ b/web/tests/CloudSessionSecurityTest.php @@ -107,6 +107,19 @@ namespace { && is_array($billingActor) && ($billingActor['session_id'] ?? null) === '' && CloudSession::count() === $sessionCount, 'Invoice-only API authentication created or queried an engine cloud session.'); + $instancePageRequest = Request::createFromEnvironment(Environment::mock([ + 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/vms/page?page=1', + ])); + $instancePageActor = null; + $instancePageNext = function ($request, $response) use (&$instancePageActor) { + $instancePageActor = $request->getAttribute('cloud_actor'); + return $response; + }; + $reply = $middleware($instancePageRequest, new Response(), $instancePageNext); + $assert($reply->getStatusCode() === 200 + && is_array($instancePageActor) && ($instancePageActor['session_id'] ?? null) === '' + && CloudSession::count() === $sessionCount, + 'Database-only VM pagination created or queried an engine cloud session.'); $user->isLogin = false; $called = false; $reply = $middleware($request, new Response(), $next); $assert($reply->getStatusCode() === 401 && !$called && !$reply->hasHeader('Location'), 'Guest API redirected or passed through.'); echo "Cloud cookie/Redis revocation, signed introspection, admin console isolation and JSON CSRF checks passed (crypto reference double only).\n"; }