From 68faea032688d9d7ccc47ae9a9049f321acbb847 Mon Sep 17 00:00:00 2001 From: codex Date: Wed, 4 Nov 2026 18:47:39 +0800 Subject: [PATCH] refactor: extract transition settlement --- ...CloudPublicNetworkTransitionSettlement.php | 536 ++++++++++++++++++ .../CloudPublicNetworkTransitionWorkflow.php | 496 +--------------- web/tests/CloudPaidIpChangeContractTest.php | 7 +- ...licIpPoolReplacementSchemaContractTest.php | 12 +- ...cNetworkTransitionWorkflowContractTest.php | 32 +- 5 files changed, 590 insertions(+), 493 deletions(-) create mode 100644 web/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php new file mode 100644 index 00000000..b8265100 --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php @@ -0,0 +1,536 @@ +public_network_transition_id === null) { + return; + } + $resolution = match ($catalogStatus) { + 'succeeded' => 'applied', + 'failed' => 'not_applied', + 'uncertain' => 'unknown', + default => throw new CloudError( + '公网网络变更本地最终化状态无效', + 409 + ), + }; + $instance = CloudInstance::where('id', (int) $job->instance_id) + ->lockForUpdate()->first(); + CloudPublicNetworkTransitionContext::lockHostBoundary( + (int) ($job->host_id ?? 0) + ); + $transition = CloudPublicNetworkTransition::where( + 'id', + (int) $job->public_network_transition_id + )->lockForUpdate()->first(); + if (!$instance instanceof CloudInstance + || !$transition instanceof CloudPublicNetworkTransition) { + throw new CloudError('公网网络变更本地冻结账本缺失', 409); + } + [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( + $job, + $instance, + $transition, + $payload, + true + ); + if ($resolution === 'unknown') { + if ((string) $transition->state !== 'effect_unknown' + || (string) $transition->effect_resolution !== 'unknown' + || (int) $transition->active_transition !== 1) { + throw new CloudError('公网网络变更未知效果账本不一致', 409); + } + $ledger = CloudPublicNetworkTransitionContext::lockLedger( + $job, + $instance, + $transition, + $source, + $target + ); + if ($ledger['projection'] !== 'prepared') { + throw new CloudError('公网网络变更未知效果投影不一致', 409); + } + foreach ($ledger['legs'] as $family => $leg) { + if ((bool) $leg->changed + && ((string) $ledger['target_claims'][$family]->state + !== 'uncertain' + || (string) $ledger['target_ips'][$family]->state + !== 'uncertain')) { + throw new CloudError( + '公网网络变更未知效果目标未锁定', + 409 + ); + } + } + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( + $transition, + $job, + $actor, + $payload, + false + ); + CloudPublicIpPoolReplacementBatchService:: + projectTransitionEvidenceLocked($parent, $job, $transition); + return; + } + if ((string) $transition->state !== 'finalization_pending' + || !hash_equals( + (string) $transition->effect_resolution, + $resolution + ) + || (int) $transition->active_transition !== 1 + || $transition->effect_resolved_at === null) { + if (self::terminalMatches($transition, $resolution)) { + $ledger = CloudPublicNetworkTransitionContext::lockLedger( + $job, + $instance, + $transition, + $source, + $target + ); + if ($ledger['projection'] !== $resolution) { + throw new CloudError( + '公网网络变更终态资源投影不一致', + 409 + ); + } + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( + $transition, + $job, + $actor, + $payload, + $resolution === 'not_applied' + ); + CloudPublicIpPoolReplacementBatchService:: + projectTransitionEvidenceLocked( + $parent, + $job, + $transition + ); + return; + } + throw new CloudError('公网网络变更最终化证据不一致', 409); + } + $ledger = CloudPublicNetworkTransitionContext::lockLedger( + $job, + $instance, + $transition, + $source, + $target + ); + $now = time(); + if ($resolution === 'applied') { + if ($ledger['projection'] === 'prepared') { + self::applyTargetLocked($ledger, $instance, $target, $now); + } elseif ($ledger['projection'] !== 'applied') { + throw new CloudError( + '公网网络变更生效投影与证据不一致', + 409 + ); + } + } else { + if ($ledger['projection'] === 'prepared') { + self::releaseTargetLocked($ledger, $now); + } elseif ($ledger['projection'] !== 'not_applied') { + throw new CloudError( + '公网网络变更未生效投影与证据不一致', + 409 + ); + } + if (!$deferPublish) { + CloudIpChangeBillingService::refundTransitionNotAppliedLocked( + $transition, + $job, + $actor, + $payload + ); + } + } + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( + $transition, + $job, + $actor, + $payload, + $resolution === 'not_applied' && !$deferPublish + ); + if (!$deferPublish) { + self::publishLocked($transition, $resolution, $now); + } + CloudPublicIpPoolReplacementBatchService:: + projectTransitionEvidenceLocked($parent, $job, $transition); + } + + /** Publish a recovery-prepared projection after the Agent fence release. */ + public static function publishPreparedLocked( + CloudJob $job, + string $resolution, + ?User $actor, + ?CloudJob $parent = null + ): void { + if ($job->public_network_transition_id === null) { + return; + } + if (!in_array($resolution, ['applied', 'not_applied'], true)) { + throw new CloudError('公网网络变更恢复结论无效', 409); + } + $instance = CloudInstance::where('id', (int) $job->instance_id) + ->lockForUpdate()->first(); + CloudPublicNetworkTransitionContext::lockHostBoundary( + (int) ($job->host_id ?? 0) + ); + $transition = CloudPublicNetworkTransition::where( + 'id', + (int) $job->public_network_transition_id + )->lockForUpdate()->first(); + if (!$instance instanceof CloudInstance + || !$transition instanceof CloudPublicNetworkTransition) { + throw new CloudError('公网网络变更恢复账本缺失', 409); + } + [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( + $job, + $instance, + $transition, + null, + false + ); + if (self::terminalMatches($transition, $resolution)) { + $ledger = CloudPublicNetworkTransitionContext::lockLedger( + $job, + $instance, + $transition, + $source, + $target + ); + if ($ledger['projection'] !== $resolution) { + throw new CloudError( + '公网网络变更恢复终态投影不一致', + 409 + ); + } + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( + $transition, + $job, + $actor, + null, + $resolution === 'not_applied' + ); + CloudPublicIpPoolReplacementBatchService:: + projectTransitionEvidenceLocked($parent, $job, $transition); + return; + } + if ((string) $transition->state !== 'finalization_pending' + || (string) $transition->effect_resolution !== $resolution + || (int) $transition->active_transition !== 1 + || !hash_equals( + (string) $transition->last_error_code, + CloudPublicNetworkTransitionEvidence::RECOVERY_PREPARE_PENDING + )) { + throw new CloudError('公网网络变更恢复预提交不一致', 409); + } + $ledger = CloudPublicNetworkTransitionContext::lockLedger( + $job, + $instance, + $transition, + $source, + $target + ); + if ($ledger['projection'] !== $resolution) { + throw new CloudError('公网网络变更恢复资源投影不一致', 409); + } + $payload = CloudPublicNetworkTransitionEvidence::recoveryPayload($job); + if ($resolution === 'not_applied') { + CloudIpChangeBillingService::refundTransitionNotAppliedLocked( + $transition, + $job, + $actor, + $payload + ); + } + CloudPublicNetworkTransitionContext::assertInvoiceAssociation( + $transition, + $job, + $actor, + $payload, + $resolution === 'not_applied' + ); + self::publishLocked($transition, $resolution, time()); + CloudPublicIpPoolReplacementBatchService:: + projectTransitionEvidenceLocked($parent, $job, $transition); + } + + /** Retry only PHP-owned writes after evidence survived a Worker crash. */ + public static function retryPendingFinalization( + int $jobId, + string $leaseToken + ): CloudJob { + $snapshot = CloudJob::find($jobId); + if (!$snapshot instanceof CloudJob) { + throw new CloudError('任务不存在', 404); + } + try { + $payload = CloudSecrets::decrypt( + (string) $snapshot->sealed_payload, + 'job-payload' + ); + } catch (\Throwable) { + throw new CloudRecoveryPayloadUnavailable( + '公网网络变更本地恢复数据无法解密', + 409 + ); + } + if (!is_array($payload) || array_is_list($payload)) { + throw new CloudRecoveryPayloadUnavailable( + '公网网络变更本地恢复数据无效', + 409 + ); + } + $identity = CloudOperationRecoveryIdentity::expectedFromPayload( + $snapshot, + $payload, + false + ); + $userId = (int) $snapshot->user_id; + $parentId = (int) ($snapshot->parent_job_id ?? 0); + DB::connection()->transaction(static function () use ( + $jobId, + $leaseToken, + $payload, + $identity, + $userId, + $parentId + ): void { + $actor = User::where('id', $userId) + ->lockForUpdate()->first(); + if (!$actor instanceof User) { + throw new CloudError('公网网络变更本地恢复账户缺失', 409); + } + $parent = $parentId > 0 + ? CloudJob::where('id', $parentId) + ->lockForUpdate()->first() + : null; + $job = CloudJob::where('id', $jobId)->lockForUpdate()->first(); + if (!$job instanceof CloudJob + || (int) $job->user_id !== $userId + || (string) $job->kind !== 'network_change' + || $job->public_network_transition_id === null + || (string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || !(bool) $job->effect_may_have_applied + || (bool) $job->safe_to_resubmit + || (string) $job->effect_resolution !== 'unknown' + || !(bool) $job->finalization_incident + || !is_string($job->lease_token) + || !hash_equals((string) $job->lease_token, $leaseToken)) { + throw new CloudError( + '公网网络变更不处于可重跑的本地收尾状态', + 409 + ); + } + if (($parentId > 0 && !$parent instanceof CloudJob) + || (int) ($job->parent_job_id ?? 0) !== $parentId) { + throw new CloudError('公网网络变更父任务关联不一致', 409); + } + $transition = CloudPublicNetworkTransition::find( + (int) $job->public_network_transition_id + ); + if (!$transition instanceof CloudPublicNetworkTransition + || (string) $transition->state !== 'finalization_pending' + || !in_array((string) $transition->effect_resolution, + ['applied', 'not_applied'], true) + || hash_equals( + (string) $transition->last_error_code, + CloudPublicNetworkTransitionEvidence:: + RECOVERY_PREPARE_PENDING + )) { + throw new CloudError( + '公网网络变更没有可安全重跑的持久化回执', + 409 + ); + } + $resolution = (string) $transition->effect_resolution; + self::finishJobLocked( + $job, + $resolution === 'applied' ? 'succeeded' : 'failed', + $payload, + $actor, + false, + $parent + ); + $now = time(); + $job->effect_resolution = $resolution; + $job->effect_resolved_at = $now; + $job->effect_resolved_by = null; + $job->effect_resolution_reason = + 'automatic_public_network_finalization'; + $safePayload = CloudInput::safeResult($payload); + $safePayload[ + CloudOperationRecoveryIdentity::payloadKey() + ] = CloudOperationRecoveryIdentity::persisted($identity); + $job->sealed_payload = CloudSecrets::encrypt( + $safePayload, + 'job-payload' + ); + $job->finalization_incident = 0; + $job->finalization_error_code = null; + $job->read_at = null; + $job->lease_token = null; + $job->lease_until = 0; + $job->available_at = 0; + $job->updated_at = $now; + $job->save(); + CloudJobService::reconcileAggregateParentEffectLocked( + $job, + null + ); + }, 3); + return CloudJob::find($jobId) ?? $snapshot; + } + + + private static function applyTargetLocked( + array $ledger, + CloudInstance $instance, + CloudPublicNetworkSnapshot $target, + int $now + ): void { + foreach ($ledger['legs'] as $family => $leg) { + if (!(bool) $leg->changed) { + continue; + } + $sourceClaim = $ledger['source_claims'][$family]; + $sourceIp = $ledger['source_ips'][$family]; + $targetClaim = $ledger['target_claims'][$family]; + $targetIp = $ledger['target_ips'][$family]; + DB::table('cloud_resource_reservation_ips') + ->where('id', (int) $sourceClaim->id)->update([ + 'active_claim' => null, + 'state' => 'released', + 'released_at' => $now, + 'release_reason' => + 'public_network_transition_succeeded', + 'updated_at' => $now, + ]); + $sourceIp->state = 'available'; + $sourceIp->reservation_id = null; + $sourceIp->reservation_ip_claim_id = null; + $sourceIp->instance_id = null; + $sourceIp->operation_id = null; + $sourceIp->updated_at = $now; + $sourceIp->save(); + DB::table('cloud_resource_reservation_ips') + ->where('id', (int) $targetClaim->id)->update([ + 'active_claim' => 1, + 'state' => 'committed', + 'released_at' => null, + 'release_reason' => '', + 'updated_at' => $now, + ]); + $targetIp->state = 'assigned'; + $targetIp->instance_id = (int) $instance->id; + $targetIp->updated_at = $now; + $targetIp->save(); + } + $spec = json_decode( + (string) $instance->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + if (!is_array($spec) || array_is_list($spec)) { + throw new CloudError('虚拟机配置记录损坏', 409); + } + foreach (['network', 'public_pool_key', 'public_pool_cidr', + 'public_ip', 'public_ip_cidr', 'gateway', 'dns_servers'] + as $retired) { + unset($spec[$retired]); + } + $spec['public_network'] = $target->toArray(); + $instance->spec_json = json_encode( + $spec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + ); + $instance->updated_at = $now; + $instance->save(); + } + + private static function releaseTargetLocked(array $ledger, int $now): void + { + foreach ($ledger['legs'] as $family => $leg) { + if (!(bool) $leg->changed) { + continue; + } + $claim = $ledger['target_claims'][$family]; + $ip = $ledger['target_ips'][$family]; + DB::table('cloud_resource_reservation_ips') + ->where('id', (int) $claim->id)->update([ + 'active_claim' => null, + 'state' => 'released', + 'released_at' => $now, + 'release_reason' => + 'public_network_transition_not_applied', + 'updated_at' => $now, + ]); + $ip->state = 'available'; + $ip->reservation_id = null; + $ip->reservation_ip_claim_id = null; + $ip->instance_id = null; + $ip->operation_id = null; + $ip->updated_at = $now; + $ip->save(); + } + } + + private static function publishLocked( + CloudPublicNetworkTransition $transition, + string $resolution, + int $now + ): void { + $transition->state = $resolution === 'applied' + ? 'succeeded' : 'failed'; + $transition->effect_resolution = $resolution; + $transition->active_transition = null; + $transition->terminal_at = $now; + $transition->last_error_code = ''; + $transition->updated_at = $now; + $transition->save(); + } + + public static function terminalMatches( + CloudPublicNetworkTransition $transition, + string $resolution + ): bool { + return (string) $transition->state === ( + $resolution === 'applied' ? 'succeeded' : 'failed' + ) + && (string) $transition->effect_resolution === $resolution + && $transition->active_transition === null + && $transition->effect_resolved_at !== null + && $transition->terminal_at !== null; + } +} + diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php index 3a995a28..35a26edd 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php @@ -812,162 +812,14 @@ final class CloudPublicNetworkTransitionWorkflow bool $deferPublish, ?CloudJob $parent = null ): void { - if ($job->public_network_transition_id === null) { - return; - } - $resolution = match ($catalogStatus) { - 'succeeded' => 'applied', - 'failed' => 'not_applied', - 'uncertain' => 'unknown', - default => throw new CloudError( - '公网网络变更本地最终化状态无效', - 409 - ), - }; - $instance = CloudInstance::where('id', (int) $job->instance_id) - ->lockForUpdate()->first(); - CloudPublicNetworkTransitionContext::lockHostBoundary( - (int) ($job->host_id ?? 0) - ); - $transition = CloudPublicNetworkTransition::where( - 'id', - (int) $job->public_network_transition_id - )->lockForUpdate()->first(); - if (!$instance instanceof CloudInstance - || !$transition instanceof CloudPublicNetworkTransition) { - throw new CloudError('公网网络变更本地冻结账本缺失', 409); - } - [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( + CloudPublicNetworkTransitionSettlement::finishJobLocked( $job, - $instance, - $transition, + $catalogStatus, $payload, - true - ); - if ($resolution === 'unknown') { - if ((string) $transition->state !== 'effect_unknown' - || (string) $transition->effect_resolution !== 'unknown' - || (int) $transition->active_transition !== 1) { - throw new CloudError('公网网络变更未知效果账本不一致', 409); - } - $ledger = CloudPublicNetworkTransitionContext::lockLedger( - $job, - $instance, - $transition, - $source, - $target - ); - if ($ledger['projection'] !== 'prepared') { - throw new CloudError('公网网络变更未知效果投影不一致', 409); - } - foreach ($ledger['legs'] as $family => $leg) { - if ((bool) $leg->changed - && ((string) $ledger['target_claims'][$family]->state - !== 'uncertain' - || (string) $ledger['target_ips'][$family]->state - !== 'uncertain')) { - throw new CloudError( - '公网网络变更未知效果目标未锁定', - 409 - ); - } - } - CloudPublicNetworkTransitionContext::assertInvoiceAssociation( - $transition, - $job, - $actor, - $payload, - false - ); - CloudPublicIpPoolReplacementBatchService:: - projectTransitionEvidenceLocked($parent, $job, $transition); - return; - } - if ((string) $transition->state !== 'finalization_pending' - || !hash_equals( - (string) $transition->effect_resolution, - $resolution - ) - || (int) $transition->active_transition !== 1 - || $transition->effect_resolved_at === null) { - if (self::terminalMatches($transition, $resolution)) { - $ledger = CloudPublicNetworkTransitionContext::lockLedger( - $job, - $instance, - $transition, - $source, - $target - ); - if ($ledger['projection'] !== $resolution) { - throw new CloudError( - '公网网络变更终态资源投影不一致', - 409 - ); - } - CloudPublicNetworkTransitionContext::assertInvoiceAssociation( - $transition, - $job, - $actor, - $payload, - $resolution === 'not_applied' - ); - CloudPublicIpPoolReplacementBatchService:: - projectTransitionEvidenceLocked( - $parent, - $job, - $transition - ); - return; - } - throw new CloudError('公网网络变更最终化证据不一致', 409); - } - $ledger = CloudPublicNetworkTransitionContext::lockLedger( - $job, - $instance, - $transition, - $source, - $target - ); - $now = time(); - if ($resolution === 'applied') { - if ($ledger['projection'] === 'prepared') { - self::applyTargetLocked($ledger, $instance, $target, $now); - } elseif ($ledger['projection'] !== 'applied') { - throw new CloudError( - '公网网络变更生效投影与证据不一致', - 409 - ); - } - } else { - if ($ledger['projection'] === 'prepared') { - self::releaseTargetLocked($ledger, $now); - } elseif ($ledger['projection'] !== 'not_applied') { - throw new CloudError( - '公网网络变更未生效投影与证据不一致', - 409 - ); - } - if (!$deferPublish) { - CloudIpChangeBillingService::refundTransitionNotAppliedLocked( - $transition, - $job, - $actor, - $payload - ); - } - } - CloudPublicNetworkTransitionContext::assertInvoiceAssociation( - $transition, - $job, $actor, - $payload, - $resolution === 'not_applied' && !$deferPublish + $deferPublish, + $parent ); - if (!$deferPublish) { - self::publishLocked($transition, $resolution, $now); - } - CloudPublicIpPoolReplacementBatchService:: - projectTransitionEvidenceLocked($parent, $job, $transition); } /** Publish a recovery-prepared projection after the Agent fence release. */ @@ -977,95 +829,12 @@ final class CloudPublicNetworkTransitionWorkflow ?User $actor, ?CloudJob $parent = null ): void { - if ($job->public_network_transition_id === null) { - return; - } - if (!in_array($resolution, ['applied', 'not_applied'], true)) { - throw new CloudError('公网网络变更恢复结论无效', 409); - } - $instance = CloudInstance::where('id', (int) $job->instance_id) - ->lockForUpdate()->first(); - CloudPublicNetworkTransitionContext::lockHostBoundary( - (int) ($job->host_id ?? 0) - ); - $transition = CloudPublicNetworkTransition::where( - 'id', - (int) $job->public_network_transition_id - )->lockForUpdate()->first(); - if (!$instance instanceof CloudInstance - || !$transition instanceof CloudPublicNetworkTransition) { - throw new CloudError('公网网络变更恢复账本缺失', 409); - } - [$source, $target] = CloudPublicNetworkTransitionContext::assertAssociation( - $job, - $instance, - $transition, - null, - false - ); - if (self::terminalMatches($transition, $resolution)) { - $ledger = CloudPublicNetworkTransitionContext::lockLedger( - $job, - $instance, - $transition, - $source, - $target - ); - if ($ledger['projection'] !== $resolution) { - throw new CloudError( - '公网网络变更恢复终态投影不一致', - 409 - ); - } - CloudPublicNetworkTransitionContext::assertInvoiceAssociation( - $transition, - $job, - $actor, - null, - $resolution === 'not_applied' - ); - CloudPublicIpPoolReplacementBatchService:: - projectTransitionEvidenceLocked($parent, $job, $transition); - return; - } - if ((string) $transition->state !== 'finalization_pending' - || (string) $transition->effect_resolution !== $resolution - || (int) $transition->active_transition !== 1 - || !hash_equals( - (string) $transition->last_error_code, - CloudPublicNetworkTransitionEvidence::RECOVERY_PREPARE_PENDING - )) { - throw new CloudError('公网网络变更恢复预提交不一致', 409); - } - $ledger = CloudPublicNetworkTransitionContext::lockLedger( - $job, - $instance, - $transition, - $source, - $target - ); - if ($ledger['projection'] !== $resolution) { - throw new CloudError('公网网络变更恢复资源投影不一致', 409); - } - $payload = CloudPublicNetworkTransitionEvidence::recoveryPayload($job); - if ($resolution === 'not_applied') { - CloudIpChangeBillingService::refundTransitionNotAppliedLocked( - $transition, - $job, - $actor, - $payload - ); - } - CloudPublicNetworkTransitionContext::assertInvoiceAssociation( - $transition, + CloudPublicNetworkTransitionSettlement::publishPreparedLocked( $job, + $resolution, $actor, - $payload, - $resolution === 'not_applied' + $parent ); - self::publishLocked($transition, $resolution, time()); - CloudPublicIpPoolReplacementBatchService:: - projectTransitionEvidenceLocked($parent, $job, $transition); } /** Retry only PHP-owned writes after evidence survived a Worker crash. */ @@ -1073,128 +842,8 @@ final class CloudPublicNetworkTransitionWorkflow int $jobId, string $leaseToken ): CloudJob { - $snapshot = CloudJob::find($jobId); - if (!$snapshot instanceof CloudJob) { - throw new CloudError('任务不存在', 404); - } - try { - $payload = CloudSecrets::decrypt( - (string) $snapshot->sealed_payload, - 'job-payload' - ); - } catch (\Throwable) { - throw new CloudRecoveryPayloadUnavailable( - '公网网络变更本地恢复数据无法解密', - 409 - ); - } - if (!is_array($payload) || array_is_list($payload)) { - throw new CloudRecoveryPayloadUnavailable( - '公网网络变更本地恢复数据无效', - 409 - ); - } - $identity = CloudOperationRecoveryIdentity::expectedFromPayload( - $snapshot, - $payload, - false - ); - $userId = (int) $snapshot->user_id; - $parentId = (int) ($snapshot->parent_job_id ?? 0); - DB::connection()->transaction(static function () use ( - $jobId, - $leaseToken, - $payload, - $identity, - $userId, - $parentId - ): void { - $actor = User::where('id', $userId) - ->lockForUpdate()->first(); - if (!$actor instanceof User) { - throw new CloudError('公网网络变更本地恢复账户缺失', 409); - } - $parent = $parentId > 0 - ? CloudJob::where('id', $parentId) - ->lockForUpdate()->first() - : null; - $job = CloudJob::where('id', $jobId)->lockForUpdate()->first(); - if (!$job instanceof CloudJob - || (int) $job->user_id !== $userId - || (string) $job->kind !== 'network_change' - || $job->public_network_transition_id === null - || (string) $job->phase !== 'terminal' - || (string) $job->outcome !== 'failed' - || (string) $job->status !== 'failed' - || !(bool) $job->effect_may_have_applied - || (bool) $job->safe_to_resubmit - || (string) $job->effect_resolution !== 'unknown' - || !(bool) $job->finalization_incident - || !is_string($job->lease_token) - || !hash_equals((string) $job->lease_token, $leaseToken)) { - throw new CloudError( - '公网网络变更不处于可重跑的本地收尾状态', - 409 - ); - } - if (($parentId > 0 && !$parent instanceof CloudJob) - || (int) ($job->parent_job_id ?? 0) !== $parentId) { - throw new CloudError('公网网络变更父任务关联不一致', 409); - } - $transition = CloudPublicNetworkTransition::find( - (int) $job->public_network_transition_id - ); - if (!$transition instanceof CloudPublicNetworkTransition - || (string) $transition->state !== 'finalization_pending' - || !in_array((string) $transition->effect_resolution, - ['applied', 'not_applied'], true) - || hash_equals( - (string) $transition->last_error_code, - CloudPublicNetworkTransitionEvidence:: - RECOVERY_PREPARE_PENDING - )) { - throw new CloudError( - '公网网络变更没有可安全重跑的持久化回执', - 409 - ); - } - $resolution = (string) $transition->effect_resolution; - self::finishJobLocked( - $job, - $resolution === 'applied' ? 'succeeded' : 'failed', - $payload, - $actor, - false, - $parent - ); - $now = time(); - $job->effect_resolution = $resolution; - $job->effect_resolved_at = $now; - $job->effect_resolved_by = null; - $job->effect_resolution_reason = - 'automatic_public_network_finalization'; - $safePayload = CloudInput::safeResult($payload); - $safePayload[ - CloudOperationRecoveryIdentity::payloadKey() - ] = CloudOperationRecoveryIdentity::persisted($identity); - $job->sealed_payload = CloudSecrets::encrypt( - $safePayload, - 'job-payload' - ); - $job->finalization_incident = 0; - $job->finalization_error_code = null; - $job->read_at = null; - $job->lease_token = null; - $job->lease_until = 0; - $job->available_at = 0; - $job->updated_at = $now; - $job->save(); - CloudJobService::reconcileAggregateParentEffectLocked( - $job, - null - ); - }, 3); - return CloudJob::find($jobId) ?? $snapshot; + return CloudPublicNetworkTransitionSettlement:: + retryPendingFinalization($jobId, $leaseToken); } private static function replayLocked( @@ -1213,7 +862,10 @@ final class CloudPublicNetworkTransitionWorkflow $terminalReplay = $job instanceof CloudJob && in_array($terminalResolution, ['applied', 'not_applied'], true) - && self::terminalMatches($transition, $terminalResolution) + && CloudPublicNetworkTransitionSettlement::terminalMatches( + $transition, + $terminalResolution + ) && (string) $job->phase === 'terminal' && in_array((string) $job->outcome, ['succeeded', 'failed'], true) @@ -1382,128 +1034,6 @@ final class CloudPublicNetworkTransitionWorkflow ); } - private static function applyTargetLocked( - array $ledger, - CloudInstance $instance, - CloudPublicNetworkSnapshot $target, - int $now - ): void { - foreach ($ledger['legs'] as $family => $leg) { - if (!(bool) $leg->changed) { - continue; - } - $sourceClaim = $ledger['source_claims'][$family]; - $sourceIp = $ledger['source_ips'][$family]; - $targetClaim = $ledger['target_claims'][$family]; - $targetIp = $ledger['target_ips'][$family]; - DB::table('cloud_resource_reservation_ips') - ->where('id', (int) $sourceClaim->id)->update([ - 'active_claim' => null, - 'state' => 'released', - 'released_at' => $now, - 'release_reason' => - 'public_network_transition_succeeded', - 'updated_at' => $now, - ]); - $sourceIp->state = 'available'; - $sourceIp->reservation_id = null; - $sourceIp->reservation_ip_claim_id = null; - $sourceIp->instance_id = null; - $sourceIp->operation_id = null; - $sourceIp->updated_at = $now; - $sourceIp->save(); - DB::table('cloud_resource_reservation_ips') - ->where('id', (int) $targetClaim->id)->update([ - 'active_claim' => 1, - 'state' => 'committed', - 'released_at' => null, - 'release_reason' => '', - 'updated_at' => $now, - ]); - $targetIp->state = 'assigned'; - $targetIp->instance_id = (int) $instance->id; - $targetIp->updated_at = $now; - $targetIp->save(); - } - $spec = json_decode( - (string) $instance->spec_json, - true, - 64, - JSON_THROW_ON_ERROR - ); - if (!is_array($spec) || array_is_list($spec)) { - throw new CloudError('虚拟机配置记录损坏', 409); - } - foreach (['network', 'public_pool_key', 'public_pool_cidr', - 'public_ip', 'public_ip_cidr', 'gateway', 'dns_servers'] - as $retired) { - unset($spec[$retired]); - } - $spec['public_network'] = $target->toArray(); - $instance->spec_json = json_encode( - $spec, - JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE - ); - $instance->updated_at = $now; - $instance->save(); - } - - private static function releaseTargetLocked(array $ledger, int $now): void - { - foreach ($ledger['legs'] as $family => $leg) { - if (!(bool) $leg->changed) { - continue; - } - $claim = $ledger['target_claims'][$family]; - $ip = $ledger['target_ips'][$family]; - DB::table('cloud_resource_reservation_ips') - ->where('id', (int) $claim->id)->update([ - 'active_claim' => null, - 'state' => 'released', - 'released_at' => $now, - 'release_reason' => - 'public_network_transition_not_applied', - 'updated_at' => $now, - ]); - $ip->state = 'available'; - $ip->reservation_id = null; - $ip->reservation_ip_claim_id = null; - $ip->instance_id = null; - $ip->operation_id = null; - $ip->updated_at = $now; - $ip->save(); - } - } - - private static function publishLocked( - CloudPublicNetworkTransition $transition, - string $resolution, - int $now - ): void { - $transition->state = $resolution === 'applied' - ? 'succeeded' : 'failed'; - $transition->effect_resolution = $resolution; - $transition->active_transition = null; - $transition->terminal_at = $now; - $transition->last_error_code = ''; - $transition->updated_at = $now; - $transition->save(); - } - - private static function terminalMatches( - CloudPublicNetworkTransition $transition, - string $resolution - ): bool { - return (string) $transition->state === ( - $resolution === 'applied' ? 'succeeded' : 'failed' - ) - && (string) $transition->effect_resolution === $resolution - && $transition->active_transition === null - && $transition->effect_resolved_at !== null - && $transition->terminal_at !== null; - } - /** * Select exact available target rows. No target row is mutated here. diff --git a/web/tests/CloudPaidIpChangeContractTest.php b/web/tests/CloudPaidIpChangeContractTest.php index 5a063210..50fca6cf 100644 --- a/web/tests/CloudPaidIpChangeContractTest.php +++ b/web/tests/CloudPaidIpChangeContractTest.php @@ -24,6 +24,9 @@ $jobs = $read('app/Services/Cloud/CloudJobService.php'); $workflow = $read( 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' ); +$settlement = $read( + 'app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php' +); $command = $read( 'app/Services/Cloud/CloudPublicNetworkTransitionCommand.php' ); @@ -156,9 +159,9 @@ $assert(str_contains($billing, && str_contains($billing, "\$invoice->status = 'refunded'"), 'IP-change charge, invoice linkage, or exactly-once refund is incomplete.'); -$assert(substr_count($workflow, +$assert(substr_count($settlement, 'CloudIpChangeBillingService::refundTransitionNotAppliedLocked(') >= 2 - && str_contains($workflow, "\$resolution === 'not_applied'") + && str_contains($settlement, "\$resolution === 'not_applied'") && !str_contains($worker, 'CloudIpChangeBillingService::refundNotAppliedLocked(') && !str_contains($worker, 'CloudPlacementService::finishNetworkChange('), diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index abdeda53..b1456806 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -16,6 +16,9 @@ $workflow = file_get_contents( $evidence = file_get_contents( $root . '/app/Services/Cloud/CloudPublicNetworkTransitionEvidence.php' ); +$settlement = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php' +); $batchPlan = file_get_contents( $root . '/app/Services/Cloud/CloudPublicNetworkTransitionBatchPlan.php' ); @@ -107,6 +110,7 @@ $assert(is_string($jobs) && !str_contains($jobs, 'enqueuePoolReplacementNetworkChangeLocked') && is_string($workflow) && is_string($evidence) + && is_string($settlement) && str_contains($workflow, 'beginPoolReplacementBatch(') && str_contains($workflow, 'CloudPublicNetworkTransitionBatchPlan $plan') && str_contains($workflow, @@ -197,19 +201,19 @@ $recordEvidence = $method( 'public static function recoveryPayload(' ); $finishTransition = $method( - $workflow, + $settlement, 'public static function finishJobLocked(', 'public static function publishPreparedLocked(' ); $publishPrepared = $method( - $workflow, + $settlement, 'public static function publishPreparedLocked(', 'public static function retryPendingFinalization(' ); $retryFinalization = $method( - $workflow, + $settlement, 'public static function retryPendingFinalization(', - 'private static function replayLocked(' + 'private static function applyTargetLocked(' ); $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 9ffa8ff7..4422b8fe 100644 --- a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php @@ -5,6 +5,7 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Services\Cloud\CloudPublicNetworkTransitionCommand; use App\Services\Cloud\CloudPublicNetworkTransitionContext; use App\Services\Cloud\CloudPublicNetworkTransitionEvidence; +use App\Services\Cloud\CloudPublicNetworkTransitionSettlement; use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow; $assert = static function (bool $condition, string $message): void { @@ -31,6 +32,9 @@ $contextSource = file_get_contents( $evidenceSource = file_get_contents( $root . '/app/Services/Cloud/CloudPublicNetworkTransitionEvidence.php' ); +$settlementSource = file_get_contents( + $root . '/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php' +); $billing = file_get_contents( $root . '/app/Services/Cloud/CloudIpChangeBillingService.php' ); @@ -50,7 +54,8 @@ $adminController = file_get_contents( $root . '/app/Controllers/CloudAdminInstanceController.php' ); $assert(is_string($source) && is_string($contextSource) - && is_string($evidenceSource) && is_string($billing) + && is_string($evidenceSource) && is_string($settlementSource) + && is_string($billing) && is_string($activeIdentity) && is_string($worker) && is_string($recovery) && is_string($tenantController) && is_string($adminController), 'Transition workflow sources are missing.'); @@ -110,6 +115,25 @@ $assert($evidence->isFinal() && $evidencePublic === [ 'recoveryPayload', ], 'Transition evidence API drifted.'); +$settlement = new ReflectionClass( + CloudPublicNetworkTransitionSettlement::class +); +$settlementPublic = array_values(array_map( + static fn (ReflectionMethod $method): string => $method->getName(), + array_filter( + $settlement->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudPublicNetworkTransitionSettlement::class + ) +)); +$assert($settlement->isFinal() && $settlementPublic === [ + 'finishJobLocked', + 'publishPreparedLocked', + 'retryPendingFinalization', + 'terminalMatches', +], 'Transition settlement API drifted.'); + $command = new ReflectionClass(CloudPublicNetworkTransitionCommand::class); foreach (['userPaidAutomatic', 'adminExact', 'poolReplacement'] as $factory) { $assert($command->hasMethod($factory) @@ -201,16 +225,16 @@ foreach ([ ['public static function publishPreparedLocked(', 'public static function retryPendingFinalization('], ] as [$start, $end]) { - $ordered($method($source, $start, $end), [ + $ordered($method($settlementSource, $start, $end), [ '$instance = CloudInstance::where(', 'CloudPublicNetworkTransitionContext::lockHostBoundary(', '$transition = CloudPublicNetworkTransition::where(', ]); } $retry = $method( - $source, + $settlementSource, 'public static function retryPendingFinalization(', - 'private static function replayLocked(' + 'private static function applyTargetLocked(' ); $ordered($retry, [ '$actor = User::where(\'id\', $userId)',