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

3408 lines
171 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudRegion;
use App\Models\CloudRegionFabric;
use App\Models\CloudVpc;
use App\Models\CloudVpcAclRule;
use App\Models\CloudVpcHostDeployment;
use App\Models\CloudVpcMember;
use App\Models\CloudVpcOperation;
use App\Models\CloudVpcPrivateIp;
use App\Models\CloudVpcRoute;
use App\Models\CloudVpcSubnet;
use App\Models\User;
/**
* PHP-owned VPC control plane.
*
* This service is intentionally independent from the general VM job queue and
* the public network mutation lane. It stores only typed tenant intent,
* serialises each VPC with its own row lock, and advances observed state only after the engine
* reports an exact desired revision/digest for every participating host.
* Tenant NICs, routes and nftables are applied by the engine's independent
* VPC dataplane lane; a VPC remains unusable until typed host readback proves
* the requested revision on every participating host.
*/
final class CloudVpcService
{
public const MAX_SUBNETS = 64;
public const MAX_MEMBERS = 4096;
public const MAX_ROUTES = 256;
public const MAX_ACL_RULES = 256;
private const KEY_PATTERN = '/^[0-9a-f]{32}$/D';
private const REQUEST_KEY_PATTERN = '/^[A-Za-z0-9_.:-]{8,128}$/D';
private const FABRIC_KEY_PATTERN = '/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D';
private const LIVE_STATES = ['applying', 'active', 'degraded', 'uncertain'];
private const PUBLIC_STATES = ['applying', 'active', 'degraded', 'uncertain', 'deleting'];
private const DIRECTIONS = ['ingress', 'egress'];
private const ACTIONS = ['allow', 'deny'];
private const PROTOCOLS = ['all', 'tcp', 'udp', 'icmp'];
/** Stable private NIC/dataplane contract shared with the engine. */
private const PRIVATE_INTERFACE = 'private0';
private const FABRIC_INTERFACE = 'wg-fabric0';
private const PRIVATE_DATAPLANE_OWNER = 'virt-cloud-vpc-dataplane-v1';
/** Return VPCs visible to an actor without contacting a host. */
public static function listing(array $actor): array
{
$query = CloudVpc::query();
if (!self::isGlobal($actor)) {
$query->where('user_id', (int) ($actor['user_id'] ?? 0));
}
$includeInfrastructure = self::canViewInfrastructure($actor);
return $query->orderByDesc('id')->limit(200)->get()
->map(static fn (CloudVpc $vpc): array => self::publicRoot($vpc, $includeInfrastructure))
->all();
}
/** Return a complete typed control-plane projection for one VPC. */
public static function show(string $vpcKey, array $actor): array
{
$vpc = self::findOwned($vpcKey, $actor, false);
return self::documentView($vpc, $actor);
}
/**
* Create a VPC reservation and its first subnet. The CIDR allocator row
* is only an address reservation; the VPC root deliberately starts in
* applying/pending until Fabric and the future data plane are observed.
*/
public static function create(array $actor, array $input): array
{
CloudInput::only($input, [
'name', 'region_id', 'cidr', 'prefix_length', 'max_members',
'request_key', 'fabric_id', 'fabric_revision', 'subnet_cidr',
'subnet_gateway',
]);
$name = CloudInput::name($input['name'] ?? null);
$regionId = self::positiveInt($input['region_id'] ?? null, 1, 1000000000,
'地区无效');
$requestKey = self::requestKey($input['request_key'] ?? null);
$maxMembers = self::positiveInt($input['max_members'] ?? 256, 1,
self::MAX_MEMBERS, 'VPC 成员上限无效');
$region = CloudRegion::where('id', $regionId)->where('status', 'active')->first();
if ($region === null) {
throw new CloudError('地区不存在或暂不可用', 409);
}
$requestedCidr = isset($input['cidr']) ? self::cidr(
$input['cidr'], 16, 24, 'VPC CIDR') : null;
$prefix = $requestedCidr === null
? (int) ($input['prefix_length'] ?? 24)
: $requestedCidr['prefix'];
if ($requestedCidr === null && !array_key_exists('prefix_length', $input)) {
$prefix = 24;
}
if ($prefix < 16 || $prefix > 24) {
throw new CloudError('VPC CIDR 前缀必须为 /16 至 /24');
}
if ($requestedCidr !== null && isset($input['prefix_length'])
&& (int) $input['prefix_length'] !== $requestedCidr['prefix']) {
throw new CloudError('VPC CIDR 与前缀长度不一致');
}
// Fabric identity and revision are platform-owned. Do not derive
// them from the mutable numeric region ID or accept a tenant-supplied
// value: a Fabric may use any stable ID and may advance its revision
// after a host/key change. Missing mappings fail before CIDR reserve.
$fabricConnection = (new CloudRegionFabric())->getConnection();
if (!$fabricConnection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
throw new CloudError('VPC Fabric 映射表尚未安装', 503);
}
$fabric = CloudRegionFabric::where('region_id', $regionId)
->where('state', 'active')->first();
if ($fabric === null) {
throw new CloudError('该地区尚未配置可用的 WireGuard Fabric', 409);
}
$fabricId = self::fabricId((string) $fabric->fabric_id);
$fabricRegion = self::fabricId((string) $fabric->fabric_region);
$fabricRevision = self::positiveInt($fabric->fabric_revision, 1,
9000000000000000, 'Fabric 版本无效');
if (array_key_exists('fabric_id', $input)
&& (string) $input['fabric_id'] !== $fabricId) {
throw new CloudError('Fabric 由平台按地区分配,不能由请求选择', 403);
}
if (array_key_exists('fabric_revision', $input)
&& (int) $input['fabric_revision'] !== $fabricRevision) {
throw new CloudError('Fabric 版本已由平台更新,请刷新后重试', 409);
}
$subnet = isset($input['subnet_cidr'])
? self::cidr($input['subnet_cidr'], $prefix, 30, '子网 CIDR')
: null;
$gateway = $input['subnet_gateway'] ?? null;
if ($gateway !== null) {
// Phase 3 deliberately has no guest default gateway. Keeping
// the nullable column makes a later data-plane migration
// explicit, but tenant input cannot enable route injection now.
throw new CloudError('当前 VPC 控制面不支持子网网关');
}
$userId = (int) ($actor['user_id'] ?? 0);
if ($userId < 1) {
throw new CloudError('账户无效', 401);
}
$allocationKey = substr(hash('sha256', 'vpc-allocation:' . $userId . ':' . $requestKey), 0, 32);
$vpcKey = substr(hash('sha256', 'vpc:' . $userId . ':' . $requestKey), 0, 32);
$requestHash = self::requestHash('vpc_create', [
'name' => $name, 'region_id' => $regionId, 'cidr' => $requestedCidr['cidr'] ?? null,
'prefix_length' => $prefix, 'max_members' => $maxMembers,
'fabric_id' => $fabricId, 'fabric_region' => $fabricRegion,
'fabric_revision' => $fabricRevision,
'subnet_cidr' => $subnet['cidr'] ?? null, 'subnet_gateway' => $gateway,
]);
$network = null;
$connection = (new CloudVpc())->getConnection();
try {
return $connection->transaction(function () use (
$actor, $name, $region, $requestKey, $requestHash, $maxMembers,
$fabricId, $fabricRegion, $fabricRevision, $subnet, $gateway, $vpcKey,
$allocationKey, $userId, $regionId, $requestedCidr, $prefix,
&$network, $connection
): array {
// Serialize region/Fabric mapping changes with VPC creation.
// The mapping is checked again after the transaction starts;
// a concurrent administrator update cannot pin an obsolete
// Fabric revision into a new desired document.
$lockedRegion = CloudRegion::where('id', $regionId)
->where('status', 'active')->lockForUpdate()->first();
$lockedFabric = CloudRegionFabric::where('region_id', $regionId)
->where('state', 'active')->lockForUpdate()->first();
if ($lockedRegion === null || $lockedFabric === null
|| (string) $lockedFabric->fabric_id !== $fabricId
|| (string) $lockedFabric->fabric_region !== $fabricRegion
|| (int) $lockedFabric->fabric_revision !== $fabricRevision) {
throw new CloudError('地区 Fabric 配置已变化,请刷新后重试', 409);
}
$region = $lockedRegion;
// Account deletion locks the owner row before checking VPCs.
// Hold that same lock across allocation and root creation so
// a concurrent create cannot appear after the final account
// deletion check and become an orphaned private network.
if ($connection->getSchemaBuilder()->hasTable('user')) {
$owner = User::where('id', $userId)->lockForUpdate()->first();
if ($owner === null) {
throw new CloudError('账户不存在', 401);
}
}
$network = CloudPrivateCidrAllocator::allocate(
$allocationKey, $userId, $regionId,
$requestedCidr['cidr'] ?? null, $prefix, $vpcKey
);
return $connection->transaction(function () use (
$actor, $name, $region, $requestKey, $requestHash, $maxMembers,
$fabricId, $fabricRegion, $fabricRevision, $subnet, $gateway, $network, $vpcKey,
$allocationKey
): array {
$existing = CloudVpc::where('vpc_key', $vpcKey)->lockForUpdate()->first();
if ($existing !== null) {
$operation = CloudVpcOperation::where('vpc_id', $existing->id)
->where('idempotency_key', $requestKey)->lockForUpdate()->first();
if ($operation !== null && ((string) $operation->kind !== 'vpc_create'
|| !hash_equals((string) $operation->request_hash, $requestHash))) {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
if ((string) $existing->name !== $name
|| (int) $existing->region_id !== (int) $region->id
|| (int) $existing->max_members !== $maxMembers
|| (string) $existing->fabric_id !== $fabricId
|| (string) $existing->fabric_region !== $fabricRegion
|| (int) $existing->fabric_revision !== $fabricRevision) {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
$existingSubnet = CloudVpcSubnet::where('vpc_id', $existing->id)
->orderBy('id')->first();
$expectedSubnet = $subnet['cidr'] ?? self::cidr(
(string) $network->cidr, 16, 30, '子网 CIDR'
)['cidr'];
if ($existingSubnet === null
|| (string) $existingSubnet->cidr !== (string) $expectedSubnet
|| ($existingSubnet->gateway_ip ?? null) !== $gateway) {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
return self::documentView($existing, $actor);
}
$now = time();
$vpc = new CloudVpc();
$vpc->vpc_key = $vpcKey;
$vpc->user_id = (int) $actor['user_id'];
$vpc->region_id = (int) $region->id;
$vpc->private_network_id = (int) $network->id;
$vpc->name = $name;
$vpc->cidr = (string) $network->cidr;
$vpc->fabric_id = $fabricId;
$vpc->fabric_region = $fabricRegion;
$vpc->fabric_revision = $fabricRevision;
$vpc->max_members = $maxMembers;
$vpc->state = 'applying';
$vpc->desired_revision = 0;
$vpc->observed_revision = 0;
$vpc->desired_digest = str_repeat('0', 64);
$vpc->observed_digest = null;
$vpc->sync_state = 'pending';
$vpc->last_operation_id = null;
$vpc->last_error_code = null;
$vpc->last_success_at = 0;
$vpc->last_failure_at = 0;
$vpc->created_at = $now;
$vpc->updated_at = $now;
$vpc->save();
$subnetValue = $subnet ?? self::cidr((string) $network->cidr, 16, 30, '子网 CIDR');
if ($subnetValue['network'] < (int) $network->network_address
|| $subnetValue['broadcast'] > (int) $network->broadcast_address) {
throw new CloudError('子网必须完全位于 VPC CIDR 内');
}
// No gateway is installed in the control-plane-only phase.
$row = new CloudVpcSubnet();
$row->subnet_key = self::randomKey();
$row->vpc_id = $vpc->id;
$row->cidr = $subnetValue['cidr'];
$row->network_address = $subnetValue['network'];
$row->broadcast_address = $subnetValue['broadcast'];
$row->prefix_length = $subnetValue['prefix'];
$row->gateway_ip = $gateway;
$row->state = 'applying';
$row->desired_revision = 0;
$row->observed_revision = 0;
$row->desired_digest = null;
$row->observed_digest = null;
$row->last_error_code = null;
$row->created_at = $now;
$row->updated_at = $now;
$row->save();
$result = self::touchDesiredLocked($vpc, 'vpc_create', $requestKey, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}, 3);
} catch (\Throwable $error) {
// If root creation failed after the allocator committed, release
// only this request's reservation. A successful root is never
// silently released by a later retry.
if ($network !== null && !CloudVpc::where('vpc_key', $vpcKey)->exists()) {
try {
CloudPrivateCidrAllocator::release($allocationKey, (int) $network->revision);
} catch (\Throwable) {
// Keep the reservation fail-closed; reconciliation can
// inspect it rather than risking reuse of an unknown CIDR.
}
}
if ($error instanceof CloudError) {
throw $error;
}
throw new CloudError('VPC 创建未完成,请稍后重试', 503);
}
}
public static function addSubnet(string $vpcKey, array $actor, array $input): array
{
CloudInput::only($input, ['cidr', 'gateway_ip', 'request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$vpc = self::lockOwned($vpcKey, $actor);
$value = self::cidr($input['cidr'] ?? null, (int) self::cidr(
(string) $vpc->cidr, 16, 24, 'VPC CIDR')['prefix'], 30, '子网 CIDR');
$gateway = $input['gateway_ip'] ?? null;
if ($gateway !== null) {
throw new CloudError('当前 VPC 控制面不支持子网网关');
}
$requestHash = self::requestHash('subnet_add', [
'cidr' => $value['cidr'], 'gateway_ip' => $gateway,
]);
return $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $value, $gateway, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'subnet_add', $requestHash)) {
return self::documentView($vpc, $actor);
}
self::assertWithinVpc($value, $vpc);
// Guest gateways are intentionally deferred to the data plane.
$subnets = CloudVpcSubnet::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$liveSubnetCount = $subnets->filter(static fn ($row): bool => !in_array(
(string) $row->state, ['deleted', 'deleting'], true
))->count();
if ($liveSubnetCount >= self::MAX_SUBNETS) {
throw new CloudError('VPC 子网数量已达到上限', 409);
}
foreach ($subnets as $row) {
if (self::overlap($value, [
'network' => (int) $row->network_address,
'broadcast' => (int) $row->broadcast_address,
])) {
throw new CloudError('子网 CIDR 与现有子网重叠', 409);
}
}
$now = time();
$row = new CloudVpcSubnet();
$row->subnet_key = self::randomKey();
$row->vpc_id = $vpc->id;
$row->cidr = $value['cidr'];
$row->network_address = $value['network'];
$row->broadcast_address = $value['broadcast'];
$row->prefix_length = $value['prefix'];
$row->gateway_ip = $gateway;
$row->state = 'applying';
$row->created_at = $row->updated_at = $now;
$row->save();
$result = self::touchDesiredLocked($vpc, 'subnet_add', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
public static function removeSubnet(string $vpcKey, string $subnetKey,
array $actor, array $input): array
{
CloudInput::only($input, ['request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$vpc = self::lockOwned($vpcKey, $actor);
self::assertKey($subnetKey, '子网');
$requestHash = self::requestHash('subnet_remove', ['subnet_key' => $subnetKey]);
return $vpc->getConnection()->transaction(function () use (
$vpc, $subnetKey, $actor, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'subnet_remove', $requestHash)) {
return self::documentView($vpc, $actor);
}
$subnet = CloudVpcSubnet::where('vpc_id', $vpc->id)
->where('subnet_key', $subnetKey)->lockForUpdate()->first();
if ($subnet === null || in_array((string) $subnet->state, ['deleted', 'deleting'], true)) {
throw new CloudError('子网不存在', 404);
}
if (CloudVpcMember::where('subnet_id', $subnet->id)
->where('state', '<>', 'deleted')->exists()) {
throw new CloudError('子网仍有私网成员,不能删除', 409);
}
if (CloudVpcPrivateIp::where('subnet_id', $subnet->id)
->where('state', '<>', 'deleted')->exists()) {
throw new CloudError('子网仍有私网地址租约,不能删除', 409);
}
$subnet->state = 'deleting';
$subnet->updated_at = time();
$subnet->save();
$result = self::touchDesiredLocked($vpc, 'subnet_remove', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
public static function attachMember(string $vpcKey, array $actor, array $input): array
{
CloudInput::only($input, ['subnet_key', 'instance_id', 'private_ip', 'request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$instanceId = self::positiveInt($input['instance_id'] ?? null, 1, 1000000000,
'虚拟机无效');
$requestHash = self::requestHash('member_attach', [
'subnet_key' => $input['subnet_key'] ?? null,
'instance_id' => $instanceId,
'private_ip' => $input['private_ip'] ?? null,
]);
$vpc = self::lockOwned($vpcKey, $actor);
return $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $input, $key, $requestHash, $instanceId
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'member_attach', $requestHash)) {
return self::documentView($vpc, $actor);
}
$subnetKey = $input['subnet_key'] ?? null;
self::assertKey($subnetKey, '子网');
$subnet = CloudVpcSubnet::where('vpc_id', $vpc->id)
->where('subnet_key', $subnetKey)->lockForUpdate()->first();
if ($subnet === null || !in_array((string) $subnet->state, self::LIVE_STATES, true)) {
throw new CloudError('子网不存在或尚未可用', 409);
}
$requestedIp = ($input['private_ip'] ?? null) !== null
? self::ipv4($input['private_ip'], '私网 IP') : null;
$existing = CloudVpcMember::where('vpc_id', $vpc->id)
->where('instance_id', $instanceId)->lockForUpdate()->first();
if ($existing !== null) {
if (in_array((string) $existing->state, ['deleted', 'deleting'], true)) {
throw new CloudError('该虚拟机的旧 VPC 成员仍在清理,暂不能重新加入', 409);
}
$existingInstance = CloudInstance::where('id', $instanceId)
->where('status', '<>', 'deleted')->lockForUpdate()->first();
if ($existingInstance === null) {
throw new CloudError('虚拟机不存在', 404);
}
if ((int) $existingInstance->user_id !== (int) $vpc->user_id
&& !self::isGlobal($actor)) {
throw new CloudError('无权使用该 VPC 成员', 403);
}
if ((string) $existingInstance->status !== 'active') {
throw new CloudError('虚拟机正在删除,不能继续使用私网成员', 409);
}
if (!$existingInstance->serviceAvailable()) {
throw new CloudError('虚拟机当前服务周期不可用,不能继续使用私网成员', 409);
}
self::assertInstanceRegion($existingInstance, (int) $vpc->region_id);
if ((int) $existing->host_id !== (int) $existingInstance->host_id) {
throw new CloudError('虚拟机宿主机已变化,请先移除旧私网成员', 409);
}
if ((int) $existing->subnet_id !== (int) $subnet->id) {
throw new CloudError('该虚拟机已加入 VPC 的其他子网,请先移除现有成员', 409);
}
$privateIp = self::lockedPrivateIpForMember($existing);
if ((int) $privateIp->subnet_id !== (int) $subnet->id
|| (string) $privateIp->private_ip !== (string) $existing->private_ip
|| (int) $privateIp->instance_id !== $instanceId
|| in_array((string) $privateIp->state, ['deleted', 'deleting'], true)) {
throw new CloudError('VPC 私网地址账本与成员不一致,请联系管理员', 503);
}
if ($requestedIp !== null
&& (string) $privateIp->private_ip !== $requestedIp) {
throw new CloudError('该虚拟机已加入 VPC 且 IP 不同', 409);
}
return self::documentView($vpc, $actor);
}
$instance = CloudInstance::where('id', $instanceId)
->where('status', '<>', 'deleted')->lockForUpdate()->first();
if ($instance === null) {
throw new CloudError('虚拟机不存在', 404);
}
if ((int) $instance->user_id !== (int) $vpc->user_id && !self::isGlobal($actor)) {
throw new CloudError('无权添加该虚拟机', 403);
}
$otherMembership = CloudVpcMember::where('instance_id', $instanceId)
->where('vpc_id', '<>', $vpc->id)->lockForUpdate()->first();
if ($otherMembership !== null) {
$message = in_array((string) $otherMembership->state,
['deleted', 'deleting'], true)
? '该虚拟机的旧 VPC 成员仍在清理,暂不能迁移'
: '首版每台虚拟机只能加入一个 VPC';
throw new CloudError($message, 409);
}
if ((string) $instance->status !== 'active' || !$instance->serviceAvailable()) {
throw new CloudError('虚拟机当前不可加入私网', 409);
}
self::assertInstanceRegion($instance, (int) $vpc->region_id);
$members = CloudVpcMember::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$liveCount = $members->filter(static fn ($row): bool => !in_array(
(string) $row->state, ['deleted', 'deleting'], true))->count();
if ($liveCount >= (int) $vpc->max_members) {
throw new CloudError('VPC 成员数量已达到上限', 409);
}
// Address leases are a separate child aggregate. Lock the full
// VPC lease set before choosing an automatic address; the unique
// address key remains the final database guard for another
// process that bypasses this service.
$privateIps = CloudVpcPrivateIp::where('vpc_id', $vpc->id)
->lockForUpdate()->get();
$ip = $requestedIp !== null
? $requestedIp
: self::firstFreeIp($subnet, $privateIps);
$ipInt = self::ipToInt($ip);
if ($ipInt <= (int) $subnet->network_address
|| $ipInt >= (int) $subnet->broadcast_address) {
throw new CloudError('私网 IP 必须位于子网可用地址范围内');
}
foreach ($privateIps as $row) {
if ((string) $row->private_ip === $ip) {
throw new CloudError('私网 IP 已被占用', 409);
}
}
// Keep the legacy member mirror as a second fail-closed guard
// while older rows are being migrated into the lease table.
foreach ($members as $row) {
if ((string) $row->private_ip === $ip) {
throw new CloudError('私网 IP 已被占用', 409);
}
}
$now = time();
$member = new CloudVpcMember();
$member->member_key = self::randomKey();
$member->vpc_id = $vpc->id;
$member->subnet_id = $subnet->id;
$member->private_ip_id = null;
$member->instance_id = $instance->id;
$member->host_id = $instance->host_id;
$member->private_ip = $ip;
$member->private_ip_int = $ipInt;
$member->state = 'applying';
$member->created_at = $member->updated_at = $now;
$member->save();
$privateIp = new CloudVpcPrivateIp();
$privateIp->ip_key = self::randomKey();
$privateIp->vpc_id = $vpc->id;
$privateIp->subnet_id = $subnet->id;
$privateIp->member_id = $member->id;
$privateIp->instance_id = $instance->id;
$privateIp->private_ip = $ip;
$privateIp->private_ip_int = $ipInt;
$privateIp->state = 'applying';
$privateIp->created_at = $privateIp->updated_at = $now;
$privateIp->save();
$member->private_ip_id = $privateIp->id;
$member->save();
$result = self::touchDesiredLocked($vpc, 'member_attach', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
public static function detachMember(string $vpcKey, string $memberKey,
array $actor, array $input): array
{
CloudInput::only($input, ['request_key']);
$key = self::requestKey($input['request_key'] ?? null);
self::assertKey($memberKey, '成员');
$requestHash = self::requestHash('member_detach', ['member_key' => $memberKey]);
$vpc = self::lockOwned($vpcKey, $actor);
return $vpc->getConnection()->transaction(function () use (
$vpc, $memberKey, $actor, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'member_detach', $requestHash)) {
return self::documentView($vpc, $actor);
}
$member = CloudVpcMember::where('vpc_id', $vpc->id)
->where('member_key', $memberKey)->lockForUpdate()->first();
if ($member === null || in_array((string) $member->state, ['deleted', 'deleting'], true)) {
throw new CloudError('VPC 成员不存在', 404);
}
if (CloudVpcRoute::where('vpc_id', $vpc->id)
->where('member_id', $member->id)
->whereNotIn('state', ['deleted', 'deleting'])
->exists()) {
throw new CloudError('该成员仍被路由引用,请先替换或删除路由', 409);
}
// Lifecycle commits lock VPC -> instance before validating the
// captured private target. Take the same order here so a detach
// cannot flip the member to deleting while a VM job is committing.
$instance = CloudInstance::where('id', (int) $member->instance_id)
->lockForUpdate()->first();
if ($instance === null || (string) $instance->status === 'deleted') {
throw new CloudError('虚拟机不存在', 404);
}
$privateIp = self::lockedPrivateIpForMember($member);
$member->state = 'deleting';
$member->updated_at = time();
$member->save();
$privateIp->state = 'deleting';
$privateIp->updated_at = time();
$privateIp->save();
$result = self::touchDesiredLocked($vpc, 'member_detach', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
/** Replace the complete typed route set; raw route commands never cross the API. */
public static function replaceRoutes(string $vpcKey, array $actor, array $input): array
{
CloudInput::only($input, ['routes', 'request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$routes = self::routeInput($input['routes'] ?? null);
$requestHash = self::requestHash('routes_replace', ['routes' => $routes]);
$vpc = self::lockOwned($vpcKey, $actor);
return $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $routes, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'routes_replace', $requestHash)) {
return self::documentView($vpc, $actor);
}
$members = CloudVpcMember::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$privateIps = CloudVpcPrivateIp::where('vpc_id', $vpc->id)
->lockForUpdate()->get()->keyBy('member_id');
$byIp = [];
foreach ($members as $member) {
if (!in_array((string) $member->state, ['deleted', 'deleting'], true)) {
$privateIp = $privateIps[(int) $member->id] ?? null;
if ($privateIp === null
|| (int) $member->private_ip_id !== (int) $privateIp->id
|| (string) $privateIp->private_ip !== (string) $member->private_ip
|| in_array((string) $privateIp->state, ['deleted', 'deleting'], true)) {
throw new CloudError('VPC 私网地址账本与成员不一致,请联系管理员', 503);
}
$byIp[(string) $privateIp->private_ip] = $member;
}
}
$rows = CloudVpcRoute::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$existingByDestination = [];
$deletedByDestination = [];
$existingByKey = [];
foreach ($rows as $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) {
$destination = (string) $route['destination']['cidr'];
if (isset($seenDestinations[$destination])) {
throw new CloudError('路由目标不能重复', 409);
}
$seenDestinations[$destination] = true;
$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');
}
$root = self::cidr((string) $vpc->cidr, 16, 24, 'VPC CIDR');
if (!self::contains($root['network'], $root['broadcast'],
$route['destination']['network'], $route['destination']['broadcast'])) {
throw new CloudError('路由目标必须位于 VPC CIDR 内');
}
$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'];
$row->broadcast_int = $route['destination']['broadcast'];
$row->prefix_length = $route['destination']['prefix'];
$row->next_hop_ip = $route['next_hop_ip'];
$row->metric = $route['metric'];
$row->state = 'applying';
$row->updated_at = $now;
$row->save();
}
$result = self::touchDesiredLocked($vpc, 'routes_replace', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
/** Replace typed private ACL rules. Default engine policy remains deny. */
public static function replaceAcl(string $vpcKey, array $actor, array $input): array
{
CloudInput::only($input, ['rules', 'request_key']);
$key = self::requestKey($input['request_key'] ?? null);
$rules = self::aclInput($input['rules'] ?? null);
$requestHash = self::requestHash('acl_replace', ['rules' => $rules]);
$vpc = self::lockOwned($vpcKey, $actor);
return $vpc->getConnection()->transaction(function () use (
$vpc, $actor, $rules, $key, $requestHash
): array {
$vpc = self::lockOwned($vpc->vpc_key, $actor);
if (self::hasOperation($vpc, $key, 'acl_replace', $requestHash)) {
return self::documentView($vpc, $actor);
}
$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) {
$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) {
$priorityKey = (string) $rule['direction'] . ':' . (int) $rule['priority'];
if (isset($seenPriorities[$priorityKey])) {
throw new CloudError('同一方向的 ACL 优先级不能重复', 409);
}
$seenPriorities[$priorityKey] = true;
$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'])) {
throw new CloudError('ACL 地址范围必须位于 VPC CIDR 内');
}
}
$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'];
$row->protocol = $rule['protocol'];
$row->source_cidr = $rule['source']['cidr'];
$row->source_int = $rule['source']['network'];
$row->source_broadcast_int = $rule['source']['broadcast'];
$row->source_prefix_length = $rule['source']['prefix'];
$row->destination_cidr = $rule['destination']['cidr'];
$row->destination_int = $rule['destination']['network'];
$row->destination_broadcast_int = $rule['destination']['broadcast'];
$row->destination_prefix_length = $rule['destination']['prefix'];
$row->port_from = $rule['port_from'];
$row->port_to = $rule['port_to'];
$row->state = 'applying';
$row->updated_at = $now;
$row->save();
}
$result = self::touchDesiredLocked($vpc, 'acl_replace', $key, $requestHash);
return self::documentView($result['vpc'], $actor);
}, 3);
}
/**
* Send the latest desired document to the private engine VPC lane. The
* engine rejects it unless the referenced Fabric is active on every host,
* then applies/readbacks the private dataplane. No general VM-job or
* public-network mutation row is created here.
*/
public static function reconcile(string $vpcKey, array $actor, bool $allowDeferredRetry = false): array
{
$vpc = self::findOwned($vpcKey, $actor, true);
$claim = $vpc->getConnection()->transaction(function () use ($vpc, $allowDeferredRetry): ?array {
$locked = CloudVpc::where('id', $vpc->id)->lockForUpdate()->first();
if ($locked === null) {
throw new CloudError('VPC 不存在', 404);
}
$operation = CloudVpcOperation::where('vpc_id', $locked->id)
->whereIn('status', $allowDeferredRetry
? ['queued', 'running', 'uncertain', 'waiting_observed']
: ['queued', 'running', 'uncertain'])
->orderByDesc('desired_revision')->lockForUpdate()->first();
if ($operation === null) {
throw new CloudError('VPC 没有待核对的目标版本', 409);
}
// A newer mutation owns the VPC's desired state. A worker can
// still have selected an older row before that mutation committed;
// retire it here before it can replay stale routes or ACLs against
// the engine. touchDesiredLocked performs the same transition
// eagerly, while this guard also repairs rows created before the
// supersede rule was introduced.
if ((int) $operation->desired_revision !== (int) $locked->desired_revision
|| (string) $operation->operation_id !== (string) ($locked->last_operation_id ?? '')) {
$operation->status = 'superseded';
$operation->error_code = 'vpc_revision_superseded';
$operation->finished_at = $now = time();
$operation->lease_token = null;
$operation->lease_until = 0;
$operation->updated_at = $now;
$operation->save();
return null;
}
$now = time();
if ((string) $operation->status === 'running'
&& (int) $operation->lease_until > $now) {
return null;
}
$payload = json_decode((string) $operation->payload_json, true);
if (!is_array($payload)
|| ($payload['operation_id'] ?? null) !== (string) $operation->operation_id) {
$corruptAt = time();
$operation->status = 'failed';
$operation->error_code = 'vpc_operation_corrupt';
$operation->finished_at = $corruptAt;
$operation->lease_token = null;
$operation->lease_until = 0;
$operation->updated_at = $corruptAt;
$operation->save();
$locked->state = 'degraded';
$locked->sync_state = 'failed';
$locked->last_error_code = 'vpc_operation_corrupt';
$locked->last_failure_at = $corruptAt;
$locked->updated_at = $corruptAt;
$locked->save();
return null;
}
$operation->status = 'running';
$operation->lease_token = self::randomKey();
$operation->lease_until = $now + 120;
$operation->finished_at = null;
$operation->attempts = (int) $operation->attempts + 1;
$operation->updated_at = $now;
$operation->save();
return [$operation, $payload];
}, 3);
if ($claim === null) {
return self::show($vpcKey, $actor);
}
[$operation, $payload] = $claim;
$leaseToken = (string) $operation->lease_token;
try {
$result = (new CloudEngineClient())->vpc('POST', '/internal/v1/vpcs/apply',
$actor, $payload, (string) $operation->operation_id);
$expectedRevision = (int) ($payload['desired_revision'] ?? 0);
$expectedDigest = (string) ($payload['desired_digest'] ?? '');
if (!is_array($result)
|| (string) ($result['operation_id'] ?? '')
!== (string) $operation->operation_id
|| (string) ($result['vpc_id'] ?? '')
!== (string) ($payload['vpc_id'] ?? '')
|| (int) ($result['desired_revision'] ?? 0) !== $expectedRevision
|| !hash_equals($expectedDigest, (string) ($result['desired_digest'] ?? ''))) {
throw new CloudError('引擎 VPC 结果与操作编号不一致,正在核对', 502);
}
$observed = is_array($result['observed'] ?? null) ? $result['observed'] : $result;
// Some engine versions expose a compact `observed` projection and
// the full typed host readback beside it. Merge the latter into
// the bounded projection before validating; never discard
// member_nics/routes/WireGuard evidence merely because the
// transport envelope used a compact view.
if (is_array($result['hosts'] ?? null)) {
if (!is_array($observed['hosts'] ?? null)) {
$observed['hosts'] = [];
}
foreach ($result['hosts'] as $hostKey => $hostItem) {
if (!is_array($hostItem)) {
continue;
}
$hostKey = (string) ($hostItem['host_id'] ?? $hostKey);
$compact = is_array($observed['hosts'][$hostKey] ?? null)
? $observed['hosts'][$hostKey] : [];
$observed['hosts'][$hostKey] = array_replace($compact, $hostItem);
}
}
if (isset($observed['operation_id'])
&& (string) $observed['operation_id'] !== (string) $operation->operation_id) {
throw new CloudError('引擎 VPC 观测与操作编号不一致,正在核对', 502);
}
if (isset($observed['vpc_id'])
&& (string) $observed['vpc_id'] !== (string) ($payload['vpc_id'] ?? '') ) {
throw new CloudError('引擎 VPC 观测目标不一致,正在核对', 502);
}
if (isset($observed['desired_revision'])
&& (int) $observed['desired_revision'] !== $expectedRevision) {
throw new CloudError('引擎 VPC 观测版本不一致,正在核对', 502);
}
if (isset($observed['desired_digest'])
&& !hash_equals($expectedDigest, (string) $observed['desired_digest'])) {
throw new CloudError('引擎 VPC 观测摘要不一致,正在核对', 502);
}
self::recordObserved($vpcKey, (int) ($payload['desired_revision'] ?? 0),
(string) ($payload['desired_digest'] ?? ''), $observed,
(string) $operation->operation_id, $leaseToken);
return self::show($vpcKey, $actor);
} catch (CloudError $error) {
$status = $error->httpStatus >= 500 ? 'uncertain' : 'failed';
$now = time();
$connection = (new CloudVpc())->getConnection();
$connection->transaction(function () use ($operation, $leaseToken, $vpc, $status, $error, $now): void {
// Keep the lock order identical to every mutator: VPC root
// first, then its operation row. This also prevents an old
// lease from overwriting a newer desired revision.
$root = CloudVpc::where('id', $vpc->id)->lockForUpdate()->first();
if ($root === null) {
return;
}
$row = CloudVpcOperation::where('operation_id', (string) $operation->operation_id)
->where('status', 'running')
->where('lease_token', $leaseToken)->lockForUpdate()->first();
if ($row === null) {
return;
}
$row->status = $status;
$row->error_code = self::safeErrorCode($error->getMessage())
?? ($status === 'uncertain' ? 'vpc_result_uncertain' : 'vpc_apply_failed');
$row->updated_at = $now;
$row->finished_at = $status === 'failed' ? $now : null;
$row->lease_until = 0;
$row->save();
if ((string) $root->last_operation_id === (string) $row->operation_id
&& (int) $root->desired_revision === (int) $row->desired_revision) {
$root->state = $status === 'uncertain' ? 'uncertain' : 'degraded';
$root->sync_state = $status === 'uncertain' ? 'uncertain' : 'failed';
$root->last_error_code = $row->error_code;
$root->last_failure_at = $now;
$root->updated_at = $now;
$root->save();
}
}, 3);
throw $error;
}
}
/** Apply an exact engine observation and enforce the all-host gate. */
public static function recordObserved(string $vpcKey, int $revision, string $digest,
array $observed, string $operationId, ?string $leaseToken = null): void
{
self::assertKey($vpcKey, 'VPC');
if ($revision < 1 || preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|| preg_match(self::KEY_PATTERN, $operationId) !== 1) {
throw new CloudError('VPC 观测版本无效', 502);
}
$connection = (new CloudVpc())->getConnection();
$connection->transaction(function () use (
$vpcKey, $revision, $digest, $observed, $operationId, $leaseToken
): void {
$vpc = CloudVpc::where('vpc_key', $vpcKey)->lockForUpdate()->first();
if ($vpc === null) {
throw new CloudError('VPC 不存在', 404);
}
if ((int) $vpc->desired_revision !== $revision
|| !hash_equals((string) $vpc->desired_digest, $digest)
|| (string) $vpc->last_operation_id !== $operationId) {
throw new CloudError('VPC 观测版本不是当前目标版本', 409);
}
// Validate the operation lease before touching any host or child
// evidence. A superseded worker must not be able to write a
// stale observation into the current revision.
$operationQuery = CloudVpcOperation::where('operation_id', $operationId)
->where('vpc_id', $vpc->id);
if ($leaseToken !== null) {
$operationQuery->where('lease_token', $leaseToken)
->where('status', 'running');
}
$operation = $operationQuery->lockForUpdate()->first();
if ($operation === null) {
throw new CloudError('VPC 操作记录不存在', 502);
}
$hosts = [];
foreach (is_array($observed['hosts'] ?? null) ? $observed['hosts'] : [] as $key => $item) {
if (!is_array($item)) {
continue;
}
$hostKey = (string) ($item['host_id'] ?? $key);
$hosts[$hostKey] = $item;
}
// Validate typed tenant dataplane evidence before evaluating the
// all-host gate. Fabric transport alone can only leave this
// independent VPC lane waiting/uncertain.
$expectedMembersByHost = [];
$allExpectedMembers = [];
$expectedDestinations = [];
$desiredRoutes = [];
$desiredContractValid = true;
try {
$desired = self::desiredDocument($vpc);
// The host adapter installs only member /32 routes and the
// explicitly configured VPC routes. The VPC/subnet CIDRs
// themselves are control-plane address ranges, not an
// allowance for a broad host route in the data plane.
foreach (is_array($desired['routes'] ?? null) ? $desired['routes'] : [] as $route) {
if (is_array($route) && isset($route['destination_cidr'])) {
$desiredRoutes[] = $route;
$expectedDestinations[] = (string) $route['destination_cidr'];
}
}
foreach (is_array($desired['members'] ?? null) ? $desired['members'] : [] as $member) {
if (!is_array($member) || !isset($member['member_id'])) {
continue;
}
$memberId = (string) $member['member_id'];
$memberHost = (string) ($member['host_id'] ?? '');
$member['private_mac'] = strtolower((string) ($member['private_mac'] ?? ''));
$expectedMembersByHost[$memberHost][$memberId] = $member;
$allExpectedMembers[$memberId] = $member;
if (isset($member['private_ip_cidr'])) {
$expectedDestinations[] = (string) $member['private_ip_cidr'];
}
}
} catch (\Throwable) {
// A malformed desired ledger is itself a closed gate.
$desiredContractValid = false;
$expectedMembersByHost = [];
$allExpectedMembers = [];
$expectedDestinations = [];
$desiredRoutes = [];
}
$expectedDestinations = array_values(array_unique(array_filter(
$expectedDestinations,
static fn ($value): bool => is_string($value) && $value !== ''
)));
foreach ($hosts as $hostKey => $item) {
if (($item['private_dataplane_verified'] ?? false) !== true) {
continue;
}
$errorCode = $desiredContractValid
? self::validateHostDataplaneEvidence(
$item,
(string) $hostKey,
$expectedMembersByHost[(string) $hostKey] ?? [],
array_values($allExpectedMembers),
$expectedDestinations,
$desiredRoutes,
$vpcKey,
$revision,
$digest
)
: 'vpc_private_readback_mismatch';
if ($errorCode !== null) {
$item['private_dataplane_verified'] = false;
$item['last_error_code'] = $errorCode;
$hosts[$hostKey] = $item;
$observedHosts = is_array($observed['hosts'] ?? null)
? $observed['hosts'] : [];
$observedHosts[$hostKey] = $item;
$observed['hosts'] = $observedHosts;
$observed['private_dataplane_verified'] = false;
} elseif (($item['removed'] ?? false) === true) {
$item['removal_verified'] = true;
$hosts[$hostKey] = $item;
$observedHosts = is_array($observed['hosts'] ?? null)
? $observed['hosts'] : [];
$observedHosts[$hostKey] = $item;
$observed['hosts'] = $observedHosts;
}
}
$required = CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted'])
->lockForUpdate()->get()->keyBy(static fn ($row): int => (int) $row->host_id);
$observedRevision = (int) ($observed['revision']
?? $observed['observed_revision'] ?? 0);
$observedDigest = (string) ($observed['digest']
?? $observed['observed_digest'] ?? '');
$privateDataplaneVerified = ($observed['private_dataplane_verified']
?? false) === true;
$globalActive = ($observed['state'] ?? null) === 'active'
&& ($observed['next_stage_allowed'] ?? false) === true
&& $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
// host operation to retry until a member is attached. Treat
// these two gate results as terminal for this revision; a later
// member mutation creates a new desired revision and operation.
$gateError = (string) ($fabricGate['error_code'] ?? '');
$terminalGate = in_array($gateError, [
'vpc_no_members', 'vpc_no_participating_hosts',
], true);
$dataPlaneDeferred = !$terminalGate
&& ($fabricGate['active'] ?? false) === true
&& ($observed['next_stage_allowed'] ?? true) === false
&& $required->count() > 0
&& $hosts !== []
&& count($hosts) === $required->count();
if ($dataPlaneDeferred) {
foreach ($hosts as $hostKey => $_item) {
if (!$required->has((int) $hostKey)) {
$dataPlaneDeferred = false;
break;
}
}
}
if ($dataPlaneDeferred) {
foreach ($required as $hostId => $_deployment) {
$item = $hosts[(string) $hostId] ?? null;
if (!is_array($item)
|| !in_array((string) ($item['state'] ?? ''), ['applying', 'active'], true)
|| ($item['transport_verified'] ?? false) !== true) {
$dataPlaneDeferred = false;
break;
}
}
}
$liveRequired = $required->filter(static fn ($row): bool =>
(string) $row->state !== 'deleting');
// A Fabric or host control-plane digest cannot prove that a
// 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,
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 = $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
// later retry lose the removal intent.
if ((string) $deployment->state !== 'deleting') {
$deployment->state = 'uncertain';
}
$deployment->last_error_code = 'vpc_host_observation_missing';
$deployment->last_failure_at = time();
$deployment->updated_at = time();
$deployment->save();
continue;
}
$itemRevision = (int) ($item['observed_revision'] ?? $item['revision'] ?? 0);
$itemDigest = (string) ($item['observed_digest'] ?? $item['digest'] ?? '');
$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';
$removalActive = $deleting
&& ($item['removed'] ?? false) === true
&& ($item['removal_verified'] ?? false) === true
&& ($item['state'] ?? null) === 'active'
&& ($item['transport_verified'] ?? false) === true
&& ($item['private_dataplane_verified'] ?? false) === true
&& $itemRevision === $revision
&& hash_equals($digest, $itemDigest);
if ($deleting) {
$hasRemovalTarget = true;
if (!$removalActive) {
$allRemovalProof = false;
}
}
$deployment->observed_revision = $itemRevision;
$deployment->observed_digest = $itemDigest !== '' ? $itemDigest : null;
// An empty-host target is only a desired control-plane
// document. Without a data-plane removal readback, preserve
// the deleting state even when the Fabric digest is exact.
if ($removalActive) {
$deployment->state = 'deleted';
$deployment->last_error_code = null;
} elseif (!$deleting) {
$deployment->state = $active ? 'active' : 'degraded';
$deployment->last_error_code = $active ? null : 'vpc_host_observation_mismatch';
} else {
$deployment->last_error_code = 'vpc_host_removal_unverified';
}
$deployment->updated_at = time();
if ($active || $removalActive) {
$deployment->last_success_at = time();
} 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) {
$observedAt = time();
foreach ([
CloudVpcSubnet::class,
CloudVpcPrivateIp::class,
CloudVpcMember::class,
CloudVpcRoute::class,
CloudVpcAclRule::class,
] as $childModel) {
$childModel::where('vpc_id', $vpc->id)
->where('state', 'deleting')
->update([
'observed_revision' => $revision,
'observed_digest' => $digest,
'state' => 'deleted',
'last_error_code' => null,
'updated_at' => $observedAt,
]);
}
$removalOnlyComplete = true;
}
$operationSucceeded = $allActive || $removalOnlyComplete;
// The engine's current observed contract is host-scoped: an
// active exact digest means the complete typed document for this
// revision was accepted by every participating host. Mirror that
// gate onto live child rows. Deletion tombstones intentionally
// remain untouched until a typed removal readback proves absence.
if ($allActive) {
$observedAt = time();
// Persist a proof marker on each member only after the full
// host-scoped private data-plane gate has passed. Older rows
// without this marker remain fail-closed in instance
// projections until a fresh observation is recorded.
CloudVpcMember::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted'])
->update([
'last_operation_id' => $operationId,
'updated_at' => $observedAt,
]);
foreach ([
CloudVpcSubnet::class,
CloudVpcPrivateIp::class,
CloudVpcMember::class,
CloudVpcRoute::class,
CloudVpcAclRule::class,
] as $childModel) {
$childModel::where('vpc_id', $vpc->id)
->where('desired_revision', $revision)
->whereNotIn('state', ['deleting', 'deleted'])
->update([
'observed_revision' => $revision,
'observed_digest' => $digest,
'state' => 'active',
'last_error_code' => null,
'updated_at' => $observedAt,
]);
}
}
$operation->observed_json = json_encode(self::boundedObserved($observed),
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
$operation->status = $operationSucceeded ? 'succeeded'
: ($dataPlaneDeferred ? 'waiting_observed'
: ($terminalGate ? 'failed' : 'uncertain'));
$operation->error_code = $operationSucceeded ? null
: ($dataPlaneDeferred ? 'vpc_data_plane_deferred'
: ($terminalGate ? $gateError : 'vpc_observation_incomplete'));
$operation->updated_at = time();
$operation->finished_at = ($operationSucceeded || $dataPlaneDeferred || $terminalGate)
? time() : null;
$operation->lease_until = 0;
$operation->save();
$vpc->observed_revision = $operationSucceeded ? $revision : (int) $vpc->observed_revision;
$vpc->observed_digest = $operationSucceeded ? $digest : $vpc->observed_digest;
$vpc->state = $operationSucceeded ? 'active' : 'degraded';
$vpc->sync_state = $operationSucceeded ? 'applied'
: ($dataPlaneDeferred ? 'waiting' : ($terminalGate ? 'failed' : 'uncertain'));
$vpc->last_error_code = $operationSucceeded ? null
: ($dataPlaneDeferred ? 'vpc_data_plane_deferred'
: ($terminalGate ? $gateError : 'vpc_observation_incomplete'));
$vpc->last_success_at = $operationSucceeded ? time() : (int) $vpc->last_success_at;
$vpc->last_failure_at = $operationSucceeded ? (int) $vpc->last_failure_at : time();
$vpc->updated_at = time();
$vpc->save();
}, 3);
}
/** Build the exact typed document signed into a VPC operation. */
public static function desiredDocument(CloudVpc $vpc): array
{
$subnets = CloudVpcSubnet::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted', 'deleting'])->orderBy('subnet_key')->get();
$members = CloudVpcMember::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted', 'deleting'])->orderBy('member_key')->get();
$routes = CloudVpcRoute::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted', 'deleting'])->orderBy('route_key')->get();
$acl = CloudVpcAclRule::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted', 'deleting'])->orderBy('priority')->orderBy('rule_key')->get();
$region = CloudRegion::where('id', (int) $vpc->region_id)->first();
$fabricRegion = (string) ($vpc->fabric_region ?? '');
if ($region === null || $fabricRegion === ''
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $fabricRegion) !== 1) {
throw new CloudError('VPC 地区记录缺失,无法生成引擎目标', 503);
}
$subnetKeys = [];
foreach ($subnets as $row) {
$subnetKeys[(int) $row->id] = (string) $row->subnet_key;
}
$instanceIds = $members->pluck('instance_id')->map(static fn ($id): int => (int) $id)
->unique()->values()->all();
$instances = $instanceIds === [] ? [] : CloudInstance::whereIn('id', $instanceIds)
->get()->keyBy('id');
$privateIpRows = $members->isEmpty() ? [] : CloudVpcPrivateIp::where('vpc_id', $vpc->id)
->whereIn('member_id', $members->pluck('id')->map(static fn ($id): int => (int) $id)->all())
->get()->keyBy('member_id');
$memberKeys = [];
$privateMacs = [];
$memberRows = [];
foreach ($members as $row) {
$instance = $instances[(int) $row->instance_id] ?? null;
$subnetKey = $subnetKeys[(int) $row->subnet_id] ?? null;
$privateIp = $privateIpRows[(int) $row->id] ?? null;
if ($instance === null || $subnetKey === null || $privateIp === null
|| (int) $row->private_ip_id !== (int) $privateIp->id
|| (int) $privateIp->subnet_id !== (int) $row->subnet_id
|| (int) $privateIp->instance_id !== (int) $row->instance_id
|| (string) $privateIp->private_ip !== (string) $row->private_ip
|| in_array((string) $privateIp->state, ['deleted', 'deleting'], true)) {
throw new CloudError('VPC 成员引用记录缺失,无法生成引擎目标', 409);
}
if ((string) $instance->status !== 'active') {
throw new CloudError('VPC 成员引用的虚拟机当前不可用,请先完成实例清理', 409);
}
$memberKey = (string) $row->member_key;
$memberKeys[(int) $row->id] = $memberKey;
// The MAC is derived from the immutable VPC/member identities so
// retries, host migration and engine restarts keep the same NIC
// identity. It is locally administered and unicast; no schema
// column is needed and the value remains part of the signed DTO.
$privateMac = self::privateMacForMember((string) $vpc->vpc_key, $memberKey);
if ($privateMac === null || isset($privateMacs[$privateMac])) {
throw new CloudError('VPC 成员私网 MAC 无效,无法生成引擎目标', 409);
}
$privateMacs[$privateMac] = $memberKey;
$memberRows[] = [
'member_id' => $memberKey,
'instance_uuid' => strtolower((string) $instance->uuid),
'host_id' => (string) $row->host_id,
'private_ip_cidr' => (string) $privateIp->private_ip . '/32',
'subnet_id' => $subnetKey,
'private_mac' => $privateMac,
];
}
$hostMembers = [];
foreach ($memberRows as $row) {
$hostMembers[$row['host_id']][] = $row['member_id'];
}
// Keep a host with an empty member list in the desired DTO while its
// deployment row is deleting. This gives the engine an explicit,
// typed removal target. The host row remains a tombstone until a
// later data-plane readback explicitly proves removal.
$deployments = CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted'])->get();
foreach ($deployments as $deployment) {
$hostMembers[(string) $deployment->host_id] ??= [];
}
$hostRows = [];
foreach ($hostMembers as $hostId => $ids) {
sort($ids, SORT_STRING);
$hostRows[] = ['host_id' => (string) $hostId, 'members' => $ids];
}
usort($hostRows, static fn (array $a, array $b): int => strcmp($a['host_id'], $b['host_id']));
$routeRows = [];
foreach ($routes as $row) {
$nextMember = $memberKeys[(int) $row->member_id] ?? null;
if ($nextMember === null) {
throw new CloudError('VPC 路由引用了不存在或正在删除的成员', 409);
}
$routeRows[] = [
'route_id' => (string) $row->route_key,
'destination_cidr' => (string) $row->destination_cidr,
'next_hop_member_id' => $nextMember,
'metric' => (int) $row->metric,
];
}
$aclRows = [];
foreach ($acl as $row) {
$aclValue = [
'acl_id' => (string) $row->rule_key,
'priority' => (int) $row->priority,
'direction' => (string) $row->direction,
'action' => (string) $row->action,
// The engine's typed vocabulary calls the unrestricted
// protocol "any"; the DB/API may retain the friendlier
// legacy spelling "all".
'protocol' => (string) $row->protocol === 'all' ? 'any' : (string) $row->protocol,
'source_cidr' => (string) $row->source_cidr,
'destination_cidr' => (string) $row->destination_cidr,
];
if ($row->port_from !== null) {
$aclValue['port_from'] = (int) $row->port_from;
$aclValue['port_to'] = (int) $row->port_to;
}
$aclRows[] = $aclValue;
}
return self::canonicalize([
'schema_version' => 1,
'vpc_id' => (string) $vpc->vpc_key,
'region' => $fabricRegion,
'fabric_id' => (string) $vpc->fabric_id,
'fabric_revision' => (int) $vpc->fabric_revision,
'cidr' => (string) $vpc->cidr,
'desired_revision' => (int) $vpc->desired_revision,
'hosts' => $hostRows,
'subnets' => array_map(static fn ($row): array => [
'subnet_id' => (string) $row->subnet_key, 'cidr' => (string) $row->cidr,
], $subnets->all()),
'members' => $memberRows,
'routes' => $routeRows,
'acls' => $aclRows,
]);
}
/**
* A VM cannot enter destructive deletion while a VPC member row still
* exists. A `deleting` row is an explicit tombstone that remains
* unusable and blocks re-attachment until future data-plane readback;
* deleting the VM first would leave the host-side removal unproven.
*/
public static function hasBlockingMembership(int $instanceId): bool
{
if ($instanceId < 1) {
return false;
}
// Keep the lifecycle guard compatible with staged migrations, while
// checking every installed ledger independently. A partial deploy
// must never turn an existing private-address row into a free delete.
$memberConnection = (new CloudVpcMember())->getConnection();
if ($memberConnection->getSchemaBuilder()->hasTable('cloud_vpc_members')
&& CloudVpcMember::where('instance_id', $instanceId)
->whereNotIn('state', ['deleted'])->exists()) {
return true;
}
$privateIpConnection = (new CloudVpcPrivateIp())->getConnection();
return $privateIpConnection->getSchemaBuilder()->hasTable('cloud_vpc_private_ips')
&& CloudVpcPrivateIp::where('instance_id', $instanceId)
->whereNotIn('state', ['deleted'])->exists();
}
public static function assertInstanceCanBeDeleted(CloudInstance $instance): void
{
if (self::hasBlockingMembership((int) $instance->id)) {
throw new CloudError('虚拟机仍加入 VPC,请先移除私网成员', 409);
}
}
/**
* Return the private-network expectation that belongs to one VM job.
*
* This deliberately reads the existing VPC ledger instead of copying a
* second target into cloud_instances/spec_json. A missing VPC schema is
* treated as the legacy "no private network" deployment; once the ledger
* exists, malformed rows are an explicit uncertain expectation and cannot
* be silently interpreted as an attached network.
*/
public static function instancePrivateExpectation(?int $instanceId): array
{
$disabled = [
'required' => false, 'state' => 'disabled', 'desired_state' => 'disabled',
'vpc_id' => null, 'member_id' => null, 'private_ip_cidr' => null,
'private_mac' => null, 'desired_revision' => 0, 'desired_digest' => null,
'reason_code' => null,
];
if ($instanceId === null || $instanceId < 1) {
return $disabled;
}
try {
$memberConnection = (new CloudVpcMember())->getConnection();
$schema = $memberConnection->getSchemaBuilder();
if (!$schema->hasTable('cloud_vpc_members')) {
return $disabled;
}
if (!$schema->hasTable('cloud_vpc_private_ips')
|| !$schema->hasTable('cloud_vpcs')) {
return [
'required' => true, 'state' => 'uncertain',
'desired_state' => 'active', 'vpc_id' => null,
'member_id' => null, 'private_ip_cidr' => null,
'private_mac' => null, 'desired_revision' => 0,
'desired_digest' => null,
'reason_code' => 'vpc_private_expectation_invalid',
];
}
$member = CloudVpcMember::where('instance_id', $instanceId)
->whereNotIn('state', ['deleted'])->orderByDesc('id')->first();
if ($member === null) {
// A private-IP lease without a live member is still a
// control-plane residue. Treat it as an uncertain target so
// lifecycle workers cannot publish a successful/public-only
// result while the orphan may remain attached on a host.
$orphanLease = CloudVpcPrivateIp::where('instance_id', $instanceId)
->whereNotIn('state', ['deleted'])->exists();
if ($orphanLease) {
return [
'required' => true, 'state' => 'uncertain',
'desired_state' => 'active', 'vpc_id' => null,
'member_id' => null, 'private_ip_cidr' => null,
'private_mac' => null, 'desired_revision' => 0,
'desired_digest' => null,
'reason_code' => 'vpc_private_expectation_invalid',
];
}
return $disabled;
}
$vpc = CloudVpc::find((int) $member->vpc_id);
$privateIp = $member->private_ip_id === null ? null
: CloudVpcPrivateIp::where('id', (int) $member->private_ip_id)->first();
$state = (string) $member->state;
$desiredState = $state === 'deleting' ? 'removed' : 'active';
// The member and its lease are one desired-state tuple. Falling
// back to the root revision/digest can hide a partially-written
// child row and would let a VM job capture a target that the VPC
// document never actually requested.
$revision = (int) ($member->desired_revision ?? 0);
$digest = self::safeDigest($member->desired_digest);
$rootRevision = (int) ($vpc?->desired_revision ?? 0);
$rootDigest = self::safeDigest($vpc?->desired_digest);
$leaseRevision = (int) ($privateIp?->desired_revision ?? 0);
$leaseDigest = self::safeDigest($privateIp?->desired_digest);
$validIp = is_string($member->private_ip)
&& filter_var($member->private_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
// `deleting` is an in-flight lease state, not proof that the
// dataplane has converged. Keep the expectation uncertain until
// the row is removed (and a fresh member is observed).
$leaseState = (string) ($privateIp?->state ?? '');
$stateMatches = $privateIp !== null && $leaseState === $state;
$ledgerMatches = $privateIp !== null
&& (int) $privateIp->vpc_id === (int) $member->vpc_id
&& (int) $privateIp->subnet_id === (int) $member->subnet_id
&& (int) ($privateIp->member_id ?? 0) === (int) $member->id
&& (int) ($privateIp->instance_id ?? 0) === $instanceId
&& (string) $privateIp->private_ip === (string) $member->private_ip
&& $stateMatches
&& !in_array($leaseState, ['deleted', 'deleting'], true);
$validRevision = $revision > 0;
$validDigest = $digest !== null;
$desiredLedgerMatches = $vpc !== null
&& $rootRevision === $revision
&& $rootDigest !== null && $digest !== null
&& self::digestMatches($rootDigest, $digest)
&& $leaseRevision === $revision
&& $leaseDigest !== null
&& self::digestMatches($digest, $leaseDigest);
if (!$validIp || !$ledgerMatches || !$validRevision || !$validDigest
|| !$desiredLedgerMatches
|| !is_string($member->member_key)
|| preg_match(self::KEY_PATTERN, (string) $member->member_key) !== 1
|| !is_string($vpc?->vpc_key)
|| preg_match(self::KEY_PATTERN, (string) $vpc->vpc_key) !== 1) {
return [
'required' => true, 'state' => 'uncertain',
'desired_state' => $desiredState,
'vpc_id' => is_string($vpc?->vpc_key) ? $vpc->vpc_key : null,
'member_id' => is_string($member->member_key) ? $member->member_key : null,
'private_ip_cidr' => $validIp ? $member->private_ip . '/32' : null,
'private_mac' => null, 'desired_revision' => max(0, $revision),
'desired_digest' => $validDigest ? $digest : null,
'reason_code' => 'vpc_private_expectation_invalid',
];
}
$privateMac = self::privateMacForMember(
(string) $vpc->vpc_key, (string) $member->member_key
);
if ($privateMac === null) {
return [
'required' => true, 'state' => 'uncertain',
'desired_state' => $desiredState,
'vpc_id' => (string) $vpc->vpc_key,
'member_id' => (string) $member->member_key,
'private_ip_cidr' => $validIp ? $member->private_ip . '/32' : null,
'private_mac' => null, 'desired_revision' => max(0, $revision),
'desired_digest' => $validDigest ? $digest : null,
'reason_code' => 'vpc_private_expectation_invalid',
];
}
return [
'required' => true, 'state' => $state,
'desired_state' => $desiredState,
'vpc_id' => (string) $vpc->vpc_key,
'member_id' => (string) $member->member_key,
'private_ip_cidr' => $member->private_ip . '/32',
'private_mac' => $privateMac,
'desired_revision' => $revision,
'desired_digest' => $digest,
'reason_code' => null,
];
} catch (\Throwable $error) {
// A live ledger that cannot be read is different from an
// installation that predates VPC tables. Fail closed for the
// former so a worker cannot publish a stale successful result.
return [
'required' => true, 'state' => 'uncertain',
'desired_state' => 'active', 'vpc_id' => null, 'member_id' => null,
'private_ip_cidr' => null, 'private_mac' => null,
'desired_revision' => 0, 'desired_digest' => null,
'reason_code' => 'vpc_private_expectation_unavailable',
];
}
}
/** Compare a job's captured target with the current ledger under a lock. */
public static function privateExpectationMatches(int $instanceId, array $captured): bool
{
if ($instanceId < 1 || $captured === []) {
return true;
}
$current = self::instancePrivateExpectation($instanceId);
// `state` is observed/transient (for example applying -> active) and
// may advance while a VM lifecycle job is running. The immutable
// target is bound by desired_state, identity, IP, revision and digest;
// removal remains strict because it changes desired_state to removed.
foreach (['required', 'desired_state', 'vpc_id', 'member_id',
'private_ip_cidr', 'private_mac', 'desired_revision', 'desired_digest'] as $key) {
if ((string) ($captured[$key] ?? null) !== (string) ($current[$key] ?? null)) {
return false;
}
}
return true;
}
/** Build a bounded instance projection for page/runtime responses. */
public static function instancePrivateProjection(int $instanceId): array
{
$expectation = self::instancePrivateExpectation($instanceId);
$base = [
'version' => 1, 'required' => (bool) $expectation['required'],
'vm_uuid' => null, 'vpc_id' => $expectation['vpc_id'] ?? null,
'member_id' => $expectation['member_id'] ?? null,
'interface' => $expectation['required'] ? 'private0' : null,
'state' => $expectation['required'] ? 'uncertain' : 'disabled',
'desired_state' => $expectation['desired_state'] ?? 'disabled',
'desired_revision' => (int) ($expectation['desired_revision'] ?? 0),
'observed_revision' => 0,
'desired_digest' => $expectation['desired_digest'] ?? null,
'observed_digest' => null, 'readback' => $expectation['required'] ? 'missing' : 'confirmed',
'link_state' => $expectation['required'] ? 'absent' : 'absent',
'private_ip_cidr' => $expectation['private_ip_cidr'] ?? null,
'private_mac' => $expectation['private_mac'] ?? null,
'reason_code' => $expectation['reason_code']
?? ($expectation['required'] ? 'vpc_private_observation_missing' : null),
'observed_at' => 0,
];
if (!$expectation['required']) {
return $base;
}
try {
$vpcKey = is_string($expectation['vpc_id'] ?? null)
? (string) $expectation['vpc_id'] : '';
$memberKey = is_string($expectation['member_id'] ?? null)
? (string) $expectation['member_id'] : '';
if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1
|| preg_match(self::KEY_PATTERN, $memberKey) !== 1) {
return $base;
}
// member_key is only unique inside a VPC. Binding the instance
// and VPC roots here prevents a stale/cross-tenant row from
// becoming a usable private projection.
$vpc = CloudVpc::where('vpc_key', $vpcKey)->first([
'id', 'vpc_key', 'state', 'sync_state', 'desired_revision',
'observed_revision', 'desired_digest', 'observed_digest',
'last_operation_id', 'last_success_at', 'updated_at',
]);
if ($vpc === null) {
return $base;
}
$member = CloudVpcMember::where('instance_id', $instanceId)
->where('vpc_id', (int) $vpc->id)
->where('member_key', $memberKey)
->whereNotIn('state', ['deleted'])
->first([
'id', 'vpc_id', 'subnet_id', 'private_ip_id', 'instance_id',
'private_ip', 'state', 'desired_revision', 'observed_revision',
'desired_digest', 'observed_digest', 'last_error_code',
'last_operation_id', 'updated_at',
]);
if ($member === null || $member->private_ip_id === null) {
return $base;
}
// A member row is not proof that its independent lease exists.
// Read back and bind every lease identity before considering the
// member's revision or digest.
$privateIp = CloudVpcPrivateIp::where('id', (int) $member->private_ip_id)
->where('vpc_id', (int) $vpc->id)
->where('member_id', (int) $member->id)
->where('instance_id', $instanceId)
->first([
'id', 'vpc_id', 'subnet_id', 'member_id', 'instance_id',
'private_ip', 'state', 'desired_revision', 'observed_revision',
'desired_digest', 'observed_digest', 'last_error_code', 'updated_at',
]);
if ($privateIp === null
|| (int) $privateIp->subnet_id !== (int) $member->subnet_id
|| (string) $privateIp->private_ip !== (string) $member->private_ip) {
return $base;
}
$observedRevision = max(0, (int) $member->observed_revision);
$observedDigest = self::safeDigest($member->observed_digest);
$privateObservedRevision = max(0, (int) $privateIp->observed_revision);
$privateObservedDigest = self::safeDigest($privateIp->observed_digest);
$privateDesiredRevision = max(0, (int) $privateIp->desired_revision);
$privateDesiredDigest = self::safeDigest($privateIp->desired_digest);
$rootDesiredRevision = max(0, (int) $vpc->desired_revision);
$rootObservedRevision = max(0, (int) $vpc->observed_revision);
$rootDesiredDigest = self::safeDigest($vpc->desired_digest);
$rootObservedDigest = self::safeDigest($vpc->observed_digest);
$rootOperationId = (string) ($vpc->last_operation_id ?? '');
// A VM job operation ID is not a VPC activation proof. The
// marker must be the current root operation that advanced the
// all-host VPC gate, and that operation must have succeeded.
$proofMarker = preg_match(self::KEY_PATTERN, $rootOperationId) === 1
&& hash_equals($rootOperationId,
(string) ($member->last_operation_id ?? ''));
$operation = $proofMarker
? CloudVpcOperation::where('vpc_id', (int) $vpc->id)
->where('operation_id', $rootOperationId)
->where('status', 'succeeded')
->first(['operation_id', 'desired_revision', 'created_at', 'finished_at'])
: null;
$operationFresh = $operation !== null
&& (int) $operation->desired_revision === (int) $base['desired_revision']
&& (int) ($operation->finished_at ?? 0) > 0
&& (int) ($operation->finished_at ?? 0)
>= (int) ($operation->created_at ?? 0)
&& (int) ($vpc->last_success_at ?? 0) > 0
&& (int) ($vpc->last_success_at ?? 0)
>= (int) ($operation->created_at ?? 0)
&& (int) ($member->updated_at ?? 0) > 0
&& (int) ($privateIp->updated_at ?? 0) > 0
&& (int) ($member->updated_at ?? 0) >= (int) ($operation->created_at ?? 0)
&& (int) ($privateIp->updated_at ?? 0) >= (int) ($operation->created_at ?? 0);
$rootExact = (string) $vpc->state === 'active'
&& (string) $vpc->sync_state === 'applied'
&& $rootDesiredRevision === (int) $base['desired_revision']
&& $rootObservedRevision === $rootDesiredRevision
&& $rootDesiredDigest !== null && $rootObservedDigest !== null
&& self::digestMatches($rootDesiredDigest, $rootObservedDigest)
&& self::digestMatches((string) $base['desired_digest'], $rootDesiredDigest);
$memberExact = (string) $member->state === 'active'
&& $observedRevision === (int) $base['desired_revision']
&& $observedDigest !== null
&& self::digestMatches((string) $base['desired_digest'], $observedDigest)
&& (int) $member->desired_revision === (int) $base['desired_revision']
&& self::digestMatches((string) $base['desired_digest'],
(string) $member->desired_digest);
$privateExact = (string) $privateIp->state === 'active'
&& $privateDesiredRevision === (int) $base['desired_revision']
&& $privateObservedRevision === $privateDesiredRevision
&& $privateDesiredDigest !== null
&& $privateObservedDigest !== null
&& self::digestMatches((string) $base['desired_digest'], $privateDesiredDigest)
&& self::digestMatches($privateDesiredDigest, $privateObservedDigest);
$confirmed = $proofMarker && $operationFresh && $rootExact
&& $memberExact && $privateExact;
$base['observed_revision'] = $observedRevision;
$base['observed_digest'] = $observedDigest;
// Keep the stable desired identity in the projection even before
// a host readback is confirmed. The observation validator below
// still requires the engine to echo the exact same MAC.
$base['private_mac'] = $expectation['private_mac'] ?? null;
$base['state'] = $confirmed ? 'active'
: ((string) $member->state === 'degraded'
|| (string) $privateIp->state === 'degraded'
? 'degraded' : 'uncertain');
$base['readback'] = $confirmed ? 'confirmed' : 'missing';
$base['reason_code'] = $confirmed ? null
: (self::safeErrorCode((string) ($privateIp->last_error_code
?? $member->last_error_code ?? ''))
?? 'vpc_private_observation_missing');
$freshness = array_values(array_filter([
(int) ($member->updated_at ?? 0),
(int) ($privateIp->updated_at ?? 0),
(int) ($vpc->last_success_at ?? 0),
], static fn (int $value): bool => $value > 0));
$base['observed_at'] = $freshness === [] ? 0 : min($freshness);
if ($confirmed) {
// The member ledger proves the VPC revision, while the
// instance network policy records whether the last gated
// operation intentionally disconnected all NICs. Pending or
// failed policy transitions must remain uncertain until the
// next engine readback, even when the previous member digest
// was exact.
$networkStatus = (string) (CloudInstance::where('id', $instanceId)
->value('network_status') ?? '');
if (in_array($networkStatus,
['blocking', 'blocking_expired', 'restore_pending', 'restoring'], true)) {
$base['state'] = 'uncertain';
$base['readback'] = 'missing';
$base['reason_code'] = 'vpc_private_observation_missing';
} elseif (in_array($networkStatus,
['blocked_traffic', 'blocked_expired'], true)) {
$base['state'] = 'suspended';
$base['link_state'] = 'down';
} else {
$base['link_state'] = 'up';
}
}
} catch (\Throwable) {
// Keep the fail-closed default projection.
}
return $base;
}
/**
* Validate one engine private_state at a mutation commit boundary.
*
* The engine's XML observation is necessary but not sufficient for an
* attached VPC: the member identity, stable MAC, desired revision and
* digest must be echoed by the VPC data-plane readback. A lifecycle
* reconcile may additionally bind the observation to its requested VM
* UUID through $expectedVmUuid.
*/
public static function validatePrivateObservation(
array $expectation, ?array $observation, string $kind,
?string $expectedVmUuid = null
): array {
$fallback = [
'version' => 1, 'required' => (bool) ($expectation['required'] ?? false),
'vm_uuid' => null, 'vpc_id' => $expectation['vpc_id'] ?? null,
'member_id' => $expectation['member_id'] ?? null,
'interface' => null, 'state' => 'uncertain',
'desired_state' => (string) ($expectation['desired_state'] ?? 'disabled'),
'desired_revision' => (int) ($expectation['desired_revision'] ?? 0),
'observed_revision' => 0,
'desired_digest' => $expectation['desired_digest'] ?? null,
'observed_digest' => null, 'readback' => 'missing',
'link_state' => 'absent', 'private_ip_cidr' => null,
'private_mac' => $expectation['private_mac'] ?? null,
'reason_code' => 'vpc_private_observation_missing',
'observed_at' => time(),
];
if (!is_array($observation)) {
return ['ok' => false, 'state' => $fallback,
'error_code' => $fallback['reason_code']];
}
if ((int) ($observation['version'] ?? 0) !== 1) {
$fallback['reason_code'] = 'vpc_private_observation_mismatch';
return ['ok' => false, 'state' => $fallback,
'error_code' => $fallback['reason_code']];
}
if ($expectedVmUuid !== null) {
$observedVmUuid = $observation['vm_uuid'] ?? null;
if (!is_string($observedVmUuid)
|| !hash_equals(strtolower($expectedVmUuid), strtolower($observedVmUuid))) {
$fallback['reason_code'] = 'vpc_private_observation_mismatch';
return ['ok' => false, 'state' => $fallback,
'error_code' => $fallback['reason_code']];
}
}
$state = $fallback;
foreach (['version', 'required', 'vm_uuid', 'vpc_id', 'member_id',
'interface', 'state', 'desired_revision', 'observed_revision',
'desired_digest', 'observed_digest', 'readback', 'link_state',
'private_ip_cidr', 'private_mac', 'reason_code', 'observed_at'] as $key) {
if (array_key_exists($key, $observation)) {
$state[$key] = $observation[$key];
}
}
$state['required'] = (bool) $state['required'];
$state['desired_revision'] = max(0, (int) $state['desired_revision']);
$state['observed_revision'] = max(0, (int) $state['observed_revision']);
$state['desired_digest'] = self::safeDigest($state['desired_digest']);
$state['observed_digest'] = self::safeDigest($state['observed_digest']);
$expectedRequired = (bool) ($expectation['required'] ?? false);
$expectedState = (string) ($expectation['desired_state'] ?? 'disabled');
$state['required'] = $expectedRequired;
$state['desired_state'] = $expectedState;
$observedVpcId = is_string($observation['vpc_id'] ?? null)
? (string) $observation['vpc_id'] : null;
$observedMemberId = is_string($observation['member_id'] ?? null)
? (string) $observation['member_id'] : null;
$state['vpc_id'] = $expectation['vpc_id'] ?? null;
$state['member_id'] = $expectation['member_id'] ?? null;
$state['desired_revision'] = (int) ($expectation['desired_revision'] ?? 0);
$state['desired_digest'] = self::safeDigest($expectation['desired_digest'] ?? null);
$state['private_ip_cidr'] = is_string($observation['private_ip_cidr'] ?? null)
? trim($observation['private_ip_cidr']) : null;
$state['private_mac'] = is_string($observation['private_mac'] ?? null)
? strtolower(trim($observation['private_mac'])) : null;
$state['state'] = is_string($observation['state'] ?? null)
? strtolower(trim($observation['state'])) : 'uncertain';
$state['readback'] = is_string($observation['readback'] ?? null)
? strtolower(trim($observation['readback'])) : 'missing';
if (!$expectedRequired) {
// When a structured observation is available, a legacy VM is
// successful only when the host readback proves that no private
// NIC exists. An unexpected private interface, even if its XML
// looks healthy, is topology drift and must not be hidden behind
// a successful public-only operation. The worker compatibility
// gate handles older responses that omit private_state entirely.
$ok = $state['state'] === 'disabled'
&& $state['readback'] === 'confirmed'
&& ($observation['required'] ?? false) === false;
if (!$ok) {
$state['state'] = 'uncertain';
$state['reason_code'] = 'vpc_private_observation_missing';
}
return ['ok' => $ok, 'state' => $state,
'error_code' => $ok ? null : $state['reason_code']];
}
$linkExpected = $expectedState === 'removed'
? 'absent'
: match ($kind) {
'network_suspend' => 'down',
// service_resume restores the VM power/autostart target. A
// quota-blocked VM may still intentionally keep every NIC down;
// network_resume is the separate operation that proves link-up.
'network_resume' => 'up',
default => null,
};
$identity = is_string($expectation['vpc_id'] ?? null)
&& is_string($expectation['member_id'] ?? null)
&& $observedVpcId !== null && $observedMemberId !== null
&& hash_equals((string) $expectation['vpc_id'], $observedVpcId)
&& hash_equals((string) $expectation['member_id'], $observedMemberId);
$shape = ($observation['required'] ?? false) === true;
if ($expectedState === 'removed') {
// Teardown evidence is allowed to omit the interface/MAC only
// when it explicitly reports the removed state. Identity,
// revision and digest below still bind the tombstone to the
// original VPC member.
$shape = $shape && in_array($state['state'], ['disabled', 'removed'], true);
} else {
$shape = $shape && ($state['interface'] ?? null) === 'private0'
&& is_string($state['private_mac'] ?? null)
&& preg_match('/^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/Di',
(string) $state['private_mac']) === 1;
}
$revision = $state['observed_revision'] === $state['desired_revision']
&& $state['desired_revision'] > 0;
$digest = is_string($state['observed_digest'])
&& is_string($state['desired_digest'])
&& hash_equals($state['desired_digest'], $state['observed_digest']);
$ip = $expectedState === 'removed'
|| (is_string($expectation['private_ip_cidr'])
&& hash_equals((string) $expectation['private_ip_cidr'], (string) $state['private_ip_cidr']));
$mac = $expectedState === 'removed'
|| (is_string($expectation['private_mac'] ?? null)
&& is_string($observation['private_mac'] ?? null)
&& is_string($state['private_mac'] ?? null)
&& hash_equals(strtolower((string) $expectation['private_mac']),
strtolower((string) $state['private_mac'])));
$desired = $expectedState === 'removed'
? in_array($state['state'], ['disabled', 'removed'], true)
: in_array($state['state'], ['active', 'suspended'], true);
$link = $linkExpected === null || $state['link_state'] === $linkExpected;
$ok = $shape && $identity && $revision && $digest && $ip && $mac && $desired && $link
&& $state['readback'] === 'confirmed';
if (!$ok) {
$state['state'] = $state['state'] === 'degraded' ? 'degraded' : 'uncertain';
$state['readback'] = $state['readback'] === 'mismatch' ? 'mismatch' : 'missing';
$state['reason_code'] = $expectedState === 'removed'
? 'vpc_private_teardown_uncertain' : 'vpc_private_observation_mismatch';
}
return ['ok' => $ok, 'state' => $state,
'error_code' => $ok ? null : $state['reason_code']];
}
/** Persist the latest VM-side observation without advancing a VPC root. */
public static function recordPrivateObservation(
int $instanceId, array $validation, string $operationId
): bool {
if ($instanceId < 1 || preg_match(self::KEY_PATTERN, $operationId) !== 1) {
return false;
}
$connection = (new CloudVpcMember())->getConnection();
$schema = $connection->getSchemaBuilder();
if (!$schema->hasTable('cloud_vpc_members')
|| !$schema->hasTable('cloud_vpc_private_ips')
|| !$schema->hasTable('cloud_vpcs')) {
return false;
}
return (bool) $connection->transaction(function () use (
$instanceId, $validation, $operationId
): bool {
// Match the VPC -> member lock order used by control-plane
// mutations. A lifecycle readback from an older desired revision
// must never be written into a newer member row.
$probe = CloudVpcMember::where('instance_id', $instanceId)
->whereNotIn('state', ['deleted'])->first();
if ($probe === null) {
return false;
}
$vpc = CloudVpc::where('id', (int) $probe->vpc_id)
->lockForUpdate()->first();
if ($vpc === null) {
return false;
}
$member = CloudVpcMember::where('id', (int) $probe->id)
->whereNotIn('state', ['deleted'])->lockForUpdate()->first();
if ($member === null) {
return false;
}
// Lock and validate the independent lease before changing either
// side of the member/lease pair. A VM readback must never copy
// its revision into a lease belonging to another member.
if ($member->private_ip_id === null) {
return false;
}
$private = CloudVpcPrivateIp::where('id', (int) $member->private_ip_id)
->where('vpc_id', (int) $vpc->id)
->where('member_id', (int) $member->id)
->where('instance_id', $instanceId)
->lockForUpdate()->first();
if ($private === null
|| (int) $private->subnet_id !== (int) $member->subnet_id
|| (string) $private->private_ip !== (string) $member->private_ip) {
return false;
}
$state = is_array($validation['state'] ?? null)
? $validation['state'] : [];
$ok = ($validation['ok'] ?? false) === true;
$desired = (string) ($state['desired_state'] ?? 'active');
$expectedRevision = max(0, (int) ($state['desired_revision'] ?? 0));
$expectedDigest = self::safeDigest($state['desired_digest'] ?? null);
$memberDigest = self::safeDigest($member->desired_digest);
if ((int) $member->desired_revision !== $expectedRevision
|| $memberDigest !== $expectedDigest) {
return false;
}
// `last_operation_id` on a member is the VPC proof marker. A
// VM lifecycle job may refresh the private lease, but must not
// replace a successful root operation marker with its unrelated
// job ID; doing so would make an already-proven VPC appear stale.
$rootOperationId = (string) ($vpc->last_operation_id ?? '');
if ($rootOperationId === '' || $rootOperationId === $operationId) {
$member->last_operation_id = $operationId;
}
$member->observed_revision = max(0, (int) ($state['observed_revision'] ?? 0));
$member->observed_digest = self::safeDigest($state['observed_digest'] ?? null);
// Mirror the member outcome into its lease row. A private-IP
// state left at `deleting` or `active` after readback would make
// the next expectation disagree with the member ledger.
$privateState = $ok
? ($desired === 'removed' ? 'deleted' : 'active')
: ($desired === 'removed' ? 'deleting' : 'uncertain');
if ($ok && $desired === 'removed') {
$member->state = 'deleted';
$member->last_error_code = null;
$private->state = $privateState;
$private->observed_revision = $member->observed_revision;
$private->observed_digest = $member->observed_digest;
$private->last_error_code = null;
$private->updated_at = time();
$private->save();
} elseif ($ok) {
$member->state = 'active';
$member->last_error_code = null;
} else {
$member->state = $desired === 'removed' ? 'deleting' : 'uncertain';
$member->last_error_code = is_string($validation['error_code'] ?? null)
? self::safeErrorCode((string) $validation['error_code']) : 'vpc_private_observation_missing';
}
$member->updated_at = time();
$member->save();
$private->state = $privateState;
$private->observed_revision = $member->observed_revision;
$private->observed_digest = $member->observed_digest;
$private->last_error_code = $member->last_error_code;
$private->updated_at = time();
$private->save();
return true;
}, 3);
}
private static function safeDigest($value): ?string
{
return is_string($value) && preg_match('/^[a-f0-9]{64}$/Di', $value) === 1
? strtolower($value) : null;
}
private static function touchDesiredLocked(CloudVpc $vpc, string $kind,
string $requestKey, string $requestHash): array
{
$vpc = CloudVpc::where('id', $vpc->id)->lockForUpdate()->firstOrFail();
$existing = CloudVpcOperation::where('vpc_id', $vpc->id)
->where('idempotency_key', $requestKey)->lockForUpdate()->first();
if ($existing !== null) {
if ((string) $existing->kind !== $kind
|| !hash_equals((string) $existing->request_hash, $requestHash)) {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
return ['vpc' => $vpc, 'operation' => $existing, 'unchanged' => true];
}
$revision = (int) $vpc->desired_revision + 1;
$vpc->desired_revision = $revision;
$vpc->state = 'applying';
$vpc->sync_state = 'pending';
$vpc->last_error_code = null;
$vpc->updated_at = time();
$vpc->save();
// A VPC mutation replaces the complete typed document. Keep older
// queued/running/uncertain rows only as audit history; they must never
// be retried after this revision becomes the current target.
$now = time();
CloudVpcOperation::where('vpc_id', $vpc->id)
->whereIn('status', ['queued', 'running', 'uncertain', 'waiting_observed'])
->where('desired_revision', '<', $revision)
->update([
'status' => 'superseded',
'error_code' => 'vpc_revision_superseded',
'finished_at' => $now,
'lease_token' => null,
'lease_until' => 0,
'updated_at' => $now,
]);
$children = [
CloudVpcSubnet::where('vpc_id', $vpc->id)->get(),
CloudVpcPrivateIp::where('vpc_id', $vpc->id)->get(),
CloudVpcMember::where('vpc_id', $vpc->id)->get(),
CloudVpcRoute::where('vpc_id', $vpc->id)->get(),
CloudVpcAclRule::where('vpc_id', $vpc->id)->get(),
];
foreach ($children as $rows) {
foreach ($rows as $row) {
$row->desired_revision = $revision;
$row->desired_digest = null;
$row->updated_at = time();
$row->save();
}
}
$hostIds = CloudVpcMember::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted', 'deleting'])
->orderBy('host_id')->pluck('host_id')->unique()->values()->all();
$hostIdSet = array_fill_keys(array_map('intval', $hostIds), true);
$existingHosts = CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->lockForUpdate()->get()->keyBy('host_id');
foreach ($hostIds as $hostId) {
$row = $existingHosts[(int) $hostId] ?? new CloudVpcHostDeployment();
if ($row->exists === false) {
$row->vpc_id = $vpc->id;
$row->host_id = (int) $hostId;
$row->created_at = time();
}
$row->fabric_revision = (int) $vpc->fabric_revision;
$row->desired_revision = $revision;
$row->desired_digest = null;
$row->state = 'applying';
$row->last_operation_id = null;
$row->updated_at = time();
$row->save();
}
foreach ($existingHosts as $hostId => $row) {
if ((string) $row->state === 'deleted') {
continue;
}
if (!isset($hostIdSet[(int) $hostId])) {
$row->state = 'deleting';
$row->desired_revision = $revision;
$row->updated_at = time();
$row->save();
}
}
$document = self::desiredDocument($vpc);
$digest = hash('sha256', self::canonicalJson($document));
$vpc->desired_digest = $digest;
$vpc->updated_at = time();
$vpc->save();
$operationId = self::randomKey();
$document['desired_digest'] = $digest;
$document['operation_id'] = $operationId;
$operation = new CloudVpcOperation();
$operation->operation_id = $operationId;
$operation->vpc_id = $vpc->id;
$operation->user_id = $vpc->user_id;
$operation->kind = $kind;
$operation->desired_revision = $revision;
$operation->idempotency_key = $requestKey;
$operation->request_hash = $requestHash;
$operation->status = 'queued';
$operation->payload_json = json_encode($document,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$operation->created_at = $operation->updated_at = time();
$operation->save();
$vpc->last_operation_id = $operationId;
$vpc->save();
CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->where('desired_revision', $revision)->update([
'desired_digest' => $digest,
'last_operation_id' => $operationId,
'updated_at' => time(),
]);
foreach ($children as $rows) {
foreach ($rows as $row) {
$row->desired_digest = $digest;
$row->updated_at = time();
$row->save();
}
}
return ['vpc' => $vpc, 'operation' => $operation, 'unchanged' => false];
}
/** Check a request key while the VPC root row is already locked. */
private static function hasOperation(CloudVpc $vpc, string $requestKey,
string $kind, string $requestHash): bool
{
$operation = CloudVpcOperation::where('vpc_id', $vpc->id)
->where('idempotency_key', $requestKey)
->lockForUpdate()->first();
if ($operation === null) {
return false;
}
if ((string) $operation->kind !== $kind
|| !hash_equals((string) $operation->request_hash, $requestHash)) {
throw new CloudError('同一请求幂等键的参数不一致', 409);
}
return true;
}
private static function requestHash(string $kind, array $value): string
{
return hash('sha256', self::canonicalJson(['kind' => $kind, 'input' => $value]));
}
/** Match Python's json.dumps(sort_keys=True,separators=(',', ':')). */
private static function canonicalize($value)
{
if (!is_array($value)) {
return $value;
}
if (array_is_list($value)) {
return array_map(static fn ($item) => self::canonicalize($item), $value);
}
$keys = array_keys($value);
sort($keys, SORT_STRING);
$result = [];
foreach ($keys as $key) {
$result[$key] = self::canonicalize($value[$key]);
}
return $result;
}
private static function canonicalJson(array $value): string
{
return json_encode(self::canonicalize($value),
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
}
private static function documentView(CloudVpc $vpc, array $actor = []): array
{
// Host placement is an administrator diagnostic. Ordinary tenants
// may see their VPC and member state, but must not learn the panel's
// host inventory or deployment revisions.
$includeHostDetails = self::canViewInfrastructure($actor);
$subnets = CloudVpcSubnet::where('vpc_id', $vpc->id)->orderBy('id')->get();
$members = CloudVpcMember::where('vpc_id', $vpc->id)->orderBy('id')->get();
$privateIps = CloudVpcPrivateIp::where('vpc_id', $vpc->id)->get()->keyBy('member_id');
$routes = CloudVpcRoute::where('vpc_id', $vpc->id)->orderBy('id')->get();
$acl = CloudVpcAclRule::where('vpc_id', $vpc->id)->orderBy('priority')->orderBy('id')->get();
$hosts = CloudVpcHostDeployment::where('vpc_id', $vpc->id)->orderBy('host_id')->get();
$operations = CloudVpcOperation::where('vpc_id', $vpc->id)->orderByDesc('id')->limit(20)->get();
return [
'vpc' => self::publicRoot($vpc, $includeHostDetails),
'subnets' => $subnets->map(static fn ($row): array => self::publicSubnet($row))->all(),
'members' => $members->map(static fn ($row): array => self::publicMember(
$row, $includeHostDetails, $privateIps[(int) $row->id] ?? null
))->all(),
'routes' => $routes->map(static fn ($row): array => self::publicRoute($row))->all(),
'acl_rules' => $acl->map(static fn ($row): array => self::publicAcl($row))->all(),
'hosts' => $includeHostDetails
? $hosts->map(static fn ($row): array => self::publicHost($row))->all()
: [],
'operations' => $operations->map(static fn ($row): array => self::publicOperation($row))->all(),
];
}
private static function publicRoot(CloudVpc $vpc, bool $includeInfrastructure = false): array
{
$desiredDigest = (string) ($vpc->desired_digest ?? '');
$observedDigest = (string) ($vpc->observed_digest ?? '');
$hostRows = CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted'])->get();
$hostsReady = $hostRows->count() > 0;
$pendingTombstone = CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->where('state', 'deleting')->exists();
foreach ([
CloudVpcSubnet::class,
CloudVpcPrivateIp::class,
CloudVpcMember::class,
CloudVpcRoute::class,
CloudVpcAclRule::class,
] as $childModel) {
if ($childModel::where('vpc_id', $vpc->id)->where('state', 'deleting')->exists()) {
$pendingTombstone = true;
break;
}
}
if ($pendingTombstone) {
$hostsReady = false;
}
// A VPC projection is not usable while any live member points at an
// instance that has left the active lifecycle state. This closes the
// window where a delete_failed/uncertain VM could leave an otherwise
// matching root digest looking healthy to the tenant UI.
$memberInstances = CloudVpcMember::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted'])->pluck('instance_id')->unique()->values()->all();
if ($memberInstances !== []) {
$instanceStates = CloudInstance::whereIn('id', $memberInstances)
->pluck('status', 'id');
foreach ($memberInstances as $instanceId) {
if ((string) ($instanceStates[(int) $instanceId] ?? '') !== 'active') {
$hostsReady = false;
break;
}
}
}
foreach ($hostRows as $host) {
if ((string) $host->state !== 'active'
|| (int) $host->desired_revision !== (int) $vpc->desired_revision
|| (int) $host->observed_revision !== (int) $vpc->desired_revision
|| !self::digestMatches((string) $host->desired_digest, $desiredDigest)
|| !self::digestMatches((string) $host->observed_digest, $desiredDigest)) {
$hostsReady = false;
break;
}
}
$rootReady = self::digestMatches($desiredDigest, $observedDigest);
$result = [
'vpc_key' => (string) $vpc->vpc_key, 'name' => (string) $vpc->name,
'region_id' => (int) $vpc->region_id, 'cidr' => (string) $vpc->cidr,
'max_members' => (int) $vpc->max_members, 'state' => (string) $vpc->state,
'sync_state' => (string) $vpc->sync_state,
'desired_revision' => (int) $vpc->desired_revision,
'observed_revision' => (int) $vpc->observed_revision,
'usable' => (string) $vpc->state === 'active'
&& (string) $vpc->sync_state === 'applied'
&& (int) $vpc->desired_revision === (int) $vpc->observed_revision
&& $rootReady && $hostsReady,
'last_operation_id' => $vpc->last_operation_id,
'last_error_code' => self::safeErrorCode((string) ($vpc->last_error_code ?? '')),
'created_at' => (int) $vpc->created_at, 'updated_at' => (int) $vpc->updated_at,
];
if ($includeInfrastructure) {
$result['fabric_id'] = (string) $vpc->fabric_id;
$result['fabric_region'] = (string) ($vpc->fabric_region ?? '');
$result['fabric_revision'] = (int) $vpc->fabric_revision;
}
return $result;
}
private static function publicSubnet($row): array
{
return ['subnet_key' => (string) $row->subnet_key, 'cidr' => (string) $row->cidr,
'gateway_ip' => $row->gateway_ip, 'state' => (string) $row->state,
'desired_revision' => (int) $row->desired_revision,
'observed_revision' => (int) $row->observed_revision,
'last_error_code' => self::safeErrorCode((string) ($row->last_error_code ?? ''))];
}
private static function publicMember($row, bool $includeHostDetails = false, $privateIp = null): array
{
$result = ['member_key' => (string) $row->member_key,
'instance_id' => (int) $row->instance_id,
'private_ip' => $privateIp === null
? (string) $row->private_ip : (string) $privateIp->private_ip,
'state' => (string) $row->state, 'desired_revision' => (int) $row->desired_revision,
'observed_revision' => (int) $row->observed_revision,
'last_error_code' => self::safeErrorCode((string) ($row->last_error_code ?? ''))];
if ($includeHostDetails) {
$result['host_id'] = (int) $row->host_id;
}
return $result;
}
private static function publicRoute($row): array
{
return ['route_key' => (string) $row->route_key,
'destination_cidr' => (string) $row->destination_cidr,
'next_hop_ip' => (string) $row->next_hop_ip, 'metric' => (int) $row->metric,
'state' => (string) $row->state, 'desired_revision' => (int) $row->desired_revision,
'observed_revision' => (int) $row->observed_revision];
}
private static function publicAcl($row): array
{
return ['rule_key' => (string) $row->rule_key, 'priority' => (int) $row->priority,
'direction' => (string) $row->direction, 'action' => (string) $row->action,
'protocol' => (string) $row->protocol, 'source_cidr' => (string) $row->source_cidr,
'destination_cidr' => (string) $row->destination_cidr,
'port_from' => $row->port_from === null ? null : (int) $row->port_from,
'port_to' => $row->port_to === null ? null : (int) $row->port_to,
'state' => (string) $row->state];
}
private static function publicHost($row): array
{
return ['host_id' => (int) $row->host_id, 'state' => (string) $row->state,
'fabric_revision' => (int) $row->fabric_revision,
'desired_revision' => (int) $row->desired_revision,
'observed_revision' => (int) $row->observed_revision,
'last_error_code' => self::safeErrorCode((string) ($row->last_error_code ?? ''))];
}
private static function publicOperation($row): array
{
return ['operation_id' => (string) $row->operation_id, 'kind' => (string) $row->kind,
'desired_revision' => (int) $row->desired_revision, 'status' => (string) $row->status,
'error_code' => self::safeErrorCode((string) ($row->error_code ?? '')),
'created_at' => (int) $row->created_at, 'updated_at' => (int) $row->updated_at,
'finished_at' => $row->finished_at === null ? null : (int) $row->finished_at];
}
private static function findOwned(string $key, array $actor, bool $write): CloudVpc
{
self::assertKey($key, 'VPC');
$query = CloudVpc::where('vpc_key', $key);
if (!self::isGlobal($actor)) {
$query->where('user_id', (int) ($actor['user_id'] ?? 0));
} elseif ($write && !($actor['can_manage'] ?? false)) {
throw new CloudError('无权修改该 VPC', 403);
}
$vpc = $query->first();
if ($vpc === null) {
throw new CloudError('VPC 不存在或无权访问', 404);
}
return $vpc;
}
private static function lockOwned(string $key, array $actor): CloudVpc
{
$query = CloudVpc::where('vpc_key', $key);
if (!self::isGlobal($actor)) {
$query->where('user_id', (int) ($actor['user_id'] ?? 0));
}
return $query->lockForUpdate()->first()
?? throw new CloudError('VPC 不存在或无权访问', 404);
}
private static function isGlobal(array $actor): bool
{
return ($actor['is_admin'] ?? false) === true
&& ($actor['is_super_admin'] ?? false) === true
&& ($actor['can_manage'] ?? false) === true;
}
private static function canViewInfrastructure(array $actor): bool
{
return ($actor['is_admin'] ?? false) === true
&& ($actor['can_manage'] ?? false) === true;
}
private static function assertKey($value, string $label): string
{
if (!is_string($value) || preg_match(self::KEY_PATTERN, $value) !== 1) {
throw new CloudError($label . '标识无效');
}
return strtolower($value);
}
private static function randomKey(): string
{
return bin2hex(random_bytes(16));
}
private static function requestKey($value): string
{
if (!is_string($value) || preg_match(self::REQUEST_KEY_PATTERN, $value) !== 1) {
throw new CloudError('请求幂等键无效');
}
return $value;
}
private static function fabricId($value): string
{
if (!is_string($value) || preg_match(self::FABRIC_KEY_PATTERN, $value) !== 1) {
throw new CloudError('Fabric 标识无效');
}
return $value;
}
private static function positiveInt($value, int $min, int $max, string $message): int
{
$parsed = filter_var($value, FILTER_VALIDATE_INT,
['options' => ['min_range' => $min, 'max_range' => $max]]);
if ($parsed === false) {
throw new CloudError($message);
}
return (int) $parsed;
}
private static function nonNegativeInt($value, int $max, string $message): int
{
return self::positiveInt($value, 0, $max, $message);
}
/** Strict canonical IPv4 CIDR parser with RFC1918 enforcement. */
private static function cidr($value, int $minPrefix, int $maxPrefix, string $label): array
{
if (!is_string($value)) {
throw new CloudError($label . '格式无效');
}
$parts = explode('/', trim($value), 2);
if (count($parts) !== 2 || filter_var($parts[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
|| !preg_match('/^(?:[0-9]|[12][0-9]|3[0-2])$/D', $parts[1])) {
throw new CloudError($label . '必须使用有效 IPv4 CIDR');
}
$prefix = (int) $parts[1];
if ($prefix < $minPrefix || $prefix > $maxPrefix) {
throw new CloudError($label . '前缀长度不在允许范围内');
}
$ip = self::ipToInt($parts[0]);
$block = (int) (2 ** (32 - $prefix));
$network = intdiv($ip, $block) * $block;
$broadcast = $network + $block - 1;
if (!self::isRfc1918($network, $broadcast)) {
throw new CloudError($label . '必须使用 RFC1918 私网地址');
}
return ['cidr' => self::intToIp($network) . '/' . $prefix,
'network' => $network, 'broadcast' => $broadcast, 'prefix' => $prefix];
}
private static function ipv4($value, string $label): string
{
if (!is_string($value) || filter_var(trim($value), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
throw new CloudError($label . '必须是 IPv4 地址');
}
return self::intToIp(self::ipToInt(trim($value)));
}
private static function ipToInt(string $ip): int
{
$packed = inet_pton($ip);
if ($packed === false || strlen($packed) !== 4) {
throw new CloudError('IPv4 地址无效');
}
$unpacked = unpack('Nvalue', $packed);
return (int) sprintf('%u', (int) $unpacked['value']);
}
private static function intToIp(int $value): string
{
$packed = pack('N', $value);
$ip = inet_ntop($packed);
if ($ip === false) {
throw new CloudError('IPv4 地址转换失败', 500);
}
return $ip;
}
private static function isRfc1918(int $network, int $broadcast): bool
{
return ($network >= self::ipToInt('10.0.0.0') && $broadcast <= self::ipToInt('10.255.255.255'))
|| ($network >= self::ipToInt('172.16.0.0') && $broadcast <= self::ipToInt('172.31.255.255'))
|| ($network >= self::ipToInt('192.168.0.0') && $broadcast <= self::ipToInt('192.168.255.255'));
}
private static function contains(int $outerNetwork, int $outerBroadcast,
int $network, int $broadcast): bool
{
return $network >= $outerNetwork && $broadcast <= $outerBroadcast;
}
private static function overlap(array $left, array $right): bool
{
return $left['network'] <= $right['broadcast'] && $right['network'] <= $left['broadcast'];
}
private static function assertWithinVpc(array $value, CloudVpc $vpc): void
{
$root = self::cidr((string) $vpc->cidr, 16, 24, 'VPC CIDR');
if (!self::contains($root['network'], $root['broadcast'], $value['network'], $value['broadcast'])) {
throw new CloudError('子网必须完全位于 VPC CIDR 内');
}
}
/**
* Return the first address not present in the durable lease ledger.
*
* Deleted rows are intentionally still occupied here. The data-plane
* phase has not yet supplied an exact removal readback, so reusing a
* tombstoned address could make an old host rule select a new VM.
*/
private static function firstFreeIp($subnet, $privateIps): string
{
$used = [];
foreach ($privateIps as $privateIp) {
$used[(int) $privateIp->private_ip_int] = true;
}
$start = (int) $subnet->network_address + 1;
$end = (int) $subnet->broadcast_address - 1;
for ($ip = $start; $ip <= $end && $ip - $start < self::MAX_MEMBERS; $ip++) {
if (!isset($used[$ip]) && (string) $subnet->gateway_ip !== self::intToIp($ip)) {
return self::intToIp($ip);
}
}
throw new CloudError('子网可用私网 IP 已耗尽', 409);
}
/**
* Lock and validate the one independent address lease owned by a member.
* A missing or mismatched row is a control-plane integrity failure; fail
* closed instead of reconstructing the address from the member duplicate.
*/
private static function lockedPrivateIpForMember(CloudVpcMember $member): CloudVpcPrivateIp
{
$privateIp = CloudVpcPrivateIp::where('vpc_id', (int) $member->vpc_id)
->where('member_id', (int) $member->id)
->lockForUpdate()->first();
if ($privateIp === null || (int) $member->private_ip_id !== (int) $privateIp->id) {
throw new CloudError('VPC 私网地址账本缺失,请联系管理员', 503);
}
return $privateIp;
}
private static function assertInstanceRegion(CloudInstance $instance, int $regionId): void
{
$fabricConnection = (new CloudRegionFabric())->getConnection();
if (!$fabricConnection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
throw new CloudError('VPC Fabric 映射表尚未安装', 503);
}
$region = CloudRegion::find($regionId);
$host = CloudHost::find((int) $instance->host_id);
$fabric = CloudRegionFabric::where('region_id', $regionId)
->where('state', 'active')->first();
if ($region === null || $host === null || $fabric === null) {
throw new CloudError('虚拟机宿主机地区信息缺失', 409);
}
$hostRegion = strtolower(trim((string) $host->region));
$accepted = [strtolower((string) $region->id), strtolower((string) $region->code),
strtolower((string) $region->name)];
if ($hostRegion === '' || !in_array($hostRegion, $accepted, true)) {
throw new CloudError('VPC 与虚拟机必须位于同一地区', 409);
}
// The engine Fabric compares its canonical region string with each
// host profile. Require the panel host record to carry that same
// value before a member can enter the desired document; otherwise a
// tenant could be accepted into a VPC that can never pass the
// all-host Fabric gate.
if (strcasecmp(trim((string) $host->region), (string) $fabric->fabric_region) !== 0) {
throw new CloudError('虚拟机宿主机地区别名与 WireGuard Fabric 不一致', 409);
}
}
private static function routeInput($value): array
{
if (!is_array($value) || !array_is_list($value) || count($value) > self::MAX_ROUTES) {
throw new CloudError('路由列表无效或超过上限');
}
$result = [];
foreach ($value as $item) {
if (!is_array($item) || array_is_list($item)) {
throw new CloudError('路由规则格式无效');
}
CloudInput::only($item, ['route_key', 'destination_cidr', 'next_hop_ip', 'metric']);
$key = self::assertKey($item['route_key'] ?? null, '路由');
// The host data plane is intentionally routed as exact /32s.
// Accepting a wider prefix here would let a tenant's route
// replace the per-member cryptokey and nft boundary, even though
// the engine later rejects it. Reject it at the PHP boundary so
// the API and engine cannot disagree about a usable target.
$destination = self::cidr($item['destination_cidr'] ?? null, 32, 32, '路由目标');
$next = self::ipv4($item['next_hop_ip'] ?? null, '路由下一跳');
$metric = self::positiveInt($item['metric'] ?? 100, 1, 65535, '路由 metric 无效');
$result[] = ['route_key' => $key, 'destination' => $destination,
'next_hop_ip' => $next, 'metric' => $metric];
}
return $result;
}
private static function aclInput($value): array
{
if (!is_array($value) || !array_is_list($value) || count($value) > self::MAX_ACL_RULES) {
throw new CloudError('ACL 规则列表无效或超过上限');
}
$result = [];
$priorities = [];
foreach ($value as $item) {
if (!is_array($item) || array_is_list($item)) {
throw new CloudError('ACL 规则格式无效');
}
CloudInput::only($item, [
'rule_key', 'priority', 'direction', 'action', 'protocol',
'source_cidr', 'destination_cidr', 'port_from', 'port_to',
]);
$key = self::assertKey($item['rule_key'] ?? null, 'ACL 规则');
$priority = self::positiveInt($item['priority'] ?? null, 1, 1000000, 'ACL 优先级无效');
if (isset($priorities[$priority])) {
throw new CloudError('ACL 优先级不能重复');
}
$priorities[$priority] = true;
$direction = $item['direction'] ?? null;
$action = $item['action'] ?? null;
$protocol = $item['protocol'] ?? null;
if (!is_string($direction) || !in_array($direction, self::DIRECTIONS, true)
|| !is_string($action) || !in_array($action, self::ACTIONS, true)
|| !is_string($protocol) || !in_array($protocol, self::PROTOCOLS, true)) {
throw new CloudError('ACL 方向、动作或协议无效');
}
$source = self::cidr($item['source_cidr'] ?? null, 8, 32, 'ACL 源地址');
$destination = self::cidr($item['destination_cidr'] ?? null, 8, 32, 'ACL 目标地址');
$from = $item['port_from'] ?? null;
$to = $item['port_to'] ?? null;
if ($from !== null || $to !== null) {
if (!in_array($protocol, ['tcp', 'udp'], true)) {
throw new CloudError('只有 TCP/UDP ACL 可以设置端口');
}
$from = self::positiveInt($from, 1, 65535, 'ACL 起始端口无效');
$to = self::positiveInt($to, $from, 65535, 'ACL 结束端口无效');
}
$result[] = ['rule_key' => $key, 'priority' => $priority,
'direction' => $direction, 'action' => $action, 'protocol' => $protocol,
'source' => $source, 'destination' => $destination,
'port_from' => $from, 'port_to' => $to];
}
return $result;
}
private static function safeErrorCode(string $value): ?string
{
return preg_match('/^[a-z0-9_]{1,64}$/D', $value) === 1 ? $value : null;
}
private static function digestMatches(string $left, string $right): bool
{
return preg_match('/^[a-f0-9]{64}$/D', $left) === 1
&& preg_match('/^[a-f0-9]{64}$/D', $right) === 1
&& hash_equals($left, $right);
}
/**
* Derive the stable locally-administered MAC used by one VPC member.
*
* Member keys are scoped to a VPC, so binding both identities prevents a
* key reused in another tenant from receiving the same NIC identity. The
* first octet is forced to unicast/local-administered (02/06/0a/0e
* families) and the remaining bytes are cryptographic hash material.
*/
private static function privateMacForMember(string $vpcKey, string $memberKey): ?string
{
if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1
|| preg_match(self::KEY_PATTERN, $memberKey) !== 1) {
return null;
}
$digest = hash('sha256', 'virt-cloud:vpc-private0:' . $vpcKey . ':' . $memberKey);
$octets = [];
for ($index = 0; $index < 6; $index++) {
$octets[] = hexdec(substr($digest, $index * 2, 2));
}
$octets[0] = ($octets[0] & 0xfc) | 0x02;
return implode(':', array_map(
static fn (int $octet): string => sprintf('%02x', $octet), $octets
));
}
private static function privateBridgeForVpc(string $vpcKey): ?string
{
return preg_match(self::KEY_PATTERN, $vpcKey) === 1
? 'vcv-' . substr(hash('sha256', $vpcKey), 0, 11) : null;
}
private static function privateNftTableForVpc(string $vpcKey): ?string
{
return preg_match(self::KEY_PATTERN, $vpcKey) === 1
? 'virt_cloud_vpc_' . substr(hash('sha256', $vpcKey), 0, 12) : null;
}
private static function privateRouteTableForVpc(string $vpcKey): ?int
{
if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1) {
return null;
}
$digest = hash('sha256', $vpcKey);
return 10000 + (hexdec(substr($digest, 12, 8)) % 10000);
}
/**
* Validate typed host-side private dataplane evidence. Raw command output
* is deliberately ignored: only bounded identity, route, ACL and XML
* readback fields can open the PHP VPC gate.
*
* A null return means the evidence is exact; otherwise the returned code
* is safe to persist as a diagnostic and keeps the host degraded.
*/
private static function validateHostDataplaneEvidence(
array $item,
string $hostId,
array $expectedMembers,
array $allMembers,
array $expectedDestinations,
array $desiredRoutes,
string $vpcKey,
int $revision,
string $digest
): ?string {
// These fields are identity evidence, not optional status hints. A
// compact/legacy host projection must therefore stay closed until a
// full typed readback is supplied by the engine.
if (!array_key_exists('vpc_id', $item)
|| !array_key_exists('host_id', $item)
|| !array_key_exists('desired_revision', $item)
|| !array_key_exists('desired_digest', $item)
|| !array_key_exists('observed_revision', $item)
|| !array_key_exists('observed_digest', $item)
|| (string) $item['vpc_id'] !== $vpcKey
|| !self::digestMatches($digest, (string) $item['desired_digest'])
|| (string) $item['host_id'] !== $hostId
|| (string) ($item['state'] ?? '') !== 'active'
|| (int) $item['desired_revision'] !== $revision
|| (int) $item['observed_revision'] !== $revision
|| !self::digestMatches($digest, (string) $item['observed_digest'])) {
return 'vpc_private_readback_mismatch';
}
// A host removal is a distinct typed proof. It must not be treated
// as an empty successful apply: all panel-owned resources and
// tenant-facing evidence must be absent before a deleting deployment
// can be finalized.
if (($item['removed'] ?? false) === true) {
$readback = $item['readback'] ?? null;
$readbackState = is_string($readback) ? strtolower($readback)
: (is_array($readback)
? strtolower((string) ($readback['state'] ?? $readback['status'] ?? ''))
: '');
foreach (['member_nics', 'routes', 'wg_allowed_ips', 'proxy_ips'] as $field) {
if (!is_array($item[$field] ?? null) || $item[$field] !== []) {
return 'vpc_private_removal_readback_mismatch';
}
}
if ($expectedMembers !== []
|| $readbackState !== 'confirmed'
|| ($item['bridge'] ?? null) !== null
|| ($item['bridge_owner'] ?? null) !== null
|| ($item['nft_table'] ?? null) !== null
|| !in_array((string) ($item['rollback'] ?? ''), ['none', 'ok'], true)) {
return 'vpc_private_removal_readback_mismatch';
}
return null;
}
$bridge = self::privateBridgeForVpc($vpcKey);
$nftTable = self::privateNftTableForVpc($vpcKey);
$routeTable = self::privateRouteTableForVpc($vpcKey);
if ($bridge === null || $nftTable === null
|| $routeTable === null
|| (string) ($item['bridge'] ?? '') !== $bridge
|| (string) ($item['bridge_owner'] ?? '') !== self::PRIVATE_DATAPLANE_OWNER
|| (string) ($item['nft_table'] ?? '') !== $nftTable
|| ($item['anti_spoof'] ?? false) !== true
|| (int) ($item['rp_filter'] ?? -1) !== 2
|| (int) ($item['proxy_arp'] ?? -1) !== 0
|| (int) ($item['proxy_arp_pvlan'] ?? -1) !== 1
|| (int) ($item['acl_revision'] ?? 0) !== $revision
|| !array_key_exists('rollback', $item)
|| !in_array((string) $item['rollback'], ['none', 'ok'], true)) {
return 'vpc_private_dataplane_unverified';
}
$readback = $item['readback'] ?? null;
$readbackState = is_string($readback) ? strtolower($readback)
: (is_array($readback)
? strtolower((string) ($readback['state'] ?? $readback['status'] ?? ''))
: '');
if ($readbackState !== 'confirmed') {
return 'vpc_private_readback_missing';
}
// The bridge uses routed guest /32s. Generic proxy ARP stays off;
// only exact panel-owned proxy-neighbour entries (with pvlan enabled
// for same-bridge next hops) may answer. A missing or broadened
// proxy set keeps the host degraded.
$proxyIps = $item['proxy_ips'] ?? null;
if (!is_array($proxyIps)) {
return 'vpc_private_proxy_arp_readback_missing';
}
$expectedProxyIps = [];
foreach ($expectedDestinations as $destination) {
if (!is_string($destination)
|| !preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\/32$/D', $destination, $match)
|| filter_var($match[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return 'vpc_private_proxy_arp_readback_mismatch';
}
$expectedProxyIps[] = $match[1];
}
$expectedProxyIps = array_values(array_unique($expectedProxyIps));
sort($expectedProxyIps, SORT_STRING);
$observedProxyIps = [];
foreach ($proxyIps as $proxyIp) {
if (!is_string($proxyIp)
|| filter_var($proxyIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return 'vpc_private_proxy_arp_readback_mismatch';
}
$observedProxyIps[] = $proxyIp;
}
$observedProxyIps = array_values(array_unique($observedProxyIps));
sort($observedProxyIps, SORT_STRING);
if ($observedProxyIps !== $expectedProxyIps) {
return 'vpc_private_proxy_arp_readback_mismatch';
}
$nics = $item['member_nics'] ?? null;
if (!is_array($nics) || count($nics) !== count($expectedMembers)) {
return 'vpc_private_nic_readback_mismatch';
}
$seen = [];
foreach ($nics as $nic) {
if (!is_array($nic)) {
return 'vpc_private_nic_readback_mismatch';
}
$memberId = (string) ($nic['member_id'] ?? '');
if ($memberId === '' || isset($seen[$memberId])
|| !isset($expectedMembers[$memberId])) {
return 'vpc_private_nic_readback_mismatch';
}
$expected = $expectedMembers[$memberId];
$observedMac = strtolower((string) ($nic['private_mac'] ?? ''));
if ((string) ($nic['interface'] ?? '') !== self::PRIVATE_INTERFACE
|| strtolower((string) ($nic['instance_uuid'] ?? ''))
!== strtolower((string) $expected['instance_uuid'])
|| (string) ($nic['private_ip_cidr'] ?? '')
!== (string) $expected['private_ip_cidr']
|| $observedMac !== strtolower((string) $expected['private_mac'])
|| ($nic['xml_verified'] ?? false) !== true) {
return 'vpc_private_nic_readback_mismatch';
}
$seen[$memberId] = true;
}
if (count($seen) !== count($expectedMembers)) {
return 'vpc_private_nic_readback_mismatch';
}
// Routes are checked against the exact host-specific next hop and
// metric. A dataplane readback must never install a default or
// otherwise broad route owned by a different subsystem.
$routes = $item['routes'] ?? null;
if (!is_array($routes)) {
return 'vpc_private_route_readback_missing';
}
$memberById = [];
foreach ($allMembers as $member) {
if (is_array($member) && isset($member['member_id'])) {
$memberById[(string) $member['member_id']] = $member;
}
}
$expectedRouteRows = [];
foreach ($allMembers as $member) {
if (!is_array($member) || !isset($member['private_ip_cidr'])) {
continue;
}
$expectedRouteRows[] = [
'destination_cidr' => (string) $member['private_ip_cidr'],
'device' => (string) (($member['host_id'] ?? '') === $hostId
? $bridge : self::FABRIC_INTERFACE),
'via' => null,
'metric' => 100,
];
}
foreach ($desiredRoutes as $desiredRoute) {
if (!is_array($desiredRoute)
|| !isset($desiredRoute['destination_cidr'])) {
return 'vpc_private_route_readback_mismatch';
}
$nextMemberId = isset($desiredRoute['next_hop_member_id'])
? (string) $desiredRoute['next_hop_member_id'] : '';
$nextMember = $nextMemberId !== ''
? ($memberById[$nextMemberId] ?? null) : null;
$nextHost = is_array($nextMember)
? (string) ($nextMember['host_id'] ?? '')
: (string) ($desiredRoute['next_hop_host_id'] ?? '');
if ($nextHost === '') {
return 'vpc_private_route_readback_mismatch';
}
$expectedRouteRows[] = [
'destination_cidr' => (string) $desiredRoute['destination_cidr'],
'device' => $nextHost === $hostId ? $bridge : self::FABRIC_INTERFACE,
'via' => $nextHost === $hostId && is_array($nextMember)
? (string) preg_replace(
'/\/32$/D', '',
(string) ($nextMember['private_ip']
?? $nextMember['private_ip_cidr'] ?? '')
)
: null,
'metric' => (int) ($desiredRoute['metric'] ?? 100),
];
}
$expectedRouteMap = [];
foreach ($expectedRouteRows as $expectedRoute) {
$via = (string) ($expectedRoute['via'] ?? '');
$key = $expectedRoute['destination_cidr'] . '|'
. $expectedRoute['device'] . '|' . $via . '|'
. (string) $expectedRoute['metric'];
if (isset($expectedRouteMap[$key])) {
return 'vpc_private_route_readback_mismatch';
}
$expectedRouteMap[$key] = true;
}
$seenRoutes = [];
foreach ($routes as $route) {
if (!is_array($route)
|| !is_string($route['destination_cidr'] ?? null)
|| !isset($route['device'])
|| !is_string($route['device'])
|| $route['device'] === ''
|| !array_key_exists('table', $route)
|| !in_array($route['device'], [$bridge, self::FABRIC_INTERFACE], true)
|| (string) ($route['owner'] ?? '') !== self::PRIVATE_DATAPLANE_OWNER) {
return 'vpc_private_route_readback_mismatch';
}
$destination = (string) $route['destination_cidr'];
if (in_array($destination, ['0.0.0.0/0', '::/0'], true)
|| !in_array($destination, $expectedDestinations, true)) {
return 'vpc_private_route_readback_mismatch';
}
$via = $route['via'] ?? null;
if ($via !== null && !is_string($via)) {
return 'vpc_private_route_readback_mismatch';
}
$metric = $route['metric'] ?? null;
if ((is_string($metric) && !ctype_digit($metric))
|| (!is_int($metric) && !is_string($metric))) {
return 'vpc_private_route_readback_mismatch';
}
$metric = (int) $metric;
$key = $destination . '|' . (string) $route['device'] . '|'
. (string) ($via ?? '') . '|' . (string) $metric;
if (isset($seenRoutes[$key])) {
return 'vpc_private_route_readback_mismatch';
}
if (!isset($expectedRouteMap[$key])) {
return 'vpc_private_route_readback_mismatch';
}
$seenRoutes[$key] = true;
if ((!is_int($route['table'])
&& !(is_string($route['table']) && is_numeric($route['table'])))
|| (int) $route['table'] !== $routeTable) {
return 'vpc_private_route_readback_mismatch';
}
}
$expectedRouteSet = array_keys($expectedRouteMap);
$observedRouteSet = array_keys($seenRoutes);
sort($expectedRouteSet, SORT_STRING);
sort($observedRouteSet, SORT_STRING);
if ($observedRouteSet !== $expectedRouteSet) {
return 'vpc_private_route_readback_mismatch';
}
// The engine reports tenant AllowedIPs separately from Fabric overlay
// addresses. Require an exact remote-member /32 set, preventing a
// broad prefix from crossing a host or VPC boundary.
$expectedPeers = [];
foreach ($allMembers as $member) {
if ((string) ($member['host_id'] ?? '') === $hostId) {
continue;
}
$peerHost = (string) ($member['host_id'] ?? '');
$expectedPeers[$peerHost][] = (string) $member['private_ip_cidr'];
}
foreach ($desiredRoutes as $route) {
if (!is_array($route)) {
return 'vpc_private_wireguard_readback_mismatch';
}
$target = null;
if (isset($route['next_hop_member_id'])) {
$target = $memberById[(string) $route['next_hop_member_id']] ?? null;
}
$peerHost = is_array($target)
? (string) ($target['host_id'] ?? '')
: (string) ($route['next_hop_host_id'] ?? '');
if ($peerHost !== '' && $peerHost !== $hostId
&& isset($route['destination_cidr'])) {
$expectedPeers[$peerHost][] = (string) $route['destination_cidr'];
}
}
foreach ($expectedPeers as &$ips) {
$ips = array_values(array_unique($ips));
sort($ips, SORT_STRING);
}
unset($ips);
$wg = $item['wg_allowed_ips'] ?? null;
if (!is_array($wg)) {
return 'vpc_private_wireguard_readback_missing';
}
$seenPeers = [];
foreach ($wg as $peer) {
if (!is_array($peer)) {
return 'vpc_private_wireguard_readback_mismatch';
}
$peerHost = (string) ($peer['peer_host_id'] ?? '');
$tenantIps = $peer['tenant_allowed_ips'] ?? $peer['allowed_ips'] ?? null;
$publicKey = $peer['public_key'] ?? null;
if ($peerHost === '' || isset($seenPeers[$peerHost])
|| !array_key_exists($peerHost, $expectedPeers)
|| !is_array($tenantIps)
|| !is_string($publicKey)
|| preg_match('/^[A-Za-z0-9+\/]{42}[A-Za-z0-9+\/]==$|^[A-Za-z0-9+\/]{43}=$/D',
$publicKey) !== 1) {
return 'vpc_private_wireguard_readback_mismatch';
}
$decodedKey = base64_decode($publicKey, true);
if ($decodedKey === false || strlen($decodedKey) !== 32
|| trim($decodedKey, "\0") === '') {
return 'vpc_private_wireguard_readback_mismatch';
}
$normalizedIps = [];
foreach ($tenantIps as $ip) {
if (!is_string($ip)) {
return 'vpc_private_wireguard_readback_mismatch';
}
$normalizedIps[] = $ip;
}
$normalizedIps = array_values(array_unique($normalizedIps));
sort($normalizedIps, SORT_STRING);
foreach ($normalizedIps as $ip) {
if (!preg_match('/^[0-9.]+\/32$/D', $ip)) {
return 'vpc_private_wireguard_readback_mismatch';
}
}
if ($normalizedIps !== $expectedPeers[$peerHost]) {
return 'vpc_private_wireguard_readback_mismatch';
}
$seenPeers[$peerHost] = true;
}
if (count($seenPeers) !== count($expectedPeers)) {
return 'vpc_private_wireguard_readback_mismatch';
}
return null;
}
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;
}
$bounded = [
'host_id' => is_string($host['host_id'] ?? null)
? substr($host['host_id'], 0, 64) : (string) $key,
'vpc_id' => is_string($host['vpc_id'] ?? null)
? substr($host['vpc_id'], 0, 64) : null,
'desired_revision' => max(0, (int) ($host['desired_revision'] ?? 0)),
'desired_digest' => is_string($host['desired_digest'] ?? null)
? substr($host['desired_digest'], 0, 64) : null,
'state' => is_string($host['state'] ?? null) ? substr($host['state'], 0, 16) : 'unknown',
'observed_revision' => max(0, (int) ($host['observed_revision'] ?? $host['revision'] ?? 0)),
'observed_digest' => is_string($host['observed_digest'] ?? $host['digest'] ?? null)
? substr((string) ($host['observed_digest'] ?? $host['digest']), 0, 64) : null,
'transport_verified' => ($host['transport_verified'] ?? false) === true,
'private_dataplane_verified' => (
($host['private_dataplane_verified'] ?? false) === true
),
'removed' => ($host['removed'] ?? false) === true,
'retiring' => ($host['retiring'] ?? false) === true,
'next_stage_allowed' => ($host['next_stage_allowed'] ?? false) === true,
];
if (is_string($host['last_error_code'] ?? null)) {
$bounded['last_error_code'] = substr($host['last_error_code'], 0, 64);
}
foreach (['bridge', 'bridge_owner', 'nft_table', 'readback', 'rollback'] as $field) {
if (is_string($host[$field] ?? null)) {
$bounded[$field] = substr($host[$field], 0, 128);
}
}
if (isset($host['anti_spoof'])) {
$bounded['anti_spoof'] = $host['anti_spoof'] === true;
}
if (isset($host['acl_revision'])) {
$bounded['acl_revision'] = max(0, (int) $host['acl_revision']);
}
if (isset($host['rp_filter'])) {
$bounded['rp_filter'] = max(0, (int) $host['rp_filter']);
}
if (isset($host['proxy_arp'])) {
$bounded['proxy_arp'] = max(0, (int) $host['proxy_arp']);
}
if (isset($host['proxy_arp_pvlan'])) {
$bounded['proxy_arp_pvlan'] = max(0, (int) $host['proxy_arp_pvlan']);
}
if (is_array($host['proxy_ips'] ?? null)) {
$bounded['proxy_ips'] = array_values(array_slice(array_map(
static fn ($ip): string => substr((string) $ip, 0, 64),
$host['proxy_ips']
), 0, 4096));
}
if (is_array($host['member_nics'] ?? null)) {
$bounded['member_nics'] = [];
foreach (array_slice($host['member_nics'], 0, 4096) as $nic) {
if (!is_array($nic)) {
continue;
}
$bounded['member_nics'][] = [
'member_id' => is_string($nic['member_id'] ?? null)
? substr($nic['member_id'], 0, 64) : null,
'instance_uuid' => is_string($nic['instance_uuid'] ?? null)
? substr($nic['instance_uuid'], 0, 64) : null,
'interface' => is_string($nic['interface'] ?? null)
? substr($nic['interface'], 0, 32) : null,
'private_ip_cidr' => is_string($nic['private_ip_cidr'] ?? null)
? substr($nic['private_ip_cidr'], 0, 64) : null,
'private_mac' => is_string($nic['private_mac'] ?? null)
? substr(strtolower($nic['private_mac']), 0, 32) : null,
'xml_verified' => ($nic['xml_verified'] ?? false) === true,
];
}
}
if (is_array($host['routes'] ?? null)) {
$bounded['routes'] = [];
foreach (array_slice($host['routes'], 0, 256) as $route) {
if (!is_array($route)) {
continue;
}
$bounded['routes'][] = [
'destination_cidr' => is_string($route['destination_cidr'] ?? null)
? substr($route['destination_cidr'], 0, 64) : null,
'device' => is_string($route['device'] ?? null)
? substr($route['device'], 0, 64) : null,
'table' => is_scalar($route['table'] ?? null)
? substr((string) $route['table'], 0, 32) : null,
'owner' => is_string($route['owner'] ?? null)
? substr($route['owner'], 0, 64) : null,
'via' => is_string($route['via'] ?? null)
? substr($route['via'], 0, 64) : null,
'metric' => is_scalar($route['metric'] ?? null)
? substr((string) $route['metric'], 0, 16) : null,
];
}
}
if (is_array($host['wg_allowed_ips'] ?? null)) {
$bounded['wg_allowed_ips'] = [];
foreach (array_slice($host['wg_allowed_ips'], 0, 256) as $peer) {
if (!is_array($peer)) {
continue;
}
$ips = $peer['tenant_allowed_ips'] ?? $peer['allowed_ips'] ?? [];
$bounded['wg_allowed_ips'][] = [
'peer_host_id' => is_string($peer['peer_host_id'] ?? null)
? substr($peer['peer_host_id'], 0, 64) : null,
'public_key' => is_string($peer['public_key'] ?? null)
? substr($peer['public_key'], 0, 64) : null,
'tenant_allowed_ips' => is_array($ips)
? array_values(array_slice(array_map(
static fn ($ip): string => substr((string) $ip, 0, 64), $ips
), 0, 4096)) : [],
];
}
}
$hosts[(string) $key] = $bounded;
}
$result = ['hosts' => $hosts];
if ($terminalProof !== null) {
$result['no_data_plane_terminal_proof'] = $terminalProof;
}
return $result;
}
}