From f6ea3a4f90639bb544b8a2649ea8ef6992308a61 Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 31 Oct 2026 06:38:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(admin-vpc):=20=E5=A2=9E=E5=8A=A0=E6=8E=A7?= =?UTF-8?q?=E5=88=B6=E9=9D=A2=E8=AF=BB=E6=A8=A1=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Cloud/CloudAdminVpcControlService.php | 586 ++++++++++++++++++ web/tests/CloudAdminVpcControlServiceTest.php | 285 +++++++++ 2 files changed, 871 insertions(+) create mode 100644 web/app/Services/Cloud/CloudAdminVpcControlService.php create mode 100644 web/tests/CloudAdminVpcControlServiceTest.php diff --git a/web/app/Services/Cloud/CloudAdminVpcControlService.php b/web/app/Services/Cloud/CloudAdminVpcControlService.php new file mode 100644 index 00000000..4ec69376 --- /dev/null +++ b/web/app/Services/Cloud/CloudAdminVpcControlService.php @@ -0,0 +1,586 @@ + self::overview($actor), + 'networks' => self::listing($actor, $input), + 'pools' => CloudAdminVpcCidrPoolService::listing(), + ]; + } + + public static function overview(array $actor): array + { + $sets = self::operationalSets(); + $total = CloudVpc::query()->where('active_claim', 1)->count(); + $portCount = CloudVpcPort::query()->where('active_claim', 1)->count(); + $batchCount = CloudVpcMembershipBatch::query() + ->where('active_claim', 1)->count(); + $degraded = count($sets['degraded']); + $changing = count($sets['changing']); + $attention = self::listing($actor, [ + 'state' => 'degraded', 'page' => 1, 'per_page' => 20, + ]); + return [ + 'feature' => [ + 'enabled' => CloudVpcFeature::enabled(), + 'settings_url' => '/admin/config', + ], + 'summary' => [ + 'total' => $total, + 'active' => max(0, $total - $degraded - $changing), + 'changing' => $changing, + 'degraded' => $degraded, + 'ports' => $portCount, + 'active_batches' => $batchCount, + ], + 'regions' => self::regionReadiness(), + 'attention' => $attention['items'], + 'updated_at' => time(), + ]; + } + + public static function listing(array $actor, array $input = []): array + { + $filters = self::filters($input); + $sets = self::operationalSets(); + $query = CloudVpc::query()->from('cloud_vpcs as vpc') + ->join('cloud_regions as region', 'region.id', '=', 'vpc.region_id') + ->leftJoin('user as owner', 'owner.id', '=', 'vpc.user_id') + ->where('vpc.active_claim', 1); + if ($filters['q'] !== '') { + $like = '%' . self::escapeLike($filters['q']) . '%'; + $query->where(static function ($search) use ($like): void { + $search->whereRaw("vpc.name LIKE ? ESCAPE '!'", [$like]) + ->orWhereRaw("vpc.vpc_key LIKE ? ESCAPE '!'", [$like]) + ->orWhereRaw("vpc.cidr LIKE ? ESCAPE '!'", [$like]) + ->orWhereRaw("owner.user_name LIKE ? ESCAPE '!'", [$like]) + ->orWhereRaw("owner.email LIKE ? ESCAPE '!'", [$like]); + }); + } + if ($filters['region_id'] > 0) { + $query->where('vpc.region_id', $filters['region_id']); + } + if ($filters['state'] === 'degraded') { + self::whereIds($query, $sets['degraded']); + } elseif ($filters['state'] === 'changing') { + self::whereIds($query, $sets['changing']); + } elseif ($filters['state'] === 'active') { + $excluded = array_values(array_unique(array_merge( + $sets['degraded'], $sets['changing'] + ))); + if ($excluded !== []) { + $query->whereNotIn('vpc.id', $excluded); + } + } + + $total = (clone $query)->count('vpc.id'); + $pages = max(1, (int) ceil($total / $filters['per_page'])); + $page = min($filters['page'], $pages); + $rows = $query->orderByDesc('vpc.updated_at')->orderByDesc('vpc.id') + ->forPage($page, $filters['per_page'])->get([ + 'vpc.*', 'region.name as region_name', + 'region.code as region_code', 'owner.user_name as owner_name', + 'owner.email as owner_email', + ]); + $ids = $rows->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $related = self::related($ids); + $items = $rows->map(static fn ($vpc): array => self::row( + $vpc, $actor, $sets, $related + ))->all(); + return [ + 'items' => $items, + 'filters' => $filters, + 'pagination' => [ + 'page' => $page, + 'per_page' => $filters['per_page'], + 'total' => $total, + 'total_pages' => $pages, + 'from' => $total === 0 ? 0 + : (($page - 1) * $filters['per_page']) + 1, + 'to' => min($total, $page * $filters['per_page']), + ], + ]; + } + + public static function detail(array $actor, int $vpcId): array + { + if ($vpcId < 1) { + throw new CloudError('VPC 不存在', 404); + } + $vpc = CloudVpc::query()->from('cloud_vpcs as vpc') + ->join('cloud_regions as region', 'region.id', '=', 'vpc.region_id') + ->leftJoin('user as owner', 'owner.id', '=', 'vpc.user_id') + ->where('vpc.id', $vpcId)->where('vpc.active_claim', 1) + ->first([ + 'vpc.*', 'region.name as region_name', + 'region.code as region_code', 'owner.user_name as owner_name', + 'owner.email as owner_email', + ]); + if ($vpc === null) { + throw new CloudError('VPC 不存在或已经删除', 404); + } + $sets = self::operationalSets(); + $related = self::related([$vpcId]); + $ports = CloudVpcPort::query()->from('cloud_vpc_ports as port') + ->leftJoin('cloud_instances as instance', + 'instance.id', '=', 'port.instance_id') + ->leftJoin('cloud_hosts as host', 'host.id', '=', + 'instance.host_id') + ->where('port.vpc_id', $vpcId)->where('port.active_claim', 1) + ->orderBy('port.id')->get([ + 'port.*', 'instance.name as instance_name', + 'instance.uuid as instance_uuid', + 'instance.spec_json as instance_spec_json', + 'instance.host_id as current_host_id', + 'host.name as host_name', + ])->map(static function ($port): array { + $spec = json_decode((string) ($port->instance_spec_json ?? ''), + true); + $public = is_array($spec) + ? (string) ($spec['public_ip'] + ?? explode('/', (string) ($spec['public_ip_cidr'] ?? ''), + 2)[0]) : ''; + return [ + 'id' => (int) $port->id, + 'instance_id' => (int) $port->instance_id, + 'instance_name' => (string) ($port->instance_name ?? ''), + 'instance_uuid' => (string) ($port->instance_uuid ?? ''), + 'host_id' => (int) ($port->migration_host_id + ?? $port->current_host_id ?? 0), + 'host_name' => (string) ($port->host_name ?? ''), + 'public_ip' => $public, + 'private_ip' => (string) $port->private_ip, + 'mac_address' => (string) $port->mac_address, + 'state' => (string) $port->state, + 'desired_revision' => (int) $port->desired_revision, + 'applied_revision' => (int) $port->applied_revision, + 'last_operation_id' => + (string) ($port->last_operation_id ?? ''), + 'last_error_code' => (string) $port->last_error_code, + 'updated_at' => (int) $port->updated_at, + 'instance_url' => '/admin/cloud/instances?q=' . rawurlencode( + (string) ($port->instance_uuid ?? $port->instance_id) + ), + ]; + })->all(); + $hostStates = CloudVpcHostState::query() + ->from('cloud_vpc_host_states as state') + ->leftJoin('cloud_hosts as host', 'host.id', '=', 'state.host_id') + ->where('state.vpc_id', $vpcId)->orderBy('state.host_id') + ->get(['state.*', 'host.name as host_name']) + ->map(static fn ($state): array => self::hostState($state))->all(); + $batches = CloudVpcMembershipBatch::query() + ->where('vpc_id', $vpcId)->orderByDesc('id')->limit(10)->get() + ->map(static fn ($batch): array => self::batch($batch))->all(); + $batchIds = array_column($batches, 'id'); + $jobs = CloudJob::query()->where(static function ($query) use ( + $vpcId, $batchIds + ): void { + $query->where('vpc_id', $vpcId); + if ($batchIds !== []) { + $query->orWhereIn('vpc_batch_id', $batchIds); + } + })->orderByDesc('id')->limit(20)->get([ + 'id', 'operation_id', 'kind', 'phase', 'outcome', 'status', + 'error_code', 'vpc_batch_id', 'created_at', 'updated_at', + ])->map(static fn ($job): array => [ + 'id' => (int) $job->id, + 'operation_id' => (string) $job->operation_id, + 'kind' => (string) $job->kind, + 'phase' => (string) $job->phase, + 'outcome' => $job->outcome === null + ? null : (string) $job->outcome, + 'status' => (string) $job->status, + 'error_code' => (string) ($job->error_code ?? ''), + 'batch_id' => $job->vpc_batch_id === null + ? null : (int) $job->vpc_batch_id, + 'updated_at' => (int) $job->updated_at, + 'url' => '/admin/operations?q=' . (int) $job->id, + ])->all(); + return [ + 'vpc' => self::row($vpc, $actor, $sets, $related), + 'ports' => $ports, + 'host_states' => $hostStates, + 'batches' => $batches, + 'jobs' => $jobs, + ]; + } + + private static function regionReadiness(): array + { + $poolPayload = CloudAdminVpcCidrPoolService::listing(); + $eligibleRegionIds = CloudVpcRegionReadiness::eligibleRegionIds(); + $poolSummary = []; + foreach ($poolPayload['items'] as $pool) { + $regionId = (int) $pool['region_id']; + $poolSummary[$regionId]['pools_total'] = + ($poolSummary[$regionId]['pools_total'] ?? 0) + 1; + if ($pool['state'] === 'active') { + $poolSummary[$regionId]['pools_active'] = + ($poolSummary[$regionId]['pools_active'] ?? 0) + 1; + $poolSummary[$regionId]['capacity'] = + ($poolSummary[$regionId]['capacity'] ?? 0) + + (int) $pool['capacity']; + $poolSummary[$regionId]['used'] = + ($poolSummary[$regionId]['used'] ?? 0) + + (int) $pool['used']; + $poolSummary[$regionId]['available'] = + ($poolSummary[$regionId]['available'] ?? 0) + + (int) $pool['available']; + } + } + $hostRows = CloudHost::query()->from('cloud_hosts as host') + ->join('cloud_host_resource_pool_memberships as membership', + 'membership.host_id', '=', 'host.id') + ->join('cloud_resource_pools as resource_pool', + 'resource_pool.id', '=', 'membership.resource_pool_id') + ->join('cloud_network_lines as network_line', + 'network_line.id', '=', 'resource_pool.line_id') + ->leftJoin('cloud_host_vpc_transports as transport', + 'transport.host_id', '=', 'host.id') + ->get([ + 'host.id', 'host.enabled', 'membership.scheduler_state', + 'resource_pool.status as pool_status', + 'network_line.status as line_status', + 'network_line.region_id', + 'transport.sync_state', 'transport.desired_revision', + 'transport.observed_revision', 'transport.last_error_code', + ]); + $hosts = []; + foreach ($hostRows as $row) { + $regionId = (int) $row->region_id; + $hostId = (int) $row->id; + $schedulable = (bool) $row->enabled + && (string) $row->scheduler_state === 'active' + && (string) $row->pool_status === 'active' + && (string) $row->line_status === 'active'; + $ready = $schedulable && (string) $row->sync_state === 'ready' + && (int) $row->desired_revision + === (int) $row->observed_revision; + $hosts[$regionId][$hostId]['schedulable'] = + ($hosts[$regionId][$hostId]['schedulable'] ?? false) + || $schedulable; + $hosts[$regionId][$hostId]['ready'] = + ($hosts[$regionId][$hostId]['ready'] ?? false) || $ready; + if ((string) ($row->last_error_code ?? '') !== '') { + $hosts[$regionId][$hostId]['error'] = + (string) $row->last_error_code; + } + } + $regions = CloudRegion::query()->orderBy('sort')->orderBy('id')->get([ + 'id', 'code', 'name', 'country_code', 'status', + ]); + return $regions->map(static function ($region) use ( + $poolSummary, $hosts, $eligibleRegionIds + ): array { + $id = (int) $region->id; + $pool = $poolSummary[$id] ?? []; + $regionHosts = $hosts[$id] ?? []; + $hostTotal = count($regionHosts); + $schedulable = count(array_filter($regionHosts, + static fn (array $host): bool => $host['schedulable'])); + $ready = count(array_filter($regionHosts, + static fn (array $host): bool => $host['ready'])); + $hasReadyHost = in_array($id, $eligibleRegionIds, true); + $blockers = []; + if ((string) $region->status !== 'active') { + $blockers[] = ['code' => 'region_disabled', + 'label' => '地区已停用']; + } + if ((int) ($pool['pools_active'] ?? 0) === 0) { + $blockers[] = ['code' => 'pool_unavailable', + 'label' => '没有启用中的 VPC 地址池']; + } elseif ((int) ($pool['available'] ?? 0) === 0) { + $blockers[] = ['code' => 'pool_exhausted', + 'label' => 'VPC 地址空间已用尽']; + } + if ($schedulable === 0) { + $blockers[] = ['code' => 'host_unavailable', + 'label' => '没有可调度计算节点']; + } elseif (!$hasReadyHost) { + $blockers[] = ['code' => 'transport_unverified', + 'label' => '计算节点 VPC 传输尚未验证']; + } + return [ + 'id' => $id, + 'code' => (string) $region->code, + 'name' => (string) $region->name, + 'country_code' => (string) $region->country_code, + 'status' => (string) $region->status, + 'pools_total' => (int) ($pool['pools_total'] ?? 0), + 'pools_active' => (int) ($pool['pools_active'] ?? 0), + 'capacity' => (int) ($pool['capacity'] ?? 0), + 'used' => (int) ($pool['used'] ?? 0), + 'available' => (int) ($pool['available'] ?? 0), + 'hosts_total' => $hostTotal, + 'hosts_schedulable' => $schedulable, + 'hosts_ready' => $ready, + 'ready' => $blockers === [] && $hasReadyHost, + 'blockers' => $blockers, + ]; + })->all(); + } + + private static function filters(array $input): array + { + $q = trim((string) ($input['q'] ?? '')); + if (mb_strlen($q) > 120) { + throw new CloudError('VPC 搜索条件不能超过 120 个字符'); + } + $state = (string) ($input['state'] ?? ''); + if (!in_array($state, self::FILTER_STATES, true)) { + throw new CloudError('VPC 状态筛选无效'); + } + $region = filter_var($input['region_id'] ?? 0, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]); + $page = filter_var($input['page'] ?? 1, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + $perPage = filter_var($input['per_page'] ?? 20, + FILTER_VALIDATE_INT); + if ($region === false || $page === false + || $perPage === false || !in_array($perPage, + self::PER_PAGE, true)) { + throw new CloudError('VPC 分页或地区筛选无效'); + } + return ['q' => $q, 'state' => $state, + 'region_id' => $region, 'page' => $page, 'per_page' => $perPage]; + } + + private static function operationalSets(): array + { + $degraded = CloudVpc::query()->where('active_claim', 1) + ->where('state', 'degraded')->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $degraded = array_merge($degraded, + CloudVpcPort::query()->from('cloud_vpc_ports as port') + ->join('cloud_vpcs as port_vpc', + 'port_vpc.id', '=', 'port.vpc_id') + ->where('port.active_claim', 1) + ->where('port_vpc.active_claim', 1) + ->where('port.last_error_code', '<>', '') + ->pluck('port.vpc_id')->map( + static fn ($id): int => (int) $id + )->all(), + CloudVpcHostState::query()->from('cloud_vpc_host_states as host_state') + ->join('cloud_vpcs as host_vpc', + 'host_vpc.id', '=', 'host_state.vpc_id') + ->where('host_vpc.active_claim', 1) + ->where(static function ($query): void { + $query->whereIn('host_state.sync_state', + ['failed', 'unknown']) + ->orWhere('host_state.last_error_code', '<>', '') + ->orWhere(static function ($readyMismatch): void { + $readyMismatch->where( + 'host_state.sync_state', 'ready' + )->where(static function ($mismatch): void { + $mismatch->whereColumn( + 'host_state.desired_revision', '<>', + 'host_state.applied_revision' + )->orWhereNull('host_state.applied_digest') + ->orWhereColumn( + 'host_state.desired_digest', '<>', + 'host_state.applied_digest' + ); + }); + }); + })->pluck('host_state.vpc_id')->map( + static fn ($id): int => (int) $id + )->all(), + CloudVpcMembershipBatch::query() + ->from('cloud_vpc_membership_batches as batch') + ->join('cloud_vpcs as batch_vpc', + 'batch_vpc.id', '=', 'batch.vpc_id') + ->where('batch.active_claim', 1) + ->where('batch_vpc.active_claim', 1) + ->where('batch.state', 'blocked') + ->pluck('batch.vpc_id')->map( + static fn ($id): int => (int) $id + )->all() + ); + $degraded = array_values(array_unique($degraded)); + $changing = array_merge( + CloudVpc::query()->where('active_claim', 1) + ->whereIn('state', ['provisioning', 'deleting']) + ->pluck('id')->map(static fn ($id): int => (int) $id)->all(), + CloudVpcMembershipBatch::query() + ->from('cloud_vpc_membership_batches as active_batch') + ->join('cloud_vpcs as active_batch_vpc', + 'active_batch_vpc.id', '=', 'active_batch.vpc_id') + ->where('active_batch.active_claim', 1) + ->where('active_batch_vpc.active_claim', 1) + ->pluck('active_batch.vpc_id')->map( + static fn ($id): int => (int) $id + )->all(), + CloudVpcHostState::query() + ->from('cloud_vpc_host_states as pending_state') + ->join('cloud_vpcs as pending_vpc', + 'pending_vpc.id', '=', 'pending_state.vpc_id') + ->where('pending_vpc.active_claim', 1) + ->whereIn('pending_state.sync_state', ['pending', 'applying']) + ->pluck('pending_state.vpc_id')->map( + static fn ($id): int => (int) $id + )->all() + ); + $changing = array_values(array_diff(array_unique($changing), $degraded)); + return ['degraded' => $degraded, 'changing' => $changing]; + } + + private static function related(array $ids): array + { + if ($ids === []) { + return ['ports' => [], 'hosts' => [], 'batches' => []]; + } + $ports = CloudVpcPort::query()->whereIn('vpc_id', $ids) + ->where('active_claim', 1) + ->selectRaw('vpc_id, COUNT(*) AS row_count') + ->groupBy('vpc_id')->pluck('row_count', 'vpc_id')->all(); + $hosts = CloudVpcHostState::query()->whereIn('vpc_id', $ids) + ->orderBy('host_id')->get()->groupBy('vpc_id')->map( + static function ($states): array { + $ready = 0; + foreach ($states as $state) { + if (self::hostReady($state)) { + $ready++; + } + } + return ['total' => $states->count(), 'ready' => $ready]; + } + )->all(); + $batches = CloudVpcMembershipBatch::query()->whereIn('vpc_id', $ids) + ->where('active_claim', 1)->orderByDesc('id')->get() + ->keyBy('vpc_id')->map(static fn ($batch): array => + self::batch($batch))->all(); + return ['ports' => $ports, 'hosts' => $hosts, 'batches' => $batches]; + } + + private static function row($vpc, array $actor, array $sets, + array $related): array + { + $id = (int) $vpc->id; + $state = in_array($id, $sets['degraded'], true) ? 'degraded' + : (in_array($id, $sets['changing'], true) ? 'changing' : 'active'); + $display = [ + 'active' => ['label' => '正常', 'tone' => 'success'], + 'changing' => ['label' => '变更中', 'tone' => 'warning'], + 'degraded' => ['label' => '需要处理', 'tone' => 'danger'], + ][$state]; + $hosts = $related['hosts'][$id] ?? ['total' => 0, 'ready' => 0]; + return [ + 'id' => $id, + 'vpc_key' => (string) $vpc->vpc_key, + 'name' => (string) $vpc->name, + 'user_id' => (int) $vpc->user_id, + 'owner_name' => AdminDataMasker::account( + (string) ($vpc->owner_name ?? '') + ), + 'owner_email' => AdminDataMasker::email( + (string) ($vpc->owner_email ?? '') + ), + 'owner_url' => ($actor['is_super_admin'] ?? false) + && ($actor['can_manage'] ?? false) + ? '/admin/user/' . (int) $vpc->user_id . '/edit' : '', + 'region_id' => (int) $vpc->region_id, + 'region_name' => (string) ($vpc->region_name ?? ''), + 'region_code' => (string) ($vpc->region_code ?? ''), + 'cidr' => (string) $vpc->cidr, + 'gateway' => (string) $vpc->gateway, + 'desired_revision' => (int) $vpc->desired_revision, + 'state' => $state, + 'raw_state' => (string) $vpc->state, + 'display' => $display, + 'port_count' => (int) ($related['ports'][$id] ?? 0), + 'host_summary' => [ + 'total' => (int) $hosts['total'], + 'ready' => (int) $hosts['ready'], + ], + 'active_batch' => $related['batches'][$id] ?? null, + 'updated_at' => (int) $vpc->updated_at, + ]; + } + + private static function batch($batch): array + { + return [ + 'id' => (int) $batch->id, + 'batch_key' => (string) $batch->batch_key, + 'job_id' => (int) $batch->parent_job_id, + 'kind' => (string) $batch->kind, + 'state' => (string) $batch->state, + 'desired_revision' => (int) $batch->desired_revision, + 'active' => $batch->active_claim !== null, + 'last_error_code' => (string) $batch->last_error_code, + 'terminal_at' => $batch->terminal_at === null + ? null : (int) $batch->terminal_at, + 'updated_at' => (int) $batch->updated_at, + 'job_url' => '/admin/operations?q=' . (int) $batch->parent_job_id, + ]; + } + + private static function hostState($state): array + { + return [ + 'id' => (int) $state->id, + 'host_id' => (int) $state->host_id, + 'host_name' => (string) ($state->host_name ?? ''), + 'sync_state' => (string) $state->sync_state, + 'desired_revision' => (int) $state->desired_revision, + 'applied_revision' => (int) $state->applied_revision, + 'digest_match' => $state->applied_digest !== null + && hash_equals((string) $state->desired_digest, + (string) $state->applied_digest), + 'ready' => self::hostReady($state), + 'last_operation_id' => + (string) ($state->last_operation_id ?? ''), + 'last_error_code' => (string) $state->last_error_code, + 'last_success_at' => (int) $state->last_success_at, + 'last_failure_at' => (int) $state->last_failure_at, + 'updated_at' => (int) $state->updated_at, + 'host_url' => '/admin/hosts?q=' . (int) $state->host_id, + ]; + } + + private static function hostReady($state): bool + { + return (string) $state->sync_state === 'ready' + && (int) $state->desired_revision === (int) $state->applied_revision + && $state->applied_digest !== null + && hash_equals((string) $state->desired_digest, + (string) $state->applied_digest) + && (string) $state->last_error_code === ''; + } + + private static function whereIds($query, array $ids): void + { + if ($ids === []) { + $query->whereRaw('1 = 0'); + return; + } + $query->whereIn('vpc.id', $ids); + } + + private static function escapeLike(string $value): string + { + return str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value); + } +} diff --git a/web/tests/CloudAdminVpcControlServiceTest.php b/web/tests/CloudAdminVpcControlServiceTest.php new file mode 100644 index 00000000..3595fb63 --- /dev/null +++ b/web/tests/CloudAdminVpcControlServiceTest.php @@ -0,0 +1,285 @@ +addConnection(['driver' => 'sqlite', 'database' => ':memory:'], + 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); +$schema->create('configurations', static function (Blueprint $table): void { + $table->increments('id'); $table->string('name'); $table->string('value'); +}); +$schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); $table->string('user_name'); + $table->string('email'); +}); +$schema->create('cloud_regions', static function (Blueprint $table): void { + $table->increments('id'); $table->string('code'); $table->string('name'); + $table->string('country_code', 2); $table->string('status'); + $table->integer('sort'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $table): void { + $table->increments('id'); $table->integer('region_id'); + $table->string('status'); +}); +$schema->create('cloud_resource_pools', static function (Blueprint $table): void { + $table->increments('id'); $table->integer('line_id'); + $table->string('status'); +}); +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); $table->string('name'); + $table->string('region'); $table->boolean('enabled'); +}); +$schema->create('cloud_host_resource_pool_memberships', + static function (Blueprint $table): void { + $table->increments('id'); $table->integer('host_id'); + $table->integer('resource_pool_id'); $table->string('scheduler_state'); + }); +$schema->create('cloud_host_vpc_transports', + static function (Blueprint $table): void { + $table->integer('host_id')->primary(); $table->string('sync_state'); + $table->integer('desired_revision'); $table->integer('observed_revision'); + $table->string('last_error_code')->default(''); + }); +$schema->create('cloud_vpc_cidr_pools', + static function (Blueprint $table): void { + $table->increments('id'); $table->string('pool_key'); + $table->integer('region_id'); $table->string('name'); + $table->string('cidr'); $table->integer('prefix_length'); + $table->integer('allocation_prefix'); $table->string('state'); + $table->integer('revision'); $table->integer('created_at'); + $table->integer('updated_at'); + }); +$schema->create('cloud_vpcs', static function (Blueprint $table): void { + $table->increments('id'); $table->string('vpc_key'); + $table->integer('user_id'); $table->integer('region_id'); + $table->integer('cidr_pool_id'); $table->string('name'); + $table->string('cidr'); $table->integer('prefix_length'); + $table->string('gateway'); $table->integer('active_claim')->nullable(); + $table->string('state'); $table->integer('desired_revision'); + $table->integer('deleted_at')->nullable(); $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); $table->string('uuid'); + $table->integer('host_id'); $table->integer('user_id'); + $table->string('name'); $table->text('spec_json'); +}); +$schema->create('cloud_vpc_ports', static function (Blueprint $table): void { + $table->increments('id'); $table->string('port_key'); + $table->integer('vpc_id'); $table->integer('instance_id'); + $table->integer('migration_host_id')->nullable(); + $table->integer('user_id'); $table->string('private_ip'); + $table->string('mac_address'); $table->integer('active_claim')->nullable(); + $table->string('state'); $table->integer('desired_revision'); + $table->integer('applied_revision'); + $table->string('last_operation_id')->nullable(); + $table->string('last_error_code')->default(''); + $table->integer('attached_at')->nullable(); + $table->integer('released_at')->nullable(); + $table->integer('created_at'); $table->integer('updated_at'); +}); +$schema->create('cloud_vpc_host_states', + static function (Blueprint $table): void { + $table->increments('id'); $table->integer('vpc_id'); + $table->integer('host_id'); $table->integer('desired_revision'); + $table->integer('applied_revision'); $table->string('desired_digest'); + $table->string('applied_digest')->nullable(); + $table->string('sync_state'); + $table->string('last_operation_id')->nullable(); + $table->string('last_error_code')->default(''); + $table->integer('last_success_at'); $table->integer('last_failure_at'); + $table->integer('created_at'); $table->integer('updated_at'); + }); +$schema->create('cloud_vpc_membership_batches', + static function (Blueprint $table): void { + $table->increments('id'); $table->string('batch_key'); + $table->integer('vpc_id'); $table->integer('user_id'); + $table->integer('parent_job_id'); $table->string('kind'); + $table->string('state'); $table->integer('desired_revision'); + $table->integer('active_claim')->nullable(); + $table->string('last_error_code')->default(''); + $table->integer('terminal_at')->nullable(); + $table->integer('created_at'); $table->integer('updated_at'); + }); +$schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); $table->string('operation_id'); + $table->string('kind'); $table->string('phase'); + $table->string('outcome')->nullable(); $table->string('status'); + $table->string('error_code')->nullable(); + $table->integer('vpc_id')->nullable(); + $table->integer('vpc_batch_id')->nullable(); + $table->integer('created_at'); $table->integer('updated_at'); +}); + +Capsule::table('configurations')->insert([ + 'name' => 'cloud_vpc_enabled', 'value' => 'true', +]); +Capsule::table('user')->insert([ + ['id' => 7, 'user_name' => 'alice', 'email' => 'alice@example.test'], + ['id' => 8, 'user_name' => 'bob', 'email' => 'bob@example.test'], +]); +Capsule::table('cloud_regions')->insert([ + ['id' => 1, 'code' => 'hkg', 'name' => '香港', + 'country_code' => 'HK', 'status' => 'active', 'sort' => 0], + ['id' => 2, 'code' => 'nrt', 'name' => '东京', + 'country_code' => 'JP', 'status' => 'active', 'sort' => 1], +]); +Capsule::table('cloud_network_lines')->insert([ + 'id' => 1, 'region_id' => 1, 'status' => 'active', +]); +Capsule::table('cloud_resource_pools')->insert([ + 'id' => 1, 'line_id' => 1, 'status' => 'active', +]); +Capsule::table('cloud_hosts')->insert([ + 'id' => 1, 'name' => 'HKG-A', 'region' => 'HongKong', 'enabled' => 1, +]); +Capsule::table('cloud_host_resource_pool_memberships')->insert([ + 'id' => 1, 'host_id' => 1, 'resource_pool_id' => 1, + 'scheduler_state' => 'active', +]); +Capsule::table('cloud_host_vpc_transports')->insert([ + 'host_id' => 1, 'sync_state' => 'ready', 'desired_revision' => 3, + 'observed_revision' => 3, 'last_error_code' => '', +]); +Capsule::table('cloud_vpc_cidr_pools')->insert([ + 'id' => 1, 'pool_key' => str_repeat('a', 32), 'region_id' => 1, + 'name' => 'HKG Private', 'cidr' => '10.0.0.0/24', + 'prefix_length' => 24, 'allocation_prefix' => 28, 'state' => 'active', + 'revision' => 1, 'created_at' => 1, 'updated_at' => 1, +]); +Capsule::table('cloud_vpcs')->insert([ + ['id' => 1, 'vpc_key' => str_repeat('1', 32), 'user_id' => 7, + 'region_id' => 1, 'cidr_pool_id' => 1, 'name' => 'production', + 'cidr' => '10.0.0.0/28', 'prefix_length' => 28, + 'gateway' => '10.0.0.1', 'active_claim' => 1, 'state' => 'active', + 'desired_revision' => 2, 'deleted_at' => null, + 'created_at' => 10, 'updated_at' => 20], + ['id' => 2, 'vpc_key' => str_repeat('2', 32), 'user_id' => 8, + 'region_id' => 1, 'cidr_pool_id' => 1, 'name' => 'staging', + 'cidr' => '10.0.0.16/28', 'prefix_length' => 28, + 'gateway' => '10.0.0.17', 'active_claim' => 1, + 'state' => 'degraded', 'desired_revision' => 4, + 'deleted_at' => null, 'created_at' => 11, 'updated_at' => 30], +]); +Capsule::table('cloud_instances')->insert([ + ['id' => 11, 'uuid' => '11111111-1111-4111-8111-111111111111', + 'host_id' => 1, 'user_id' => 7, 'name' => 'vm-prod', + 'spec_json' => json_encode(['public_ip' => '192.0.2.11'])], + ['id' => 12, 'uuid' => '22222222-2222-4222-8222-222222222222', + 'host_id' => 1, 'user_id' => 8, 'name' => 'vm-stage', + 'spec_json' => json_encode(['public_ip_cidr' => '192.0.2.12/24'])], +]); +Capsule::table('cloud_vpc_ports')->insert([ + ['id' => 1, 'port_key' => str_repeat('3', 32), 'vpc_id' => 1, + 'instance_id' => 11, 'migration_host_id' => null, 'user_id' => 7, + 'private_ip' => '10.0.0.2', 'mac_address' => '02:00:00:00:00:01', + 'active_claim' => 1, 'state' => 'attached', 'desired_revision' => 2, + 'applied_revision' => 2, 'last_operation_id' => str_repeat('a', 32), + 'last_error_code' => '', 'attached_at' => 20, 'released_at' => null, + 'created_at' => 10, 'updated_at' => 20], + ['id' => 2, 'port_key' => str_repeat('4', 32), 'vpc_id' => 2, + 'instance_id' => 12, 'migration_host_id' => null, 'user_id' => 8, + 'private_ip' => '10.0.0.18', 'mac_address' => '02:00:00:00:00:02', + 'active_claim' => 1, 'state' => 'attached', 'desired_revision' => 4, + 'applied_revision' => 3, 'last_operation_id' => str_repeat('b', 32), + 'last_error_code' => 'vpc_result_uncertain', 'attached_at' => 21, + 'released_at' => null, 'created_at' => 11, 'updated_at' => 30], +]); +$digest = str_repeat('d', 64); +Capsule::table('cloud_vpc_host_states')->insert([ + ['id' => 1, 'vpc_id' => 1, 'host_id' => 1, 'desired_revision' => 2, + 'applied_revision' => 2, 'desired_digest' => $digest, + 'applied_digest' => $digest, 'sync_state' => 'ready', + 'last_operation_id' => str_repeat('c', 32), 'last_error_code' => '', + 'last_success_at' => 20, 'last_failure_at' => 0, + 'created_at' => 10, 'updated_at' => 20], + ['id' => 2, 'vpc_id' => 2, 'host_id' => 1, 'desired_revision' => 4, + 'applied_revision' => 3, 'desired_digest' => str_repeat('e', 64), + 'applied_digest' => null, 'sync_state' => 'unknown', + 'last_operation_id' => str_repeat('f', 32), + 'last_error_code' => 'vpc_result_uncertain', + 'last_success_at' => 0, 'last_failure_at' => 30, + 'created_at' => 11, 'updated_at' => 30], +]); +Capsule::table('cloud_vpc_membership_batches')->insert([ + 'id' => 1, 'batch_key' => str_repeat('5', 32), 'vpc_id' => 2, + 'user_id' => 8, 'parent_job_id' => 91, 'kind' => 'attach', + 'state' => 'blocked', 'desired_revision' => 4, 'active_claim' => 1, + 'last_error_code' => 'vpc_result_uncertain', 'terminal_at' => null, + 'created_at' => 25, 'updated_at' => 30, +]); +Capsule::table('cloud_jobs')->insert([ + 'id' => 91, 'operation_id' => str_repeat('6', 32), + 'kind' => 'vpc_membership_batch', 'phase' => 'awaiting_receipt', + 'outcome' => null, 'status' => 'running', + 'error_code' => 'vpc_result_uncertain', 'vpc_id' => 2, + 'vpc_batch_id' => 1, 'created_at' => 25, 'updated_at' => 30, +]); + +$actor = ['is_admin' => true, 'is_super_admin' => true, 'can_manage' => true]; +$overview = CloudAdminVpcControlService::overview($actor); +$assert($overview['feature']['enabled'] === true + && $overview['summary'] === [ + 'total' => 2, 'active' => 1, 'changing' => 0, 'degraded' => 1, + 'ports' => 2, 'active_batches' => 1, + ], 'Administrator VPC overview summary is inconsistent.'); +$assert(count($overview['regions']) === 2 + && $overview['regions'][0]['ready'] === true + && $overview['regions'][0]['available'] === 14 + && $overview['regions'][0]['hosts_ready'] === 1, + 'Ready VPC region projection is incomplete.'); +$assert($overview['regions'][1]['ready'] === false + && count($overview['regions'][1]['blockers']) === 2, + 'Unavailable VPC region did not expose its blockers.'); +$assert(count($overview['attention']) === 1 + && $overview['attention'][0]['id'] === 2, + 'Degraded VPC was not projected into the attention list.'); + +$degraded = CloudAdminVpcControlService::listing($actor, [ + 'state' => 'degraded', 'page' => '1', 'per_page' => '20', +]); +$assert($degraded['pagination']['total'] === 1 + && $degraded['items'][0]['state'] === 'degraded' + && $degraded['items'][0]['active_batch']['job_id'] === 91, + 'Degraded VPC listing or active batch projection is incorrect.'); +$search = CloudAdminVpcControlService::listing($actor, [ + 'q' => 'production', 'region_id' => '1', 'per_page' => '20', +]); +$assert($search['pagination']['total'] === 1 + && $search['items'][0]['id'] === 1 + && $search['items'][0]['host_summary'] === ['total' => 1, 'ready' => 1], + 'VPC search, region filter or host summary is incorrect.'); + +$detail = CloudAdminVpcControlService::detail($actor, 1); +$assert($detail['vpc']['name'] === 'production' + && count($detail['ports']) === 1 + && $detail['ports'][0]['public_ip'] === '192.0.2.11' + && $detail['host_states'][0]['ready'] === true + && $detail['batches'] === [] && $detail['jobs'] === [], + 'Healthy VPC detail projection is incomplete.'); +$degradedDetail = CloudAdminVpcControlService::detail($actor, 2); +$assert($degradedDetail['host_states'][0]['ready'] === false + && $degradedDetail['jobs'][0]['url'] === '/admin/operations?q=91', + 'VPC detail did not retain the exact task recovery navigation.'); +try { + CloudAdminVpcControlService::detail($actor, 999); + throw new RuntimeException('Missing VPC detail was returned.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 404, + 'Missing VPC detail used the wrong response status.'); +} + +echo "Administrator VPC control-plane read model passed.\n";