feat: route pool replacement through dual-stack transitions

go
codex 3 weeks ago
parent 13132bc419
commit 61c99a4680

@ -3,13 +3,9 @@ namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\CloudTemplate;
use App\Models\CloudUserIso;
use App\Models\User;
@ -2694,150 +2690,6 @@ final class CloudJobService
}, 3);
}
/**
* Create one administrator-owned child of a durable public-pool
* replacement batch. The caller owns the instance/host/network ledger
* locks and has already proved that all batch targets fit atomically.
* This method repeats the exact per-instance identity checks, freezes the
* same strict Agent body as an ordinary network_change, and fences the
* target address before the surrounding transaction may commit.
*/
public static function enqueuePoolReplacementNetworkChangeLocked(
CloudInstance $instance,
CloudResourceReservation $reservation,
CloudHostNetworkAttachment $sourceAttachment,
CloudHostNetworkAttachment $targetAttachment,
CloudPublicIpPool $sourcePool,
CloudPublicIpPool $targetPool,
CloudPublicIp $sourceIp,
CloudPublicIp $targetIp,
CloudJob $parent,
int $actorUserId,
string $batchKey
): CloudJob {
CloudPublicNetworkTransitionGate::assertWriterReady();
if ($actorUserId < 1
|| preg_match('/^[a-f0-9]{32}$/D', $batchKey) !== 1
|| (string) $parent->kind
!== 'public_ip_pool_replacement_batch'
|| (string) $parent->execution_mode !== 'local'
|| $parent->parent_job_id !== null
|| (int) $parent->user_id !== $actorUserId
|| (int) $instance->host_id !== (int) $reservation->host_id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) $instance->resource_pool_id
|| (string) $reservation->state !== 'committed'
|| (int) $reservation->network_attachment_id
!== (int) $sourceAttachment->id
|| (int) $reservation->public_ip_pool_id
!== (int) $sourcePool->id
|| (int) $reservation->public_ip_id !== (int) $sourceIp->id
|| (int) $sourceAttachment->host_id !== (int) $instance->host_id
|| (int) $targetAttachment->host_id !== (int) $instance->host_id
|| (int) $sourceAttachment->line_id
!== (int) $targetAttachment->line_id
|| (int) $sourcePool->host_id !== (int) $instance->host_id
|| (int) $targetPool->host_id !== (int) $instance->host_id
|| (int) $sourcePool->network_attachment_id
!== (int) $sourceAttachment->id
|| (int) $targetPool->network_attachment_id
!== (int) $targetAttachment->id
|| (int) $sourceIp->host_id !== (int) $instance->host_id
|| (int) $targetIp->host_id !== (int) $instance->host_id
|| (int) $sourceIp->public_ip_pool_id !== (int) $sourcePool->id
|| (int) $targetIp->public_ip_pool_id !== (int) $targetPool->id
|| (string) $sourceIp->state !== 'assigned'
|| (int) $sourceIp->reservation_id !== (int) $reservation->id
|| (int) $sourceIp->instance_id !== (int) $instance->id
|| !hash_equals(
(string) $reservation->operation_id,
(string) ($sourceIp->operation_id ?? '')
)
|| (string) $targetIp->state !== 'available'
|| $targetIp->reservation_id !== null
|| $targetIp->instance_id !== null
|| $targetIp->operation_id !== null
|| !self::publicIpBelongsToPool($targetIp, $targetPool)
|| !self::instancePublicIpMatches($instance, $sourceIp)
|| !CloudNetworkSelector::isValid(
(string) $targetAttachment->network_selector
)
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $targetPool->pool_key) !== 1) {
throw new CloudError(
'批量更换公网 IP 的实例或网络账本不一致',
409
);
}
if (self::blockingQueryForInstance((int) $instance->id)->exists()) {
throw new CloudError('虚拟机已有任务,请等待完成', 409);
}
$body = [
'network' => (string) $targetAttachment->network_selector,
'public_pool_key' => (string) $targetPool->pool_key,
'public_pool_cidr' => (string) $targetPool->cidr,
'public_ip_cidr' => (string) $targetIp->address . '/'
. (int) $targetIp->prefix_length,
'gateway' => (string) $targetPool->gateway,
'dns_servers' => self::poolDnsServers($targetPool),
'confirm_restart' => true,
];
$requestKey = substr(
'pool-replacement-' . $batchKey . '-' . (int) $instance->id,
0,
128
);
$fingerprint = hash('sha256', json_encode([
'kind' => 'network_change',
'instance_id' => (int) $instance->id,
'parent_job_id' => (int) $parent->id,
'body' => $body,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
if (CloudJob::where('user_id', $actorUserId)
->where('request_idempotency_key', $requestKey)->exists()) {
throw new CloudError('批量更换公网 IP 子任务标识冲突', 409);
}
$now = time();
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->request_idempotency_key = $requestKey;
$job->request_fingerprint = $fingerprint;
$job->parent_job_id = (int) $parent->id;
$job->instance_id = (int) $instance->id;
$job->user_id = $actorUserId;
$job->host_id = (int) $instance->host_id;
$job->kind = 'network_change';
$job->execution_mode = 'agent';
$job->sealed_payload = CloudSecrets::encrypt([
'method' => 'POST',
'request_target' => '/v1/vms/'
. rawurlencode((string) $instance->uuid) . '/network',
'body' => $body,
'credential' => null,
'owner_id' => (int) $instance->user_id,
'can_manage' => true,
'source_public_ip_id' => (int) $sourceIp->id,
'target_public_ip_id' => (int) $targetIp->id,
'source_network_attachment_id' => (int) $sourceAttachment->id,
'target_network_attachment_id' => (int) $targetAttachment->id,
'source_public_ip_pool_id' => (int) $sourcePool->id,
'target_public_ip_pool_id' => (int) $targetPool->id,
'public_pool_replacement_batch_key' => $batchKey,
], 'job-payload');
$job->available_at = $job->created_at = $job->updated_at = $now;
$job->save();
$targetIp->state = 'changing';
$targetIp->instance_id = (int) $instance->id;
$targetIp->operation_id = (string) $job->operation_id;
$targetIp->updated_at = $now;
$targetIp->save();
return $job;
}
/**
* Queue the irreversible second phase of expiry cleanup.
*
@ -4249,77 +4101,4 @@ final class CloudJobService
]];
}
private static function publicIpBelongsToPool(CloudPublicIp $ip,
CloudPublicIpPool $pool): bool
{
$parts = explode('/', (string) $pool->cidr, 2);
if (count($parts) !== 2 || !ctype_digit($parts[1])) {
return false;
}
$prefix = (int) $parts[1];
if ($prefix < 24 || $prefix > 30
|| (int) $ip->prefix_length !== (int) $pool->guest_prefix_length) {
return false;
}
$address = self::ipv4Number((string) $ip->address);
$network = self::ipv4Number($parts[0]);
if ($address === null || $network === null) {
return false;
}
$block = 2 ** (32 - $prefix);
$base = (int) (floor($network / $block) * $block);
return $address > $base && $address < $base + $block - 1;
}
private static function instancePublicIpMatches(CloudInstance $instance,
CloudPublicIp $ip): bool
{
$spec = json_decode((string) $instance->spec_json, true);
$recorded = is_array($spec) && !array_is_list($spec)
? ($spec['public_ip_cidr'] ?? null) : null;
return is_string($recorded) && hash_equals(
(string) $ip->address . '/' . (int) $ip->prefix_length,
trim($recorded)
);
}
private static function ipv4Number(string $value): ?int
{
if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return null;
}
$packed = inet_pton($value);
if ($packed === false || strlen($packed) !== 4) {
return null;
}
$parts = unpack('Nnumber', $packed);
return is_array($parts) && isset($parts['number'])
? (int) sprintf('%u', $parts['number']) : null;
}
private static function poolDnsServers(CloudPublicIpPool $pool): array
{
try {
$values = json_decode(
(string) $pool->dns_servers_json,
true,
16,
JSON_THROW_ON_ERROR
);
} catch (\Throwable $error) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
if (!is_array($values) || !array_is_list($values)
|| $values === [] || count($values) > 4
|| count(array_filter($values, static fn ($value): bool =>
is_string($value) && filter_var(
$value,
FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4
) !== false
)) !== count($values)) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
return array_values($values);
}
}

@ -0,0 +1,45 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPoolReplacementBatch;
use App\Models\CloudPublicIpPoolReplacementBatchItem;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\User;
use Illuminate\Support\Collection;
/** Caller-locked, exact topology for one pool-replacement child. */
final class CloudPublicNetworkTransitionBatchPlan
{
/**
* @param array<int,object> $allClaimsSorted
* @param array<int,object> $activeClaimsByFamily
* @param array<int,CloudPublicIp> $sourceIpsByFamily
*/
public function __construct(
public readonly User $actor,
public readonly CloudJob $parent,
public readonly CloudPublicIpPoolReplacementBatch $batch,
public readonly CloudPublicIpPoolReplacementBatchItem $item,
public readonly CloudInstance $instance,
public readonly CloudHost $host,
public readonly CloudHostAgent $agent,
public readonly CloudResourcePool $resourcePool,
public readonly CloudHostNetworkAttachment $attachment,
public readonly CloudResourceReservation $reservation,
public readonly Collection $poolsById,
public readonly Collection $ipsById,
public readonly array $allClaimsSorted,
public readonly array $activeClaimsByFamily,
public readonly array $sourceIpsByFamily,
public readonly CloudPublicIp $exactTargetIp
) {
}
}

@ -53,8 +53,8 @@ final class CloudPublicNetworkTransitionCommand
}
/**
* Stage 6 will own batch aggregation; this command freezes only the exact
* per-instance target and immutable batch-item association.
* The batch coordinator owns aggregation; this command freezes only one
* exact per-instance target and its immutable batch-item association.
*
* @param array<int,array{pool_key:string,address_cidr:string}> $targets
*/

@ -57,6 +57,157 @@ final class CloudPublicNetworkTransitionWorkflow
}, 3);
}
/**
* Freeze one child of a pool-replacement batch inside the caller's outer
* transaction. The batch coordinator already owns the canonical actor ->
* parent -> instances -> host/agent -> transitions -> resource pools ->
* attachments/pools -> reservations -> claims/IPs lock chain. This seam
* therefore performs no lock acquisition and never opens a transaction.
*/
public static function beginPoolReplacementBatch(
CloudPublicNetworkTransitionCommand $command,
CloudPublicNetworkTransitionBatchPlan $plan
): CloudPublicNetworkTransitionDispatch {
$actorUser = $plan->actor;
$parent = $plan->parent;
$item = $plan->item;
$batch = $plan->batch;
$instance = $plan->instance;
$host = $plan->host;
$agent = $plan->agent;
$resourcePool = $plan->resourcePool;
$reservation = $plan->reservation;
$sourceAttachment = $plan->attachment;
$allClaims = $plan->allClaimsSorted;
$activeClaims = $plan->activeClaimsByFamily;
$sourceIps = $plan->sourceIpsByFamily;
$pools = $plan->poolsById;
$ips = $plan->ipsById;
$targetIp = $plan->exactTargetIp;
$family = (int) $item->address_family;
$targets = $command->targets();
if ($command->kind() !== 'pool_replacement'
|| DB::connection()->transactionLevel() < 1
|| (int) $actorUser->id !== $command->actorUserId()
|| (int) $parent->id !== (int) $command->parentJobId()
|| (string) $parent->kind
!== 'public_ip_pool_replacement_batch'
|| (string) $parent->execution_mode !== 'local'
|| $parent->parent_job_id !== null
|| $parent->host_id !== null
|| $parent->public_network_transition_id !== null
|| (int) $parent->user_id !== $command->actorUserId()
|| (int) $item->id !== (int) $command->batchItemId()
|| (int) $item->batch_id !== (int) $batch->id
|| (int) $item->instance_id !== $command->instanceId()
|| (string) $item->state !== 'preparing'
|| $item->child_job_id !== null
|| (int) $batch->parent_job_id !== (int) $parent->id
|| (int) $batch->requested_by_user_id
!== $command->actorUserId()
|| (int) $batch->host_id !== (int) $host->id
|| (string) $batch->state !== 'running'
|| (int) ($batch->active_claim ?? 0) !== 1
|| (int) $instance->id !== $command->instanceId()
|| (int) $instance->host_id !== (int) $host->id
|| (int) $agent->host_id !== (int) $host->id
|| (int) $resourcePool->id !== (int) $instance->resource_pool_id
|| (int) $reservation->id !== (int) $instance->reservation_id
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) $resourcePool->id
|| (string) $reservation->state !== 'committed'
|| (int) $item->source_reservation_id !== (int) $reservation->id
|| !in_array($family, self::FAMILIES, true)
|| array_keys($targets) !== [$family]
|| count($activeClaims) !== 2
|| !isset($activeClaims[4], $activeClaims[6])
|| !$sourceIps[4] instanceof CloudPublicIp
|| !$sourceIps[6] instanceof CloudPublicIp
|| (int) $activeClaims[$family]->public_ip_id
!== (int) $item->source_public_ip_id
|| (int) $targetIp->id !== (int) $item->target_public_ip_id) {
throw new CloudError('公网地址池迁移子任务身份无效', 409);
}
if (!$host instanceof CloudHost || !(bool) $host->enabled
|| !$agent instanceof CloudHostAgent || !$agent->isReady()
|| !$resourcePool instanceof CloudResourcePool
|| !$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
|| (int) $item->source_reservation_id !== (int) $reservation->id) {
throw new CloudError('公网地址池迁移资源账本不一致', 409);
}
$sourcePool = $pools->get(
(int) $activeClaims[$family]->public_ip_pool_id
);
$targetPool = $pools->get((int) $targetIp->public_ip_pool_id);
$attachmentId = (int) $activeClaims[4]->network_attachment_id;
$target = $targets[$family];
if (!$sourcePool instanceof CloudPublicIpPool
|| !$targetPool instanceof CloudPublicIpPool
|| !$sourceAttachment instanceof CloudHostNetworkAttachment
|| (int) $activeClaims[6]->network_attachment_id !== $attachmentId
|| (int) $item->source_network_attachment_id !== $attachmentId
|| (int) $item->target_network_attachment_id !== $attachmentId
|| (int) $sourcePool->id
!== (int) $batch->source_public_ip_pool_id
|| (int) $targetPool->id
!== (int) $batch->target_public_ip_pool_id
|| (int) $sourcePool->address_family !== $family
|| (int) $targetPool->address_family !== $family
|| (int) $sourcePool->host_id !== (int) $instance->host_id
|| (int) $targetPool->host_id !== (int) $instance->host_id
|| (int) $sourcePool->network_attachment_id !== $attachmentId
|| (int) $targetPool->network_attachment_id !== $attachmentId
|| (int) $sourceAttachment->line_id
!== (int) $resourcePool->line_id
|| !hash_equals((string) $targetPool->pool_key,
(string) $target['pool_key'])
|| !hash_equals(
(string) $targetIp->address . '/'
. (int) $targetIp->prefix_length,
(string) $target['address_cidr']
)) {
throw new CloudError('公网地址池迁移冻结拓扑不一致', 409);
}
foreach (self::FAMILIES as $sourceFamily) {
self::assertCommittedSourceLeg(
$activeClaims[$sourceFamily],
$sourceIps[$sourceFamily],
(int) $reservation->id,
(int) $instance->id
);
}
$dispatch = self::freezeTransitionLocked(
$command,
$actorUser,
$instance,
$agent,
$resourcePool,
$reservation,
$allClaims,
$activeClaims,
$sourceIps,
$sourceAttachment,
collect([(int) $sourceAttachment->id => $sourceAttachment]),
$pools,
$ips,
$targetIp,
$host
);
$item->child_job_id = $dispatch->jobId();
$item->state = 'queued';
$item->updated_at = time();
$item->save();
return $dispatch;
}
/**
* Reserve a transition while the caller owns the actor row and the outer
* transaction. This internal seam must never create a nested transaction:
@ -317,7 +468,41 @@ final class CloudPublicNetworkTransitionWorkflow
$sourceIps[$family] = $sourceIp;
}
$sourceAttachment = $attachments->get($sourceAttachmentId);
return self::freezeTransitionLocked(
$command,
$actorUser,
$instance,
$agent,
$resourcePool,
$reservation,
$allClaims,
$activeClaims,
$sourceIps,
$attachments->get($sourceAttachmentId),
$attachments,
$pools,
$ips
);
}
private static function freezeTransitionLocked(
CloudPublicNetworkTransitionCommand $command,
User $actorUser,
CloudInstance $instance,
CloudHostAgent $agent,
CloudResourcePool $resourcePool,
CloudResourceReservation $reservation,
array $allClaims,
array $activeClaims,
array $sourceIps,
CloudHostNetworkAttachment $sourceAttachment,
$attachments,
$pools,
$ips,
?CloudPublicIp $exactTargetIp = null,
?CloudHost $lockedHost = null
): CloudPublicNetworkTransitionDispatch {
$reservationId = (int) $reservation->id;
$sourceSnapshot = self::snapshot(
$instance,
$agent,
@ -339,19 +524,57 @@ final class CloudPublicNetworkTransitionWorkflow
);
self::assertInstanceSnapshot($instance, $sourceSnapshot);
[$targetAttachment, $targetClaims, $targetIps, $changed] =
self::selectTargetLocked(
$command,
$instance,
$agent,
$sourceAttachment,
$activeClaims,
$sourceIps,
$attachments,
$pools,
$ips,
(int) $resourcePool->line_id
if ($exactTargetIp instanceof CloudPublicIp) {
$targetFamilies = array_keys($command->targets());
$family = count($targetFamilies) === 1
? (int) $targetFamilies[0] : 0;
$targetPool = $pools->get(
(int) $exactTargetIp->public_ip_pool_id
);
if (!in_array($family, self::FAMILIES, true)
|| !$targetPool instanceof CloudPublicIpPool
|| (int) $targetPool->address_family !== $family
|| (int) $targetPool->network_attachment_id
!== (int) $sourceAttachment->id
|| !self::poolUsable(
$targetPool,
$instance,
$agent,
$attachments,
(int) $resourcePool->line_id
)
|| !self::ipAvailableForPool(
$exactTargetIp,
$targetPool,
$lockedHost
)
|| (int) $exactTargetIp->id === (int) $sourceIps[$family]->id) {
throw new CloudError('公网地址池迁移精确目标已不可用', 409);
}
$targetAttachment = $sourceAttachment;
$targetClaims = $activeClaims;
$targetIps = $sourceIps;
$targetClaims[$family] = (object) [
'network_attachment_id' => (int) $sourceAttachment->id,
'public_ip_pool_id' => (int) $targetPool->id,
];
$targetIps[$family] = $exactTargetIp;
$changed = [$family => true];
} else {
[$targetAttachment, $targetClaims, $targetIps, $changed] =
self::selectTargetLocked(
$command,
$instance,
$agent,
$sourceAttachment,
$activeClaims,
$sourceIps,
$attachments,
$pools,
$ips,
(int) $resourcePool->line_id
);
}
$targetSnapshot = self::snapshot(
$instance,
$agent,
@ -465,10 +688,30 @@ final class CloudPublicNetworkTransitionWorkflow
if ($updated !== 1) {
throw new CloudError('目标公网地址声明绑定失败', 409);
}
$targetClaim = DB::table('cloud_resource_reservation_ips')
->where('id', $claimId)->first();
$boundIp = CloudPublicIp::where('id', (int) $targetIp->id)
->first();
$targetClaim = (object) [
'id' => $claimId,
'reservation_id' => $reservationId,
'address_family' => $family,
'claim_generation' => $generation,
'active_claim' => null,
'network_attachment_id' =>
(int) $targetPool->network_attachment_id,
'public_ip_pool_id' => (int) $targetPool->id,
'public_ip_id' => (int) $targetIp->id,
'operation_id' => $operationId,
'state' => 'reserved',
'released_at' => null,
'release_reason' => '',
'created_at' => $now,
'updated_at' => $now,
];
$targetIp->state = 'reserved';
$targetIp->reservation_id = $reservationId;
$targetIp->reservation_ip_claim_id = $claimId;
$targetIp->instance_id = null;
$targetIp->operation_id = $operationId;
$targetIp->updated_at = $now;
$boundIp = $targetIp;
$effectiveClaims[$family] = $targetClaim;
$effectiveIps[$family] = $boundIp;
self::insertTransitionLeg(
@ -496,7 +739,7 @@ final class CloudPublicNetworkTransitionWorkflow
$job->operation_id = $operationId;
$job->request_idempotency_key = $command->requestKey();
$job->request_fingerprint = $command->fingerprint();
$job->parent_job_id = null;
$job->parent_job_id = $command->parentJobId();
$job->invoice_id = $invoice?->id;
$job->instance_id = (int) $instance->id;
$job->public_network_transition_id = (int) $transition->id;
@ -2568,7 +2811,7 @@ final class CloudPublicNetworkTransitionWorkflow
}
private static function ipAvailableForPool(CloudPublicIp $ip,
CloudPublicIpPool $pool): bool
CloudPublicIpPool $pool, ?CloudHost $lockedHost = null): bool
{
if ((string) $ip->state !== 'available'
|| $ip->reservation_id !== null
@ -2577,7 +2820,7 @@ final class CloudPublicNetworkTransitionWorkflow
return false;
}
try {
self::assertAddressInPool($ip, $pool);
self::assertAddressInPool($ip, $pool, $lockedHost);
return true;
} catch (\Throwable) {
return false;
@ -2661,7 +2904,7 @@ final class CloudPublicNetworkTransitionWorkflow
}
private static function assertAddressInPool(CloudPublicIp $ip,
CloudPublicIpPool $pool): void
CloudPublicIpPool $pool, ?CloudHost $lockedHost = null): void
{
try {
$contract = CloudPublicIpPoolContract::fromRow($pool);
@ -2678,7 +2921,9 @@ final class CloudPublicNetworkTransitionWorkflow
throw new \InvalidArgumentException();
}
$management = CloudPanelUsageService::managementAddress(
CloudHost::find((int) $pool->host_id)
$lockedHost instanceof CloudHost
? $lockedHost
: CloudHost::find((int) $pool->host_id)
);
if (is_string($management) && $management !== ''
&& $address->equals(CloudIpAddress::parse($management))) {

File diff suppressed because it is too large Load Diff

@ -38,7 +38,10 @@ $assert(is_string($service)
'The browser boundary can select instances or target IPs directly.');
$assert(str_contains(
$service,
'enqueuePoolReplacementNetworkChangeLocked'
'beginPoolReplacementBatch('
) && str_contains(
$service,
'new CloudPublicNetworkTransitionBatchPlan('
) && str_contains($service, "'active_claim', 1")
&& str_contains($service, "'network_change_effect_unknown'"),
'Replacement service lost durable child jobs or unknown-effect fencing.');

@ -10,6 +10,12 @@ $itemModel = file_get_contents(
$root . '/app/Models/CloudPublicIpPoolReplacementBatchItem.php'
);
$jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php');
$workflow = file_get_contents(
$root . '/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php'
);
$batchPlan = file_get_contents(
$root . '/app/Services/Cloud/CloudPublicNetworkTransitionBatchPlan.php'
);
$worker = file_get_contents($root . '/app/Services/Cloud/CloudWorkerService.php');
$assert = static function (bool $condition, string $message): void {
@ -88,13 +94,17 @@ $assert(is_string($service)
&& str_contains($service, 'self::assertAdminRead($actor)'),
'Replacement service lost revision fencing, overlap locking, or unknown-effect convergence.');
$assert(is_string($jobs)
&& str_contains($jobs,
'enqueuePoolReplacementNetworkChangeLocked')
&& str_contains($jobs,
"'public_pool_replacement_batch_key' => \$batchKey")
&& str_contains($jobs, "'confirm_restart' => true")
&& str_contains($jobs, "\$targetIp->state = 'changing'"),
'Replacement children no longer freeze ordinary network-change identity.');
&& !str_contains($jobs, 'enqueuePoolReplacementNetworkChangeLocked')
&& is_string($workflow)
&& str_contains($workflow, 'beginPoolReplacementBatch(')
&& str_contains($workflow, 'CloudPublicNetworkTransitionBatchPlan $plan')
&& str_contains($workflow,
'$transition->pool_replacement_batch_item_id =')
&& str_contains($workflow,
'$job->parent_job_id = $command->parentJobId()')
&& is_string($batchPlan)
&& str_contains($batchPlan, 'final class CloudPublicNetworkTransitionBatchPlan'),
'Replacement children do not use the canonical dual-stack transition seam.');
$assert(is_string($worker)
&& str_contains($worker,
'CloudPublicIpPoolReplacementBatchService::finishChildLocked')
@ -130,10 +140,11 @@ $startPositions = array_map(
'$instances = CloudInstance::whereIn(',
'$host = CloudHost::where(',
'$agent = CloudHostAgent::where(',
'$resourcePools = CloudResourcePool::whereIn(',
'$attachments = CloudHostNetworkAttachment::whereIn(',
'$pools = CloudPublicIpPool::whereIn(',
'$reservations = CloudResourceReservation::whereIn(',
'$ips = CloudPublicIp::whereIn(',
'$ips = CloudPublicIp::where(',
]
);
$sortedStartPositions = $startPositions;
@ -142,6 +153,22 @@ $assert(!in_array(false, $startPositions, true)
&& $startPositions === $sortedStartPositions
&& count(array_unique($startPositions)) === count($startPositions),
'Replacement start reversed actor/job/instance/host/catalog locks.');
$ipCatalogStart = strpos($lockedStart, '$allClaims = DB::table(');
$ipCatalogEnd = strpos($lockedStart, '$sourceIpIds = [];',
$ipCatalogStart === false ? 0 : $ipCatalogStart);
$ipCatalogLock = $ipCatalogStart === false || $ipCatalogEnd === false
? '' : substr(
$lockedStart,
$ipCatalogStart,
$ipCatalogEnd - $ipCatalogStart
);
$assert($ipCatalogLock !== ''
&& !str_contains($ipCatalogLock, '$catalogIpIds')
&& str_contains($ipCatalogLock, "->orWhereIn(\n"
. " 'public_ip_pool_id'")
&& str_contains($ipCatalogLock,
"->orderBy('id')->lockForUpdate()->get()->keyBy('id')"),
'Replacement start can discover IP catalog rows outside its current locking read.');
$finishResolved = $method(
$service,
'public static function finishResolvedChildLocked(',
@ -167,6 +194,10 @@ sort($sortedPositions, SORT_NUMERIC);
$assert(!in_array(false, $positions, true)
&& $positions === $sortedPositions
&& count(array_unique($positions)) === count($positions)
&& str_contains($finishChild, 'assertItemTransitionTopology(')
&& str_contains($service, "(string) \$transition->kind !== 'pool_replacement'")
&& str_contains($service,
"(string) \$child->execution_mode !== 'agent'")
&& !str_contains($finishResolved, 'CloudHost::where(')
&& !str_contains($converge, 'lockForUpdate()'),
'Replacement convergence reversed parent/pool/batch locks.');

@ -36,10 +36,16 @@ $placementSource = $read('app/Services/Cloud/CloudPlacementService.php');
$migrationSource = $read(
'app/Services/Cloud/CloudInstanceMigrationService.php'
);
$batchSource = $read(
'app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php'
);
$batch = $method(
$read('app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php'),
$batchSource,
'public static function start('
);
$workflow = $read(
'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php'
);
$backupRestore = $method(
$read('app/Services/Cloud/CloudBackupService.php'),
'public static function restore('
@ -68,10 +74,6 @@ $migrationCleanup = $method(
$migrationSource,
'public static function cleanupRetained('
);
$poolChild = $method(
$jobs,
'public static function enqueuePoolReplacementNetworkChangeLocked('
);
$networkFinalizer = $method(
$placementSource,
'public static function finishNetworkChange('
@ -125,10 +127,11 @@ $assert($before($worker,
"'phase' => 'dispatching'")
&& $before($worker, "'instance_migration_'", "'phase' => 'dispatching'"),
'Worker defense runs after an old operation may be dispatched.');
$assert($before($batch,
'CloudPublicNetworkTransitionGate::assertWriterReady()',
'new CloudPublicIpPoolReplacementBatch()'),
'Pool-replacement gate runs after a batch may be created.');
$assert(!str_contains($jobs, 'enqueuePoolReplacementNetworkChangeLocked')
&& !str_contains($batch, 'CloudPublicNetworkTransitionGate::assertWriterReady()')
&& str_contains($batchSource, 'beginPoolReplacementBatch(')
&& str_contains($workflow, 'CloudPublicNetworkTransitionBatchPlan $plan'),
'Pool replacement retained the retired scalar writer or legacy gate.');
$assert($before($backupRestore,
'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()',
'headObject(')
@ -157,13 +160,10 @@ $assert($before($migrationEnsureCleanup,
'CloudPublicNetworkTransitionGate::assertMigrationReady()',
'getConnection()->transaction'),
'A migration recovery entry can create retry intent before its gate.');
$assert($before($poolChild,
'CloudPublicNetworkTransitionGate::assertWriterReady()',
'new CloudJob()')
&& $before($networkFinalizer,
$assert($before($networkFinalizer,
'CloudPublicNetworkTransitionGate::assertWriterReady()',
'lockForUpdate()'),
'An old network-change child/finalizer can mutate before its gate.');
'An old network-change finalizer can mutate before its gate.');
$assert(str_contains($deletedInstance,
'CloudPublicNetworkTransitionGate::assertPortableRestoreReady()')
&& !str_contains($placementSource, 'releaseLockedReservation(')

@ -58,6 +58,7 @@ $public = array_values(array_map(
));
$assert($workflow->isFinal() && $public === [
'begin',
'beginPoolReplacementBatch',
'markDispatched',
'markJobUncertain',
'recordEvidence',
@ -76,12 +77,17 @@ foreach (['userPaidAutomatic', 'adminExact', 'poolReplacement'] as $factory) {
$begin = $method(
$source,
'public static function begin(',
'public static function beginPoolReplacementBatch('
);
$batchBegin = $method(
$source,
'public static function beginPoolReplacementBatch(',
'private static function reserveTransitionLocked('
);
$reserve = $method(
$source,
'private static function reserveTransitionLocked(',
'public static function markDispatched('
'private static function freezeTransitionLocked('
);
$ordered = static function (string $body, array $needles) use ($assert): void {
$cursor = -1;
@ -97,8 +103,16 @@ $ordered($begin, [
'self::reserveTransitionLocked($command, $actorUser)',
]);
$assert(substr_count($begin, 'transaction(') === 1
&& !str_contains($reserve, 'transaction('),
&& !str_contains($reserve, 'transaction(')
&& !str_contains($batchBegin, 'transaction(')
&& !str_contains($batchBegin, 'lockForUpdate(')
&& !preg_match('/::(?:find|where|whereIn)\(/', $batchBegin),
'Reservation seam introduced a nested transaction.');
$assert(str_contains($batchBegin,
'CloudPublicNetworkTransitionBatchPlan $plan')
&& str_contains($batchBegin, '$item->state = \'queued\'')
&& str_contains($batchBegin, '$item->child_job_id = $dispatch->jobId()'),
'Batch transition seam no longer consumes only a caller-locked plan.');
$ordered($reserve, [
'$jobHint = CloudJob::where(',
'$existingParent = CloudJob::where(',

Loading…
Cancel
Save