From 0c80deb6d7031ea970844d665180831f517dfe7e Mon Sep 17 00:00:00 2001 From: codex Date: Wed, 4 Nov 2026 18:34:59 +0800 Subject: [PATCH] refactor: extract transition ledger context --- .../CloudPublicNetworkTransitionContext.php | 624 ++++++++++++++++ .../CloudPublicNetworkTransitionWorkflow.php | 665 +----------------- ...licIpPoolReplacementSchemaContractTest.php | 2 +- ...cNetworkTransitionWorkflowContractTest.php | 33 +- 4 files changed, 691 insertions(+), 633 deletions(-) create mode 100644 web/app/Services/Cloud/CloudPublicNetworkTransitionContext.php diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionContext.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionContext.php new file mode 100644 index 00000000..39e431c8 --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionContext.php @@ -0,0 +1,624 @@ + transition -> topology -> reservation -> legs -> + * claims/IPs acquisition order while hiding the frozen dual-stack ledger. + */ +final class CloudPublicNetworkTransitionContext +{ + private const FAMILIES = [4, 6]; + + /** @return array{0:CloudHost,1:CloudHostAgent} */ + public static function lockHostBoundary(int $hostId): array + { + if ($hostId < 1) { + throw new CloudError('公网网络变更宿主机身份缺失', 409); + } + $host = CloudHost::where('id', $hostId) + ->lockForUpdate()->first(); + $agent = CloudHostAgent::where('host_id', $hostId) + ->lockForUpdate()->first(); + if (!$host instanceof CloudHost + || !$agent instanceof CloudHostAgent) { + throw new CloudError('公网网络变更宿主机账本缺失', 409); + } + return [$host, $agent]; + } + + /** + * @return array{0:CloudPublicNetworkSnapshot,1:CloudPublicNetworkSnapshot} + */ + public static function assertAssociation( + CloudJob $job, + CloudInstance $instance, + CloudPublicNetworkTransition $transition, + ?array $payload, + bool $requirePayload + ): array { + $jobInvoiceId = $job->invoice_id === null + ? null : (int) $job->invoice_id; + $transitionInvoiceId = $transition->invoice_id === null + ? null : (int) $transition->invoice_id; + if ((string) $job->kind !== 'network_change' + || (string) $job->execution_mode !== 'agent' + || (int) $job->public_network_transition_id + !== (int) $transition->id + || (int) $job->instance_id !== (int) $instance->id + || (int) $transition->instance_id !== (int) $instance->id + || (int) $job->host_id !== (int) $instance->host_id + || (int) $transition->host_id !== (int) $instance->host_id + || (int) $transition->reservation_id + !== (int) $instance->reservation_id + || (int) $job->user_id + !== (int) $transition->requested_by_user_id + || !hash_equals( + (string) $job->operation_id, + (string) $transition->operation_id + ) + || $jobInvoiceId !== $transitionInvoiceId + || preg_match('/^[a-f0-9]{32}$/D', + (string) $transition->operation_id) !== 1 + || preg_match('/^[a-f0-9]{64}$/D', + (string) $transition->source_claim_set_sha256) !== 1 + || preg_match('/^[a-f0-9]{64}$/D', + (string) $transition->target_claim_set_sha256) !== 1) { + throw new CloudError('公网网络变更任务与冻结账本不一致', 409); + } + try { + $source = CloudPublicNetworkSnapshot::fromArray(json_decode( + (string) $transition->source_public_network_json, + true, + 16, + JSON_THROW_ON_ERROR + )); + $target = CloudPublicNetworkSnapshot::fromArray(json_decode( + (string) $transition->target_public_network_json, + true, + 16, + JSON_THROW_ON_ERROR + )); + $spec = json_decode( + (string) $instance->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + $projected = CloudPublicNetworkSnapshot::fromArray( + is_array($spec) ? ($spec['public_network'] ?? null) : null + ); + } catch (\Throwable) { + throw new CloudError('公网网络变更冻结快照损坏', 409); + } + if (!hash_equals( + (string) $transition->source_public_network_sha256, + $source->fingerprint() + ) + || !hash_equals( + (string) $transition->target_public_network_sha256, + $target->fingerprint() + ) + || hash_equals($source->fingerprint(), $target->fingerprint()) + || (!hash_equals( + $projected->fingerprint(), + $source->fingerprint() + ) && !hash_equals( + $projected->fingerprint(), + $target->fingerprint() + ))) { + throw new CloudError('公网网络变更冻结快照摘要不一致', 409); + } + if ($requirePayload) { + $body = is_array($payload['body'] ?? null) + && !array_is_list($payload['body']) + ? $payload['body'] : null; + $bodyKeys = is_array($body) ? array_keys($body) : []; + $unexpected = array_diff( + $bodyKeys, + ['operation_id', 'public_network', 'confirm_restart'] + ); + if ($body === null || $unexpected !== [] + || ($body['confirm_restart'] ?? null) !== true + || ($payload['public_network_transition_id'] ?? null) + !== (int) $transition->id + || !hash_equals( + (string) ($payload['source_claim_set_sha256'] ?? ''), + (string) $transition->source_claim_set_sha256 + ) + || !hash_equals( + (string) ($payload['target_claim_set_sha256'] ?? ''), + (string) $transition->target_claim_set_sha256 + )) { + throw new CloudError('公网网络变更任务载荷关联无效', 409); + } + try { + $requested = CloudPublicNetworkSnapshot::fromArray( + $body['public_network'] ?? null + ); + } catch (\Throwable) { + throw new CloudError('公网网络变更任务目标无效', 409); + } + if (!hash_equals( + $requested->fingerprint(), + $target->fingerprint() + )) { + throw new CloudError('公网网络变更任务目标已漂移', 409); + } + } + return [$source, $target]; + } + + public static function assertInvoiceAssociation( + CloudPublicNetworkTransition $transition, + CloudJob $job, + ?User $actor, + ?array $payload, + bool $expectRefunded + ): void { + if ((string) $transition->kind !== 'user_paid') { + if ($transition->invoice_id !== null || $job->invoice_id !== null + || ($payload !== null && ( + ($payload['price_cents'] ?? null) !== null + || ($payload['charged_amount'] ?? null) !== null + || ($payload['currency'] ?? null) !== null + ))) { + throw new CloudError('非付费公网网络变更账单关联无效', 409); + } + return; + } + if (!$actor instanceof User + || (int) $actor->id !== (int) $transition->requested_by_user_id + || $transition->invoice_id === null + || (int) $job->invoice_id !== (int) $transition->invoice_id) { + throw new CloudError('付费公网网络变更账户关联无效', 409); + } + $invoice = CloudInvoice::where( + 'id', + (int) $transition->invoice_id + )->lockForUpdate()->first(); + if (!$invoice instanceof CloudInvoice + || (string) $invoice->purpose + !== CloudIpChangeBillingService::PURPOSE + || (int) $invoice->instance_id !== (int) $transition->instance_id + || (int) $invoice->user_id !== (int) $actor->id + || (string) $invoice->currency !== 'USD' + || (string) $invoice->paid_via !== 'balance' + || $invoice->paid_at === null + || !hash_equals( + 'public-network-transition-' + . (string) $transition->transition_key, + (string) $invoice->payment_reference + ) + || (string) $invoice->status + !== ($expectRefunded ? 'refunded' : 'paid')) { + throw new CloudError('付费公网网络变更账单关联不一致', 409); + } + if ($payload === null) { + return; + } + $priceCents = $payload['price_cents'] ?? null; + $amount = $payload['charged_amount'] ?? null; + if (!is_int($priceCents) || $priceCents < 1 + || !is_string($amount) + || ($payload['currency'] ?? null) !== 'USD' + || CloudMoney::cents($amount) !== $priceCents + || CloudMoney::cents((string) $invoice->amount) !== $priceCents) { + throw new CloudError('付费公网网络变更冻结金额不一致', 409); + } + } + + /** + * Lock and validate the exact dual-stack ledger frozen by a transition. + * + * @return array{reservation:CloudResourceReservation,legs:array, + * source_claims:array,target_claims:array, + * source_ips:array,target_ips:array, + * projection:string} + */ + public static function lockLedger( + CloudJob $job, + CloudInstance $instance, + CloudPublicNetworkTransition $transition, + CloudPublicNetworkSnapshot $source, + CloudPublicNetworkSnapshot $target + ): array { + self::lockFrozenTopologyLocked($transition, $source, $target); + $reservation = CloudResourceReservation::where( + 'id', + (int) $transition->reservation_id + )->lockForUpdate()->first(); + if (!$reservation instanceof CloudResourceReservation + || (string) $reservation->state !== 'committed' + || (int) $reservation->instance_id !== (int) $instance->id + || (int) $reservation->host_id !== (int) $instance->host_id + || (int) $reservation->resource_pool_id + !== (int) $instance->resource_pool_id) { + throw new CloudError('公网网络变更资源预留关联不一致', 409); + } + $legRows = DB::table('cloud_public_network_transition_ips') + ->where('transition_id', (int) $transition->id) + ->orderBy('address_family')->orderBy('id') + ->lockForUpdate()->get()->all(); + $legs = []; + $claimIds = []; + foreach ($legRows as $leg) { + $family = (int) ($leg->address_family ?? 0); + if (!in_array($family, self::FAMILIES, true) + || isset($legs[$family]) + || (int) ($leg->source_claim_id ?? 0) < 1 + || ((bool) ($leg->changed ?? false)) + !== ($leg->target_claim_id !== null)) { + throw new CloudError('公网网络变更双栈明细损坏', 409); + } + $legs[$family] = $leg; + $claimIds[] = (int) $leg->source_claim_id; + if ($leg->target_claim_id !== null) { + $claimIds[] = (int) $leg->target_claim_id; + } + } + if (array_keys($legs) !== self::FAMILIES) { + throw new CloudError('公网网络变更双栈明细不完整', 409); + } + $claimIds = array_values(array_unique($claimIds)); + sort($claimIds, SORT_NUMERIC); + $claims = DB::table('cloud_resource_reservation_ips') + ->whereIn('id', $claimIds)->orderBy('id') + ->lockForUpdate()->get()->keyBy('id'); + if ($claims->count() !== count($claimIds)) { + throw new CloudError('公网网络变更地址声明缺失', 409); + } + $ipIds = []; + foreach ($claims as $claim) { + $ipIds[] = (int) $claim->public_ip_id; + } + $ipIds = array_values(array_unique($ipIds)); + sort($ipIds, SORT_NUMERIC); + $ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id') + ->lockForUpdate()->get()->keyBy('id'); + if ($ips->count() !== count($ipIds)) { + throw new CloudError('公网网络变更地址记录缺失', 409); + } + + $sourceClaims = []; + $targetClaims = []; + $sourceIps = []; + $targetIps = []; + $projection = null; + foreach (self::FAMILIES as $family) { + $leg = $legs[$family]; + $sourceClaim = $claims->get((int) $leg->source_claim_id); + $sourceIp = is_object($sourceClaim) + ? $ips->get((int) $sourceClaim->public_ip_id) : null; + if (!is_object($sourceClaim) + || !$sourceIp instanceof CloudPublicIp) { + throw new CloudError('公网网络变更源声明缺失', 409); + } + self::assertFrozenRowIdentity( + $sourceClaim, + $sourceIp, + $family, + (int) $reservation->id, + $source, + (int) $transition->source_network_attachment_id, + (int) $transition->host_id + ); + $sourceClaims[$family] = $sourceClaim; + $sourceIps[$family] = $sourceIp; + if (!(bool) $leg->changed) { + if ($leg->target_claim_id !== null + || !self::sourceActive( + $sourceClaim, + $sourceIp, + (int) $instance->id + ) + || !hash_equals( + $source->address($family), + $target->address($family) + )) { + throw new CloudError('公网网络变更未变更明细不一致', 409); + } + $targetClaims[$family] = $sourceClaim; + $targetIps[$family] = $sourceIp; + continue; + } + $targetClaim = $claims->get((int) $leg->target_claim_id); + $targetIp = is_object($targetClaim) + ? $ips->get((int) $targetClaim->public_ip_id) : null; + if (!is_object($targetClaim) + || !$targetIp instanceof CloudPublicIp + || (int) $targetClaim->id === (int) $sourceClaim->id) { + throw new CloudError('公网网络变更目标声明缺失', 409); + } + self::assertFrozenRowIdentity( + $targetClaim, + $targetIp, + $family, + (int) $reservation->id, + $target, + (int) $transition->target_network_attachment_id, + (int) $transition->host_id + ); + $targetClaims[$family] = $targetClaim; + $targetIps[$family] = $targetIp; + $legProjection = self::legProjection( + $sourceClaim, + $sourceIp, + $targetClaim, + $targetIp, + $instance, + $transition + ); + if ($projection === null) { + $projection = $legProjection; + } elseif ($projection !== $legProjection) { + throw new CloudError('公网网络变更双栈投影部分提交', 409); + } + } + $projection ??= 'prepared'; + if (!hash_equals( + self::frozenClaimSetDigest( + (int) $reservation->id, + $sourceClaims, + $sourceIps, + $source + ), + (string) $transition->source_claim_set_sha256 + ) + || !hash_equals( + self::frozenClaimSetDigest( + (int) $reservation->id, + $targetClaims, + $targetIps, + $target + ), + (string) $transition->target_claim_set_sha256 + )) { + throw new CloudError('公网网络变更声明集合摘要不一致', 409); + } + $spec = json_decode((string) $instance->spec_json, true); + $projected = CloudPublicNetworkSnapshot::fromArray( + is_array($spec) ? ($spec['public_network'] ?? null) : null + ); + $expectedSpec = $projection === 'applied' ? $target : $source; + if (!hash_equals( + $projected->fingerprint(), + $expectedSpec->fingerprint() + )) { + throw new CloudError('公网网络变更实例投影与账本不一致', 409); + } + return [ + 'reservation' => $reservation, + 'legs' => $legs, + 'source_claims' => $sourceClaims, + 'target_claims' => $targetClaims, + 'source_ips' => $sourceIps, + 'target_ips' => $targetIps, + 'projection' => $projection, + ]; + } + + private static function lockFrozenTopologyLocked( + CloudPublicNetworkTransition $transition, + CloudPublicNetworkSnapshot $source, + CloudPublicNetworkSnapshot $target + ): void { + $attachmentIds = array_values(array_unique([ + (int) $transition->source_network_attachment_id, + (int) $transition->target_network_attachment_id, + ])); + sort($attachmentIds, SORT_NUMERIC); + $attachments = CloudHostNetworkAttachment::whereIn( + 'id', $attachmentIds + )->orderBy('id')->lockForUpdate()->get(); + if ($attachments->count() !== count($attachmentIds)) { + throw new CloudError('公网网络变更冻结附件缺失', 409); + } + + $poolKeys = []; + foreach ([$source->toArray(), $target->toArray()] as $snapshot) { + foreach (['ipv4', 'ipv6'] as $leg) { + $poolKeys[(string) $snapshot[$leg]['pool_key']] = true; + } + } + $poolKeys = array_keys($poolKeys); + sort($poolKeys, SORT_STRING); + $pools = CloudPublicIpPool::where( + 'host_id', (int) $transition->host_id + )->whereIn('pool_key', $poolKeys)->orderBy('id') + ->lockForUpdate()->get(); + if ($pools->count() !== count($poolKeys)) { + throw new CloudError('公网网络变更冻结地址池缺失', 409); + } + } + + private static function assertFrozenRowIdentity( + object $claim, + CloudPublicIp $ip, + int $family, + int $reservationId, + CloudPublicNetworkSnapshot $network, + int $attachmentId, + int $hostId + ): void { + if ((int) ($claim->reservation_id ?? 0) !== $reservationId + || (int) ($claim->address_family ?? 0) !== $family + || (int) ($claim->claim_generation ?? 0) < 1 + || (int) ($claim->network_attachment_id ?? 0) !== $attachmentId + || (int) ($claim->public_ip_pool_id ?? 0) < 1 + || (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id + || (int) $ip->host_id !== $hostId + || (int) $ip->address_family !== $family + || (int) $ip->public_ip_pool_id + !== (int) $claim->public_ip_pool_id + || !hash_equals( + (string) $ip->address . '/' . (int) $ip->prefix_length, + $network->address($family) + ) + || preg_match('/^[a-f0-9]{32}$/D', + (string) ($claim->operation_id ?? '')) !== 1) { + throw new CloudError('公网网络变更声明具体身份不一致', 409); + } + } + + private static function sourceActive( + object $claim, + CloudPublicIp $ip, + int $instanceId + ): bool { + return (int) ($claim->active_claim ?? 0) === 1 + && (string) ($claim->state ?? '') === 'committed' + && $claim->released_at === null + && (string) $ip->state === 'assigned' + && (int) ($ip->reservation_id ?? 0) + === (int) $claim->reservation_id + && (int) ($ip->reservation_ip_claim_id ?? 0) + === (int) $claim->id + && (int) ($ip->instance_id ?? 0) === $instanceId + && hash_equals( + (string) ($claim->operation_id ?? ''), + (string) ($ip->operation_id ?? '') + ); + } + + private static function legProjection( + object $sourceClaim, + CloudPublicIp $sourceIp, + object $targetClaim, + CloudPublicIp $targetIp, + CloudInstance $instance, + CloudPublicNetworkTransition $transition + ): string { + $sourceActive = self::sourceActive( + $sourceClaim, + $sourceIp, + (int) $instance->id + ); + $sourceReleased = $sourceClaim->active_claim === null + && (string) $sourceClaim->state === 'released' + && $sourceClaim->released_at !== null + && (string) $sourceClaim->release_reason + === 'public_network_transition_succeeded' + && (string) $sourceIp->state === 'available' + && $sourceIp->reservation_id === null + && $sourceIp->reservation_ip_claim_id === null + && $sourceIp->instance_id === null + && $sourceIp->operation_id === null; + $targetPrepared = $targetClaim->active_claim === null + && in_array((string) $targetClaim->state, + ['reserved', 'uncertain'], true) + && $targetClaim->released_at === null + && (string) $targetIp->state === (string) $targetClaim->state + && (int) ($targetIp->reservation_id ?? 0) + === (int) $transition->reservation_id + && (int) ($targetIp->reservation_ip_claim_id ?? 0) + === (int) $targetClaim->id + && $targetIp->instance_id === null + && hash_equals( + (string) $transition->operation_id, + (string) $targetClaim->operation_id + ) + && hash_equals( + (string) $transition->operation_id, + (string) $targetIp->operation_id + ); + $targetActive = (int) ($targetClaim->active_claim ?? 0) === 1 + && (string) $targetClaim->state === 'committed' + && $targetClaim->released_at === null + && (string) $targetIp->state === 'assigned' + && (int) ($targetIp->reservation_id ?? 0) + === (int) $transition->reservation_id + && (int) ($targetIp->reservation_ip_claim_id ?? 0) + === (int) $targetClaim->id + && (int) ($targetIp->instance_id ?? 0) === (int) $instance->id + && hash_equals( + (string) $transition->operation_id, + (string) $targetClaim->operation_id + ) + && hash_equals( + (string) $transition->operation_id, + (string) $targetIp->operation_id + ); + $targetReleased = $targetClaim->active_claim === null + && (string) $targetClaim->state === 'released' + && $targetClaim->released_at !== null + && (string) $targetClaim->release_reason + === 'public_network_transition_not_applied' + && (string) $targetIp->state === 'available' + && $targetIp->reservation_id === null + && $targetIp->reservation_ip_claim_id === null + && $targetIp->instance_id === null + && $targetIp->operation_id === null; + if ($sourceActive && $targetPrepared) { + return 'prepared'; + } + if ($sourceReleased && $targetActive) { + return 'applied'; + } + if ($sourceActive && $targetReleased) { + return 'not_applied'; + } + throw new CloudError('公网网络变更地址账本部分提交', 409); + } + + private static function frozenClaimSetDigest( + int $reservationId, + array $claims, + array $ips, + CloudPublicNetworkSnapshot $network + ): string { + $canonical = []; + $attachmentId = null; + foreach (self::FAMILIES as $family) { + $claim = $claims[$family] ?? null; + $ip = $ips[$family] ?? null; + if (!is_object($claim) || !$ip instanceof CloudPublicIp + || (int) ($claim->reservation_id ?? 0) !== $reservationId + || (int) ($claim->address_family ?? 0) !== $family + || (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id + || !hash_equals( + (string) $ip->address . '/' . (int) $ip->prefix_length, + $network->address($family) + )) { + throw new CloudError('公网网络变更摘要输入不一致', 409); + } + $currentAttachment = (int) $claim->network_attachment_id; + if ($attachmentId === null) { + $attachmentId = $currentAttachment; + } elseif ($attachmentId !== $currentAttachment) { + throw new CloudError('公网网络变更摘要跨越网络接入', 409); + } + $canonical[] = [ + 'family' => $family, + 'claim_id' => (int) $claim->id, + 'claim_generation' => (int) $claim->claim_generation, + 'claim_operation_id' => (string) $claim->operation_id, + 'public_ip_id' => (int) $claim->public_ip_id, + 'network_attachment_id' => $currentAttachment, + 'public_ip_pool_id' => (int) $claim->public_ip_pool_id, + ]; + } + return hash('sha256', json_encode([ + 'reservation_id' => $reservationId, + 'claims' => $canonical, + 'public_network_sha256' => $network->fingerprint(), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); + } +} + diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php index 8b08dcdf..6463eb1d 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php @@ -266,7 +266,7 @@ final class CloudPublicNetworkTransitionWorkflow } if ($existingHint instanceof CloudPublicNetworkTransition) { - [$replayHost] = self::lockHostBoundaryLocked( + [$replayHost] = CloudPublicNetworkTransitionContext::lockHostBoundary( (int) $existingHint->host_id ); $existing = CloudPublicNetworkTransition::where( @@ -307,7 +307,7 @@ final class CloudPublicNetworkTransitionWorkflow throw new CloudError('虚拟机不满足公网网络变更条件', 409); } - [$host, $agent] = self::lockHostBoundaryLocked( + [$host, $agent] = CloudPublicNetworkTransitionContext::lockHostBoundary( (int) $instance->host_id ); @@ -843,7 +843,9 @@ final class CloudPublicNetworkTransitionWorkflow } $instance = CloudInstance::where('id', (int) $job->instance_id) ->lockForUpdate()->first(); - self::lockHostBoundaryLocked((int) ($job->host_id ?? 0)); + CloudPublicNetworkTransitionContext::lockHostBoundary( + (int) ($job->host_id ?? 0) + ); $transition = CloudPublicNetworkTransition::where( 'id', (int) $job->public_network_transition_id @@ -852,7 +854,7 @@ final class CloudPublicNetworkTransitionWorkflow || !$transition instanceof CloudPublicNetworkTransition) { throw new CloudError('公网网络变更未知效果账本缺失', 409); } - [$source, $target] = self::assertAssociationLocked( + [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( $job, $instance, $transition, @@ -862,7 +864,7 @@ final class CloudPublicNetworkTransitionWorkflow if ((string) $transition->state === 'finalization_pending' || in_array((string) $transition->state, ['succeeded', 'failed'], true)) { - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -888,7 +890,7 @@ final class CloudPublicNetworkTransitionWorkflow ); return; } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -914,7 +916,7 @@ final class CloudPublicNetworkTransitionWorkflow $ip->updated_at = $now; $ip->save(); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1002,7 +1004,9 @@ final class CloudPublicNetworkTransitionWorkflow } $instance = CloudInstance::where('id', (int) $job->instance_id) ->lockForUpdate()->first(); - self::lockHostBoundaryLocked((int) ($job->host_id ?? 0)); + CloudPublicNetworkTransitionContext::lockHostBoundary( + (int) ($job->host_id ?? 0) + ); $transition = CloudPublicNetworkTransition::where( 'id', (int) $job->public_network_transition_id @@ -1011,7 +1015,7 @@ final class CloudPublicNetworkTransitionWorkflow || !$transition instanceof CloudPublicNetworkTransition) { throw new CloudError('公网网络变更冻结账本缺失', 409); } - [$source, $target] = self::assertAssociationLocked( + [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( $job, $instance, $transition, @@ -1029,7 +1033,7 @@ final class CloudPublicNetworkTransitionWorkflow 409 ); } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1042,7 +1046,7 @@ final class CloudPublicNetworkTransitionWorkflow 409 ); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1071,7 +1075,7 @@ final class CloudPublicNetworkTransitionWorkflow if ($resolution === 'applied') { self::assertAppliedResult($instance, $target, $result); } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1085,7 +1089,7 @@ final class CloudPublicNetworkTransitionWorkflow 409 ); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1117,7 +1121,7 @@ final class CloudPublicNetworkTransitionWorkflow } if ((string) $transition->state === 'effect_unknown' && $resolution === 'unknown') { - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1142,7 +1146,7 @@ final class CloudPublicNetworkTransitionWorkflow ); } } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1158,7 +1162,7 @@ final class CloudPublicNetworkTransitionWorkflow return; } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1171,7 +1175,7 @@ final class CloudPublicNetworkTransitionWorkflow 409 ); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1243,7 +1247,9 @@ final class CloudPublicNetworkTransitionWorkflow }; $instance = CloudInstance::where('id', (int) $job->instance_id) ->lockForUpdate()->first(); - self::lockHostBoundaryLocked((int) ($job->host_id ?? 0)); + CloudPublicNetworkTransitionContext::lockHostBoundary( + (int) ($job->host_id ?? 0) + ); $transition = CloudPublicNetworkTransition::where( 'id', (int) $job->public_network_transition_id @@ -1252,7 +1258,7 @@ final class CloudPublicNetworkTransitionWorkflow || !$transition instanceof CloudPublicNetworkTransition) { throw new CloudError('公网网络变更本地冻结账本缺失', 409); } - [$source, $target] = self::assertAssociationLocked( + [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( $job, $instance, $transition, @@ -1265,7 +1271,7 @@ final class CloudPublicNetworkTransitionWorkflow || (int) $transition->active_transition !== 1) { throw new CloudError('公网网络变更未知效果账本不一致', 409); } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1287,7 +1293,7 @@ final class CloudPublicNetworkTransitionWorkflow ); } } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1306,7 +1312,7 @@ final class CloudPublicNetworkTransitionWorkflow || (int) $transition->active_transition !== 1 || $transition->effect_resolved_at === null) { if (self::terminalMatches($transition, $resolution)) { - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1319,7 +1325,7 @@ final class CloudPublicNetworkTransitionWorkflow 409 ); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1336,7 +1342,7 @@ final class CloudPublicNetworkTransitionWorkflow } throw new CloudError('公网网络变更最终化证据不一致', 409); } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1371,7 +1377,7 @@ final class CloudPublicNetworkTransitionWorkflow ); } } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1400,7 +1406,9 @@ final class CloudPublicNetworkTransitionWorkflow } $instance = CloudInstance::where('id', (int) $job->instance_id) ->lockForUpdate()->first(); - self::lockHostBoundaryLocked((int) ($job->host_id ?? 0)); + CloudPublicNetworkTransitionContext::lockHostBoundary( + (int) ($job->host_id ?? 0) + ); $transition = CloudPublicNetworkTransition::where( 'id', (int) $job->public_network_transition_id @@ -1409,7 +1417,7 @@ final class CloudPublicNetworkTransitionWorkflow || !$transition instanceof CloudPublicNetworkTransition) { throw new CloudError('公网网络变更恢复账本缺失', 409); } - [$source, $target] = self::assertAssociationLocked( + [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( $job, $instance, $transition, @@ -1417,7 +1425,7 @@ final class CloudPublicNetworkTransitionWorkflow false ); if (self::terminalMatches($transition, $resolution)) { - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1430,7 +1438,7 @@ final class CloudPublicNetworkTransitionWorkflow 409 ); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1450,7 +1458,7 @@ final class CloudPublicNetworkTransitionWorkflow )) { throw new CloudError('公网网络变更恢复预提交不一致', 409); } - $ledger = self::lockLedgerLocked( + $ledger = CloudPublicNetworkTransitionContext::lockLedger( $job, $instance, $transition, @@ -1469,7 +1477,7 @@ final class CloudPublicNetworkTransitionWorkflow $payload ); } - self::assertInvoiceAssociationLocked( + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( $transition, $job, $actor, @@ -1609,23 +1617,6 @@ final class CloudPublicNetworkTransitionWorkflow return CloudJob::find($jobId) ?? $snapshot; } - /** @return array{0:CloudHost,1:CloudHostAgent} */ - private static function lockHostBoundaryLocked(int $hostId): array - { - if ($hostId < 1) { - throw new CloudError('公网网络变更宿主机身份缺失', 409); - } - $host = CloudHost::where('id', $hostId) - ->lockForUpdate()->first(); - $agent = CloudHostAgent::where('host_id', $hostId) - ->lockForUpdate()->first(); - if (!$host instanceof CloudHost - || !$agent instanceof CloudHostAgent) { - throw new CloudError('公网网络变更宿主机账本缺失', 409); - } - return [$host, $agent]; - } - private static function replayLocked( CloudPublicNetworkTransition $transition, CloudPublicNetworkTransitionCommand $command, @@ -1811,584 +1802,6 @@ final class CloudPublicNetworkTransitionWorkflow ); } - /** - * @return array{0:CloudPublicNetworkSnapshot,1:CloudPublicNetworkSnapshot} - */ - private static function assertAssociationLocked( - CloudJob $job, - CloudInstance $instance, - CloudPublicNetworkTransition $transition, - ?array $payload, - bool $requirePayload - ): array { - $jobInvoiceId = $job->invoice_id === null - ? null : (int) $job->invoice_id; - $transitionInvoiceId = $transition->invoice_id === null - ? null : (int) $transition->invoice_id; - if ((string) $job->kind !== 'network_change' - || (string) $job->execution_mode !== 'agent' - || (int) $job->public_network_transition_id - !== (int) $transition->id - || (int) $job->instance_id !== (int) $instance->id - || (int) $transition->instance_id !== (int) $instance->id - || (int) $job->host_id !== (int) $instance->host_id - || (int) $transition->host_id !== (int) $instance->host_id - || (int) $transition->reservation_id - !== (int) $instance->reservation_id - || (int) $job->user_id - !== (int) $transition->requested_by_user_id - || !hash_equals( - (string) $job->operation_id, - (string) $transition->operation_id - ) - || $jobInvoiceId !== $transitionInvoiceId - || preg_match('/^[a-f0-9]{32}$/D', - (string) $transition->operation_id) !== 1 - || preg_match('/^[a-f0-9]{64}$/D', - (string) $transition->source_claim_set_sha256) !== 1 - || preg_match('/^[a-f0-9]{64}$/D', - (string) $transition->target_claim_set_sha256) !== 1) { - throw new CloudError('公网网络变更任务与冻结账本不一致', 409); - } - try { - $source = CloudPublicNetworkSnapshot::fromArray(json_decode( - (string) $transition->source_public_network_json, - true, - 16, - JSON_THROW_ON_ERROR - )); - $target = CloudPublicNetworkSnapshot::fromArray(json_decode( - (string) $transition->target_public_network_json, - true, - 16, - JSON_THROW_ON_ERROR - )); - $spec = json_decode( - (string) $instance->spec_json, - true, - 64, - JSON_THROW_ON_ERROR - ); - $projected = CloudPublicNetworkSnapshot::fromArray( - is_array($spec) ? ($spec['public_network'] ?? null) : null - ); - } catch (\Throwable) { - throw new CloudError('公网网络变更冻结快照损坏', 409); - } - if (!hash_equals( - (string) $transition->source_public_network_sha256, - $source->fingerprint() - ) - || !hash_equals( - (string) $transition->target_public_network_sha256, - $target->fingerprint() - ) - || hash_equals($source->fingerprint(), $target->fingerprint()) - || (!hash_equals( - $projected->fingerprint(), - $source->fingerprint() - ) && !hash_equals( - $projected->fingerprint(), - $target->fingerprint() - ))) { - throw new CloudError('公网网络变更冻结快照摘要不一致', 409); - } - if ($requirePayload) { - $body = is_array($payload['body'] ?? null) - && !array_is_list($payload['body']) - ? $payload['body'] : null; - $bodyKeys = is_array($body) ? array_keys($body) : []; - $unexpected = array_diff( - $bodyKeys, - ['operation_id', 'public_network', 'confirm_restart'] - ); - if ($body === null || $unexpected !== [] - || ($body['confirm_restart'] ?? null) !== true - || ($payload['public_network_transition_id'] ?? null) - !== (int) $transition->id - || !hash_equals( - (string) ($payload['source_claim_set_sha256'] ?? ''), - (string) $transition->source_claim_set_sha256 - ) - || !hash_equals( - (string) ($payload['target_claim_set_sha256'] ?? ''), - (string) $transition->target_claim_set_sha256 - )) { - throw new CloudError('公网网络变更任务载荷关联无效', 409); - } - try { - $requested = CloudPublicNetworkSnapshot::fromArray( - $body['public_network'] ?? null - ); - } catch (\Throwable) { - throw new CloudError('公网网络变更任务目标无效', 409); - } - if (!hash_equals( - $requested->fingerprint(), - $target->fingerprint() - )) { - throw new CloudError('公网网络变更任务目标已漂移', 409); - } - } - return [$source, $target]; - } - - private static function assertInvoiceAssociationLocked( - CloudPublicNetworkTransition $transition, - CloudJob $job, - ?User $actor, - ?array $payload, - bool $expectRefunded - ): void { - if ((string) $transition->kind !== 'user_paid') { - if ($transition->invoice_id !== null || $job->invoice_id !== null - || ($payload !== null && ( - ($payload['price_cents'] ?? null) !== null - || ($payload['charged_amount'] ?? null) !== null - || ($payload['currency'] ?? null) !== null - ))) { - throw new CloudError('非付费公网网络变更账单关联无效', 409); - } - return; - } - if (!$actor instanceof User - || (int) $actor->id !== (int) $transition->requested_by_user_id - || $transition->invoice_id === null - || (int) $job->invoice_id !== (int) $transition->invoice_id) { - throw new CloudError('付费公网网络变更账户关联无效', 409); - } - $invoice = CloudInvoice::where( - 'id', - (int) $transition->invoice_id - )->lockForUpdate()->first(); - if (!$invoice instanceof CloudInvoice - || (string) $invoice->purpose - !== CloudIpChangeBillingService::PURPOSE - || (int) $invoice->instance_id !== (int) $transition->instance_id - || (int) $invoice->user_id !== (int) $actor->id - || (string) $invoice->currency !== 'USD' - || (string) $invoice->paid_via !== 'balance' - || $invoice->paid_at === null - || !hash_equals( - 'public-network-transition-' - . (string) $transition->transition_key, - (string) $invoice->payment_reference - ) - || (string) $invoice->status - !== ($expectRefunded ? 'refunded' : 'paid')) { - throw new CloudError('付费公网网络变更账单关联不一致', 409); - } - if ($payload === null) { - return; - } - $priceCents = $payload['price_cents'] ?? null; - $amount = $payload['charged_amount'] ?? null; - if (!is_int($priceCents) || $priceCents < 1 - || !is_string($amount) - || ($payload['currency'] ?? null) !== 'USD' - || CloudMoney::cents($amount) !== $priceCents - || CloudMoney::cents((string) $invoice->amount) !== $priceCents) { - throw new CloudError('付费公网网络变更冻结金额不一致', 409); - } - } - - /** - * Lock and validate the exact dual-stack ledger frozen by a transition. - * - * @return array{reservation:CloudResourceReservation,legs:array, - * source_claims:array,target_claims:array, - * source_ips:array,target_ips:array, - * projection:string} - */ - private static function lockLedgerLocked( - CloudJob $job, - CloudInstance $instance, - CloudPublicNetworkTransition $transition, - CloudPublicNetworkSnapshot $source, - CloudPublicNetworkSnapshot $target - ): array { - self::lockFrozenTopologyLocked($transition, $source, $target); - $reservation = CloudResourceReservation::where( - 'id', - (int) $transition->reservation_id - )->lockForUpdate()->first(); - if (!$reservation instanceof CloudResourceReservation - || (string) $reservation->state !== 'committed' - || (int) $reservation->instance_id !== (int) $instance->id - || (int) $reservation->host_id !== (int) $instance->host_id - || (int) $reservation->resource_pool_id - !== (int) $instance->resource_pool_id) { - throw new CloudError('公网网络变更资源预留关联不一致', 409); - } - $legRows = DB::table('cloud_public_network_transition_ips') - ->where('transition_id', (int) $transition->id) - ->orderBy('address_family')->orderBy('id') - ->lockForUpdate()->get()->all(); - $legs = []; - $claimIds = []; - foreach ($legRows as $leg) { - $family = (int) ($leg->address_family ?? 0); - if (!in_array($family, self::FAMILIES, true) - || isset($legs[$family]) - || (int) ($leg->source_claim_id ?? 0) < 1 - || ((bool) ($leg->changed ?? false)) - !== ($leg->target_claim_id !== null)) { - throw new CloudError('公网网络变更双栈明细损坏', 409); - } - $legs[$family] = $leg; - $claimIds[] = (int) $leg->source_claim_id; - if ($leg->target_claim_id !== null) { - $claimIds[] = (int) $leg->target_claim_id; - } - } - if (array_keys($legs) !== self::FAMILIES) { - throw new CloudError('公网网络变更双栈明细不完整', 409); - } - $claimIds = array_values(array_unique($claimIds)); - sort($claimIds, SORT_NUMERIC); - $claims = DB::table('cloud_resource_reservation_ips') - ->whereIn('id', $claimIds)->orderBy('id') - ->lockForUpdate()->get()->keyBy('id'); - if ($claims->count() !== count($claimIds)) { - throw new CloudError('公网网络变更地址声明缺失', 409); - } - $ipIds = []; - foreach ($claims as $claim) { - $ipIds[] = (int) $claim->public_ip_id; - } - $ipIds = array_values(array_unique($ipIds)); - sort($ipIds, SORT_NUMERIC); - $ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id') - ->lockForUpdate()->get()->keyBy('id'); - if ($ips->count() !== count($ipIds)) { - throw new CloudError('公网网络变更地址记录缺失', 409); - } - - $sourceClaims = []; - $targetClaims = []; - $sourceIps = []; - $targetIps = []; - $projection = null; - foreach (self::FAMILIES as $family) { - $leg = $legs[$family]; - $sourceClaim = $claims->get((int) $leg->source_claim_id); - $sourceIp = is_object($sourceClaim) - ? $ips->get((int) $sourceClaim->public_ip_id) : null; - if (!is_object($sourceClaim) - || !$sourceIp instanceof CloudPublicIp) { - throw new CloudError('公网网络变更源声明缺失', 409); - } - self::assertFrozenRowIdentity( - $sourceClaim, - $sourceIp, - $family, - (int) $reservation->id, - $source, - (int) $transition->source_network_attachment_id, - (int) $transition->host_id - ); - $sourceClaims[$family] = $sourceClaim; - $sourceIps[$family] = $sourceIp; - if (!(bool) $leg->changed) { - if ($leg->target_claim_id !== null - || !self::sourceActive( - $sourceClaim, - $sourceIp, - (int) $instance->id - ) - || !hash_equals( - $source->address($family), - $target->address($family) - )) { - throw new CloudError('公网网络变更未变更明细不一致', 409); - } - $targetClaims[$family] = $sourceClaim; - $targetIps[$family] = $sourceIp; - continue; - } - $targetClaim = $claims->get((int) $leg->target_claim_id); - $targetIp = is_object($targetClaim) - ? $ips->get((int) $targetClaim->public_ip_id) : null; - if (!is_object($targetClaim) - || !$targetIp instanceof CloudPublicIp - || (int) $targetClaim->id === (int) $sourceClaim->id) { - throw new CloudError('公网网络变更目标声明缺失', 409); - } - self::assertFrozenRowIdentity( - $targetClaim, - $targetIp, - $family, - (int) $reservation->id, - $target, - (int) $transition->target_network_attachment_id, - (int) $transition->host_id - ); - $targetClaims[$family] = $targetClaim; - $targetIps[$family] = $targetIp; - $legProjection = self::legProjection( - $sourceClaim, - $sourceIp, - $targetClaim, - $targetIp, - $instance, - $transition - ); - if ($projection === null) { - $projection = $legProjection; - } elseif ($projection !== $legProjection) { - throw new CloudError('公网网络变更双栈投影部分提交', 409); - } - } - $projection ??= 'prepared'; - if (!hash_equals( - self::frozenClaimSetDigest( - (int) $reservation->id, - $sourceClaims, - $sourceIps, - $source - ), - (string) $transition->source_claim_set_sha256 - ) - || !hash_equals( - self::frozenClaimSetDigest( - (int) $reservation->id, - $targetClaims, - $targetIps, - $target - ), - (string) $transition->target_claim_set_sha256 - )) { - throw new CloudError('公网网络变更声明集合摘要不一致', 409); - } - $spec = json_decode((string) $instance->spec_json, true); - $projected = CloudPublicNetworkSnapshot::fromArray( - is_array($spec) ? ($spec['public_network'] ?? null) : null - ); - $expectedSpec = $projection === 'applied' ? $target : $source; - if (!hash_equals( - $projected->fingerprint(), - $expectedSpec->fingerprint() - )) { - throw new CloudError('公网网络变更实例投影与账本不一致', 409); - } - return [ - 'reservation' => $reservation, - 'legs' => $legs, - 'source_claims' => $sourceClaims, - 'target_claims' => $targetClaims, - 'source_ips' => $sourceIps, - 'target_ips' => $targetIps, - 'projection' => $projection, - ]; - } - - private static function lockFrozenTopologyLocked( - CloudPublicNetworkTransition $transition, - CloudPublicNetworkSnapshot $source, - CloudPublicNetworkSnapshot $target - ): void { - $attachmentIds = array_values(array_unique([ - (int) $transition->source_network_attachment_id, - (int) $transition->target_network_attachment_id, - ])); - sort($attachmentIds, SORT_NUMERIC); - $attachments = CloudHostNetworkAttachment::whereIn( - 'id', $attachmentIds - )->orderBy('id')->lockForUpdate()->get(); - if ($attachments->count() !== count($attachmentIds)) { - throw new CloudError('公网网络变更冻结附件缺失', 409); - } - - $poolKeys = []; - foreach ([$source->toArray(), $target->toArray()] as $snapshot) { - foreach (['ipv4', 'ipv6'] as $leg) { - $poolKeys[(string) $snapshot[$leg]['pool_key']] = true; - } - } - $poolKeys = array_keys($poolKeys); - sort($poolKeys, SORT_STRING); - $pools = CloudPublicIpPool::where( - 'host_id', (int) $transition->host_id - )->whereIn('pool_key', $poolKeys)->orderBy('id') - ->lockForUpdate()->get(); - if ($pools->count() !== count($poolKeys)) { - throw new CloudError('公网网络变更冻结地址池缺失', 409); - } - } - - private static function assertFrozenRowIdentity( - object $claim, - CloudPublicIp $ip, - int $family, - int $reservationId, - CloudPublicNetworkSnapshot $network, - int $attachmentId, - int $hostId - ): void { - if ((int) ($claim->reservation_id ?? 0) !== $reservationId - || (int) ($claim->address_family ?? 0) !== $family - || (int) ($claim->claim_generation ?? 0) < 1 - || (int) ($claim->network_attachment_id ?? 0) !== $attachmentId - || (int) ($claim->public_ip_pool_id ?? 0) < 1 - || (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id - || (int) $ip->host_id !== $hostId - || (int) $ip->address_family !== $family - || (int) $ip->public_ip_pool_id - !== (int) $claim->public_ip_pool_id - || !hash_equals( - (string) $ip->address . '/' . (int) $ip->prefix_length, - $network->address($family) - ) - || preg_match('/^[a-f0-9]{32}$/D', - (string) ($claim->operation_id ?? '')) !== 1) { - throw new CloudError('公网网络变更声明具体身份不一致', 409); - } - } - - private static function sourceActive( - object $claim, - CloudPublicIp $ip, - int $instanceId - ): bool { - return (int) ($claim->active_claim ?? 0) === 1 - && (string) ($claim->state ?? '') === 'committed' - && $claim->released_at === null - && (string) $ip->state === 'assigned' - && (int) ($ip->reservation_id ?? 0) - === (int) $claim->reservation_id - && (int) ($ip->reservation_ip_claim_id ?? 0) - === (int) $claim->id - && (int) ($ip->instance_id ?? 0) === $instanceId - && hash_equals( - (string) ($claim->operation_id ?? ''), - (string) ($ip->operation_id ?? '') - ); - } - - private static function legProjection( - object $sourceClaim, - CloudPublicIp $sourceIp, - object $targetClaim, - CloudPublicIp $targetIp, - CloudInstance $instance, - CloudPublicNetworkTransition $transition - ): string { - $sourceActive = self::sourceActive( - $sourceClaim, - $sourceIp, - (int) $instance->id - ); - $sourceReleased = $sourceClaim->active_claim === null - && (string) $sourceClaim->state === 'released' - && $sourceClaim->released_at !== null - && (string) $sourceClaim->release_reason - === 'public_network_transition_succeeded' - && (string) $sourceIp->state === 'available' - && $sourceIp->reservation_id === null - && $sourceIp->reservation_ip_claim_id === null - && $sourceIp->instance_id === null - && $sourceIp->operation_id === null; - $targetPrepared = $targetClaim->active_claim === null - && in_array((string) $targetClaim->state, - ['reserved', 'uncertain'], true) - && $targetClaim->released_at === null - && (string) $targetIp->state === (string) $targetClaim->state - && (int) ($targetIp->reservation_id ?? 0) - === (int) $transition->reservation_id - && (int) ($targetIp->reservation_ip_claim_id ?? 0) - === (int) $targetClaim->id - && $targetIp->instance_id === null - && hash_equals( - (string) $transition->operation_id, - (string) $targetClaim->operation_id - ) - && hash_equals( - (string) $transition->operation_id, - (string) $targetIp->operation_id - ); - $targetActive = (int) ($targetClaim->active_claim ?? 0) === 1 - && (string) $targetClaim->state === 'committed' - && $targetClaim->released_at === null - && (string) $targetIp->state === 'assigned' - && (int) ($targetIp->reservation_id ?? 0) - === (int) $transition->reservation_id - && (int) ($targetIp->reservation_ip_claim_id ?? 0) - === (int) $targetClaim->id - && (int) ($targetIp->instance_id ?? 0) === (int) $instance->id - && hash_equals( - (string) $transition->operation_id, - (string) $targetClaim->operation_id - ) - && hash_equals( - (string) $transition->operation_id, - (string) $targetIp->operation_id - ); - $targetReleased = $targetClaim->active_claim === null - && (string) $targetClaim->state === 'released' - && $targetClaim->released_at !== null - && (string) $targetClaim->release_reason - === 'public_network_transition_not_applied' - && (string) $targetIp->state === 'available' - && $targetIp->reservation_id === null - && $targetIp->reservation_ip_claim_id === null - && $targetIp->instance_id === null - && $targetIp->operation_id === null; - if ($sourceActive && $targetPrepared) { - return 'prepared'; - } - if ($sourceReleased && $targetActive) { - return 'applied'; - } - if ($sourceActive && $targetReleased) { - return 'not_applied'; - } - throw new CloudError('公网网络变更地址账本部分提交', 409); - } - - private static function frozenClaimSetDigest( - int $reservationId, - array $claims, - array $ips, - CloudPublicNetworkSnapshot $network - ): string { - $canonical = []; - $attachmentId = null; - foreach (self::FAMILIES as $family) { - $claim = $claims[$family] ?? null; - $ip = $ips[$family] ?? null; - if (!is_object($claim) || !$ip instanceof CloudPublicIp - || (int) ($claim->reservation_id ?? 0) !== $reservationId - || (int) ($claim->address_family ?? 0) !== $family - || (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id - || !hash_equals( - (string) $ip->address . '/' . (int) $ip->prefix_length, - $network->address($family) - )) { - throw new CloudError('公网网络变更摘要输入不一致', 409); - } - $currentAttachment = (int) $claim->network_attachment_id; - if ($attachmentId === null) { - $attachmentId = $currentAttachment; - } elseif ($attachmentId !== $currentAttachment) { - throw new CloudError('公网网络变更摘要跨越网络接入', 409); - } - $canonical[] = [ - 'family' => $family, - 'claim_id' => (int) $claim->id, - 'claim_generation' => (int) $claim->claim_generation, - 'claim_operation_id' => (string) $claim->operation_id, - 'public_ip_id' => (int) $claim->public_ip_id, - 'network_attachment_id' => $currentAttachment, - 'public_ip_pool_id' => (int) $claim->public_ip_pool_id, - ]; - } - return hash('sha256', json_encode([ - 'reservation_id' => $reservationId, - 'claims' => $canonical, - 'public_network_sha256' => $network->fingerprint(), - ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)); - } - private static function applyTargetLocked( array $ledger, CloudInstance $instance, diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index 876d2b1c..eb16347c 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -205,7 +205,7 @@ $publishPrepared = $method( $retryFinalization = $method( $workflow, 'public static function retryPendingFinalization(', - 'private static function lockHostBoundaryLocked(' + 'private static function replayLocked(' ); $positions = array_map( static fn (string $needle): int|false => strpos($projector, $needle), diff --git a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php index f6f25a7c..a7cac18f 100644 --- a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php @@ -3,6 +3,7 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Services\Cloud\CloudPublicNetworkTransitionCommand; +use App\Services\Cloud\CloudPublicNetworkTransitionContext; use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; $assert = static function (bool $condition, string $message): void { @@ -23,6 +24,9 @@ $root = dirname(__DIR__); $source = file_get_contents( $root . '/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' ); +$contextSource = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkTransitionContext.php' +); $billing = file_get_contents( $root . '/app/Services/Cloud/CloudIpChangeBillingService.php' ); @@ -41,7 +45,7 @@ $tenantController = file_get_contents( $adminController = file_get_contents( $root . '/app/Controllers/CloudAdminInstanceController.php' ); -$assert(is_string($source) && is_string($billing) +$assert(is_string($source) && is_string($contextSource) && is_string($billing) && is_string($activeIdentity) && is_string($worker) && is_string($recovery) && is_string($tenantController) && is_string($adminController), 'Transition workflow sources are missing.'); @@ -67,6 +71,23 @@ $assert($workflow->isFinal() && $public === [ 'retryPendingFinalization', ], 'Stage 4 transition seam drifted.'); +$context = new ReflectionClass(CloudPublicNetworkTransitionContext::class); +$contextPublic = array_values(array_map( + static fn (ReflectionMethod $method): string => $method->getName(), + array_filter( + $context->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudPublicNetworkTransitionContext::class + ) +)); +$assert($context->isFinal() && $contextPublic === [ + 'lockHostBoundary', + 'assertAssociation', + 'assertInvoiceAssociation', + 'lockLedger', +], 'Locked transition context API drifted.'); + $command = new ReflectionClass(CloudPublicNetworkTransitionCommand::class); foreach (['userPaidAutomatic', 'adminExact', 'poolReplacement'] as $factory) { $assert($command->hasMethod($factory) @@ -118,7 +139,7 @@ $ordered($reserve, [ '$existingParent = CloudJob::where(', '$existingJob = CloudJob::where(', '$instance = CloudInstance::where(', - '[$replayHost] = self::lockHostBoundaryLocked(', + '[$replayHost] = CloudPublicNetworkTransitionContext::lockHostBoundary(', '$existing = CloudPublicNetworkTransition::where(', ]); $assert(str_contains($source, @@ -131,7 +152,7 @@ $assert(str_contains($source, $ordered($reserve, [ '$priorJob = CloudJob::where(', '$instance = CloudInstance::where(', - '[$host, $agent] = self::lockHostBoundaryLocked(', + '[$host, $agent] = CloudPublicNetworkTransitionContext::lockHostBoundary(', '$active = CloudPublicNetworkTransition::where(', '$resourcePool = CloudResourcePool::where(', '$attachments = CloudHostNetworkAttachment::whereIn(', @@ -152,14 +173,14 @@ foreach ([ ] as [$start, $end]) { $ordered($method($source, $start, $end), [ '$instance = CloudInstance::where(', - 'self::lockHostBoundaryLocked(', + 'CloudPublicNetworkTransitionContext::lockHostBoundary(', '$transition = CloudPublicNetworkTransition::where(', ]); } $retry = $method( $source, 'public static function retryPendingFinalization(', - 'private static function lockHostBoundaryLocked(' + 'private static function replayLocked(' ); $ordered($retry, [ '$actor = User::where(\'id\', $userId)', @@ -168,7 +189,7 @@ $ordered($retry, [ 'self::finishJobLocked(', ]); $topology = $method( - $source, + $contextSource, 'private static function lockFrozenTopologyLocked(', 'private static function assertFrozenRowIdentity(' );