From 6eef9f03a55f61df93ed412e8fa5fed9bd948e29 Mon Sep 17 00:00:00 2001 From: codex Date: Wed, 4 Nov 2026 18:09:18 +0800 Subject: [PATCH] refactor: retire legacy single-stack network writers --- .../CloudAdminOperationRecoveryService.php | 22 +- web/app/Services/Cloud/CloudBackupService.php | 126 +--- .../Cloud/CloudOperationRecoveryIdentity.php | 241 +------- .../Services/Cloud/CloudPlacementService.php | 579 ------------------ .../CloudPublicNetworkTransitionGate.php | 31 - web/app/Services/Cloud/CloudWorkerService.php | 128 +--- ...dAutomaticOperationRecoveryServiceTest.php | 12 +- .../CloudNetworkIpLedgerContractTest.php | 58 +- .../CloudOperationRecoveryMatrixTest.php | 112 +++- web/tests/CloudPaidIpChangeContractTest.php | 18 +- .../CloudPortableBackupFinalizerTest.php | 11 +- .../CloudPortableRestoreJobDispatcherTest.php | 19 +- .../CloudPortableRestoreTargetServiceTest.php | 9 - ...licNetworkLegacyWriterGateContractTest.php | 295 +++------ 14 files changed, 213 insertions(+), 1448 deletions(-) delete mode 100644 web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php diff --git a/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php b/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php index 2c58ec2f..7df43865 100644 --- a/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php +++ b/web/app/Services/Cloud/CloudAdminOperationRecoveryService.php @@ -57,8 +57,6 @@ final class CloudAdminOperationRecoveryService 'bandwidth_mbps' => 'integer', 'hostname' => 'string', 'public_network' => 'public_network', - 'public_ip_cidr' => 'string', - 'public_pool_key' => 'string', 'public_pool_cidr' => 'string', 'gateway' => 'string', 'dns_servers' => 'string_list', @@ -629,6 +627,7 @@ final class CloudAdminOperationRecoveryService 'finalization_incident', 'finalization_error_code', 'result_json', 'sealed_payload', 'instance_id', 'snapshot_id', 'backup_id', 'backup_restore_id', 'backup_recovery_id', 'parent_job_id', + 'public_network_transition_id', 'supersedes_job_id', 'vpc_repair_root_job_id', 'vpc_id', 'vpc_port_id', 'vpc_batch_id', 'user_id', 'order_id', @@ -640,6 +639,14 @@ final class CloudAdminOperationRecoveryService && !in_array((string) $job->kind, $requiredKinds, true)) { throw new CloudError('任务类型不支持自动效果恢复', 409); } + if ((string) $job->kind === 'backup_restore' + && !CloudPortableRestoreFinalizer::owns($job)) { + throw new CloudError('旧备份恢复任务不支持效果恢复', 409); + } + if ((string) $job->kind === 'network_change' + && (int) ($job->public_network_transition_id ?? 0) < 1) { + throw new CloudError('公网网络任务缺少转换账本', 409); + } if ((string) $job->execution_mode !== 'agent' || CloudJobService::isAggregateKind((string) $job->kind)) { throw new CloudError( @@ -1234,9 +1241,9 @@ final class CloudAdminOperationRecoveryService 'status', 'originally_running', 'power_state_restored', 'resources_resized', ], - 'network_change' => $publicNetworkTransition - ? ['uuid', 'network_changed', 'public_network'] - : ['uuid', 'network_changed'], + 'network_change' => [ + 'uuid', 'network_changed', 'public_network', + ], 'reinstall' => ['uuid', 'reinstall_committed'], 'delete', 'delete_force', 'expiry_delete', 'instance_migration_cleanup', @@ -1276,13 +1283,10 @@ final class CloudAdminOperationRecoveryService 'backup_recover' => [ 'backup_key', 'sha256', 'restored', 'power_state', ], - 'backup_restore' => $portableRestoreAttempt ? [ + 'backup_restore' => [ 'uuid', 'name', 'vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps', 'public_network', 'machine', 'firmware', 'secure_boot', 'backup_key', 'sha256', - ] : [ - 'uuid', 'public_ip_cidr', 'public_pool_key', 'backup_key', - 'sha256', ], 'instance_migration_prepare' => [ 'migration_id', 'manifest_digest', 'artifacts', diff --git a/web/app/Services/Cloud/CloudBackupService.php b/web/app/Services/Cloud/CloudBackupService.php index 7792d36b..08bd3ed7 100644 --- a/web/app/Services/Cloud/CloudBackupService.php +++ b/web/app/Services/Cloud/CloudBackupService.php @@ -1137,13 +1137,9 @@ final class CloudBackupService if ($job->kind === 'backup_create') { self::finishCreateLocked($job, $status, $result, $payload); } elseif ($job->kind === 'backup_restore') { - if (CloudPortableRestoreFinalizer::owns($job)) { - CloudPortableRestoreFinalizer::finishJobLocked( - $job, $status, $result, $payload, $deferPublish - ); - } else { - self::finishRestoreLocked($job, $status, $result, $payload); - } + CloudPortableRestoreFinalizer::finishJobLocked( + $job, $status, $result, $payload, $deferPublish + ); } elseif ($job->kind === 'backup_recover') { self::finishRecoveryLocked($job, $status, $result, $payload); } elseif ($job->kind === 'backup_workspace_cleanup') { @@ -1293,16 +1289,8 @@ final class CloudBackupService ->where('last_operation_id', (string) $job->operation_id) ->update(['state' => 'uncertain', 'error_code' => 'finalization_incident', 'updated_at' => time()]); - } elseif ($job->kind === 'backup_restore' - && $job->backup_restore_id !== null) { - if (CloudPortableRestoreFinalizer::owns($job)) { - CloudPortableRestoreFinalizer::markJobUncertain($job); - } else { - CloudBackupRestore::where('id', (int) $job->backup_restore_id) - ->where('operation_id', (string) $job->operation_id) - ->update(['state' => 'uncertain', 'error_code' => - 'finalization_incident', 'updated_at' => time()]); - } + } elseif ($job->kind === 'backup_restore') { + CloudPortableRestoreFinalizer::markJobUncertain($job); } elseif ($job->kind === 'backup_recover' && $job->backup_recovery_id !== null) { CloudBackupRecovery::where( @@ -1413,110 +1401,6 @@ final class CloudBackupService $backup->save(); } - private static function finishRestoreLocked(CloudJob $job, string $status, - $result, array $payload): void - { - $restore = $job->backup_restore_id === null ? null - : CloudBackupRestore::where('id', (int) $job->backup_restore_id) - ->lockForUpdate()->first(); - $backup = $job->backup_id === null ? null - : CloudInstanceBackup::where('id', (int) $job->backup_id) - ->lockForUpdate()->first(); - $instance = $job->instance_id === null ? null - : CloudInstance::where('id', (int) $job->instance_id) - ->lockForUpdate()->first(); - if ($restore === null || $backup === null || $instance === null - || (int) $restore->backup_id !== (int) $backup->id - || (int) $restore->target_instance_id !== (int) $instance->id - || (int) $restore->target_host_id !== (int) $job->host_id - || !hash_equals((string) $restore->operation_id, - (string) $job->operation_id) - || !hash_equals((string) $restore->restore_key, - (string) ($payload['restore_key'] ?? '')) - || !hash_equals((string) $backup->backup_key, - (string) ($payload['backup_key'] ?? '')) - || (int) $instance->user_id !== (int) ($payload['owner_id'] ?? 0) - || !hash_equals(strtolower((string) $restore->new_uuid), - strtolower((string) $instance->uuid))) { - throw new CloudRecoveryInstanceStateConflict( - '备份恢复任务与实例、资源或目录账本不一致', 409 - ); - } - if ($status === 'running') { - return; - } - $requestedIp = $payload['body']['public_ip_cidr'] ?? null; - if (!is_string($requestedIp)) { - throw new CloudRecoveryInstanceStateConflict( - '备份恢复任务缺少公网 IP 快照', 409 - ); - } - $now = time(); - if ($status === 'uncertain') { - CloudPlacementService::finishBackupRestore( - $restore, (int) $instance->id, $requestedIp, 'uncertain' - ); - $restore->state = 'uncertain'; - $restore->error_code = 'operation_effect_unknown'; - } elseif ($status === 'failed') { - CloudPlacementService::finishBackupRestore( - $restore, (int) $instance->id, $requestedIp, 'failed' - ); - $restore->state = 'failed'; - $restore->error_code = 'backup_restore_failed'; - $instance->status = 'deleted'; - $instance->network_status = 'inactive'; - $instance->sealed_credential = null; - $instance->updated_at = $now; - $instance->save(); - } elseif ($status === 'succeeded') { - $vm = is_array($result['vm'] ?? null) ? $result['vm'] : $result; - if (!is_array($result) || !is_array($vm) - || !hash_equals((string) $backup->backup_key, - (string) ($result['backup_key'] ?? '')) - || !hash_equals((string) $backup->sha256, - (string) ($result['sha256'] ?? '')) - || !hash_equals(strtolower((string) $restore->new_uuid), - strtolower((string) ($vm['uuid'] ?? ''))) - || !hash_equals($requestedIp, - (string) ($vm['public_ip_cidr'] ?? '')) - || !hash_equals((string) ($payload['body']['public_pool_key'] ?? ''), - (string) ($vm['public_pool_key'] ?? ''))) { - throw new CloudError( - 'Agent 恢复成功结果与备份、实例或公网 IP 预留不一致', - 502 - ); - } - CloudPlacementService::finishBackupRestore( - $restore, (int) $instance->id, $requestedIp, 'succeeded' - ); - $spec = self::decodeSpec((string) $instance->spec_json); - $sourceSpec = self::decodeSpec((string) $backup->spec_json); - $spec = CloudInstanceMetadata::merge($spec, $vm); - foreach (['os_source', 'os_name', 'login_name'] as $field) { - if (isset($sourceSpec[$field])) { - $spec[$field] = $sourceSpec[$field]; - } - } - $spec['managed'] = true; - $spec['restored_from_backup'] = (string) $backup->backup_key; - $instance->spec_json = json_encode($spec, - JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE); - $instance->status = 'active'; - $instance->service_status = 'exempt'; - $instance->network_status = 'active'; - $instance->updated_at = $now; - $instance->save(); - self::recordRuntime($instance, $vm); - $restore->state = 'ready'; - $restore->error_code = ''; - $restore->ready_at = $now; - } - $restore->updated_at = $now; - $restore->save(); - } - private static function finishRecoveryLocked(CloudJob $job, string $status, $result, array $payload): void { diff --git a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php index f64696a6..e8456f4e 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php @@ -14,14 +14,10 @@ use App\Models\CloudBackupRestore; use App\Models\CloudBackupRestoreAttempt; use App\Models\CloudBackupRecovery; use App\Models\CloudHostStorageConfiguration; -use App\Models\CloudHostNetworkAttachment; use App\Models\CloudJob; use App\Models\CloudOrder; -use App\Models\CloudPublicIp; -use App\Models\CloudPublicIpPool; use App\Models\CloudPublicNetworkTransition; use App\Models\CloudResourceReservation; -use App\Models\CloudResourcePool; use App\Models\CloudRescueTemplate; use App\Models\CloudRescueTemplateReplica; use App\Models\CloudTemplate; @@ -399,9 +395,6 @@ final class CloudOperationRecoveryIdentity 'backup_create' => self::backupCreateAction( $job, $payload, $instance, $method, $target, $base, $body ), - 'backup_restore' => self::backupRestoreAction( - $job, $payload, $instance, $method, $target, $base, $body - ), 'backup_recover' => self::backupRecoverAction( $job, $payload, $instance, $method, $target, $base, $body ), @@ -949,21 +942,10 @@ final class CloudOperationRecoveryIdentity bool $forAppliedEffect ): array { if ((string) $job->kind === 'backup_restore') { - if (isset($payload['attempt_key'])) { - return self::portableRestoreAttemptIdentity( - $job, - $payload, - $method, - $target, - $body - ); + if (!isset($payload['attempt_key'])) { + self::invalidPayload('恢复任务缺少尝试权威'); } - // Existing in-flight restore jobs may still need read-only - // journal reconciliation during a rolling upgrade. They cannot - // create a new legacy restore because the public gate is closed, - // but discarding their exact identity would turn a known effect - // into an unrecoverable operator incident. - return self::legacyBackupRestoreIdentity( + return self::portableRestoreAttemptIdentity( $job, $payload, $method, @@ -1139,43 +1121,6 @@ final class CloudOperationRecoveryIdentity return [$envelope->action(), $envelope->resourceId()]; } - /** @return array{0:string,1:string} */ - private static function legacyBackupRestoreIdentity( - CloudJob $job, - array $payload, - string $method, - string $target, - array $body - ): array { - $instanceId = filter_var( - $job->instance_id, - FILTER_VALIDATE_INT, - ['options' => ['min_range' => 1]] - ); - $instance = $instanceId === false ? null - : CloudInstance::find((int) $instanceId); - if (!$instance instanceof CloudInstance - || (int) $instance->host_id !== (int) $job->host_id - || (int) ($payload['owner_id'] ?? 0) - !== (int) $instance->user_id) { - throw new CloudRecoveryInstanceStateConflict( - '旧恢复任务与实例账本不匹配', - 409 - ); - } - $uuid = strtolower((string) $instance->uuid); - $action = self::backupRestoreAction( - $job, - $payload, - $instance, - $method, - $target, - '/v1/vms/' . rawurlencode($uuid), - $body - ); - return [$action, $uuid]; - } - private static function backupProvisionIdentity( CloudJob $job, array $payload, @@ -1764,24 +1709,7 @@ final class CloudOperationRecoveryIdentity ): string { self::expectRequest($method, $target, 'POST', $base . '/network'); if ($job->public_network_transition_id === null) { - self::assertAllowedBody($body, [ - 'operation_id', 'network', 'public_pool_key', - 'public_pool_cidr', 'public_ip_cidr', 'gateway', - 'dns_servers', 'confirm_restart', - ]); - if (($body['confirm_restart'] ?? null) !== true - || !is_string($body['network'] ?? null) - || !is_string($body['public_pool_key'] ?? null) - || preg_match('/^[a-f0-9]{32}$/D', - $body['public_pool_key']) !== 1 - || !is_string($body['public_pool_cidr'] ?? null) - || !is_string($body['public_ip_cidr'] ?? null) - || !is_string($body['gateway'] ?? null) - || !is_array($body['dns_servers'] ?? null) - || !array_is_list($body['dns_servers'])) { - self::invalidPayload('公网 IP 变更请求无效'); - } - return 'change-network'; + self::invalidPayload('公网网络变更缺少转换账本'); } self::assertAllowedBody($body, [ 'operation_id', 'public_network', 'confirm_restart', @@ -1975,167 +1903,6 @@ final class CloudOperationRecoveryIdentity return 'create-backup:' . $key . ':' . $mode; } - private static function backupRestoreAction( - CloudJob $job, - array $payload, - CloudInstance $instance, - string $method, - string $target, - string $base, - array $body - ): string { - self::expectRequest($method, $target, 'POST', $base . '/restore-backup'); - self::assertAllowedBody($body, [ - 'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu', - 'memory_mib', 'disk_gib', 'bandwidth_mbps', 'network', - 'template_id', 'template_revision', 'template_generation_token', - 'startup_script', 'hostname', 'guest_ssh_public_key', - 'root_password', 'public_pool_key', 'public_pool_cidr', - 'public_ip_cidr', 'gateway', 'dns_servers', - 'platform_network_policy_snapshot', 'debian_12_network_fix', - 'backup_key', 'source_url', 'source_size_bytes', 'source_sha256', - ]); - $restoreId = filter_var($job->backup_restore_id, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); - $backupId = filter_var($job->backup_id, FILTER_VALIDATE_INT, - ['options' => ['min_range' => 1]]); - $restore = $restoreId === false ? null - : CloudBackupRestore::find((int) $restoreId); - $backup = $backupId === false ? null - : CloudInstanceBackup::find((int) $backupId); - $reservationId = filter_var($payload['reservation_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); - $reservation = $reservationId === false ? null - : CloudResourceReservation::find((int) $reservationId); - $ip = $reservation === null ? null - : CloudPublicIp::find((int) $reservation->public_ip_id); - $attachment = $reservation === null ? null - : CloudHostNetworkAttachment::find( - (int) $reservation->network_attachment_id - ); - $resourcePool = $reservation === null ? null - : CloudResourcePool::find((int) $reservation->resource_pool_id); - $publicPool = $reservation === null ? null - : CloudPublicIpPool::find((int) $reservation->public_ip_pool_id); - $instanceSpec = json_decode((string) $instance->spec_json, true); - $backupSpec = $backup === null ? null - : json_decode((string) $backup->spec_json, true); - $key = $payload['backup_key'] ?? null; - $expectedReservationId = (int) $instance->reservation_id; - $expectedUuid = strtolower((string) $instance->uuid); - $expectedReservationDisk = (int) ($body['disk_gib'] ?? 0); - $publicPoolDns = $publicPool === null ? null : json_decode( - (string) $publicPool->dns_servers_json, - true - ); - if ($restore === null || $backup === null - || $reservation === null || $ip === null - || $attachment === null || $resourcePool === null - || $publicPool === null - || !is_array($publicPoolDns) || !array_is_list($publicPoolDns) - || (int) $restore->backup_id !== (int) $backup->id - || (int) $restore->target_instance_id !== (int) $instance->id - || (int) $restore->target_host_id !== (int) $job->host_id - || (int) $restore->reservation_id !== (int) $reservation->id - || $expectedReservationId !== (int) $reservation->id - || (int) $reservation->backup_restore_id !== (int) $restore->id - || (int) $reservation->instance_id !== (int) $instance->id - || (int) $reservation->host_id !== (int) $job->host_id - || (int) $reservation->user_id !== (int) $instance->user_id - || (int) $reservation->resource_pool_id - !== (int) $instance->resource_pool_id - || (int) $attachment->host_id !== (int) $job->host_id - || (int) $attachment->line_id !== (int) $resourcePool->line_id - || (int) $reservation->network_attachment_id - !== (int) $attachment->id - || (int) $publicPool->host_id !== (int) $job->host_id - || (int) $publicPool->network_attachment_id - !== (int) $attachment->id - || (int) $reservation->public_ip_pool_id - !== (int) $publicPool->id - || !in_array((string) $reservation->state, - ['held', 'uncertain', 'committed'], true) - || (int) $ip->host_id !== (int) $job->host_id - || (int) $ip->public_ip_pool_id !== (int) $publicPool->id - || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id - || !hash_equals((string) $reservation->operation_id, - (string) ($ip->operation_id ?? '')) - || !hash_equals((string) $restore->operation_id, - (string) $job->operation_id) - || !hash_equals((string) $restore->restore_key, - (string) ($payload['restore_key'] ?? '')) - || !is_string($key) - || preg_match(self::CATALOG_ID_PATTERN, $key) !== 1 - || !hash_equals((string) $backup->backup_key, $key) - || ($body['backup_key'] ?? null) !== $key - || strtolower((string) ($body['uuid'] ?? '')) !== $expectedUuid - || ($body['source'] ?? null) !== '' - || !CloudNetworkSelector::isValid($body['network'] ?? null) - || !hash_equals( - (string) $attachment->network_selector, - (string) ($body['network'] ?? '') - ) - || !hash_equals( - (string) $publicPool->pool_key, - (string) ($body['public_pool_key'] ?? '') - ) - || !hash_equals( - (string) $publicPool->cidr, - (string) ($body['public_pool_cidr'] ?? '') - ) - || !hash_equals( - (string) $publicPool->gateway, - (string) ($body['gateway'] ?? '') - ) - || ($body['dns_servers'] ?? null) !== $publicPoolDns - || !is_array($instanceSpec) || array_is_list($instanceSpec) - || !is_array($backupSpec) || array_is_list($backupSpec) - || !is_bool($backupSpec['debian_12_network_fix'] ?? null) - || ($body['debian_12_network_fix'] ?? null) - !== $backupSpec['debian_12_network_fix'] - || ($instanceSpec['debian_12_network_fix'] ?? null) - !== $backupSpec['debian_12_network_fix'] - || !hash_equals((string) $restore->new_name, - (string) ($body['name'] ?? '')) - || !hash_equals((string) $instance->name, - (string) ($body['name'] ?? '')) - || (int) ($body['vcpu'] ?? 0) - !== (int) $reservation->cpu_cores - || (int) ($body['memory_mib'] ?? 0) - !== (int) $reservation->memory_mib - || (int) ($body['disk_gib'] ?? 0) - !== (int) ($backupSpec['disk_gib'] ?? 0) - || (int) $reservation->disk_gib !== $expectedReservationDisk - || (int) ($body['bandwidth_mbps'] ?? 0) - !== (int) ($instanceSpec['bandwidth_mbps'] ?? 0) - || (int) ($body['vcpu'] ?? 0) - !== (int) ($backupSpec['vcpu'] - ?? $backupSpec['cpu_cores'] ?? 0) - || (int) ($body['memory_mib'] ?? 0) - !== (int) ($backupSpec['memory_mib'] - ?? $backupSpec['ram_mib'] ?? 0) - || (int) ($body['bandwidth_mbps'] ?? 0) - !== (int) ($backupSpec['bandwidth_mbps'] ?? 0) - || !hash_equals( - (string) $ip->address . '/' . (int) $ip->prefix_length, - (string) ($body['public_ip_cidr'] ?? '') - ) - || !is_string($body['source_url'] ?? null) - || !str_starts_with($body['source_url'], 'https://') - || filter_var($body['source_size_bytes'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false - || (int) $body['source_size_bytes'] - !== (int) $backup->object_size_bytes - || !is_string($body['source_sha256'] ?? null) - || preg_match('/^[a-f0-9]{64}$/D', - $body['source_sha256']) !== 1 - || !hash_equals((string) $backup->sha256, - (string) $body['source_sha256'])) { - self::invalidPayload('备份恢复请求无效'); - } - return 'restore-backup:' . $key; - } - private static function backupWorkspaceCleanupAction( CloudJob $job, array $payload, diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index a53efe39..802f496f 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -12,8 +12,6 @@ use App\Models\CloudHostStorageConfiguration; use App\Models\CloudInstance; use App\Models\CloudNetworkLine; use App\Models\CloudOffer; -use App\Models\CloudPublicIp; -use App\Models\CloudPublicIpPool; use App\Models\CloudRegion; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; @@ -891,327 +889,6 @@ final class CloudPlacementService ); } - /** - * Reserve target capacity and a fresh IPv4 for an administrator restore. - * The restore row and operation ID are created before this method runs. - * - * @return array{reservation:CloudResourceReservation,host:CloudHost, - * public_ip:CloudPublicIp,network:array} - */ - public static function reserveBackupRestore(CloudBackupRestore $restore, - int $userId, array $resources, int $requiredResourcePoolId, - int $additionalDiskGib = 0): array - { - self::assertBackupRestoreTransitionReady($restore); - $resources = self::upgradeResources($resources); - $capacityResources = $resources; - $capacityResources['disk_gib'] += max(0, $additionalDiskGib); - $hostId = (int) $restore->target_host_id; - if ($hostId < 1 || $requiredResourcePoolId < 1) { - throw new CloudError('备份恢复目标身份无效', 409); - } - $poolRef = CloudResourcePool::find($requiredResourcePoolId); - $lineRef = $poolRef === null ? null - : CloudNetworkLine::find((int) $poolRef->line_id); - $region = $lineRef === null ? null - : CloudRegion::where('id', (int) $lineRef->region_id) - ->lockForUpdate()->first(); - $line = $lineRef === null ? null - : CloudNetworkLine::where('id', (int) $lineRef->id) - ->lockForUpdate()->first(); - $pool = $poolRef === null ? null - : CloudResourcePool::where('id', (int) $poolRef->id) - ->lockForUpdate()->first(); - $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); - $membership = CloudHostResourcePoolMembership::where( - 'host_id', $hostId - )->where('resource_pool_id', $requiredResourcePoolId) - ->lockForUpdate()->first(); - $policy = CloudHostCapacityPolicy::where('host_id', $hostId) - ->lockForUpdate()->first(); - $storage = CloudHostStorageConfiguration::where('host_id', $hostId) - ->lockForUpdate()->first(); - $agent = CloudHostAgent::where('host_id', $hostId) - ->lockForUpdate()->first(); - if ($host === null || $membership === null || $pool === null - || $line === null || $region === null || $policy === null - || $storage === null || !$storage->isApplied() - || $agent === null || !$agent->isReady() - || !(bool) $host->enabled - || (string) $membership->scheduler_state !== 'active' - || (int) $membership->resource_pool_id !== $requiredResourcePoolId - || (int) $pool->id !== $requiredResourcePoolId - || (int) $pool->line_id !== (int) $line->id - || (int) $line->region_id !== (int) $region->id - || (string) $pool->status !== 'active' - || (string) $line->status !== 'active' - || (string) $region->status !== 'active') { - throw new CloudError('所选目标宿主机暂不支持备份恢复', 409); - } - $networkCandidates = CloudPlacementNetworkService::lockedCandidates( - $hostId, - (int) $line->id, - $agent - ); - if ($networkCandidates === []) { - throw new CloudError('目标宿主机的线路网络接入尚未就绪', 409); - } - $reservations = CloudResourceReservation::where('host_id', $hostId) - ->whereIn('state', ['held', 'uncertain', 'committed']) - ->orderBy('id')->lockForUpdate()->get(); - if (!self::hasCapacity( - $policy, - CloudPanelUsageService::forHost($hostId, $reservations), - $capacityResources - )) { - throw new CloudError('目标宿主机没有足够的可用容量', 409); - } - - $network = CloudPlacementNetworkService::lockAvailableSelection( - $hostId, - $networkCandidates - ); - if ($network === null) { - throw new CloudError('目标宿主机没有可分配的公网 IP', 409); - } - $attachment = $network['attachment']; - $selectedPool = $network['public_pool']; - $ip = $network['public_ip']; - $dns = self::poolDnsServers($selectedPool); - $reservation = new CloudResourceReservation(); - $reservation->reservation_key = bin2hex(random_bytes(16)); - $reservation->operation_id = (string) $restore->operation_id; - $reservation->order_id = null; - $reservation->backup_restore_id = (int) $restore->id; - $reservation->offer_id = null; - $reservation->resource_pool_id = (int) $pool->id; - $reservation->host_id = $hostId; - $reservation->user_id = $userId; - $reservation->instance_id = null; - $reservation->network_attachment_id = (int) $attachment->id; - $reservation->public_ip_pool_id = (int) $selectedPool->id; - $reservation->public_ip_id = (int) $ip->id; - $reservation->cpu_cores = $resources['cpu_cores']; - $reservation->memory_mib = $resources['memory_mib']; - // A maintenance restore reserves the root disk plus every transported - // snapshot volume. The finalizer normalizes this temporary claim back - // to the root disk once the snapshot catalog is atomically rebound. - $reservation->disk_gib = $capacityResources['disk_gib']; - $reservation->state = 'held'; - $reservation->expires_at = null; - $reservation->released_at = null; - $reservation->release_reason = ''; - $reservation->created_at = $reservation->updated_at = time(); - $reservation->save(); - - $ip->state = 'reserved'; - $ip->reservation_id = (int) $reservation->id; - $ip->instance_id = null; - $ip->operation_id = (string) $restore->operation_id; - $ip->updated_at = time(); - $ip->save(); - return [ - 'reservation' => $reservation, - 'host' => $host, - 'public_ip' => $ip, - 'network' => [ - 'network' => (string) $attachment->network_selector, - 'public_pool_key' => (string) $selectedPool->pool_key, - 'public_pool_cidr' => (string) $selectedPool->cidr, - 'public_ip_cidr' => (string) $ip->address . '/' - . (int) $ip->prefix_length, - 'gateway' => (string) $selectedPool->gateway, - 'dns_servers' => $dns, - 'resource_pool_id' => (int) $pool->id, - 'resource_pool_name' => (string) $pool->name, - 'line_id' => (int) $line->id, - 'line_name' => (string) $line->name, - 'region_id' => (int) $region->id, - 'region_name' => (string) $region->name, - 'country_code' => strtoupper((string) $region->country_code), - ], - ]; - } - - /** - * Re-open an already held restore placement without selecting new capacity. - * - * Maintenance migration reserves its target before the source is stopped. - * The backup finalizer must therefore consume that exact host/address - * reservation instead of racing a second scheduler pass after downtime has - * begun. - * - * @return array{reservation:CloudResourceReservation,network:array} - */ - public static function preparedBackupRestorePlacement( - CloudBackupRestore $restore, - int $instanceId - ): array { - self::assertBackupRestoreTransitionReady($restore); - $reservation = CloudResourceReservation::where( - 'backup_restore_id', - (int) $restore->id - )->lockForUpdate()->first(); - $ip = $reservation === null ? null : CloudPublicIp::where( - 'id', - (int) $reservation->public_ip_id - )->lockForUpdate()->first(); - $pool = $reservation === null ? null : CloudPublicIpPool::where( - 'id', - (int) $reservation->public_ip_pool_id - )->lockForUpdate()->first(); - $attachment = $reservation === null ? null - : CloudHostNetworkAttachment::where( - 'id', - (int) $reservation->network_attachment_id - )->lockForUpdate()->first(); - $resourcePool = $reservation === null ? null - : CloudResourcePool::find((int) $reservation->resource_pool_id); - $membership = $reservation === null ? null - : CloudHostResourcePoolMembership::where( - 'host_id', - (int) $reservation->host_id - )->where( - 'resource_pool_id', - (int) $reservation->resource_pool_id - )->first(); - if ($reservation === null || $ip === null || $pool === null - || $attachment === null || $resourcePool === null - || $membership === null - || (int) $restore->reservation_id !== (int) $reservation->id - || (int) $restore->target_host_id !== (int) $reservation->host_id - || (int) $reservation->backup_restore_id !== (int) $restore->id - || (int) $reservation->instance_id !== $instanceId - || (string) $reservation->state !== 'held' - || (string) $membership->scheduler_state !== 'active' - || (int) $attachment->host_id !== (int) $reservation->host_id - || (int) $attachment->line_id !== (int) $resourcePool->line_id - || (int) $pool->host_id !== (int) $reservation->host_id - || (int) $pool->network_attachment_id !== (int) $attachment->id - || (int) $ip->host_id !== (int) $reservation->host_id - || (int) $ip->public_ip_pool_id !== (int) $pool->id - || (string) $ip->state !== 'reserved' - || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id - || $ip->instance_id !== null - || !hash_equals( - (string) $restore->operation_id, - (string) $reservation->operation_id - ) - || !hash_equals( - (string) $reservation->operation_id, - (string) ($ip->operation_id ?? '') - ) - || preg_match('/^[a-f0-9]{32}$/D', - (string) $pool->pool_key) !== 1 - || !CloudNetworkSelector::isValid( - (string) $attachment->network_selector - )) { - throw new CloudRecoveryInstanceStateConflict( - '维护迁移目标预留在源实例停机后发生变化', - 409 - ); - } - return [ - 'reservation' => $reservation, - 'network' => [ - 'network' => (string) $attachment->network_selector, - 'public_pool_key' => (string) $pool->pool_key, - 'public_pool_cidr' => (string) $pool->cidr, - 'public_ip_cidr' => (string) $ip->address . '/' - . (int) $ip->prefix_length, - 'gateway' => (string) $pool->gateway, - 'dns_servers' => self::poolDnsServers($pool), - 'resource_pool_id' => (int) $reservation->resource_pool_id, - ], - ]; - } - - /** Commit, release, or fence one restore reservation after exact evidence. */ - public static function finishBackupRestore(CloudBackupRestore $restore, - int $instanceId, string $publicIpCidr, string $status): void - { - self::assertBackupRestoreTransitionReady($restore); - $host = CloudHost::where('id', (int) $restore->target_host_id) - ->lockForUpdate()->first(); - $reservation = CloudResourceReservation::where( - 'backup_restore_id', (int) $restore->id - )->lockForUpdate()->first(); - $ip = $reservation === null ? null : CloudPublicIp::where( - 'id', (int) $reservation->public_ip_id - )->lockForUpdate()->first(); - if ($host === null || $reservation === null || $ip === null - || (int) $reservation->host_id !== (int) $host->id - || (int) $reservation->backup_restore_id !== (int) $restore->id - || !hash_equals((string) $reservation->operation_id, - (string) $restore->operation_id) - || !hash_equals((string) $ip->address . '/' - . (int) $ip->prefix_length, $publicIpCidr)) { - throw new CloudError('备份恢复的资源预留账本不一致', 409); - } - if ((string) $reservation->state === 'committed') { - if ((string) $ip->state !== 'assigned' - || (int) $reservation->instance_id !== $instanceId - || (int) $ip->instance_id !== $instanceId - || (int) $ip->reservation_id !== (int) $reservation->id - || !hash_equals((string) $reservation->operation_id, - (string) $ip->operation_id)) { - throw new CloudError('已恢复实例的资源账本不一致', 409); - } - if ($status !== 'succeeded' && $status !== 'uncertain') { - throw new CloudError('已恢复实例不能回滚资源预留', 409); - } - return; - } - if ((string) $reservation->state === 'released') { - if ((string) $ip->state !== 'available' - || $ip->reservation_id !== null - || $ip->instance_id !== null - || $ip->operation_id !== null) { - throw new CloudError('已释放的备份恢复资源账本不一致', 409); - } - if ($status !== 'failed') { - throw new CloudError('已释放的备份恢复不能重新提交资源', 409); - } - return; - } - if (!in_array((string) $reservation->state, - ['held', 'uncertain'], true) - || !in_array((string) $ip->state, - ['reserved', 'uncertain'], true) - || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id - || !hash_equals((string) $reservation->operation_id, - (string) ($ip->operation_id ?? '')) - || (int) ($reservation->instance_id ?? 0) !== $instanceId) { - throw new CloudError('备份恢复的资源预留状态无效', 409); - } - $now = time(); - if ($status === 'succeeded') { - $reservation->state = 'committed'; - $reservation->instance_id = $instanceId; - $reservation->expires_at = null; - $ip->state = 'assigned'; - $ip->instance_id = $instanceId; - } elseif ($status === 'failed') { - $reservation->state = 'released'; - $reservation->released_at = $now; - $reservation->release_reason = 'backup_restore_not_applied'; - $reservation->expires_at = null; - $ip->state = 'available'; - $ip->reservation_id = null; - $ip->instance_id = null; - $ip->operation_id = null; - } elseif ($status === 'uncertain') { - $reservation->state = 'uncertain'; - $reservation->expires_at = null; - $ip->state = 'uncertain'; - } else { - throw new \InvalidArgumentException('Invalid backup restore result'); - } - $reservation->updated_at = $ip->updated_at = $now; - $reservation->save(); - $ip->save(); - } - /** Keep an ambiguous create and both addresses unavailable for reconciliation. */ public static function markUncertain(CloudOrder $order): void { @@ -1311,144 +988,6 @@ final class CloudPlacementService ); } - /** Atomically settle the PHP-side address ledger for a network-change job. */ - public static function finishNetworkChange(CloudInstance $instance, - string $operationId, int $sourceIpId, int $targetIpId, - int $sourceAttachmentId, int $targetAttachmentId, int $sourcePoolId, - int $targetPoolId, string $outcome): void - { - CloudPublicNetworkTransitionGate::assertWriterReady(); - if (!in_array($outcome, ['succeeded', 'failed', 'uncertain'], true) - || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1 - || min($sourceIpId, $targetIpId, $sourceAttachmentId, - $targetAttachmentId, $sourcePoolId, $targetPoolId) < 1 - || $sourceIpId === $targetIpId) { - throw new CloudError('公网 IP 变更账本参数无效', 409); - } - $host = CloudHost::where('id', (int) $instance->host_id) - ->lockForUpdate()->first(); - - // Host is the sentinel for every host-scoped writer. Lock attachment - // and pool rows in numeric order before the reservation/IP ledger so - // placement and network changes cannot invert their lock hierarchy. - $attachmentIds = array_values(array_unique([ - $sourceAttachmentId, - $targetAttachmentId, - ])); - sort($attachmentIds, SORT_NUMERIC); - $attachments = CloudHostNetworkAttachment::whereIn( - 'id', - $attachmentIds - )->orderBy('id')->lockForUpdate()->get()->keyBy('id'); - $sourceAttachment = $attachments->get($sourceAttachmentId); - $targetAttachment = $attachments->get($targetAttachmentId); - $poolIds = array_values(array_unique([$sourcePoolId, $targetPoolId])); - sort($poolIds, SORT_NUMERIC); - $pools = CloudPublicIpPool::whereIn('id', $poolIds)->orderBy('id') - ->lockForUpdate()->get()->keyBy('id'); - $sourcePool = $pools->get($sourcePoolId); - $targetPool = $pools->get($targetPoolId); - $reservation = $instance->reservation_id === null ? null - : CloudResourceReservation::where('id', (int) $instance->reservation_id) - ->lockForUpdate()->first(); - $reservationPool = $reservation === null ? null - : CloudResourcePool::find((int) $reservation->resource_pool_id); - if ($host === null || $sourceAttachment === null - || $targetAttachment === null - || $sourcePool === null || $targetPool === null - || $reservationPool === null - || (int) $sourceAttachment->host_id !== (int) $host->id - || (int) $targetAttachment->host_id !== (int) $host->id - || (int) $reservation->resource_pool_id - !== (int) ($instance->resource_pool_id ?? 0) - || (int) $sourceAttachment->line_id - !== (int) $reservationPool->line_id - || (int) $targetAttachment->line_id - !== (int) $reservationPool->line_id - || (int) $sourcePool->host_id !== (int) $host->id - || (int) $targetPool->host_id !== (int) $host->id - || (int) $sourcePool->network_attachment_id - !== $sourceAttachmentId - || (int) $targetPool->network_attachment_id - !== $targetAttachmentId - || preg_match('/^[a-f0-9]{32}$/D', (string) $targetPool->pool_key) !== 1 - || $reservation === null - || (string) $reservation->state !== 'committed' - || (int) $reservation->host_id !== (int) $host->id - || (int) ($reservation->instance_id ?? 0) !== (int) $instance->id - || (int) ($reservation->network_attachment_id ?? 0) - !== $sourceAttachmentId - || (int) ($reservation->public_ip_pool_id ?? 0) !== $sourcePoolId - || (int) $reservation->public_ip_id !== $sourceIpId) { - throw new CloudError('虚拟机公网 IP 资源预留不一致', 409); - } - - $ipIds = [$sourceIpId, $targetIpId]; - sort($ipIds, SORT_NUMERIC); - $ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id') - ->lockForUpdate()->get()->keyBy('id'); - $source = $ips->get($sourceIpId); - $target = $ips->get($targetIpId); - if ($source === null || $target === null - || (int) $source->host_id !== (int) $host->id - || (int) $target->host_id !== (int) $host->id - || (int) ($source->public_ip_pool_id ?? 0) !== $sourcePoolId - || (int) ($target->public_ip_pool_id ?? 0) !== $targetPoolId - || (string) $source->state !== 'assigned' - || (int) ($source->reservation_id ?? 0) !== (int) $reservation->id - || (int) ($source->instance_id ?? 0) !== (int) $instance->id - || !hash_equals((string) $reservation->operation_id, - (string) ($source->operation_id ?? '')) - || !in_array((string) $target->state, ['changing', 'uncertain'], true) - || $target->reservation_id !== null - || (int) ($target->instance_id ?? 0) !== (int) $instance->id - || !hash_equals($operationId, (string) ($target->operation_id ?? ''))) { - throw new CloudError('公网 IP 变更账本关联不一致', 409); - } - if ($outcome === 'succeeded' - && !self::publicIpBelongsToPool($target, $targetPool)) { - throw new CloudError('公网 IP 变更结果与地址池账本不一致', 409); - } - - $now = time(); - if ($outcome === 'uncertain') { - $target->state = 'uncertain'; - $target->updated_at = $now; - $target->save(); - return; - } - if ($outcome === 'failed') { - $target->state = 'available'; - $target->reservation_id = null; - $target->instance_id = null; - $target->operation_id = null; - $target->updated_at = $now; - $target->save(); - return; - } - - // reservation_id is unique: release the old row before binding the new - // one, while both rows and the reservation remain locked. - $source->state = 'available'; - $source->reservation_id = null; - $source->instance_id = null; - $source->operation_id = null; - $source->updated_at = $now; - $source->save(); - - $reservation->public_ip_id = $targetIpId; - $reservation->network_attachment_id = $targetAttachmentId; - $reservation->public_ip_pool_id = $targetPoolId; - $reservation->save(); - - $target->state = 'assigned'; - $target->reservation_id = (int) $reservation->id; - $target->instance_id = (int) $instance->id; - $target->operation_id = (string) $reservation->operation_id; - $target->updated_at = $now; - $target->save(); - } - private static function tryHost(int $hostId, CloudResourcePool $pool, CloudOrder $order, CloudOffer $offer, array $resources, array $payload, @@ -1619,33 +1158,6 @@ final class CloudPlacementService return $payload; } - /** Return the validated DNS snapshot frozen on one public address pool. */ - private static function poolDnsServers(CloudPublicIpPool $pool): array - { - try { - $dnsServers = json_decode( - (string) $pool->dns_servers_json, - true, - 16, - JSON_THROW_ON_ERROR - ); - } catch (\Throwable $error) { - throw new CloudError('公网地址池 DNS 配置损坏', 409); - } - if (!is_array($dnsServers) || !array_is_list($dnsServers) - || $dnsServers === [] - || count($dnsServers) > 4 - || count(array_filter($dnsServers, static fn ($value): bool => - is_string($value) && filter_var( - $value, - FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4 - ) !== false - )) !== count($dnsServers)) { - throw new CloudError('公网地址池 DNS 配置损坏', 409); - } - return array_values($dnsServers); - } private static function assertOrderOffer(CloudOrder $order, CloudOffer $offer, Shop $plan): void @@ -1699,15 +1211,6 @@ final class CloudPlacementService return substr($reason, 0, 64); } - private static function assertBackupRestoreTransitionReady( - CloudBackupRestore $restore - ): void { - if ($restore->backup_id === null) { - CloudPublicNetworkTransitionGate:: - assertLegacyMigrationWriterRetired(); - } - CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); - } private static function markReservationReleased( CloudResourceReservation $reservation, @@ -2055,87 +1558,5 @@ final class CloudPlacementService ); } - private static function availablePublicIpQuery(int $hostId, int $publicPoolId, - int $prefixLength) - { - return CloudPublicIp::query()->where('host_id', $hostId) - ->where('public_ip_pool_id', $publicPoolId) - ->where('prefix_length', $prefixLength) - ->where('state', 'available') - ->whereNull('reservation_id')->whereNull('instance_id') - ->whereNull('operation_id')->orderBy('id'); - } - - private static function publicIpBelongsToPool(CloudPublicIp $ip, - CloudPublicIpPool $pool): bool - { - if ((int) $ip->prefix_length !== (int) $pool->guest_prefix_length) { - return false; - } - if (!self::ipv4BelongsToCidr( - (string) $ip->address, (string) $pool->cidr - )) { - return false; - } - $blocked = [(string) $pool->gateway]; - $managementAddress = CloudPanelUsageService::managementAddress( - CloudHost::find((int) $pool->host_id) - ); - if ($managementAddress !== null) { - $blocked[] = $managementAddress; - } - foreach (['dns_servers_json', 'reserved_ips_json'] as $field) { - try { - $values = json_decode((string) $pool->{$field}, true, - 16, JSON_THROW_ON_ERROR); - } catch (\Throwable $error) { - return false; - } - if (!is_array($values) || !array_is_list($values)) { - return false; - } - foreach ($values as $value) { - if (!is_string($value) - || filter_var($value, FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4) === false) { - return false; - } - $blocked[] = $value; - } - } - return !in_array((string) $ip->address, $blocked, true); - } - - private static function ipv4BelongsToCidr(string $addressValue, - string $cidr): bool - { - $parts = explode('/', $cidr, 2); - if (count($parts) !== 2 || !ctype_digit($parts[1])) { - return false; - } - $prefix = (int) $parts[1]; - $address = self::ipv4Number($addressValue); - $network = self::ipv4Number($parts[0]); - if ($address === null || $network === null || $prefix < 24 || $prefix > 30) { - return false; - } - $block = 2 ** (32 - $prefix); - $base = (int) (floor($network / $block) * $block); - return $address > $base && $address < $base + $block - 1; - } - - private static function ipv4Number(string $value): ?int - { - if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { - return null; - } - $packed = inet_pton($value); - if ($packed === false || strlen($packed) !== 4) { - return null; - } - $parts = unpack('Nnumber', $packed); - return is_array($parts) && isset($parts['number']) - ? (int) sprintf('%u', $parts['number']) : null; - } } diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php deleted file mode 100644 index c84ccb26..00000000 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionGate.php +++ /dev/null @@ -1,31 +0,0 @@ -kind === 'network_change' && $job->public_network_transition_id === null) { - CloudPublicNetworkTransitionGate::assertWriterReady(); + throw new CloudError('旧公网网络写任务已停用', 409); } elseif ((string) $job->kind === 'backup_restore') { self::assertPortableRestoreDispatchReady($job, $payload); } elseif (str_starts_with( @@ -1674,40 +1674,9 @@ final class CloudWorkerService ]; } if ($kind === 'backup_restore') { - $body = is_array($payload['body'] ?? null) - ? $payload['body'] : []; - if (is_string($payload['attempt_key'] ?? null) - && preg_match('/^[a-f0-9]{32}$/D', - $payload['attempt_key']) === 1) { - return CloudPortableRestoreJobEnvelope:: - compactRecoveryPayload($payload); - } - // Existing legacy jobs remain inspectable while the external - // portable-restore gate is closed. No capability URL or object - // storage runtime is copied into their post-effect envelope. - return [ - CloudOperationRecoveryIdentity::payloadKey() => $identity, - 'owner_id' => $payload['owner_id'] ?? null, - 'can_manage' => $payload['can_manage'] ?? null, - 'backup_key' => $payload['backup_key'] ?? null, - 'restore_key' => $payload['restore_key'] ?? null, - 'reservation_id' => $payload['reservation_id'] ?? null, - 'maintenance_migration_id' => - $payload['maintenance_migration_id'] ?? null, - 'body' => [ - 'vcpu' => $body['vcpu'] ?? null, - 'memory_mib' => $body['memory_mib'] ?? null, - 'disk_gib' => $body['disk_gib'] ?? null, - 'bandwidth_mbps' => $body['bandwidth_mbps'] ?? null, - 'network' => $body['network'] ?? null, - 'public_ip_cidr' => $body['public_ip_cidr'] ?? null, - 'public_pool_key' => $body['public_pool_key'] ?? null, - 'public_pool_cidr' => - $body['public_pool_cidr'] ?? null, - 'gateway' => $body['gateway'] ?? null, - 'dns_servers' => $body['dns_servers'] ?? null, - ], - ]; + return CloudPortableRestoreJobEnvelope::compactRecoveryPayload( + $payload + ); } if ($kind === 'instance_migration_prepare') { $body = is_array($payload['body'] ?? null) @@ -2661,93 +2630,6 @@ final class CloudWorkerService $preparedRecoveryMarker !== null, $aggregateParent ); - } elseif ($job->kind === 'network_change' - && $job->public_network_transition_id === null - && in_array($catalogStatus, - ['succeeded', 'failed', 'uncertain'], true)) { - $instance = $job->instance_id === null ? null - : CloudInstance::where('id', $job->instance_id) - ->lockForUpdate()->first(); - $sourceIpId = filter_var($payload['source_public_ip_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); - $targetIpId = filter_var($payload['target_public_ip_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); - $sourceAttachmentId = filter_var( - $payload['source_network_attachment_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] - ); - $targetAttachmentId = filter_var( - $payload['target_network_attachment_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] - ); - $sourcePoolId = filter_var( - $payload['source_public_ip_pool_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] - ); - $targetPoolId = filter_var( - $payload['target_public_ip_pool_id'] ?? null, - FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] - ); - if ($instance === null || $sourceIpId === false - || $targetIpId === false || $sourceAttachmentId === false - || $targetAttachmentId === false - || $sourcePoolId === false || $targetPoolId === false) { - throw new CloudError('公网 IP 变更任务缺少账本关联', 409); - } - if ($catalogStatus === 'succeeded') { - $requested = is_array($payload['body'] ?? null) - ? ($payload['body']['public_ip_cidr'] ?? null) : null; - $requestedPoolKey = is_array($payload['body'] ?? null) - ? ($payload['body']['public_pool_key'] ?? null) : null; - $confirmed = is_array($result) - ? ($result['public_ip_cidr'] ?? null) : null; - $confirmedPoolKey = is_array($result) - ? ($result['public_pool_key'] ?? null) : null; - if (!is_string($requested) || !is_string($confirmed) - || !is_string($requestedPoolKey) - || !is_string($confirmedPoolKey) - || $requested !== $confirmed - || !hash_equals($requestedPoolKey, $confirmedPoolKey)) { - throw new CloudError( - 'Agent 成功结果缺少已确认的公网 IP 或地址池', 502 - ); - } - $decoded = json_decode((string) $instance->spec_json, true); - if (!is_array($decoded) || array_is_list($decoded)) { - throw new CloudError('虚拟机配置记录损坏,无法保存新的公网 IP', 409); - } - CloudPlacementService::finishNetworkChange($instance, - (string) $job->operation_id, (int) $sourceIpId, - (int) $targetIpId, (int) $sourceAttachmentId, - (int) $targetAttachmentId, - (int) $sourcePoolId, (int) $targetPoolId, 'succeeded'); - $decoded['public_ip_cidr'] = $confirmed; - $instance->spec_json = json_encode($decoded, - JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE); - self::recordRuntime($instance, is_array($result) ? $result : [], - (string) $job->kind, $payload); - $instance->updated_at = time(); - $instance->save(); - } else { - CloudPlacementService::finishNetworkChange($instance, - (string) $job->operation_id, (int) $sourceIpId, - (int) $targetIpId, (int) $sourceAttachmentId, - (int) $targetAttachmentId, - (int) $sourcePoolId, (int) $targetPoolId, - $catalogStatus); - if ($catalogStatus === 'failed') { - // Only a proven not-applied result releases the target - // address and returns a tenant charge. An uncertain - // effect keeps both the IP and money ledgers fenced - // until the original operation is reconciled. - CloudIpChangeBillingService::refundNotAppliedLocked( - $job, - $user, - 'not_applied' - ); - } - } } elseif ($status === 'succeeded' && $job->kind === 'create') { $vm = is_array($result) ? ($result['vm'] ?? $result) : []; $uuid = $vm['uuid'] ?? ''; @@ -3908,7 +3790,7 @@ final class CloudWorkerService if (!CloudPortableRestoreFinalizer::owns($job) || !is_string($attemptKey) || preg_match('/^[a-f0-9]{32}$/D', $attemptKey) !== 1) { - CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); + throw new CloudError('旧备份恢复任务已停用', 409); } } diff --git a/web/tests/CloudAutomaticOperationRecoveryServiceTest.php b/web/tests/CloudAutomaticOperationRecoveryServiceTest.php index 7e441064..5372b810 100644 --- a/web/tests/CloudAutomaticOperationRecoveryServiceTest.php +++ b/web/tests/CloudAutomaticOperationRecoveryServiceTest.php @@ -848,19 +848,13 @@ namespace { ['hostname' => 'not-a-settings-recovery.example'] ); Capsule::table('cloud_jobs')->where('id', $nonSettingsId)->update([ - 'kind' => 'network_change', + 'kind' => 'action', 'sealed_payload' => CloudSecrets::encrypt([ 'method' => 'POST', - 'request_target' => '/v1/vms/' . $nonSettingsUuid . '/network', + 'request_target' => '/v1/vms/' . $nonSettingsUuid . '/actions', 'body' => [ 'operation_id' => str_repeat('0f', 16), - 'network' => 'bridge:br0', - 'public_pool_key' => str_repeat('a', 32), - 'public_pool_cidr' => '203.0.113.0/24', - 'public_ip_cidr' => '203.0.113.10/24', - 'gateway' => '203.0.113.1', - 'dns_servers' => ['1.1.1.1'], - 'confirm_restart' => true, + 'action' => 'start', ], 'owner_id' => 1, 'can_manage' => false, diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index 2ec343a6..a3a89696 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -38,19 +38,6 @@ $pendingEnd = is_string($placement) ? strpos($placement, 'private static function availableIpHosts') : false; $pendingMethod = $pendingStart !== false && $pendingEnd !== false ? substr($placement, $pendingStart, $pendingEnd - $pendingStart) : ''; -$availableStart = is_string($placement) - ? strpos($placement, 'private static function availablePublicIpQuery') : false; -$availableEnd = is_string($placement) - ? strpos($placement, 'private static function publicIpBelongsToPool') : false; -$availableMethod = $availableStart !== false && $availableEnd !== false - ? substr($placement, $availableStart, $availableEnd - $availableStart) : ''; -$finishStart = is_string($placement) - ? strpos($placement, 'public static function finishNetworkChange') : false; -$finishEnd = is_string($placement) - ? strpos($placement, 'private static function tryHost', $finishStart ?: 0) : false; -$finishMethod = $finishStart !== false && $finishEnd !== false - ? substr($placement, $finishStart, $finishEnd - $finishStart) : ''; - $assert = static function ($condition, string $message): void { if (!$condition) { throw new RuntimeException($message); @@ -154,16 +141,14 @@ $assert(is_string($jobs) && is_string($workflow) && is_string($command) 'Canonical workflow no longer owns and freezes the dual-stack ledger identity.'); $assert(is_string($worker) && str_contains($worker, - 'CloudPublicNetworkTransitionGate::assertWriterReady()') - && str_contains($worker, 'CloudPlacementService::finishNetworkChange') - && str_contains($worker, '$confirmedPoolKey') - && str_contains($worker, '$sourceAttachmentId') - && str_contains($worker, '$targetAttachmentId') - && str_contains($worker, '$catalogStatus') + "throw new CloudError('旧公网网络写任务已停用', 409)") + && str_contains($worker, + 'CloudPublicNetworkTransitionWorkflow::finishJobLocked(') + && !str_contains($worker, 'CloudPlacementService::finishNetworkChange') && str_contains($worker, "\$job->phase = 'terminal'") && str_contains($worker, '$job->outcome = $status') && str_contains($worker, '$effectMayHaveApplied'), - 'Worker no longer confirms pool identity or settles network changes from one terminal receipt.'); + 'Worker retained the scalar writer or bypassed canonical transition settlement.'); $assert(is_string($placement) && is_string($placementNetwork) && is_string($allocation) @@ -176,34 +161,17 @@ $assert(is_string($placement) "\$payload['body']['public_network'] = \$publicNetwork->toArray()") && str_contains($placement, 'CloudPublicNetworkAllocationService::releaseBundle(') - && str_contains($placement, - 'releaseCommittedBundle(') && str_contains($allocation, "->where('active_claim', 1)") && str_contains($allocation, 'reservation_ip_claim_id') - && str_contains($placement, - '(int) $ip->prefix_length !== (int) $pool->guest_prefix_length') - && str_contains($finishMethod, - 'CloudPublicNetworkTransitionGate::assertWriterReady()'), - 'Placement no longer uses active dual-stack claims or fails closed for retired scalar network changes.'); -$assert(str_contains($placement, - 'CloudPlacementNetworkService::lockedCandidates(') - && str_contains($placement, - 'CloudPlacementNetworkService::lockAvailableSelection(') - && str_contains($placementNetwork, 'MAX_PUBLIC_IPS_PER_POOL + 1') - && str_contains($placementNetwork, 'foreach ($ips as $ip)') - && str_contains($placementNetwork, 'addressAllowedByPool(') - && str_contains($placementNetwork, "['dns_servers_json', 'reserved_ips_json']"), - 'A malformed first address can still hide the rest of an otherwise usable pool.'); -$assert($finishMethod !== '' - && !str_contains($finishMethod, '$reservation->updated_at = $now'), - 'Network-only changes must not make committed capacity look newly pending.'); + && !str_contains($placement, 'finishNetworkChange(') + && !str_contains($placement, 'availablePublicIpQuery(') + && !str_contains($placement, 'publicIpBelongsToPool('), + 'Placement retained a retired scalar network writer.'); +$assert(str_contains($allocation, 'lockReservableAddressCandidate(') + && str_contains($allocation, 'rawAddressAllowedByPool(') + && str_contains($placementNetwork, 'addressAllowedByPool('), + 'Canonical allocation lost address-level pool validation.'); $assert(str_contains($pendingMethod, 'CloudPanelUsageService::forHosts($candidateIds)') && !str_contains($pendingMethod, 'resource_pool_id'), 'Advisory pending usage is no longer deducted once per physical host across memberships.'); -$assert(str_contains($availableMethod, "->where('state', 'available')") - && str_contains($availableMethod, "->whereNull('reservation_id')") - && str_contains($availableMethod, "->whereNull('instance_id')") - && str_contains($availableMethod, "->whereNull('operation_id')"), - 'Placement no longer rejects stale ownership fields on an apparently available address.'); - echo "Cloud network IP ledger contract tests passed\n"; diff --git a/web/tests/CloudOperationRecoveryMatrixTest.php b/web/tests/CloudOperationRecoveryMatrixTest.php index fd3090d9..369da215 100644 --- a/web/tests/CloudOperationRecoveryMatrixTest.php +++ b/web/tests/CloudOperationRecoveryMatrixTest.php @@ -47,6 +47,7 @@ namespace { use App\Services\Cloud\CloudOperationRecoveryPolicy; use App\Services\Cloud\CloudPortableRestoreCompatibility; use App\Services\Cloud\CloudPublicNetworkAllocationService; + use App\Services\Cloud\CloudPublicNetworkSnapshot; use App\Services\Cloud\CloudRecoveryInstanceStateConflict; use App\Services\Cloud\CloudSecrets; use App\Services\Cloud\CloudVpcProjection; @@ -122,6 +123,7 @@ namespace { $table->integer('backup_id')->nullable(); $table->integer('backup_restore_id')->nullable(); $table->integer('backup_recovery_id')->nullable(); + $table->integer('public_network_transition_id')->nullable(); $table->integer('vpc_id')->nullable(); $table->integer('vpc_port_id')->nullable(); $table->integer('user_id'); @@ -158,6 +160,18 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_public_network_transitions', static function ( + Blueprint $table + ): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('host_id'); + $table->string('operation_id'); + $table->text('target_public_network_json'); + $table->string('target_public_network_sha256'); + $table->string('source_claim_set_sha256'); + $table->string('target_claim_set_sha256'); + }); $schema->create('cloud_agent_completion_events', static function (Blueprint $table): void { $table->string('event_id')->primary(); @@ -691,6 +705,7 @@ namespace { 'backup_id' => $backupId, 'backup_restore_id' => $backupRestoreId, 'backup_recovery_id' => $backupRecoveryId, + 'public_network_transition_id' => null, 'vpc_id' => $vpcId, 'vpc_port_id' => $vpcPortId, 'user_id' => $userId, @@ -1516,22 +1531,66 @@ namespace { ] ); - $instanceFixture( + $networkSnapshot = CloudPublicNetworkSnapshot::fromArray([ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('c', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.20/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('d', 32), + 'pool_cidr' => '2606:4700:4700:20::/64', + 'address_cidr' => '2606:4700:4700:20::20/64', + 'gateway' => '2606:4700:4700:20::1', + 'gateway_on_link' => false, + ], + 'dns_servers' => ['9.9.9.9', '2001:4860:4860::8888'], + ]); + $sourceClaimSetSha256 = str_repeat('1', 64); + $targetClaimSetSha256 = str_repeat('2', 64); + $networkRecord = $instanceFixture( 'network_change', 'public-ip-change', 'POST', '/network', [ - 'network' => 'bridge:br0', - 'public_pool_key' => str_repeat('c', 32), - 'public_pool_cidr' => '203.0.113.0/24', - 'public_ip_cidr' => '203.0.113.20/24', - 'gateway' => '203.0.113.1', - 'dns_servers' => ['1.1.1.1'], + 'public_network' => $networkSnapshot->toArray(), 'confirm_restart' => true, ], 'change-network', - ['uuid' => $instanceUuid, 'network_changed' => true] + [ + 'uuid' => $instanceUuid, + 'network_changed' => true, + 'public_network' => $networkSnapshot->toArray(), + ], + [ + 'public_network_transition_id' => 1, + 'source_claim_set_sha256' => $sourceClaimSetSha256, + 'target_claim_set_sha256' => $targetClaimSetSha256, + ] + ); + Capsule::table('cloud_public_network_transitions')->insert([ + 'id' => 1, + 'instance_id' => $instanceId, + 'host_id' => $hostId, + 'operation_id' => $networkRecord['operation_id'], + 'target_public_network_json' => json_encode( + $networkSnapshot->toArray(), + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ), + 'target_public_network_sha256' => $networkSnapshot->fingerprint(), + 'source_claim_set_sha256' => $sourceClaimSetSha256, + 'target_claim_set_sha256' => $targetClaimSetSha256, + ]); + Capsule::table('cloud_jobs')->where('id', $networkRecord['id'])->update([ + 'public_network_transition_id' => 1, + ]); + $fixtures['network_change'][0]['job'] = CloudJob::findOrFail( + $networkRecord['id'] ); $instanceFixture( 'instance_settings', @@ -2937,7 +2996,7 @@ namespace { 'created_at' => $now - 180, 'updated_at' => $now - 20, ]); - $dedicatedFixtures['backup_restore'] = $restoreRecord + [ + $legacyRestoreFixture = $restoreRecord + [ 'expected_action' => 'restore-backup:' . $restoreBackupKey, 'expected_resource' => $restoreUuid, ]; @@ -3082,6 +3141,7 @@ namespace { 'user_iso_import' => 'aggregate', 'user_iso_delete' => 'aggregate', ]; + $retiredIdentityKinds = ['backup_restore']; $genericKinds = array_keys(array_filter( $manifestOperations, static fn (array $operation): bool => @@ -3096,7 +3156,8 @@ namespace { $coveredKinds = array_merge( $fixtureKinds, array_keys($dedicatedFixtures), - array_keys($classificationOnlyKinds) + array_keys($classificationOnlyKinds), + $retiredIdentityKinds ); $contractKinds = array_keys($manifestOperations); sort($coveredKinds, SORT_STRING); @@ -3464,6 +3525,18 @@ namespace { 'An access token bypassed sensitive-key filtering.' ); + $legacyRestoreRejected = false; + try { + CloudOperationRecoveryIdentity::expectedFromPayload( + $legacyRestoreFixture['job'], + $legacyRestoreFixture['payload'] + ); + } catch (CloudError $error) { + $legacyRestoreRejected = $error->httpStatus === 409; + } + $assert($legacyRestoreRejected, + 'A restore without attempt ownership retained a recovery identity.'); + foreach ($dedicatedFixtures as $kind => $fixture) { $identity = CloudOperationRecoveryIdentity::expectedFromPayload( $fixture['job'], @@ -3512,25 +3585,6 @@ namespace { 'Create absence projection is no longer complete.'); $expectStateConflict(static fn () => CloudWorkerService::recoveryContext($fixture['job'])); - } elseif ($kind === 'backup_restore') { - $assert(CloudOperationRecoveryPolicy::identityScope($kind) - === 'create' - && $identity['resource_id'] - === $fixture['expected_resource'], - 'Backup restore identity lost its target VM scope.'); - $context = CloudWorkerService::recoveryContext($fixture['job']); - $assert(($context['instance']->id ?? null) - === $restoreInstanceId - && $context['payload'] === $fixture['payload'], - 'Backup restore lost its fenced recovery context.'); - $projection = $projectionMethod->invoke(null, [ - 'creation_absent' => true, - 'managed_artifacts_absent' => true, - ], 'backup_restore', 'not_applied'); - $assert(($projection['creation_absent'] ?? null) === true - && ($projection['managed_artifacts_absent'] ?? null) - === true, - 'Backup restore absence projection is no longer complete.'); } else { $assert(CloudOperationRecoveryPolicy::identityScope($kind) === 'storage' diff --git a/web/tests/CloudPaidIpChangeContractTest.php b/web/tests/CloudPaidIpChangeContractTest.php index c04791fd..5a063210 100644 --- a/web/tests/CloudPaidIpChangeContractTest.php +++ b/web/tests/CloudPaidIpChangeContractTest.php @@ -156,20 +156,12 @@ $assert(str_contains($billing, && str_contains($billing, "\$invoice->status = 'refunded'"), 'IP-change charge, invoice linkage, or exactly-once refund is incomplete.'); -$networkFinish = strpos($worker, - 'CloudPlacementService::finishNetworkChange($instance'); -$networkFinishEnd = strpos($worker, - "} elseif (\$status === 'succeeded' && \$job->kind === 'create')", - $networkFinish === false ? 0 : $networkFinish); -$networkSettlement = $networkFinish !== false && $networkFinishEnd !== false - ? substr($worker, $networkFinish, $networkFinishEnd - $networkFinish) - : ''; -$assert($networkSettlement !== '' - && str_contains($networkSettlement, - "if (\$catalogStatus === 'failed')") - && str_contains($networkSettlement, +$assert(substr_count($workflow, + 'CloudIpChangeBillingService::refundTransitionNotAppliedLocked(') >= 2 + && str_contains($workflow, "\$resolution === 'not_applied'") + && !str_contains($worker, 'CloudIpChangeBillingService::refundNotAppliedLocked(') - && str_contains($networkSettlement, "'not_applied'"), + && !str_contains($worker, 'CloudPlacementService::finishNetworkChange('), 'Network settlement no longer refunds only a conclusive not-applied result.'); $assert(str_contains($config, diff --git a/web/tests/CloudPortableBackupFinalizerTest.php b/web/tests/CloudPortableBackupFinalizerTest.php index cb9be959..cb88ab77 100644 --- a/web/tests/CloudPortableBackupFinalizerTest.php +++ b/web/tests/CloudPortableBackupFinalizerTest.php @@ -9,7 +9,6 @@ use App\Models\CloudJob; use App\Services\Cloud\CloudBackupService; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudPortableRestoreCompatibility; -use App\Services\Cloud\CloudPublicNetworkTransitionGate; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -468,14 +467,6 @@ $fixture = static function (int $id, string $outcome) use ( ]; }; -try { - CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); - throw new RuntimeException('Portable restore gate unexpectedly opened.'); -} catch (CloudError $error) { - $assert($error->httpStatus === 409, - 'Closed portable restore gate returned the wrong status.'); -} - // In-place recovery keeps the existing instance identity and converges only // from an exact backup/ledger/Agent result tuple. $recoveryOperation = str_repeat('e', 32); @@ -558,4 +549,4 @@ $assert((string) $recovery->state === 'succeeded' === str_repeat('a', 32), 'In-place backup recovery did not preserve disk-authoritative guest identity and the current network.'); -echo "Portable backup finalizers and closed restore gate passed.\n"; +echo "Portable backup finalizer behavior tests passed.\n"; diff --git a/web/tests/CloudPortableRestoreJobDispatcherTest.php b/web/tests/CloudPortableRestoreJobDispatcherTest.php index 39092165..d4925017 100644 --- a/web/tests/CloudPortableRestoreJobDispatcherTest.php +++ b/web/tests/CloudPortableRestoreJobDispatcherTest.php @@ -553,14 +553,17 @@ $rejectsInspection( ), 'Portable restore inspection accepted an IPv4 scalar-only projection.' ); -$inspectProjection->invoke( - null, - $inspectionBase + ['effect_projection' => $legacyScalarProjection], - (string) $job->operation_id, - 'backup_restore', - true, - false, - false +$rejectsInspection( + static fn () => $inspectProjection->invoke( + null, + $inspectionBase + ['effect_projection' => $legacyScalarProjection], + (string) $job->operation_id, + 'backup_restore', + true, + false, + false + ), + 'Legacy restore inspection retained an IPv4 scalar-only projection.' ); $notAppliedInspection = $inspectionBase; $notAppliedInspection['operation_status'] = 'failed'; diff --git a/web/tests/CloudPortableRestoreTargetServiceTest.php b/web/tests/CloudPortableRestoreTargetServiceTest.php index a52afd0d..29b2c2a2 100644 --- a/web/tests/CloudPortableRestoreTargetServiceTest.php +++ b/web/tests/CloudPortableRestoreTargetServiceTest.php @@ -9,7 +9,6 @@ use App\Services\Cloud\CloudPlatformTestNetworkPolicy; use App\Services\Cloud\CloudPortableRestoreCompatibility; use App\Services\Cloud\CloudPortableRestoreTargetPlan; use App\Services\Cloud\CloudPortableRestoreTargetService; -use App\Services\Cloud\CloudPublicNetworkTransitionGate; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -748,12 +747,4 @@ try { 'Oversized system disk returned the wrong error status.'); } -try { - CloudPublicNetworkTransitionGate::assertPortableRestoreReady(); - throw new RuntimeException('Portable restore dispatch gate opened.'); -} catch (CloudError $error) { - $assert($error->httpStatus === 409, - 'Closed portable restore gate returned the wrong status.'); -} - echo "Portable restore target scheduling tests passed.\n"; diff --git a/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php b/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php index 6433288d..51fd84b3 100644 --- a/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php +++ b/web/tests/CloudPublicNetworkLegacyWriterGateContractTest.php @@ -13,239 +13,84 @@ $assert = static function (bool $condition, string $message): void { throw new RuntimeException($message); } }; -$method = static function (string $source, string $needle): string { - $start = strpos($source, $needle); - if ($start === false) { - return ''; - } - $next = strpos($source, "\n public ", $start + strlen($needle)); - return $next === false ? substr($source, $start) - : substr($source, $start, $next - $start); -}; -$before = static function (string $source, string $left, - string $right): bool { - $leftAt = strpos($source, $left); - $rightAt = strpos($source, $right); - return $leftAt !== false && $rightAt !== false && $leftAt < $rightAt; -}; -$gate = $read('app/Services/Cloud/CloudPublicNetworkTransitionGate.php'); -$jobs = $read('app/Services/Cloud/CloudJobService.php'); +$services = $root . '/app/Services/Cloud'; +$assert(!is_file($services . '/CloudPublicNetworkTransitionGate.php'), + 'The retired public-network compatibility gate still exists.'); + +$placement = $read('app/Services/Cloud/CloudPlacementService.php'); $worker = $read('app/Services/Cloud/CloudWorkerService.php'); -$placementSource = $read('app/Services/Cloud/CloudPlacementService.php'); +$jobs = $read('app/Services/Cloud/CloudJobService.php'); +$backup = $read('app/Services/Cloud/CloudBackupService.php'); +$identity = $read('app/Services/Cloud/CloudOperationRecoveryIdentity.php'); +$adminRecovery = $read( + 'app/Services/Cloud/CloudAdminOperationRecoveryService.php' +); $deleteAuthority = $read( 'app/Services/Cloud/CloudInstanceResourceRelease.php' ); -$restoreDeleteSource = $read( - 'app/Services/Cloud/CloudPortableRestoreInstanceDeletion.php' -); -$migrationSource = $read( - 'app/Services/Cloud/CloudInstanceMigrationService.php' -); -$batchSource = $read( - 'app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php' -); -$batch = $method( - $batchSource, - 'public static function start(' -); -$workflow = $read( - 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' -); -$backupRestore = $method( - $read('app/Services/Cloud/CloudBackupService.php'), - 'public static function restore(' -); -$migration = $method( - $migrationSource, - 'public static function start(' -); -$placement = $method( - $placementSource, - 'public static function reserveBackupRestore(' -); -$placementGate = substr($placementSource, (int) strpos( - $placementSource, - 'private static function assertBackupRestoreTransitionReady(' -)); -$migrationEnsureCleanup = $method( - $migrationSource, - 'public static function ensureTargetResidueCleanup(' -); -$migrationRecover = $method( - $migrationSource, - 'public static function recover(' -); -$migrationCleanup = $method( - $migrationSource, - 'public static function cleanupRetained(' -); -$networkFinalizer = $method( - $placementSource, - 'public static function finishNetworkChange(' -); -$enqueue = $method( - $jobs, - 'public static function enqueue(' -); -$forceDelete = $method( - $jobs, - 'public static function enqueueForceDelete(' -); -$expiryDelete = $method( - $jobs, - 'public static function enqueueExpiryDelete(' -); -$deletedInstance = $method( - $deleteAuthority, - 'public static function releaseAfterConfirmedDelete(' -); -$assert(str_contains($gate, 'assertWriterReady') - && str_contains($gate, 'assertPortableRestoreReady') - && str_contains($gate, 'assertLegacyMigrationWriterRetired') - && !str_contains($gate, 'assertMigrationReady') - && !str_contains($gate, 'assertInstanceDeleteReady'), - 'Legacy-writer gate retained instance deletion ownership.'); -$enqueueStart = strpos($jobs, 'public static function enqueue('); -$enqueueTransaction = strpos($jobs, 'return $instance->getConnection()->transaction', - $enqueueStart === false ? 0 : $enqueueStart); -$enqueueReject = strpos($enqueue, "if (\$kind === 'network_change')"); -$enqueueRejectError = strpos($enqueue, '旧公网网络写入口已停用'); -$assert($enqueueStart !== false && $enqueueReject !== false - && $enqueueRejectError !== false && $enqueueTransaction !== false - && $enqueueReject < $enqueueTransaction - && $enqueueRejectError < $enqueueTransaction - && !str_contains($enqueue, 'paidNetworkChangeExpectedAmount') - && !str_contains($enqueue, "['public_ip_cidr', 'public_pool_key'") - && !str_contains($enqueue, '$networkLedger'), - 'Ordinary enqueue retained a scalar network writer or rejects it too late.'); -$assert(str_contains($worker, - "(string) \$job->kind === 'network_change'\n" - . ' && $job->public_network_transition_id === null') +foreach ([ + 'reserveBackupRestore(', + 'preparedBackupRestorePlacement(', + 'finishBackupRestore(', + 'finishNetworkChange(', + 'assertBackupRestoreTransitionReady(', + 'availablePublicIpQuery(', + 'publicIpBelongsToPool(', +] as $retired) { + $assert(!str_contains($placement, $retired), + 'Placement retained retired writer: ' . $retired); +} + +$assert(str_contains($jobs, "if (\$kind === 'network_change')") + && str_contains($jobs, '旧公网网络写入口已停用') && str_contains($worker, - 'CloudPublicNetworkTransitionGate::assertWriterReady()'), - 'Worker does not distinguish canonical transition jobs from legacy rows.'); -$assert($before($worker, - "(string) \$job->kind === 'network_change'", - "'phase' => 'dispatching'") - && $before($worker, - "(string) \$job->kind === 'backup_restore'", - "'phase' => 'dispatching'") - && $before($worker, - 'CloudOperationRecoveryIdentity::expectedFromPayload(', - "'phase' => 'dispatching'"), - 'Worker defense runs after an old operation may be dispatched.'); -$restoreDispatchGate = strpos( - $worker, - 'self::assertPortableRestoreDispatchReady($job, $payload)' -); -$restoreDispatchCas = strpos($worker, "'phase' => 'dispatching'"); -$restoreWire = strpos( - $worker, - 'self::portableRestoreDispatchPayload($job, $payload)' -); -$assert($restoreDispatchGate !== false && $restoreDispatchCas !== false - && $restoreWire !== false - && $restoreDispatchGate < $restoreDispatchCas - && $restoreDispatchGate < $restoreWire + "throw new CloudError('旧公网网络写任务已停用', 409)") && str_contains($worker, - '!CloudPortableRestoreFinalizer::owns($job)') + "throw new CloudError('旧备份恢复任务已停用', 409)") && str_contains($worker, - "preg_match('/^[a-f0-9]{32}$/D', \$attemptKey) !== 1") - && !str_contains($worker, - "(string) \$job->kind === 'backup_restore'\n" - . " && isset(\$payload['attempt_key'])"), - 'Worker portable restore gate can be bypassed before dispatch.'); -$assert(!str_contains($jobs, 'enqueuePoolReplacementNetworkChangeLocked') - && !str_contains($batch, 'CloudPublicNetworkTransitionGate::assertWriterReady()') - && str_contains($batchSource, 'beginPoolReplacementBatch(') - && str_contains($workflow, 'CloudPublicNetworkTransitionBatchPlan $plan'), - 'Pool replacement retained the retired scalar writer or legacy gate.'); -$assert(!str_contains($backupRestore, - 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()') - && str_contains($backupRestore, - 'CloudPortableRestoreRequestService::request(') - && !str_contains($backupRestore, 'headObject(') - && !str_contains($backupRestore, 'presignedGet(') - && !str_contains($backupRestore, 'new CloudBackupRestore()') - && !str_contains($backupRestore, 'reserveBackupRestore('), - 'Portable-restore request seam retained the retired writer or closed gate.'); -$assert(!str_contains($migration, - 'CloudPublicNetworkTransitionGate::') - && str_contains($migration, 'reserveMaintenanceMigrationTarget('), - 'Canonical dual-stack migration start is still behind a legacy gate.'); -$assert(str_contains($placement, - 'self::assertBackupRestoreTransitionReady($restore)') - && str_contains($placementGate, - 'assertLegacyMigrationWriterRetired()') - && str_contains($placementGate, - 'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()'), - 'Placement lacks a defense-in-depth gate for old restore writers.'); -$assert(!str_contains($migrationEnsureCleanup, - 'CloudPublicNetworkTransitionGate::') - && !str_contains($migrationRecover, - 'CloudPublicNetworkTransitionGate::') - && !str_contains($migrationCleanup, - 'CloudPublicNetworkTransitionGate::') - && str_contains($migrationEnsureCleanup, 'getConnection()->transaction') - && str_contains($migrationRecover, 'getConnection()->transaction') - && str_contains($migrationCleanup, 'getConnection()->transaction'), - 'Canonical migration recovery is still gated or lost its transaction.'); -$assert($before($networkFinalizer, - 'CloudPublicNetworkTransitionGate::assertWriterReady()', - 'lockForUpdate()'), - 'An old network-change finalizer can mutate before its gate.'); -$assert(str_contains($deletedInstance, - 'CloudPortableRestoreInstanceDeletion::releaseCommitted(') - && str_contains($deleteAuthority, + 'CloudPublicNetworkTransitionWorkflow::finishJobLocked(') + && !str_contains($worker, 'CloudPlacementService::finishNetworkChange('), + 'Worker or enqueue retained a dispatchable scalar public-network path.'); + +$assert(!str_contains($backup, 'finishRestoreLocked(') + && str_contains($backup, + 'CloudPortableRestoreFinalizer::finishJobLocked(') + && str_contains($backup, + 'CloudPortableRestoreFinalizer::markJobUncertain('), + 'Backup restore retained its singular-IP finalizer.'); + +foreach ([ + 'legacyBackupRestoreIdentity(', + 'backupRestoreAction(', +] as $retired) { + $assert(!str_contains($identity, $retired), + 'Recovery identity retained legacy restore support: ' . $retired); +} +$assert(!str_contains($adminRecovery, "'public_ip_cidr'") + && !str_contains($adminRecovery, "'public_pool_key'"), + 'Administrator recovery retained scalar restore-result fields.'); + +$php = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( + $services, + FilesystemIterator::SKIP_DOTS +)); +foreach ($php as $file) { + if (!$file->isFile() || $file->getExtension() !== 'php') { + continue; + } + $source = file_get_contents($file->getPathname()); + $assert(is_string($source) + && !str_contains($source, 'CloudPublicNetworkTransitionGate'), + 'Production service retained the legacy gate: ' + . $file->getFilename()); +} + +$assert(str_contains($deleteAuthority, 'CloudPublicNetworkAllocationService::currentClaimSet(') - && str_contains($restoreDeleteSource, - 'backup_restore_attempt_key') - && str_contains($restoreDeleteSource, - "(string) \$attempt->state !== 'succeeded'") - && str_contains($restoreDeleteSource, - "(string) \$attempt->effect_resolution !== 'applied'") - && str_contains($restoreDeleteSource, - 'CloudPublicNetworkAllocationService::releaseCommittedBundle(') - && str_contains($restoreDeleteSource, - 'CloudReleasedPublicNetworkBundleVerifier::verify(') - && !str_contains($placementSource, 'releaseDeletedInstance(') - && !str_contains($placementSource, 'releaseLockedReservation(') - && !str_contains($placementSource, 'reservationNetworkMatches('), - 'Restored-instance deletion does not distinguish legacy and attempt-owned ledgers.'); -$enqueueDeleteGate = strpos( - $enqueue, - 'CloudInstanceResourceRelease::assertCanDispatchDelete(' -); -$enqueueTransaction = strpos($enqueue, 'getConnection()->transaction'); -$enqueueInstanceLock = strpos($enqueue, "CloudInstance::where('id'"); -$enqueueLockedDeleteGate = $enqueueInstanceLock === false ? false : strpos( - $enqueue, - 'CloudInstanceResourceRelease::assertCanDispatchDelete(', - $enqueueInstanceLock -); -$enqueueJob = strpos($enqueue, 'new CloudJob()'); -$assert($enqueueDeleteGate !== false && $enqueueTransaction !== false - && $enqueueDeleteGate < $enqueueTransaction - && $enqueueLockedDeleteGate !== false && $enqueueJob !== false - && $enqueueLockedDeleteGate < $enqueueJob, - 'Restored-instance delete gate can run after durable job creation.'); -$assert($before($forceDelete, - 'CloudInstanceResourceRelease::assertCanDispatchDelete(', - 'new CloudJob()'), - 'Restored-instance force-delete gate runs after durable job creation.'); -$assert($before($expiryDelete, - 'CloudInstanceResourceRelease::assertCanDispatchDelete(', - 'new CloudJob()'), - 'Restored-instance expiry-delete gate runs after durable job creation.'); -$workerDeleteGate = strpos( - $worker, - 'assertCanDispatchDelete($deleteInstance)' -); -$workerDispatch = strpos($worker, "'phase' => 'dispatching'"); -$assert($workerDeleteGate !== false && $workerDispatch !== false - && $workerDeleteGate < $workerDispatch, - 'Worker can dispatch a restored-instance delete before its gate.'); + && str_contains($deleteAuthority, + 'CloudPortableRestoreInstanceDeletion::releaseCommitted('), + 'Deleting canonical instances lost dual-stack source authority.'); -echo "Legacy public-network writer gate contracts passed.\n"; +echo "Legacy public-network writers are retired.\n";