refactor: extract transition settlement
parent
5743ffe113
commit
68faea0326
@ -0,0 +1,536 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudJob;
|
||||
use App\Models\CloudPublicNetworkTransition;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Capsule\Manager as DB;
|
||||
|
||||
/**
|
||||
* Owns local resource settlement after durable Agent evidence exists.
|
||||
*
|
||||
* The workflow facade and evidence module never mutate final public-network
|
||||
* ownership directly. This module applies or releases the prepared target,
|
||||
* performs the one allowed refund, and publishes the durable terminal state.
|
||||
*/
|
||||
final class CloudPublicNetworkTransitionSettlement
|
||||
{
|
||||
public static function finishJobLocked(
|
||||
CloudJob $job,
|
||||
string $catalogStatus,
|
||||
array $payload,
|
||||
?User $actor,
|
||||
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(
|
||||
$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;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue