From b1e8a46a65576f643076c69aa2d369209aea136b Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 8 Oct 2026 05:28:25 +0800 Subject: [PATCH] feat: add tenant vpc user console --- docs/INTEGRATION_PLAN.md | 6 +- web/app/Controllers/CloudPageController.php | 34 + .../Services/Cloud/CloudVpcPageService.php | 93 ++ web/app/Services/Cloud/CloudVpcService.php | 188 +++- web/config/routes.php | 1 + web/public/cloud/app.js | 1 + web/public/cloud/vpc.css | 2 + web/public/cloud/vpc.js | 820 ++++++++++++++++++ web/resources/views/venix/cloud/page.tpl | 3 + .../views/venix/cloud/pages/vpcs.tpl | 58 ++ web/resources/views/venix/layout_assets.tpl | 2 +- .../views/venix/user/panel_sidebar.tpl | 3 + .../CloudVpcControlPlaneContractTest.php | 25 + web/tests/CloudVpcUserPageContractTest.php | 136 +++ 14 files changed, 1357 insertions(+), 15 deletions(-) create mode 100644 web/app/Services/Cloud/CloudVpcPageService.php create mode 100644 web/public/cloud/vpc.css create mode 100644 web/public/cloud/vpc.js create mode 100644 web/resources/views/venix/cloud/pages/vpcs.tpl create mode 100644 web/tests/CloudVpcUserPageContractTest.php diff --git a/docs/INTEGRATION_PLAN.md b/docs/INTEGRATION_PLAN.md index 5e0b11fe..764a9d31 100644 --- a/docs/INTEGRATION_PLAN.md +++ b/docs/INTEGRATION_PLAN.md @@ -189,8 +189,10 @@ Debian 13 ifupdown、nft 语法、重启、防火墙重载、跨宿主机握手 tombstone 和宿主机回读闭环之前不会释放;这会保留地址以避免未知状态下复用, 不能把 allocator 的 `active` 误认为已经可以回收。后续删除流程必须先阻断新成员 变更、确认所有成员/路由/ACL 已收敛,再以独立 revision 和 CAS 释放 reservation。 -删除中的宿主机或子资源 tombstone 仍会关闭 `usable`;当前没有删除回读证据, -因此不能在只剩其余宿主机 active 时提前放行。空 VPC 也不会进入 active,必须先有 +删除中的宿主机、私网 NIC、地址、子网或成员 tombstone 仍会关闭 `usable`;这些 +对象没有专门的删除回读证据时,不能在只剩其余宿主机 active 时提前放行。Route/ACL +tombstone 属于已纳入每台宿主机精确路由、nft 和 revision/digest 回读的对象,只有所有 +仍存活的宿主机逐一匹配后才会收敛为 `deleted`。空 VPC 也不会进入 active,必须先有 至少一个成员宿主机通过 Fabric 门禁。 VM 删除与 VPC 成员是两个独立状态机:仍有成员(包括 `deleting` tombstone)时, diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index f592c857..b15eb058 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -11,6 +11,8 @@ use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudInvoiceDetailPageService; use App\Services\Cloud\CloudInvoicePageService; use App\Services\Cloud\CloudUserIsoFeature; +use App\Services\Cloud\CloudVpcPageService; +use App\Services\Cloud\CloudVpcService; use App\Services\UserDrawerService; use App\Services\View; @@ -48,6 +50,37 @@ final class CloudPageController ]); } + /** + * Tenant VPC page. The initial document is database-only; the browser + * uses the typed /api/v1/vpcs endpoints for mutations and readback polls. + */ + public function vpcs($request, $response, $args) + { + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + $pageData = CloudVpcPageService::bootstrap($actor); + try { + $vpcs = CloudVpcService::listing($actor); + } catch (\Throwable) { + // Keep the shell renderable during a rolling schema migration; + // the API error is shown by the page's explicit retry path. + $vpcs = []; + } + $payload = [ + 'user' => $this->userBootstrap($user, $actor), + 'vpcs' => $vpcs, + 'regions' => $pageData['regions'], + 'instances' => $pageData['instances'], + 'scope_label' => ($actor['is_admin'] ?? false) + ? '管理员权限范围内的 VPC' : '仅显示当前账户资源', + ]; + + return $this->render($response, 'vpcs', 'VPC 私网', '', '', [ + 'cloud_vpc_bootstrap_json' => $this->safeJson($payload), + 'cloud_vpc_scope_label' => $payload['scope_label'], + ]); + } + public function detail($request, $response, $args) { $vmId = isset($args['id']) ? (string) $args['id'] : ''; @@ -315,6 +348,7 @@ final class CloudPageController $smarty->assign('cloud_reinstall_ssh_keys', []); $smarty->assign('cloud_reinstall_catalog_unavailable', false); $smarty->assign('cloud_reinstall_bootstrap_json', '{}'); + $smarty->assign('cloud_vpc_bootstrap_json', '{}'); $smarty->assign('panel_announcements_bootstrap_json', UserDrawerService::announcementBootstrapJson()); foreach ($values as $name => $value) { $smarty->assign($name, $value); diff --git a/web/app/Services/Cloud/CloudVpcPageService.php b/web/app/Services/Cloud/CloudVpcPageService.php new file mode 100644 index 00000000..e2a4e0de --- /dev/null +++ b/web/app/Services/Cloud/CloudVpcPageService.php @@ -0,0 +1,93 @@ + self::regions(), + 'instances' => self::instances($actor), + ]; + } + + private static function regions(): array + { + try { + $connection = (new CloudRegionFabric())->getConnection(); + $schema = $connection->getSchemaBuilder(); + if (!$schema->hasTable('cloud_region_fabrics')) { + return []; + } + return CloudRegionFabric::query() + ->join('cloud_regions as region', 'region.id', '=', 'cloud_region_fabrics.region_id') + ->where('cloud_region_fabrics.state', 'active') + ->where('cloud_region_fabrics.fabric_revision', '>', 0) + ->where('region.status', 'active') + ->orderByDesc('region.sort')->orderBy('region.id') + ->get([ + 'region.id as id', 'region.name', 'region.country_code', + ]) + ->map(static fn ($row): array => [ + 'id' => (int) $row->id, + 'name' => trim((string) $row->name), + 'country_code' => strtoupper(trim((string) ($row->country_code ?? ''))), + ])->all(); + } catch (\Throwable) { + // A rolling schema install should leave the page usable while + // making the unavailable Fabric choice explicit to the tenant. + return []; + } + } + + private static function instances(array $actor): array + { + $userId = (int) ($actor['user_id'] ?? 0); + if ($userId < 1) { + return []; + } + try { + return CloudInstance::query() + ->where('user_id', $userId) + ->where('status', 'active') + ->orderBy('name')->orderBy('id')->limit(200)->get([ + 'id', 'name', 'spec_json', 'service_status', 'expires_at', + ])->map(static function ($row): array { + $spec = json_decode((string) $row->spec_json, true); + $spec = is_array($spec) && !array_is_list($spec) ? $spec : []; + $regionId = filter_var($spec['region_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + $region = trim((string) ($spec['region'] ?? $spec['location'] ?? '')); + // A future expiry does not make a blocked/suspended + // service eligible for a private-network attachment. + // Keep this projection identical to CloudInstance's + // serviceAvailable() lifecycle gate. + $available = (string) $row->service_status === 'exempt' + || ((string) $row->service_status === 'active' + && $row->expires_at !== null + && (int) $row->expires_at > time()); + return [ + 'id' => (int) $row->id, + 'name' => (string) $row->name, + 'region_id' => $regionId === false ? null : (int) $regionId, + 'region' => $region, + 'service_available' => $available, + ]; + })->all(); + } catch (\Throwable) { + return []; + } + } +} diff --git a/web/app/Services/Cloud/CloudVpcService.php b/web/app/Services/Cloud/CloudVpcService.php index 889a3632..cb08564f 100644 --- a/web/app/Services/Cloud/CloudVpcService.php +++ b/web/app/Services/Cloud/CloudVpcService.php @@ -621,8 +621,23 @@ final class CloudVpcService } $rows = CloudVpcRoute::where('vpc_id', $vpc->id)->lockForUpdate()->get(); $existingByDestination = []; + $deletedByDestination = []; + $existingByKey = []; foreach ($rows as $row) { - $existingByDestination[(string) $row->destination_cidr] = $row; + $existingByKey[(string) $row->route_key] = $row; + if ((string) $row->state === 'deleted') { + // A proven tombstone still owns the destination/key + // unique indexes. It may be revived by a later complete + // replacement, but must never be reopened merely because + // another save includes unrelated routes. + $deletedByDestination[(string) $row->destination_cidr] = $row; + } else { + $existingByDestination[(string) $row->destination_cidr] = $row; + } + } + if ($rows->contains(static fn ($row): bool => + (string) $row->state === 'deleting')) { + throw new CloudError('路由仍在清理,请等待宿主机回读后再保存', 409); } $seenDestinations = []; foreach ($routes as $route) { @@ -631,18 +646,30 @@ final class CloudVpcService throw new CloudError('路由目标不能重复', 409); } $seenDestinations[$destination] = true; - $existing = $existingByDestination[$destination] ?? null; - if ($existing !== null && (string) $existing->route_key !== $route['route_key']) { + $existing = $existingByDestination[$destination] + ?? $deletedByDestination[$destination] ?? null; + if ($existing !== null + && (string) $existing->state !== 'deleted' + && (string) $existing->route_key !== $route['route_key']) { throw new CloudError('路由目标已存在,请沿用原 route_key 修改', 409); } + $sameKey = $existingByKey[$route['route_key']] ?? null; + if ($sameKey !== null && $existing !== null + && (int) $sameKey->id !== (int) $existing->id) { + throw new CloudError('route_key 已被其他路由使用', 409); + } } foreach ($rows as $row) { + if ((string) $row->state === 'deleted') { + continue; + } $row->state = 'deleting'; $row->updated_at = time(); $row->save(); } $now = time(); foreach ($routes as $route) { + $destination = (string) $route['destination']['cidr']; $next = $byIp[$route['next_hop_ip']] ?? null; if ($next === null) { throw new CloudError('路由下一跳必须是本 VPC 的成员私网 IP'); @@ -654,12 +681,20 @@ final class CloudVpcService } $row = CloudVpcRoute::where('vpc_id', $vpc->id) ->where('route_key', $route['route_key'])->lockForUpdate()->first(); + if ($row === null) { + // Reuse a proven tombstone when the user recreates the + // same destination with a fresh browser-generated key. + // This satisfies both unique indexes without exposing + // historical keys in the tenant editor. + $row = $deletedByDestination[$destination] ?? null; + } if ($row === null) { $row = new CloudVpcRoute(); $row->route_key = $route['route_key']; $row->vpc_id = $vpc->id; $row->created_at = $now; } + $row->route_key = $route['route_key']; $row->member_id = $next->id; $row->destination_cidr = $route['destination']['cidr']; $row->destination_int = $route['destination']['network']; @@ -694,8 +729,20 @@ final class CloudVpcService $root = self::cidr((string) $vpc->cidr, 16, 24, 'VPC CIDR'); $rows = CloudVpcAclRule::where('vpc_id', $vpc->id)->lockForUpdate()->get(); $existingByPriority = []; + $deletedByPriority = []; + $existingByKey = []; foreach ($rows as $row) { - $existingByPriority[(string) $row->direction . ':' . (int) $row->priority] = $row; + $priorityKey = (string) $row->direction . ':' . (int) $row->priority; + $existingByKey[(string) $row->rule_key] = $row; + if ((string) $row->state === 'deleted') { + $deletedByPriority[$priorityKey] = $row; + } else { + $existingByPriority[$priorityKey] = $row; + } + } + if ($rows->contains(static fn ($row): bool => + (string) $row->state === 'deleting')) { + throw new CloudError('ACL 仍在清理,请等待宿主机回读后再保存', 409); } $seenPriorities = []; foreach ($rules as $rule) { @@ -704,18 +751,30 @@ final class CloudVpcService throw new CloudError('同一方向的 ACL 优先级不能重复', 409); } $seenPriorities[$priorityKey] = true; - $existing = $existingByPriority[$priorityKey] ?? null; - if ($existing !== null && (string) $existing->rule_key !== $rule['rule_key']) { + $existing = $existingByPriority[$priorityKey] + ?? $deletedByPriority[$priorityKey] ?? null; + if ($existing !== null + && (string) $existing->state !== 'deleted' + && (string) $existing->rule_key !== $rule['rule_key']) { throw new CloudError('ACL 优先级已存在,请沿用原 rule_key 修改', 409); } + $sameKey = $existingByKey[$rule['rule_key']] ?? null; + if ($sameKey !== null && $existing !== null + && (int) $sameKey->id !== (int) $existing->id) { + throw new CloudError('rule_key 已被其他 ACL 使用', 409); + } } foreach ($rows as $row) { + if ((string) $row->state === 'deleted') { + continue; + } $row->state = 'deleting'; $row->updated_at = time(); $row->save(); } $now = time(); foreach ($rules as $rule) { + $priorityKey = (string) $rule['direction'] . ':' . (int) $rule['priority']; foreach (['source', 'destination'] as $side) { if (!self::contains($root['network'], $root['broadcast'], $rule[$side]['network'], $rule[$side]['broadcast'])) { @@ -724,12 +783,18 @@ final class CloudVpcService } $row = CloudVpcAclRule::where('vpc_id', $vpc->id) ->where('rule_key', $rule['rule_key'])->lockForUpdate()->first(); + if ($row === null) { + // As with routes, a terminal tombstone can be reused for + // the same direction/priority without exposing its key. + $row = $deletedByPriority[$priorityKey] ?? null; + } if ($row === null) { $row = new CloudVpcAclRule(); $row->rule_key = $rule['rule_key']; $row->vpc_id = $vpc->id; $row->created_at = $now; } + $row->rule_key = $rule['rule_key']; $row->priority = $rule['priority']; $row->direction = $rule['direction']; $row->action = $rule['action']; @@ -1060,6 +1125,8 @@ final class CloudVpcService && $privateDataplaneVerified && $observedRevision === $revision && hash_equals($digest, $observedDigest); + $pendingHostTombstone = $required->contains(static fn ($row): bool => + (string) $row->state === 'deleting'); $fabricGate = is_array($observed['fabric_gate'] ?? null) ? $observed['fabric_gate'] : []; // An empty VPC is a valid tenant reservation, but there is no @@ -1098,9 +1165,9 @@ final class CloudVpcService $liveRequired = $required->filter(static fn ($row): bool => (string) $row->state !== 'deleting'); // A Fabric or host control-plane digest cannot prove that a - // deleting child/host is gone from the data plane. Keep every - // tombstone closed until the typed private-NIC/route/nft evidence - // is introduced by the engine. + // deleting private interface/address/subnet is gone. Route and + // ACL tombstones may be closed later, but only after the exact + // per-host route/nft readback gate. $pendingChildTombstone = false; foreach ([ CloudVpcSubnet::class, @@ -1115,21 +1182,26 @@ final class CloudVpcService break; } } - $pendingHostTombstone = $required->contains(static fn ($row): bool => - (string) $row->state === 'deleting'); $allActive = $globalActive && $liveRequired->count() > 0 && !$pendingChildTombstone && !$pendingHostTombstone; + // Keep this independent from child tombstones: route/ACL rows can + // close after exact host readback, while private NIC/address rows + // still require their explicit removal proof. + $allLiveHostsExact = $globalActive && $liveRequired->count() > 0 + && !$pendingHostTombstone; $allRemovalProof = true; $hasRemovalTarget = false; foreach ($hosts as $hostKey => $_item) { if (!$required->has((int) $hostKey)) { $allActive = false; + $allLiveHostsExact = false; } } foreach ($required as $hostId => $deployment) { $item = $hosts[(string) $hostId] ?? null; if (!is_array($item)) { $allActive = false; + $allLiveHostsExact = false; // A deleting host remains a tombstone until an exact // desired revision proves that the empty-host target was // accepted. Converting it to uncertain would make a @@ -1148,6 +1220,7 @@ final class CloudVpcService $active = $globalActive && ($item['state'] ?? null) === 'active' && ($item['transport_verified'] ?? false) === true && ($item['private_dataplane_verified'] ?? false) === true + && ($item['removed'] ?? false) !== true && $itemRevision <= $revision && $itemRevision === $revision && hash_equals($digest, $itemDigest); $deleting = (string) $deployment->state === 'deleting'; @@ -1185,9 +1258,82 @@ final class CloudVpcService } else { $deployment->last_failure_at = time(); $allActive = false; + if (!$deleting) { + $allLiveHostsExact = false; + } } $deployment->save(); } + // A terminal no-members/no-participating-hosts response is a + // positive control-plane proof only when this revision has no + // host deployment left to remove. In that case no host-side + // route or nft object can still be owned by this VPC, so route + // and ACL tombstones may converge without pretending that a + // private NIC, address, member, or subnet was removed. Keep the + // proof in the operation audit; the operation itself remains a + // terminal gate failure until a future member mutation creates a + // real host dataplane target. + $noDataPlaneTerminalProof = $terminalGate + && $required->count() === 0 + && $liveRequired->count() === 0 + && $hosts === [] + && !$pendingHostTombstone; + if ($noDataPlaneTerminalProof) { + $observed['no_data_plane_terminal_proof'] = [ + 'revision' => $revision, + 'digest' => $digest, + 'gate' => $gateError, + ]; + $observedAt = time(); + foreach ([CloudVpcRoute::class, CloudVpcAclRule::class] as $childModel) { + $childModel::where('vpc_id', $vpc->id) + ->where('desired_revision', $revision) + ->where('state', 'deleting') + ->update([ + 'observed_revision' => $revision, + 'observed_digest' => $digest, + 'state' => 'deleted', + 'last_error_code' => null, + 'updated_at' => $observedAt, + ]); + } + } + // Routes and ACLs are part of the exact host dataplane digest. + // Close their tombstones only after every required live host was + // individually matched above; a top-level active envelope with a + // missing or mismatched host must remain fail-closed. + if ($allLiveHostsExact) { + $observedAt = time(); + foreach ([CloudVpcRoute::class, CloudVpcAclRule::class] as $childModel) { + $childModel::where('vpc_id', $vpc->id) + ->where('desired_revision', $revision) + ->where('state', 'deleting') + ->update([ + 'observed_revision' => $revision, + 'observed_digest' => $digest, + 'state' => 'deleted', + 'last_error_code' => null, + 'updated_at' => $observedAt, + ]); + } + } + // Re-read after route/ACL closure so their former tombstones do + // not keep an otherwise exact VPC in degraded state. + $pendingChildTombstone = false; + foreach ([ + CloudVpcSubnet::class, + CloudVpcPrivateIp::class, + CloudVpcMember::class, + CloudVpcRoute::class, + CloudVpcAclRule::class, + ] as $childModel) { + if ($childModel::where('vpc_id', $vpc->id) + ->where('state', 'deleting')->exists()) { + $pendingChildTombstone = true; + break; + } + } + $allActive = $allLiveHostsExact && !$pendingChildTombstone; $removalOnlyComplete = $hasRemovalTarget && $allRemovalProof && $liveRequired->count() === 0 && !$pendingChildTombstone; if ($hasRemovalTarget && $allRemovalProof && $liveRequired->count() === 0) { @@ -3121,6 +3267,20 @@ final class CloudVpcService private static function boundedObserved(array $value): array { $hosts = []; + $terminalProof = null; + $proof = $value['no_data_plane_terminal_proof'] ?? null; + if (is_array($proof) + && (int) ($proof['revision'] ?? 0) > 0 + && preg_match('/^[a-f0-9]{64}$/D', (string) ($proof['digest'] ?? '')) === 1 + && in_array((string) ($proof['gate'] ?? ''), [ + 'vpc_no_members', 'vpc_no_participating_hosts', + ], true)) { + $terminalProof = [ + 'revision' => (int) $proof['revision'], + 'digest' => strtolower((string) $proof['digest']), + 'gate' => (string) $proof['gate'], + ]; + } foreach (is_array($value['hosts'] ?? null) ? $value['hosts'] : [] as $key => $host) { if (!is_array($host) || count($hosts) >= 256) { continue; @@ -3238,6 +3398,10 @@ final class CloudVpcService } $hosts[(string) $key] = $bounded; } - return ['hosts' => $hosts]; + $result = ['hosts' => $hosts]; + if ($terminalProof !== null) { + $result['no_data_plane_terminal_proof'] = $terminalProof; + } + return $result; } } diff --git a/web/config/routes.php b/web/config/routes.php index e0b8854c..f1b4f836 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -92,6 +92,7 @@ $app->group('/user', function () { $this->get('/', 'App\Controllers\CloudPageController:home'); $this->get('/cloud', 'App\Controllers\CloudPageController:index'); $this->get('/cloud/instances', 'App\Controllers\CloudPageController:instances'); + $this->get('/cloud/vpcs', 'App\Controllers\CloudPageController:vpcs'); $this->get('/cloud/instances/{id:[0-9]+}', 'App\Controllers\CloudPageController:detail'); $this->get('/cloud/instances/{id:[0-9]+}/reinstall', 'App\Controllers\CloudPageController:reinstall'); $this->get('/cloud/instances/{id:[0-9]+}/rescue', 'App\Controllers\CloudPageController:rescue'); diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js index 75db7a10..8ce75291 100644 --- a/web/public/cloud/app.js +++ b/web/public/cloud/app.js @@ -1,5 +1,6 @@ const pageModules = Object.freeze({ instances: '/cloud/instances.js', + vpcs: '/cloud/vpc.js', detail: '/cloud/detail.js', deploy: '/cloud/deploy.js', isos: '/cloud/iso-images.js', diff --git a/web/public/cloud/vpc.css b/web/public/cloud/vpc.css new file mode 100644 index 00000000..8aad7a28 --- /dev/null +++ b/web/public/cloud/vpc.css @@ -0,0 +1,2 @@ +.vpc-page-heading{align-items:flex-end}.vpc-overview{margin-bottom:18px}.vpc-notice{margin:-4px 0 18px;padding:11px 14px;border:1px solid #cfe9ea;border-radius:9px;background:#effafa;color:#28767d;font-size:11px;line-height:1.6}.vpc-notice.success{border-color:#ccead9;background:#effaf4;color:#26775c}.vpc-notice.warning{border-color:#f0d8aa;background:#fff8eb;color:#916323}.vpc-columns{display:grid;grid-template-columns:minmax(300px,.72fr) minmax(0,1.28fr);gap:18px;align-items:start}.vpc-list-panel,.vpc-detail-panel,.vpc-create-panel{min-width:0}.vpc-list{display:grid;gap:9px;padding:15px}.vpc-list-row{display:flex;align-items:center;justify-content:space-between;gap:13px;width:100%;padding:15px 16px;border:1px solid #e1eaee;border-radius:10px;background:#fff;color:inherit;text-align:left;transition:border-color .15s,background .15s,box-shadow .15s;cursor:pointer}.vpc-list-row:hover{border-color:#9fd5d8;background:#f8fcfc}.vpc-list-row.selected{border-color:#41b6ba;background:#f1faf9;box-shadow:0 0 0 3px rgba(40,171,177,.1)}.vpc-list-main{display:grid;gap:7px;min-width:0}.vpc-list-heading{display:flex;align-items:center;flex-wrap:wrap;gap:8px;min-width:0}.vpc-list-heading strong{min-width:0;overflow-wrap:anywhere;color:#2d4659;font-size:13px}.vpc-list-main>small,.vpc-list-meta small{color:#8495a4;font-size:10px;line-height:1.4}.vpc-list-meta{display:grid;justify-items:end;gap:5px;flex:none;text-align:right}.vpc-state-pill{display:inline-flex;align-items:center;gap:5px;width:max-content;max-width:100%;padding:4px 8px;border-radius:999px;background:#f0f3f5;color:#718394;font-size:9px;font-weight:800;white-space:nowrap}.vpc-state-pill:before{width:5px;height:5px;border-radius:50%;background:currentColor;content:""}.vpc-state-pill.active{background:#e8f7ef;color:#23805d}.vpc-state-pill.applying{background:#eaf5f8;color:#277c91}.vpc-state-pill.waiting{background:#eef5fb;color:#4274a6}.vpc-state-pill.uncertain{background:#fff5e3;color:#a26d1e}.vpc-state-pill.degraded,.vpc-state-pill.failed{background:#fff0f1;color:#ae4854}.vpc-state-pill.deleting{background:#fff3ee;color:#aa6740}.vpc-detail-panel{overflow:hidden}.vpc-detail{display:grid;gap:14px;padding:18px}.vpc-detail-overview{padding:17px;border:1px solid #dce9ed;border-radius:11px;background:#f9fcfc}.vpc-detail-overview-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.vpc-readback-note{flex:1;min-width:180px;color:#728896;font-size:10px;line-height:1.5}.vpc-detail-actions{display:flex;gap:7px;margin-left:auto}.vpc-facts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;margin:16px 0 0;border:1px solid #e1eaee;border-radius:8px;overflow:hidden;background:#e1eaee}.vpc-fact{min-width:0;padding:10px 12px;background:#fff}.vpc-fact dt{margin-bottom:5px;color:#8a9aa8;font-size:9px;font-weight:800}.vpc-fact dd{margin:0;overflow-wrap:anywhere;color:#3c5668;font-size:11px;font-weight:700}.vpc-subpanel{padding:17px;border:1px solid #e4ebef;border-radius:11px;background:#fff}.vpc-subpanel-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:14px}.vpc-subpanel-heading h3{margin:0 0 5px;color:#304a5d;font-size:14px}.vpc-subpanel-heading p{margin:0;color:#8797a5;font-size:10px;line-height:1.55}.vpc-subpanel-count{color:#93a1ae;font-size:10px}.vpc-form,.vpc-inline-form{display:grid;gap:15px}.vpc-form{padding:21px 24px 23px}.vpc-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vpc-inline-form{grid-template-columns:repeat(2,minmax(0,1fr));align-items:end;padding:13px;border:1px solid #e2eaee;border-radius:9px;background:#fbfcfd}.vpc-member-form{grid-template-columns:repeat(4,minmax(0,1fr))}.vpc-inline-form .field{min-width:0}.vpc-inline-form .button{min-height:38px}.vpc-form-actions,.vpc-editor-toolbar{display:flex;justify-content:flex-end;gap:8px;align-items:center}.vpc-row-list{display:grid;gap:8px;margin-top:12px}.vpc-data-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:11px 12px;border:1px solid #e5ecef;border-radius:8px;background:#fcfefe}.vpc-row-copy{display:grid;gap:4px;min-width:0}.vpc-row-copy strong{overflow-wrap:anywhere;color:#3b5567;font-size:11px}.vpc-row-copy small{color:#8798a6;font-size:9px;line-height:1.4}.vpc-row-copy .vpc-row-error{color:#ad5b4f}.vpc-empty-inline{margin:0;padding:13px;color:#91a0ac;font-size:10px;text-align:center}.button.danger{border-color:#efd9dd;color:#b04a57}.button.danger:not(:disabled):hover{background:#fff0f1}.vpc-editor-list{display:grid;gap:8px}.vpc-editor-row{display:grid;grid-template-columns:minmax(130px,1.25fr) minmax(130px,1.1fr) 95px auto;gap:8px;align-items:end;padding:10px;border:1px solid #e5ecef;border-radius:8px;background:#fcfefe}.vpc-acl-row{grid-template-columns:72px 94px 84px 86px minmax(125px,1fr) minmax(125px,1fr) 90px 90px auto}.vpc-editor-row .field{min-width:0}.vpc-editor-row .field label{font-size:9px;margin-bottom:5px}.vpc-editor-row .field input,.vpc-editor-row .field select{height:35px;padding:0 8px;font-size:10px}.vpc-editor-toolbar{margin-top:11px;justify-content:space-between}.vpc-editor-toolbar .button:first-child{margin-right:auto}.vpc-operation-list{display:grid;gap:1px;border:1px solid #e5ecef;border-radius:8px;overflow:hidden;background:#e5ecef}.vpc-operation-row{display:grid;grid-template-columns:minmax(100px,1fr) auto minmax(110px,1fr);align-items:center;gap:10px;padding:10px 12px;background:#fff;color:#516a7c;font-size:10px}.vpc-operation-row small{color:#8c9ba8;text-align:right;overflow-wrap:anywhere}.vpc-create-panel{margin-top:18px}.vpc-create-panel .panel-heading{align-items:center}.vpc-create-panel[hidden]{display:none}@media(max-width:1050px){.vpc-columns{grid-template-columns:1fr}.vpc-list-panel{order:0}.vpc-detail-panel{order:1}.vpc-member-form{grid-template-columns:repeat(2,minmax(0,1fr))}.vpc-acl-row{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(max-width:740px){.vpc-form{padding:18px 19px 20px}.vpc-form-grid,.vpc-inline-form{grid-template-columns:1fr}.vpc-list{padding:12px}.vpc-list-row{align-items:flex-start;flex-direction:column}.vpc-list-meta{justify-items:start;text-align:left}.vpc-detail{padding:12px}.vpc-facts{grid-template-columns:repeat(2,minmax(0,1fr))}.vpc-subpanel{padding:14px}.vpc-editor-row,.vpc-acl-row{grid-template-columns:repeat(2,minmax(0,1fr))}.vpc-editor-row .button{grid-column:1/-1;justify-self:end}.vpc-operation-row{grid-template-columns:minmax(80px,1fr) auto}.vpc-operation-row small{grid-column:1/-1;text-align:left}.vpc-detail-overview-heading{align-items:flex-start}.vpc-detail-actions{width:100%;margin-left:0}.vpc-detail-actions .button{flex:1}}@media(max-width:510px){.vpc-facts{grid-template-columns:1fr}.vpc-page-heading .heading-actions{width:100%}.vpc-page-heading .heading-actions .button{flex:1}.vpc-form-actions .button{width:100%}.vpc-editor-toolbar{align-items:stretch;flex-wrap:wrap}.vpc-editor-toolbar .button{flex:1}.vpc-editor-toolbar .button:first-child{margin-right:0}} +.vpc-tombstone-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:11px 12px;border:1px dashed #e6c9a8;border-radius:8px;background:#fffaf2;color:#8a6a3b}.vpc-tombstone-row strong{overflow-wrap:anywhere;font-size:11px}.vpc-tombstone-row small{color:#a17e4d;font-size:9px;line-height:1.4;text-align:right} diff --git a/web/public/cloud/vpc.js b/web/public/cloud/vpc.js new file mode 100644 index 00000000..52968d08 --- /dev/null +++ b/web/public/cloud/vpc.js @@ -0,0 +1,820 @@ +import { toast } from './toast.js?v=2026100802'; + +const byId = id => document.getElementById(id); +const state = { + csrfToken: '', userId: '', regions: [], instances: [], vpcs: [], + selectedKey: '', selected: null, busy: false, stopped: false, detailDirty: false, + listEpoch: 0, detailEpoch: 0, listController: null, detailController: null, + pollTimer: 0, +}; + +const STATUS_LABELS = Object.freeze({ + applying: '应用中', waiting: '等待宿主机回读', uncertain: '结果待核对', + degraded: '部分失败', active: '已生效', deleting: '清理中', unknown: '状态未知', +}); + +function element(tag, className = '', textContent = '') { + const node = document.createElement(tag); + if (className) node.className = className; + if (textContent !== '') node.textContent = String(textContent); + return node; +} + +function field(label, value, className = '') { + const wrapper = element('div', `vpc-fact ${className}`.trim()); + wrapper.append(element('dt', '', label), element('dd', '', value)); + return wrapper; +} + +function setError(message = '') { + const node = byId('vpc-page-error'); + if (!node) return; + node.textContent = message; + node.hidden = !message; +} + +function setNotice(message = '', kind = '') { + const node = byId('vpc-page-notice'); + if (!node) return; + node.textContent = message; + node.className = `vpc-notice ${kind}`.trim(); + node.hidden = !message; +} + +function setFormError(id, message = '') { + const node = byId(id); + if (!node) return; + node.textContent = message; + node.hidden = !message; +} + +function secureTransportRequired() { + return location.protocol !== 'https:' + && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname); +} + +async function api(path, options = {}) { + const method = String(options.method || 'GET').toUpperCase(); + const headers = new Headers({ Accept: 'application/json', ...(options.headers || {}) }); + if (!['GET', 'HEAD'].includes(method)) { + if (secureTransportRequired()) throw new Error('请通过 HTTPS 修改 VPC 私网配置。'); + if (!state.csrfToken) throw new Error('会话安全令牌缺失,请刷新页面。'); + headers.set('X-CSRF-Token', state.csrfToken); + headers.set('Content-Type', 'application/json'); + } + const response = await fetch(path, { + method, headers, credentials: 'same-origin', cache: 'no-store', + signal: options.signal, + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + let payload = null; + try { payload = response.status === 204 ? null : 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?.error + || `请求失败 (${response.status})`)); + } + return payload; +} + +function requestKey(prefix) { + const uuid = typeof crypto?.randomUUID === 'function' + ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`; + return `${prefix}-${uuid}`.slice(0, 128); +} + +function entityKey() { + const value = typeof crypto?.randomUUID === 'function' + ? crypto.randomUUID().replaceAll('-', '') + : `${Date.now()}${Math.random().toString(16).slice(2)}`; + return value.replace(/[^a-f0-9]/gi, '').toLowerCase().padEnd(32, '0').slice(0, 32); +} + +function safeText(value, fallback = '—') { + const text = value === null || value === undefined ? '' : String(value).trim(); + return text || fallback; +} + +function rootStatus(root) { + const sync = String(root?.sync_state || '').toLowerCase(); + const raw = String(root?.state || '').toLowerCase(); + if (root?.usable === true) return 'active'; + if (sync === 'waiting' || sync === 'waiting_observed') return 'waiting'; + if (sync === 'uncertain' || raw === 'uncertain') return 'uncertain'; + if (raw === 'degraded' || sync === 'failed') return 'degraded'; + if (raw === 'deleting') return 'deleting'; + if (raw === 'applying' || ['pending', 'queued', 'running'].includes(sync)) return 'applying'; + return raw === 'active' ? 'uncertain' : (raw || 'unknown'); +} + +function childStatus(value) { + const raw = String(value || '').toLowerCase(); + return ['active', 'applying', 'waiting', 'uncertain', 'degraded', 'deleting', 'deleted'] + .includes(raw) ? raw : 'unknown'; +} + +function statusPill(status, extra = '') { + const normalized = status === 'waiting_observed' ? 'waiting' : String(status || 'unknown'); + const pill = element('span', `vpc-state-pill ${normalized}`.trim(), + STATUS_LABELS[normalized] || normalized); + if (extra) pill.title = extra; + return pill; +} + +function errorLabel(code) { + return { + vpc_no_members: 'VPC 已创建;加入至少一个实例后才会应用私网数据面。', + vpc_data_plane_deferred: 'Fabric 已就绪,正在等待私网数据面回读。', + vpc_observation_incomplete: '宿主机回读尚未完整,请稍后核对。', + }[String(code || '')] || ''; +} + +function regionName(regionId) { + const row = state.regions.find(item => Number(item.id) === Number(regionId)); + return row ? safeText(row.name, `地区 ${regionId}`) : `地区 ${regionId || '未知'}`; +} + +function instanceName(instanceId) { + const row = state.instances.find(item => Number(item.id) === Number(instanceId)); + return row ? safeText(row.name, `实例 #${instanceId}`) : `实例 #${instanceId}`; +} + +function instanceRegion(instanceId) { + const row = state.instances.find(item => Number(item.id) === Number(instanceId)); + return row ? safeText(row.region, '地区待核验') : '地区待核验'; +} + +function normalizeRoot(value) { + if (!value || typeof value !== 'object') return null; + return { + ...value, + vpc_key: String(value.vpc_key || ''), + name: String(value.name || '未命名 VPC'), + cidr: String(value.cidr || ''), + region_id: Number(value.region_id || 0), + desired_revision: Number(value.desired_revision || 0), + observed_revision: Number(value.observed_revision || 0), + last_error_code: value.last_error_code ? String(value.last_error_code) : '', + }; +} + +function normalizeDocument(value) { + if (!value || typeof value !== 'object') return null; + const root = normalizeRoot(value.vpc); + if (!root) return null; + return { + vpc: root, + subnets: Array.isArray(value.subnets) ? value.subnets : [], + members: Array.isArray(value.members) ? value.members : [], + routes: Array.isArray(value.routes) ? value.routes : [], + acl_rules: Array.isArray(value.acl_rules) ? value.acl_rules : [], + operations: Array.isArray(value.operations) ? value.operations : [], + }; +} + +function needsPolling() { + return state.vpcs.some(vpc => rootStatus(vpc) !== 'active') + || (state.selected && rootStatus(state.selected.vpc) !== 'active'); +} + +function markDetailDirty() { + if (state.detailDirty) return; + state.detailDirty = true; + setNotice('详情中有未保存修改,自动状态核对已暂停。', 'warning'); +} + +function confirmDetailMutation() { + return !state.detailDirty + || confirm('当前 VPC 有未保存修改,继续操作会丢失这些修改。继续吗?'); +} + +function clearDetailDirty() { + state.detailDirty = false; +} + +function refreshRouteEditorState() { + const editor = byId('vpc-route-editor'); + if (!editor) return; + const allowed = new Set((state.selected?.members || []) + .filter(item => !['deleting', 'deleted'].includes(childStatus(item.state))) + .map(item => String(item.private_ip || ''))); + for (const row of editor.querySelectorAll('.vpc-editor-row')) { + const value = row.querySelector('[data-route-field="next_hop_ip"]')?.value || ''; + if (!value || !allowed.has(String(value))) row.dataset.invalid = 'true'; + else delete row.dataset.invalid; + } + const blocked = Boolean(editor.querySelector('[data-vpc-tombstone-state="deleting"]')); + const save = document.querySelector('[data-vpc-save="routes"]'); + if (save) save.disabled = state.busy || blocked + || Boolean(editor.querySelector('[data-invalid="true"]')); +} + +function schedulePoll(delay = needsPolling() ? 8000 : 30000) { + clearTimeout(state.pollTimer); + if (state.stopped || document.visibilityState === 'hidden') return; + state.pollTimer = window.setTimeout(async () => { + if (state.stopped || document.visibilityState === 'hidden') return; + if (state.busy) { schedulePoll(1500); return; } + await loadList(true); + if (state.selectedKey && !state.detailDirty) { + await loadDetail(state.selectedKey, true); + } + schedulePoll(); + }, delay); +} + +function renderSummary() { + const active = state.vpcs.filter(item => rootStatus(item) === 'active').length; + const attention = state.vpcs.length - active; + byId('vpc-stat-total').textContent = String(state.vpcs.length); + byId('vpc-stat-active').textContent = String(active); + byId('vpc-stat-attention').textContent = String(attention); + byId('vpc-list-caption').textContent = state.vpcs.length + ? `${state.vpcs.length} 个 VPC · 状态每 ${needsPolling() ? '8' : '30'} 秒自动核对` + : '还没有已创建的 VPC'; +} + +function renderList() { + const container = byId('vpc-list'); + container.replaceChildren(); + const rows = state.vpcs.map(root => { + const row = element('button', `vpc-list-row${root.vpc_key === state.selectedKey ? ' selected' : ''}`); + row.type = 'button'; + row.dataset.vpcKey = root.vpc_key; + const main = element('span', 'vpc-list-main'); + const heading = element('span', 'vpc-list-heading'); + heading.append(element('strong', '', root.name), statusPill(rootStatus(root), root.last_error_code)); + main.append(heading, element('small', '', `${root.cidr} · ${regionName(root.region_id)}`)); + const meta = element('span', 'vpc-list-meta'); + meta.append(element('small', '', `目标 revision ${root.desired_revision || 0}`), + element('small', '', root.usable === true ? '宿主机回读已确认' : '等待实际回读')); + row.append(main, meta); + return row; + }); + container.append(...rows); + byId('vpc-list-empty').hidden = rows.length !== 0; + byId('vpc-list-reconcile').disabled = !state.selectedKey || state.busy + || rootStatus(state.vpcs.find(item => item.vpc_key === state.selectedKey)) === 'active'; + renderSummary(); +} + +function section(title, description, className = '') { + const card = element('section', `vpc-subpanel ${className}`.trim()); + const header = element('div', 'vpc-subpanel-heading'); + header.append(element('div', '', ''), element('span', 'vpc-subpanel-count', '')); + header.firstChild.append(element('h3', '', title), element('p', '', description)); + card.append(header); + return card; +} + +function button(label, className = 'button button-outline small') { + const node = element('button', className, label); + node.type = 'button'; + return node; +} + +function input(labelText, value = '', type = 'text', placeholder = '') { + const wrapper = element('div', 'field'); + const id = `vpc-field-${Math.random().toString(16).slice(2)}`; + const label = element('label', '', labelText); + const control = document.createElement(type === 'select' ? 'select' : 'input'); + control.id = id; + if (type !== 'select') { + control.type = type; control.value = value === null ? '' : String(value); + if (placeholder) control.placeholder = placeholder; + } + label.htmlFor = id; + wrapper.append(label, control); + return { wrapper, control }; +} + +function renderDetail() { + const container = byId('vpc-detail'); + const doc = state.selected; + if (!doc) { container.replaceChildren(); return; } + const root = doc.vpc; + container.replaceChildren(); + byId('vpc-detail-title').textContent = root.name; + byId('vpc-detail-caption').textContent = `${root.cidr} · ${regionName(root.region_id)}`; + + const overview = element('section', 'vpc-detail-overview'); + const overviewHeading = element('div', 'vpc-detail-overview-heading'); + const status = rootStatus(root); + const rootHint = errorLabel(root.last_error_code); + overviewHeading.append(statusPill(status, root.last_error_code), + element('span', 'vpc-readback-note', root.usable === true + ? 'WireGuard、私网路由和实例网卡均已回读确认。' + : (rootHint || '配置仍在宿主机应用或核对,期间不要重复创建同一成员。'))); + const actions = element('div', 'vpc-detail-actions'); + const reconcile = button('核对 / 重试', 'button button-primary small'); + reconcile.dataset.vpcAction = 'reconcile'; reconcile.disabled = state.busy || status === 'active'; + actions.append(reconcile); + overviewHeading.append(actions); + const facts = element('dl', 'vpc-facts'); + facts.append(field('VPC CIDR', root.cidr), field('地区', regionName(root.region_id)), + field('目标 revision', root.desired_revision || 0), field('已观测 revision', root.observed_revision || 0), + field('同步状态', safeText(root.sync_state)), field('最近错误', root.last_error_code || '无')); + overview.append(overviewHeading, facts); + container.append(overview); + + container.append(renderSubnets(doc)); + container.append(renderMembers(doc)); + container.append(renderRoutes(doc)); + container.append(renderAcl(doc)); + container.append(renderOperations(doc)); + clearDetailDirty(); +} + +function renderSubnets(doc) { + const card = section('子网与 CIDR', '子网是 VPC 内的地址范围;当前数据面使用成员精确 /32,不自动提供网关。', 'vpc-subnets'); + const form = element('form', 'vpc-inline-form'); form.dataset.vpcForm = 'subnet'; + const cidr = input('新增子网 CIDR', '', 'text', '10.40.1.0/24'); + cidr.control.name = 'cidr'; cidr.control.required = true; cidr.control.maxLength = 18; + const save = button('添加子网', 'button button-primary small'); save.type = 'submit'; + form.append(cidr.wrapper, save); card.append(form); + const list = element('div', 'vpc-row-list'); + for (const row of doc.subnets) { + const item = element('div', 'vpc-data-row'); + const copy = element('div', 'vpc-row-copy'); + copy.append(element('strong', '', row.cidr || '未知子网'), element('small', '', `状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`)); + if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code)); + const remove = button('删除', 'button button-outline small danger'); + remove.dataset.vpcRemoveSubnet = row.subnet_key; + remove.disabled = state.busy || ['deleting', 'deleted'].includes(childStatus(row.state)); + item.append(copy, remove); list.append(item); + } + if (!doc.subnets.length) list.append(element('p', 'vpc-empty-inline', '暂无子网。')); + card.append(list); return card; +} + +function renderMembers(doc) { + const card = section('成员与私网 IP', '把同一地区的实例加入 VPC;私网 IP 由 PHP 租约账本分配并在宿主机回读后生效。', 'vpc-members'); + const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member'; + const subnet = input('加入子网', '', 'select'); subnet.control.name = 'subnet_key'; subnet.control.required = true; + for (const row of doc.subnets.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))) { + subnet.control.append(new Option(row.cidr, row.subnet_key)); + } + const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true; + const vpcRegionId = Number(doc.vpc.region_id || 0); + const attached = new Set(doc.members + .filter(item => childStatus(item.state) !== 'deleted') + .map(item => Number(item.instance_id))); + for (const row of state.instances.filter(item => item.service_available !== false)) { + const sameRegion = !row.region_id || Number(row.region_id) === vpcRegionId; + const alreadyAttached = attached.has(Number(row.id)); + const suffix = alreadyAttached ? ' · 已在当前 VPC' : (!sameRegion ? ' · 地区不匹配' : ''); + const option = new Option(`${row.name} · ${safeText(row.region, '地区待核验')}${suffix}`, String(row.id)); + option.dataset.regionId = row.region_id || ''; + option.disabled = alreadyAttached || !sameRegion; + instance.control.append(option); + } + const ip = input('指定私网 IP(可选)', '', 'text', '自动分配'); ip.control.name = 'private_ip'; ip.control.maxLength = 15; + const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit'; + form.append(subnet.wrapper, instance.wrapper, ip.wrapper, save); card.append(form); + const list = element('div', 'vpc-row-list'); + for (const row of doc.members.filter(item => childStatus(item.state) !== 'deleted')) { + const item = element('div', 'vpc-data-row'); + const copy = element('div', 'vpc-row-copy'); + copy.append(element('strong', '', `${instanceName(row.instance_id)} · ${safeText(row.private_ip)}`), + element('small', '', `${instanceRegion(row.instance_id)} · 状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`)); + if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code)); + const remove = button('退出 VPC', 'button button-outline small danger'); + remove.dataset.vpcRemoveMember = row.member_key; + remove.disabled = state.busy || childStatus(row.state) === 'deleting'; + item.append(copy, remove); list.append(item); + } + if (!doc.members.some(item => childStatus(item.state) !== 'deleted')) list.append(element('p', 'vpc-empty-inline', '暂无成员。')); + card.append(list); return card; +} + +function routeRow(value = {}) { + const row = element('div', 'vpc-editor-row'); + row.dataset.routeKey = value.route_key || entityKey(); + const destination = input('目标 /32', value.destination_cidr || '', 'text', '10.40.2.7/32'); + destination.control.dataset.routeField = 'destination_cidr'; + const nextHop = input('下一跳成员 IP', value.next_hop_ip || '', 'select'); + nextHop.control.dataset.routeField = 'next_hop_ip'; + const members = (state.selected?.members || []) + .filter(item => !['deleting', 'deleted'].includes(childStatus(item.state))); + let foundNextHop = false; + for (const member of members) { + const memberIp = String(member.private_ip || ''); + if (memberIp === String(value.next_hop_ip || '')) foundNextHop = true; + nextHop.control.append(new Option(`${safeText(member.private_ip)} · ${instanceName(member.instance_id)}`, memberIp)); + } + nextHop.control.value = String(value.next_hop_ip || ''); + if (!foundNextHop) { + row.dataset.invalid = 'true'; + if (value.next_hop_ip) { + const missing = new Option(`${value.next_hop_ip} · 成员状态待核验`, value.next_hop_ip); + missing.disabled = true; + nextHop.control.append(missing); + nextHop.control.value = String(value.next_hop_ip); + } + } + const metric = input('Metric', value.metric || 100, 'number'); metric.control.min = '1'; metric.control.max = '65535'; metric.control.dataset.routeField = 'metric'; + const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'route'; + row.append(destination.wrapper, nextHop.wrapper, metric.wrapper, remove); return row; +} + +function renderRoutes(doc) { + const card = section('Route', '路由目标当前限制为 VPC 内的精确 /32,下一跳必须是本 VPC 成员私网 IP。保存会替换整套路由。', 'vpc-routes'); + const list = element('div', 'vpc-editor-list'); list.id = 'vpc-route-editor'; + const tombstones = doc.routes.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state))); + const editable = doc.routes.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state))); + for (const row of editable) list.append(routeRow(row)); + for (const row of tombstones) { + const item = element('div', 'vpc-tombstone-row'); + item.dataset.vpcTombstone = 'true'; + item.dataset.vpcTombstoneState = childStatus(row.state); + const pending = childStatus(row.state) === 'deleting'; + item.append(element('strong', '', row.destination_cidr || '已删除路由'), + element('small', '', pending + ? '状态:清理中;完成前不能覆盖整套路由' + : '状态:已清理;这是历史记录,可继续编辑其他路由')); + list.append(item); + } + if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义路由;同 VPC 成员的 /32 由数据面维护。')); + const toolbar = element('div', 'vpc-editor-toolbar'); + const add = button('添加路由', 'button button-outline small'); add.dataset.editorAdd = 'route'; + const save = button('保存路由', 'button button-primary small'); save.dataset.vpcSave = 'routes'; + const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting'); + add.disabled = state.busy || pendingTombstones; + save.disabled = state.busy || pendingTombstones || Boolean(list.querySelector('[data-invalid="true"]')); + toolbar.append(add, save); card.append(list, toolbar); return card; +} + +function aclRow(value = {}) { + const row = element('div', 'vpc-editor-row vpc-acl-row'); + row.dataset.aclKey = value.rule_key || entityKey(); + const priority = input('优先级', value.priority || 100, 'number'); priority.control.min = '1'; priority.control.max = '1000000'; priority.control.dataset.aclField = 'priority'; + const direction = input('方向', '', 'select'); direction.control.dataset.aclField = 'direction'; + for (const option of [['ingress', '入站'], ['egress', '出站']]) direction.control.append(new Option(option[1], option[0])); + direction.control.value = value.direction || 'ingress'; + const action = input('动作', '', 'select'); action.control.dataset.aclField = 'action'; + for (const option of [['allow', '允许'], ['deny', '拒绝']]) action.control.append(new Option(option[1], option[0])); + action.control.value = value.action || 'deny'; + const protocol = input('协议', '', 'select'); protocol.control.dataset.aclField = 'protocol'; + for (const option of [['all', '全部'], ['tcp', 'TCP'], ['udp', 'UDP'], ['icmp', 'ICMP']]) protocol.control.append(new Option(option[1], option[0])); + protocol.control.value = value.protocol || 'all'; + const source = input('源 CIDR', value.source_cidr || '', 'text', '10.40.0.0/16'); source.control.dataset.aclField = 'source_cidr'; + const destination = input('目标 CIDR', value.destination_cidr || '', 'text', '10.40.0.0/16'); destination.control.dataset.aclField = 'destination_cidr'; + const from = input('起始端口', value.port_from ?? '', 'number', 'TCP/UDP 可选'); from.control.min = '1'; from.control.max = '65535'; from.control.dataset.aclField = 'port_from'; + const to = input('结束端口', value.port_to ?? '', 'number', 'TCP/UDP 可选'); to.control.min = '1'; to.control.max = '65535'; to.control.dataset.aclField = 'port_to'; + const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'acl'; + row.append(priority.wrapper, direction.wrapper, action.wrapper, protocol.wrapper, source.wrapper, destination.wrapper, from.wrapper, to.wrapper, remove); return row; +} + +function renderAcl(doc) { + const card = section('VPC ACL', '默认策略由数据面保持拒绝;这里只提交结构化规则,不会修改实例公网防火墙。保存会替换整套 ACL。', 'vpc-acl'); + const list = element('div', 'vpc-editor-list'); list.id = 'vpc-acl-editor'; + const tombstones = doc.acl_rules.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state))); + const editable = doc.acl_rules.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state))); + for (const row of editable) list.append(aclRow(row)); + for (const row of tombstones) { + const item = element('div', 'vpc-tombstone-row'); + item.dataset.vpcTombstone = 'true'; + item.dataset.vpcTombstoneState = childStatus(row.state); + const pending = childStatus(row.state) === 'deleting'; + item.append(element('strong', '', `规则 ${safeText(row.rule_key)}`), + element('small', '', pending + ? '状态:清理中;完成前不能覆盖整套 ACL' + : '状态:已清理;这是历史记录,可继续编辑其他规则')); + list.append(item); + } + if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义 ACL 规则。')); + const toolbar = element('div', 'vpc-editor-toolbar'); + const add = button('添加规则', 'button button-outline small'); add.dataset.editorAdd = 'acl'; + const save = button('保存 ACL', 'button button-primary small'); save.dataset.vpcSave = 'acl'; + const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting'); + add.disabled = state.busy || pendingTombstones; + save.disabled = state.busy || pendingTombstones; + toolbar.append(add, save); card.append(list, toolbar); return card; +} + +function renderOperations(doc) { + const card = section('最近操作', '每次修改都会生成独立的 VPC revision;只有宿主机精确回读后才会进入 active。', 'vpc-operations'); + const list = element('div', 'vpc-operation-list'); + for (const row of doc.operations.slice(0, 12)) { + const item = element('div', 'vpc-operation-row'); + item.append(element('span', '', safeText(row.kind)), statusPill(row.status === 'waiting_observed' ? 'waiting' : row.status), + element('small', '', `revision ${row.desired_revision || 0}${row.error_code ? ` · ${row.error_code}` : ''}`)); + list.append(item); + } + if (!doc.operations.length) list.append(element('p', 'vpc-empty-inline', '暂无操作记录。')); + card.append(list); return card; +} + +function createRegionOptions() { + const select = byId('vpc-create-region'); + select.replaceChildren(); + if (!state.regions.length) { + select.append(new Option('暂无可用 Fabric 地区', '')); + select.disabled = true; + byId('vpc-create-region-hint').textContent = '管理员尚未完成可用 Fabric 映射,暂不能创建 VPC。'; + return; + } + select.disabled = false; + select.append(new Option('请选择地区', '')); + for (const row of state.regions) select.append(new Option(String(row.name), String(row.id))); +} + +async function loadList(silent = false) { + const epoch = ++state.listEpoch; + state.listController?.abort(); state.listController = new AbortController(); + try { + const payload = await api('/api/v1/vpcs', { signal: state.listController.signal }); + if (epoch !== state.listEpoch || state.stopped) return; + state.vpcs = Array.isArray(payload?.vpcs) ? payload.vpcs.map(normalizeRoot).filter(Boolean) : []; + renderList(); + if (!silent) setError(''); + } catch (error) { + if (error?.name === 'AbortError') return; + if (!silent || !state.vpcs.length) setError(error.message); + } +} + +async function loadDetail(key, silent = false, allowDirty = false) { + if (!key) return; + if (state.detailDirty && !allowDirty) return; + const epoch = ++state.detailEpoch; + state.detailController?.abort(); state.detailController = new AbortController(); + try { + const payload = await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, { signal: state.detailController.signal }); + if (epoch !== state.detailEpoch || state.stopped || key !== state.selectedKey) return; + state.selected = normalizeDocument(payload); + byId('vpc-detail-panel').hidden = !state.selected; + renderDetail(); + if (!silent) setError(''); + } catch (error) { + if (error?.name === 'AbortError') return; + if (!silent) setError(error.message); + } +} + +async function selectVpc(key) { + if (state.detailDirty + && !confirm('当前 VPC 有未保存修改,切换后会丢失这些修改。继续吗?')) return; + clearDetailDirty(); + state.selectedKey = String(key || ''); + state.selected = null; + byId('vpc-detail-panel').hidden = !state.selectedKey; + renderList(); + await loadDetail(state.selectedKey); + schedulePoll(5000); +} + +async function applyDocument(payload, message = '') { + const doc = normalizeDocument(payload); + if (doc) { + clearDetailDirty(); + state.selected = doc; + state.selectedKey = doc.vpc.vpc_key; + if (!state.vpcs.some(item => item.vpc_key === doc.vpc.vpc_key)) state.vpcs.unshift(doc.vpc); + else state.vpcs = state.vpcs.map(item => item.vpc_key === doc.vpc.vpc_key ? doc.vpc : item); + byId('vpc-detail-panel').hidden = false; + renderList(); renderDetail(); + } + if (message) { setNotice(message, 'success'); toast(message, 'success'); } + schedulePoll(1500); +} + +async function mutate(path, method, body, message) { + if (state.busy) return null; + clearTimeout(state.pollTimer); + const controls = [...document.querySelectorAll('#vpc-workspace button, #vpc-workspace input, #vpc-workspace select')]; + const previousDisabled = new Map(controls.map(node => [node, node.disabled])); + state.busy = true; controls.forEach(node => { node.disabled = true; }); + let succeeded = false; + try { + const payload = await api(path, { method, body }); + await applyDocument(payload, message); + succeeded = true; + return payload; + } catch (error) { + setError(error.message); setNotice(''); return null; + } finally { + state.busy = false; + if (!succeeded) previousDisabled.forEach((disabled, node) => { node.disabled = disabled; }); + createRegionOptions(); renderList(); + if (succeeded && state.selected) renderDetail(); + else refreshRouteEditorState(); + schedulePoll(succeeded ? 1500 : undefined); + } +} + +async function createVpc(event) { + event.preventDefault(); if (state.busy) return; + setFormError('vpc-create-error', ''); setError(''); + clearTimeout(state.pollTimer); + const form = event.currentTarget; + const body = { + name: form.name.value.trim(), region_id: Number(form.region_id.value), + cidr: form.cidr.value.trim(), max_members: Number(form.max_members.value || 256), + }; + if (form.subnet_cidr.value.trim()) body.subnet_cidr = form.subnet_cidr.value.trim(); + // Keep one idempotency key for the same form values until the server has + // acknowledged the create. A lost 202 response must be retryable without + // allocating a second VPC/CIDR; changing the values starts a new intent. + const fingerprint = JSON.stringify(body); + if (form.dataset.requestFingerprint !== fingerprint + || !/^[A-Za-z0-9_.:-]{8,128}$/.test(form.dataset.requestKey || '')) { + form.dataset.requestKey = requestKey('vpc-create'); + form.dataset.requestFingerprint = fingerprint; + } + body.request_key = form.dataset.requestKey; + state.busy = true; + try { + const payload = await api('/api/v1/vpcs', { method: 'POST', body }); + delete form.dataset.requestKey; delete form.dataset.requestFingerprint; + form.reset(); form.max_members.value = '256'; + byId('vpc-create-panel').hidden = true; + await applyDocument(payload, 'VPC 已创建,正在等待宿主机回读。'); + } catch (error) { setFormError('vpc-create-error', error.message); } + finally { state.busy = false; createRegionOptions(); renderList(); schedulePoll(1500); } +} + +async function submitSubnet(form) { + if (!confirmDetailMutation()) return; + const value = form.cidr.value.trim(); + if (!value) return; + const payload = await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets`, 'POST', { + cidr: value, request_key: requestKey('subnet-add'), + }, '子网目标已提交,等待宿主机回读。'); + if (payload) form.reset(); +} + +async function submitMember(form) { + if (!confirmDetailMutation()) return; + const body = { subnet_key: form.subnet_key.value, instance_id: Number(form.instance_id.value), request_key: requestKey('member-add') }; + if (form.private_ip.value.trim()) body.private_ip = form.private_ip.value.trim(); + await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body, + '实例已加入 VPC 目标,私网网卡将在实际回读后显示为可用。'); +} + +function readRoutes() { + return [...document.querySelectorAll('#vpc-route-editor .vpc-editor-row')].map(row => ({ + route_key: row.dataset.routeKey, + destination_cidr: row.querySelector('[data-route-field="destination_cidr"]').value.trim(), + next_hop_ip: row.querySelector('[data-route-field="next_hop_ip"]').value, + metric: Number(row.querySelector('[data-route-field="metric"]').value || 100), + })); +} + +function readAcl() { + return [...document.querySelectorAll('#vpc-acl-editor .vpc-editor-row')].map(row => { + const value = fieldName => row.querySelector(`[data-acl-field="${fieldName}"]`).value.trim(); + const item = { + rule_key: row.dataset.aclKey, priority: Number(value('priority') || 100), + direction: value('direction'), action: value('action'), protocol: value('protocol'), + source_cidr: value('source_cidr'), destination_cidr: value('destination_cidr'), + port_from: value('port_from') === '' ? null : Number(value('port_from')), + port_to: value('port_to') === '' ? null : Number(value('port_to')), + }; + return item; + }); +} + +async function saveEditor(kind) { + if (kind === 'routes') { + refreshRouteEditorState(); + if (document.querySelector('#vpc-route-editor [data-vpc-tombstone-state="deleting"]')) { + setError('路由仍有删除中的记录,待宿主机回读完成后再保存整套路由。'); + return; + } + if (document.querySelector('#vpc-route-editor [data-invalid="true"]')) { + setError('路由下一跳必须选择当前仍在 VPC 中的成员私网 IP。'); + return; + } + } + if (kind === 'acl' && document.querySelector('#vpc-acl-editor [data-vpc-tombstone-state="deleting"]')) { + setError('ACL 仍有删除中的记录,待宿主机回读完成后再保存整套 ACL。'); + return; + } + const body = kind === 'routes' + ? { routes: readRoutes(), request_key: requestKey('routes') } + : { rules: readAcl(), request_key: requestKey('acl') }; + await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/${kind === 'routes' ? 'routes' : 'acl'}`, + 'PUT', body, `${kind === 'routes' ? '路由' : 'ACL'} 目标已提交,等待宿主机回读。`); +} + +async function reconcile() { + if (!state.selectedKey || state.busy) return; + if (state.detailDirty + && !confirm('当前 VPC 有未保存修改,核对后会丢失这些修改。继续吗?')) return; + await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/reconcile`, 'POST', {}, '已请求重新核对 VPC 状态。'); +} + +async function removeSubnet(key) { + if (!state.selectedKey || state.busy || !confirmDetailMutation() + || !confirm('确认删除这个子网?子网必须没有成员和地址租约。')) return; + await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets/${encodeURIComponent(key)}`, + 'DELETE', { request_key: requestKey('subnet-remove') }, '子网删除目标已提交。'); +} + +async function removeMember(key) { + if (!state.selectedKey || state.busy || !confirmDetailMutation() + || !confirm('确认让这个实例退出 VPC?宿主机回读确认前,私网 IP 不会重新分配。')) return; + await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members/${encodeURIComponent(key)}`, + 'DELETE', { request_key: requestKey('member-remove') }, '成员退出目标已提交,等待私网网卡移除回读。'); +} + +function handleClick(event) { + const listRow = event.target.closest('[data-vpc-key]'); + if (listRow && listRow.closest('#vpc-list')) { selectVpc(listRow.dataset.vpcKey); return; } + const removeSubnetKey = event.target.closest('[data-vpc-remove-subnet]')?.dataset.vpcRemoveSubnet; + if (removeSubnetKey) { removeSubnet(removeSubnetKey); return; } + const removeMemberKey = event.target.closest('[data-vpc-remove-member]')?.dataset.vpcRemoveMember; + if (removeMemberKey) { removeMember(removeMemberKey); return; } + const action = event.target.closest('[data-vpc-action]')?.dataset.vpcAction; + if (action === 'reconcile') { reconcile(); return; } + const add = event.target.closest('[data-editor-add]')?.dataset.editorAdd; + if (add) { + const list = byId(add === 'route' ? 'vpc-route-editor' : 'vpc-acl-editor'); + if (list.querySelector('[data-vpc-tombstone-state="deleting"]')) return; + list.querySelector('.vpc-empty-inline')?.remove(); + list.append(add === 'route' ? routeRow() : aclRow()); + markDetailDirty(); + refreshRouteEditorState(); + return; + } + const remove = event.target.closest('[data-editor-remove]')?.dataset.editorRemove; + if (remove) { + event.target.closest('.vpc-editor-row')?.remove(); markDetailDirty(); refreshRouteEditorState(); return; + } + const save = event.target.closest('[data-vpc-save]')?.dataset.vpcSave; + if (save) saveEditor(save); +} + +function handleSubmit(event) { + const kind = event.target.dataset.vpcForm; + if (kind === 'subnet') { event.preventDefault(); submitSubnet(event.target); } + if (kind === 'member') { event.preventDefault(); submitMember(event.target); } +} + +function handleDetailInput(event) { + if (event.target.closest('#vpc-detail')) { + markDetailDirty(); + if (event.target.matches('[data-route-field="next_hop_ip"]')) refreshRouteEditorState(); + } +} + +function readBootstrap() { + const node = byId('vpc-bootstrap'); + let payload; + try { payload = JSON.parse(node?.textContent || '{}'); } catch { throw new Error('VPC 页面初始数据无效,请刷新页面。'); } + const user = payload?.user; + if (!user || !/^[a-f0-9]{64}$/.test(String(user.csrf_token || '')) + || !/^[1-9]\d*$/.test(String(user.user_id || ''))) { + throw new Error('VPC 页面安全会话缺失,请刷新页面。'); + } + state.csrfToken = String(user.csrf_token); state.userId = String(user.user_id); + state.regions = Array.isArray(payload.regions) ? payload.regions : []; + state.instances = Array.isArray(payload.instances) ? payload.instances : []; + state.vpcs = Array.isArray(payload.vpcs) ? payload.vpcs.map(normalizeRoot).filter(Boolean) : []; +} + +function bind() { + byId('vpc-create-open').addEventListener('click', () => { + const form = byId('vpc-create-form'); + form.reset(); form.max_members.value = '256'; + delete form.dataset.requestKey; delete form.dataset.requestFingerprint; + byId('vpc-create-panel').hidden = false; byId('vpc-create-name').focus(); + }); + byId('vpc-create-close').addEventListener('click', () => { + const form = byId('vpc-create-form'); + byId('vpc-create-panel').hidden = true; + delete form.dataset.requestKey; delete form.dataset.requestFingerprint; + }); + byId('vpc-create-form').addEventListener('submit', createVpc); + byId('vpc-refresh').addEventListener('click', async () => { + if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return; + await loadList(); if (state.selectedKey) await loadDetail(state.selectedKey, false, true); schedulePoll(8000); + }); + byId('vpc-list-reconcile').addEventListener('click', reconcile); + byId('vpc-workspace').addEventListener('click', handleClick); + byId('vpc-workspace').addEventListener('submit', handleSubmit); + byId('vpc-workspace').addEventListener('input', handleDetailInput); + byId('vpc-workspace').addEventListener('change', handleDetailInput); + byId('vpc-detail-refresh').addEventListener('click', () => { + if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return; + loadDetail(state.selectedKey, false, true); + }); + document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') schedulePoll(1000); else clearTimeout(state.pollTimer); }); + window.addEventListener('beforeunload', () => { state.stopped = true; state.listController?.abort(); state.detailController?.abort(); clearTimeout(state.pollTimer); }, { once: true }); +} + +export async function initialize() { + try { + readBootstrap(); bind(); createRegionOptions(); renderList(); + await loadList(); + if (state.vpcs.length) await selectVpc(state.selectedKey || state.vpcs[0].vpc_key); + schedulePoll(3000); + } catch (error) { setError(error.message); } +} diff --git a/web/resources/views/venix/cloud/page.tpl b/web/resources/views/venix/cloud/page.tpl index 7cfd326c..21900332 100644 --- a/web/resources/views/venix/cloud/page.tpl +++ b/web/resources/views/venix/cloud/page.tpl @@ -9,6 +9,7 @@ + {if $cloud_page == 'vpcs'}{/if}
@@ -23,6 +24,8 @@ {if $cloud_page == 'instances'} {include file='cloud/pages/instances.tpl'} + {elseif $cloud_page == 'vpcs'} + {include file='cloud/pages/vpcs.tpl'} {elseif $cloud_page == 'detail'} {include file='cloud/pages/detail.tpl'} {elseif $cloud_page == 'deploy'} diff --git a/web/resources/views/venix/cloud/pages/vpcs.tpl b/web/resources/views/venix/cloud/pages/vpcs.tpl new file mode 100644 index 00000000..e55ba68b --- /dev/null +++ b/web/resources/views/venix/cloud/pages/vpcs.tpl @@ -0,0 +1,58 @@ +
+
+
+ PRIVATE NETWORK +

VPC 私网

+

在同一地区的实例之间建立受控三层私网。私网配置只有在宿主机实际回读确认后才会显示为可用。

+
+
+ + +
+
+ + + + +
+
VPC
0{$cloud_vpc_scope_label|default:'仅显示当前账户资源'}
+
已确认可用
0所有参与宿主机均已回读
+
需要关注
0正在应用或等待核对
+
+ +
+
+
+

VPC 列表

正在读取 VPC 状态…

+
+
+
+ +
+ + +
+ + + + +
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 90ef3d82..d7e6eab8 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100801' scope='global'} +{assign var=venix_asset_version value='2026100802' scope='global'} diff --git a/web/resources/views/venix/user/panel_sidebar.tpl b/web/resources/views/venix/user/panel_sidebar.tpl index 9a2f0736..c956c23d 100644 --- a/web/resources/views/venix/user/panel_sidebar.tpl +++ b/web/resources/views/venix/user/panel_sidebar.tpl @@ -17,6 +17,9 @@ 我的实例 + + VPC 私网 + 部署实例 diff --git a/web/tests/CloudVpcControlPlaneContractTest.php b/web/tests/CloudVpcControlPlaneContractTest.php index c55b81d1..145315e5 100644 --- a/web/tests/CloudVpcControlPlaneContractTest.php +++ b/web/tests/CloudVpcControlPlaneContractTest.php @@ -86,6 +86,31 @@ $assert(str_contains($service, "'observed_revision' => " . '$revision') && str_contains($service, 'CloudVpcAclRule::class') && str_contains($service, 'whereNotIn(\'state\', [\'deleted\'])'), 'VPC child observed revisions are not advanced with the all-host gate.'); +$assert(str_contains($service, 'deletedByDestination') + && str_contains($service, 'deletedByPriority') + && str_contains($service, 'CloudVpcRoute::class, CloudVpcAclRule::class') + && str_contains($service, '$allLiveHostsExact') + && str_contains($service, "where('desired_revision', \$revision)") + && str_contains($service, 'individually matched above'), + 'VPC route/ACL tombstones must close only after exact readback and remain safely reusable.'); +$terminalProofStart = strpos($service, '$noDataPlaneTerminalProof'); +$terminalProofEnd = $terminalProofStart === false ? false + : strpos($service, '// Routes and ACLs are part of the exact host dataplane digest.', + $terminalProofStart); +$terminalProofBlock = ($terminalProofStart !== false && $terminalProofEnd !== false) + ? substr($service, $terminalProofStart, $terminalProofEnd - $terminalProofStart) : ''; +$assert($terminalProofBlock !== '' + && str_contains($terminalProofBlock, '$terminalGate') + && str_contains($terminalProofBlock, '$required->count() === 0') + && str_contains($terminalProofBlock, '$liveRequired->count() === 0') + && str_contains($terminalProofBlock, '$hosts === []') + && str_contains($terminalProofBlock, '!$pendingHostTombstone') + && str_contains($terminalProofBlock, 'no_data_plane_terminal_proof') + && str_contains($terminalProofBlock, 'CloudVpcRoute::class, CloudVpcAclRule::class') + && !str_contains($terminalProofBlock, 'CloudVpcMember::class') + && !str_contains($terminalProofBlock, 'CloudVpcPrivateIp::class') + && !str_contains($terminalProofBlock, 'CloudVpcSubnet::class'), + 'Empty-VPC terminal proof may close only route/ACL tombstones and must not release private member resources.'); $assert(!str_contains($service, 'CloudJob') && !str_contains($service, 'network_change') && !str_contains($service, 'publicIpCidr'), diff --git a/web/tests/CloudVpcUserPageContractTest.php b/web/tests/CloudVpcUserPageContractTest.php new file mode 100644 index 00000000..fae066b7 --- /dev/null +++ b/web/tests/CloudVpcUserPageContractTest.php @@ -0,0 +1,136 @@ + (string) file_get_contents($root . '/' . $path); +$assert = static function ($condition, string $message): void { + if (!$condition) { + throw new RuntimeException($message); + } +}; + +$controller = $read('app/Controllers/CloudPageController.php'); +$pageService = $read('app/Services/Cloud/CloudVpcPageService.php'); +$middleware = $read('app/Middleware/CloudApi.php'); +$routes = $read('config/routes.php'); +$shell = $read('resources/views/venix/cloud/page.tpl'); +$template = $read('resources/views/venix/cloud/pages/vpcs.tpl'); +$sidebar = $read('resources/views/venix/user/panel_sidebar.tpl'); +$app = $read('public/cloud/app.js'); +$script = $read('public/cloud/vpc.js'); +$styles = $read('public/cloud/vpc.css'); + +$controllerStart = strpos($controller, 'public function vpcs('); +$controllerEnd = strpos($controller, 'public function detail(', $controllerStart ?: 0); +$controllerSection = $controllerStart !== false && $controllerEnd !== false + ? substr($controller, $controllerStart, $controllerEnd - $controllerStart) : ''; + +$assert($controllerSection !== '' + && str_contains($controllerSection, 'CloudAccess::actor(false)') + && str_contains($controllerSection, 'CloudVpcPageService::bootstrap($actor)') + && str_contains($controllerSection, 'CloudVpcService::listing($actor)') + && str_contains($controllerSection, "'cloud_vpc_bootstrap_json'") + && str_contains($controllerSection, '$this->safeJson($payload)'), + 'VPC page must use an owner-scoped, safe database bootstrap and the typed listing projection.'); +$assert(str_contains($controller, 'use App\\Services\\Cloud\\CloudVpcPageService;') + && str_contains($controller, "'cloud_vpc_bootstrap_json', '{}'") + && !str_contains($controllerSection, 'CloudEngineClient') + && !str_contains($controllerSection, 'CloudHost'), + 'VPC first paint must not contact libvirt or expose host inventory.'); + +$assert(str_contains($pageService, 'CloudRegionFabric') + && str_contains($pageService, "->where('cloud_region_fabrics.state', 'active')") + && str_contains($pageService, "->where('cloud_region_fabrics.fabric_revision', '>', 0)") + && str_contains($pageService, "->where('region.status', 'active')") + && str_contains($pageService, "->where('user_id', \$userId)") + && str_contains($pageService, "->where('status', 'active')") + && str_contains($pageService, "(string) \$row->service_status === 'active'") + && str_contains($pageService, "(int) \$row->expires_at > time()") + && str_contains($pageService, '->limit(200)') + && !str_contains($pageService, 'CloudEngineClient') + && !str_contains($pageService, "'host_id'"), + 'VPC bootstrap must expose only active Fabric regions and bounded owner-scoped instances.'); + +$assert(str_contains($routes, "\$this->get('/cloud/vpcs', 'App\\Controllers\\CloudPageController:vpcs');"), + 'Authenticated user routes must expose the VPC page.'); +$assert(str_contains($middleware, "^/api/v1/vpcs(?:/[0-9a-f]{32}(?:/.*)?)?\$#D") + && str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'), + 'VPC API requests must stay in the PHP/database-only auth lane.'); +$assert(str_contains($sidebar, 'href="/user/cloud/vpcs"') + && str_contains($sidebar, "panel_cloud_active_key == 'vpcs'") + && str_contains($sidebar, 'VPC 私网'), + 'The user cloud navigation must expose and mark the VPC page.'); +$assert(str_contains($shell, "cloud_page == 'vpcs'") + && str_contains($shell, "cloud/pages/vpcs.tpl") + && str_contains($shell, '/cloud/vpc.css'), + 'The cloud shell must load the dedicated VPC view and styles.'); +$assert(str_contains($app, "vpcs: '/cloud/vpc.js'"), + 'Cloud page module routing must load the VPC module.'); + +foreach ([ + 'vpc-create-form', 'vpc-create-region', 'vpc-create-cidr', 'vpc-create-subnet', + 'vpc-list', 'vpc-detail', 'vpc-list-reconcile', 'vpc-bootstrap', +] as $id) { + $assert(str_contains($template, 'id="' . $id . '"'), + 'VPC view is missing required control ' . $id . '.'); +} +foreach (['子网与 CIDR', '成员与私网 IP', 'Route', 'VPC ACL', '最近操作'] as $label) { + $assert(str_contains($script, $label), + 'VPC module is missing section ' . $label . '.'); +} +$assert(str_contains($template, '创建 VPC'), + 'VPC view is missing the create form.'); + +$assert(str_contains($script, "'/api/v1/vpcs'") + && str_contains($script, '/subnets') + && str_contains($script, '/members') + && str_contains($script, '/reconcile') + && str_contains($script, "kind === 'routes'") + && str_contains($script, ": 'acl'") + && str_contains($script, "'DELETE'") + && str_contains($script, "'PUT'"), + 'VPC module must cover create, subnet, member, route, ACL, reconcile and deletion APIs.'); + +$assert(str_contains($script, 'X-CSRF-Token') + && str_contains($script, 'credentials: \'same-origin\'') + && str_contains($script, 'request_key') + && str_contains($script, 'function entityKey()') + && str_contains($script, 'route_key: row.dataset.routeKey') + && str_contains($script, 'rule_key: row.dataset.aclKey'), + 'VPC mutations must use same-origin CSRF protection and separate idempotency/entity keys.'); + +foreach (['applying', 'degraded', 'uncertain', 'waiting', 'active'] as $status) { + $assert(str_contains($script, $status), + 'VPC UI lost state projection for ' . $status . '.'); +} +$assert(str_contains($script, 'usable === true') + && str_contains($script, 'desired_revision') + && str_contains($script, 'observed_revision') + && str_contains($script, 'setTimeout') + && str_contains($script, 'visibilitychange') + && str_contains($script, 'AbortController') + && str_contains($script, 'loadDetail(state.selectedKey, true)') + && str_contains($script, 'state.detailDirty') + && str_contains($script, 'allowDirty = false'), + 'VPC UI must poll desired/observed state, pause hidden tabs and only show active after usable readback.'); +$assert(str_contains($script, 'data-vpc-tombstone-state="deleting"') + && str_contains($script, 'pendingTombstones') + && str_contains($script, 'sameRegion') + && str_contains($script, 'alreadyAttached') + && str_contains($script, 'option.disabled') + && str_contains($script, 'requestFingerprint') + && str_contains($script, 'confirmDetailMutation'), + 'VPC editors must preserve dirty drafts, block only in-flight tombstones and constrain member choices.'); +$assert(!str_contains($script, '/internal/v1/') + && !str_contains($script, 'host_id') + && !str_contains($script, 'credential_cipher'), + 'Tenant VPC JavaScript must not call private engine endpoints or expose host credentials.'); + +$assert(str_contains($styles, '.vpc-state-pill') + && str_contains($styles, '.vpc-columns') + && str_contains($styles, '@media'), + 'VPC page needs dedicated state/list/detail responsive styling.'); + +echo "Tenant VPC page, API wiring and state-polling contract passed.\n";