From fa941beb3c374610ba3a1acb4c3f92c455d5cf8a Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 18:35:42 +0800 Subject: [PATCH] refactor: establish batch transition identity contract --- web/app/Command/CloudSetup.php | 6 +- .../CloudPublicIpPoolReplacementBatchItem.php | 1 + .../CloudPublicNetworkTransitionCommand.php | 31 +++++--- .../CloudPublicNetworkTransitionWorkflow.php | 6 ++ web/sql/cloud.sql | 10 ++- web/tests/CloudFreshSchemaContractTest.php | 2 +- ...pPoolReplacementItemSchemaBehaviorTest.php | 73 +++++++++++++++++++ ...licIpPoolReplacementSchemaContractTest.php | 22 +++++- ...licNetworkTransitionSchemaContractTest.php | 2 +- ...oudPublicNetworkTransitionWorkflowTest.php | 60 ++++++++++----- .../CloudRescueCatalogSchemaContractTest.php | 2 +- .../CloudTemplateImportIntentContractTest.php | 2 +- .../CloudTrafficPoolSchemaContractTest.php | 2 +- web/tests/CloudVpcSchemaContractTest.php | 2 +- 14 files changed, 180 insertions(+), 41 deletions(-) create mode 100644 web/tests/CloudPublicIpPoolReplacementItemSchemaBehaviorTest.php diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index c84668dd..7187a072 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'; + private const SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'; private const MAIN_TABLES = [ 'cloud_regions', 'cloud_traffic_pool_groups', 'cloud_network_lines', 'cloud_resource_pools', @@ -231,7 +231,8 @@ final class CloudSetup 'last_error_code', 'terminal_at', 'created_at', 'updated_at', ], 'cloud_public_ip_pool_replacement_batch_items' => [ - 'id', 'batch_id', 'instance_id', 'source_reservation_id', + 'id', 'batch_id', 'instance_id', 'address_family', + 'source_reservation_id', 'source_public_ip_id', 'target_public_ip_id', 'source_network_attachment_id', 'target_network_attachment_id', 'child_job_id', 'state', @@ -520,6 +521,7 @@ final class CloudSetup ], 'cloud_public_ip_pool_replacement_batch_items' => [ 'chk_cloud_public_pool_replacement_item_ip', + 'chk_cloud_public_pool_replacement_item_family', 'chk_cloud_public_pool_replacement_item_state', ], 'cloud_backup_subscriptions' => [ diff --git a/web/app/Models/CloudPublicIpPoolReplacementBatchItem.php b/web/app/Models/CloudPublicIpPoolReplacementBatchItem.php index ce5cec23..d4266890 100644 --- a/web/app/Models/CloudPublicIpPoolReplacementBatchItem.php +++ b/web/app/Models/CloudPublicIpPoolReplacementBatchItem.php @@ -11,6 +11,7 @@ final class CloudPublicIpPoolReplacementBatchItem extends Model 'id' => 'int', 'batch_id' => 'int', 'instance_id' => 'int', + 'address_family' => 'int', 'source_reservation_id' => 'int', 'source_public_ip_id' => 'int', 'target_public_ip_id' => 'int', diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionCommand.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionCommand.php index 993f206a..a9d5b178 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionCommand.php +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionCommand.php @@ -14,7 +14,8 @@ final class CloudPublicNetworkTransitionCommand private readonly string $fingerprint, private readonly array $targets, private readonly ?int $priceCents, - private readonly ?int $batchItemId + private readonly ?int $batchItemId, + private readonly ?int $parentJobId ) { } @@ -28,6 +29,7 @@ final class CloudPublicNetworkTransitionCommand $requestKey, [4 => null], CloudMoney::cents($expectedAmount), + null, null ); } @@ -45,6 +47,7 @@ final class CloudPublicNetworkTransitionCommand $requestKey, self::normalizeTargets($targets), null, + null, null ); } @@ -56,11 +59,12 @@ final class CloudPublicNetworkTransitionCommand * @param array $targets */ public static function poolReplacement(int $instanceId, int $actorUserId, - string $requestKey, int $batchItemId, array $targets): self + string $requestKey, int $parentJobId, int $batchItemId, + array $targets): self { - if ($batchItemId < 1) { + if ($parentJobId < 1 || $batchItemId < 1) { throw new \InvalidArgumentException( - 'Public-network batch item is invalid.' + 'Public-network batch identity is invalid.' ); } return self::make( @@ -70,13 +74,14 @@ final class CloudPublicNetworkTransitionCommand $requestKey, self::normalizeTargets($targets), null, - $batchItemId + $batchItemId, + $parentJobId ); } private static function make(string $kind, int $instanceId, int $actorUserId, string $requestKey, array $targets, - ?int $priceCents, ?int $batchItemId): self + ?int $priceCents, ?int $batchItemId, ?int $parentJobId): self { if (!in_array($kind, ['user_paid', 'admin_manual', 'pool_replacement'], true) @@ -84,11 +89,14 @@ final class CloudPublicNetworkTransitionCommand || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1 || $targets === [] || ($kind === 'user_paid' && ($priceCents === null - || $priceCents < 1 || $batchItemId !== null)) + || $priceCents < 1 || $batchItemId !== null + || $parentJobId !== null)) || ($kind === 'admin_manual' - && ($priceCents !== null || $batchItemId !== null)) + && ($priceCents !== null || $batchItemId !== null + || $parentJobId !== null)) || ($kind === 'pool_replacement' - && ($priceCents !== null || $batchItemId === null))) { + && ($priceCents !== null || $batchItemId === null + || $parentJobId === null || $parentJobId < 1))) { throw new \InvalidArgumentException( 'Public-network transition command is invalid.' ); @@ -100,6 +108,7 @@ final class CloudPublicNetworkTransitionCommand 'targets' => $targets, 'price_cents' => $priceCents, 'batch_item_id' => $batchItemId, + 'parent_job_id' => $parentJobId, ]; $fingerprint = hash('sha256', json_encode( $identity, @@ -122,7 +131,8 @@ final class CloudPublicNetworkTransitionCommand $fingerprint, $targets, $priceCents, - $batchItemId + $batchItemId, + $parentJobId ); } @@ -173,4 +183,5 @@ final class CloudPublicNetworkTransitionCommand public function targets(): array { return $this->targets; } public function priceCents(): ?int { return $this->priceCents; } public function batchItemId(): ?int { return $this->batchItemId; } + public function parentJobId(): ?int { return $this->parentJobId; } } diff --git a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php index 8049b4aa..d3ae2ce9 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php +++ b/web/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php @@ -31,6 +31,12 @@ final class CloudPublicNetworkTransitionWorkflow public static function begin( CloudPublicNetworkTransitionCommand $command ): CloudPublicNetworkTransitionDispatch { + if ($command->kind() === 'pool_replacement') { + throw new CloudError( + '地址池替换必须通过原子批次工作流提交', + 409 + ); + } return DB::connection()->transaction(static function () use ( $command ): CloudPublicNetworkTransitionDispatch { diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index acb70e05..ca7dfd4f 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -451,12 +451,13 @@ CREATE TABLE cloud_public_ip_pool_replacement_batch_items ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, batch_id BIGINT UNSIGNED NOT NULL, instance_id BIGINT UNSIGNED NOT NULL, + address_family TINYINT UNSIGNED NOT NULL, source_reservation_id BIGINT UNSIGNED NOT NULL, source_public_ip_id BIGINT UNSIGNED NOT NULL, target_public_ip_id BIGINT UNSIGNED NOT NULL, source_network_attachment_id BIGINT UNSIGNED NOT NULL, target_network_attachment_id BIGINT UNSIGNED NOT NULL, - child_job_id BIGINT UNSIGNED NOT NULL, + child_job_id BIGINT UNSIGNED DEFAULT NULL, state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, last_error_code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', created_at BIGINT UNSIGNED NOT NULL, @@ -470,8 +471,13 @@ CREATE TABLE cloud_public_ip_pool_replacement_batch_items ( CONSTRAINT chk_cloud_public_pool_replacement_item_ip CHECK ( source_public_ip_id <> target_public_ip_id ), + CONSTRAINT chk_cloud_public_pool_replacement_item_family CHECK ( + address_family IN (4,6) + ), CONSTRAINT chk_cloud_public_pool_replacement_item_state CHECK ( - state IN ('queued','succeeded','failed','unknown') + (state = 'preparing' AND child_job_id IS NULL) + OR (state IN ('queued','succeeded','failed','unknown') + AND child_job_id IS NOT NULL) ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/web/tests/CloudFreshSchemaContractTest.php b/web/tests/CloudFreshSchemaContractTest.php index b81baac8..5ad777c2 100644 --- a/web/tests/CloudFreshSchemaContractTest.php +++ b/web/tests/CloudFreshSchemaContractTest.php @@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false $assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema), 'cloud.sql retained an engine-prefixed identifier.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") + "SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"), 'Outbound Agent schema must reject the incompatible earlier Go database.'); $assert(str_contains($schema, diff --git a/web/tests/CloudPublicIpPoolReplacementItemSchemaBehaviorTest.php b/web/tests/CloudPublicIpPoolReplacementItemSchemaBehaviorTest.php new file mode 100644 index 00000000..41790b82 --- /dev/null +++ b/web/tests/CloudPublicIpPoolReplacementItemSchemaBehaviorTest.php @@ -0,0 +1,73 @@ +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); +$database->exec(<<<'SQL' +CREATE TABLE batch_items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + batch_id INTEGER NOT NULL, + instance_id INTEGER NOT NULL, + address_family INTEGER NOT NULL, + source_public_ip_id INTEGER NOT NULL, + target_public_ip_id INTEGER NOT NULL, + child_job_id INTEGER DEFAULT NULL, + state TEXT NOT NULL, + UNIQUE (batch_id, instance_id), + UNIQUE (child_job_id), + UNIQUE (batch_id, target_public_ip_id), + CHECK (source_public_ip_id <> target_public_ip_id), + CHECK (address_family IN (4,6)), + CHECK ( + (state = 'preparing' AND child_job_id IS NULL) + OR (state IN ('queued','succeeded','failed','unknown') + AND child_job_id IS NOT NULL) + ) +) +SQL); + +$insert = $database->prepare( + 'INSERT INTO batch_items ' + . '(batch_id, instance_id, address_family, source_public_ip_id, ' + . 'target_public_ip_id, child_job_id, state) ' + . 'VALUES (?, ?, ?, ?, ?, ?, ?)' +); +$rejects = static function (callable $callback, string $message): void { + try { + $callback(); + } catch (PDOException) { + return; + } + throw new RuntimeException($message); +}; + +$insert->execute([1, 10, 4, 100, 101, null, 'preparing']); +$insert->execute([1, 11, 6, 200, 201, 900, 'queued']); +$insert->execute([2, 12, 4, 300, 301, null, 'preparing']); + +$rejects( + static fn () => $insert->execute([1, 13, 4, 400, 401, 901, + 'preparing']), + 'Preparing batch item accepted an already-linked child.' +); +$rejects( + static fn () => $insert->execute([1, 14, 6, 500, 501, null, 'queued']), + 'Queued batch item accepted a missing child.' +); +$rejects( + static fn () => $insert->execute([1, 15, 5, 600, 601, null, + 'preparing']), + 'Batch item accepted an unsupported address family.' +); +$rejects( + static fn () => $insert->execute([1, 16, 4, 700, 700, null, + 'preparing']), + 'Batch item accepted the same source and target address.' +); +$rejects( + static fn () => $insert->execute([2, 17, 4, 800, 801, 900, 'failed']), + 'Batch item reused one child job across batches.' +); + +echo "Cloud public-IP pool replacement item schema behavior passed.\n"; diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index 12f619f8..b1aa2f1b 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -6,6 +6,9 @@ $setup = file_get_contents($root . '/app/Command/CloudSetup.php'); $service = file_get_contents( $root . '/app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php' ); +$itemModel = file_get_contents( + $root . '/app/Models/CloudPublicIpPoolReplacementBatchItem.php' +); $jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); $worker = file_get_contents($root . '/app/Services/Cloud/CloudWorkerService.php'); @@ -27,21 +30,36 @@ $assert(is_string($schema) && str_contains($schema, 'source_public_ip_pool_id, active_claim') && str_contains($schema, 'target_public_ip_pool_id, active_claim, id') && str_contains($schema, 'cloud_public_pool_replacement_child') - && str_contains($schema, "state IN ('queued','succeeded','failed','unknown')") + && str_contains($schema, 'address_family TINYINT UNSIGNED NOT NULL') + && str_contains($schema, 'child_job_id BIGINT UNSIGNED DEFAULT NULL') + && str_contains($schema, + 'chk_cloud_public_pool_replacement_item_family') + && str_contains($schema, 'address_family IN (4,6)') + && str_contains($schema, + "state = 'preparing' AND child_job_id IS NULL") + && str_contains($schema, + "state IN ('queued','succeeded','failed','unknown')") + && str_contains($schema, 'AND child_job_id IS NOT NULL') && str_contains($schema, "state IN ('running','blocked','succeeded','failed')"), 'Public-pool replacement lacks durable batch, child, or active-claim schema.'); $assert(is_string($setup) && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") + "SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'") && str_contains($setup, "'cloud_public_ip_pool_replacement_batches'") && str_contains($setup, "'cloud_public_ip_pool_replacement_batch_items'") && str_contains($setup, "'chk_cloud_public_pool_replacement_source_initial'") + && str_contains($setup, + "'chk_cloud_public_pool_replacement_item_family'") && str_contains($setup, "'chk_cloud_public_pool_replacement_claim'"), 'CloudSetup does not enforce the replacement batch schema.'); +$assert(is_string($itemModel) + && str_contains($itemModel, "'address_family' => 'int'") + && str_contains($itemModel, "'child_job_id' => 'int'"), + 'Replacement batch-item model lost family or nullable-child identity.'); $assert(is_string($service) && str_contains($service, 'expected_source_revision') && str_contains($service, 'expected_target_revision') diff --git a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php index cb034f6e..8babe648 100644 --- a/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionSchemaContractTest.php @@ -170,7 +170,7 @@ $assert(str_contains($setup, 'CloudSetup does not verify index uniqueness and ordered columns.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") + "SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'") && str_contains($setup, "'cloud_public_network_transitions'") && str_contains($setup, "'cloud_public_network_transition_ips'") && str_contains($setup, "'reservation_ip_claim_id'") diff --git a/web/tests/CloudPublicNetworkTransitionWorkflowTest.php b/web/tests/CloudPublicNetworkTransitionWorkflowTest.php index aa9a47ac..4a9a603b 100644 --- a/web/tests/CloudPublicNetworkTransitionWorkflowTest.php +++ b/web/tests/CloudPublicNetworkTransitionWorkflowTest.php @@ -1303,26 +1303,48 @@ namespace { Capsule::table('cloud_invoices')->where('id', $invoice->id) ->update(['amount' => '5.00']); - $batch = CloudPublicNetworkTransitionWorkflow::begin( - CloudPublicNetworkTransitionCommand::poolReplacement( - 10, - 99, - 'pool-replace-net-0010', - 77, - [4 => [ - 'pool_key' => str_repeat('c', 32), - 'address_cidr' => '8.8.9.22/24', - ]] - ) + $batchCommand = CloudPublicNetworkTransitionCommand::poolReplacement( + 10, + 99, + 'pool-replace-net-0010', + 900, + 77, + [4 => [ + 'pool_key' => str_repeat('c', 32), + 'address_cidr' => '8.8.9.22/24', + ]] ); - $batchTransition = Capsule::table('cloud_public_network_transitions') - ->where('id', $batch->transitionId())->first(); - $assert($batchTransition !== null - && (int) $batchTransition->pool_replacement_batch_item_id === 77 - && $batchTransition->invoice_id === null - && (int) Capsule::table('cloud_jobs')->where('id', $batch->jobId()) - ->value('public_network_transition_id') === $batch->transitionId(), - 'Pool-replacement transition lost batch or job association.'); + $otherParent = CloudPublicNetworkTransitionCommand::poolReplacement( + 10, + 99, + 'pool-replace-net-0010', + 901, + 77, + [4 => [ + 'pool_key' => str_repeat('c', 32), + 'address_cidr' => '8.8.9.22/24', + ]] + ); + $beforeBatchTransitions = Capsule::table( + 'cloud_public_network_transitions' + )->count(); + $beforeBatchJobs = Capsule::table('cloud_jobs')->count(); + $rejects( + static fn () => CloudPublicNetworkTransitionWorkflow::begin( + $batchCommand + ), + 'Public begin accepted a pool-replacement command without its batch.' + ); + $assert($batchCommand->parentJobId() === 900 + && $batchCommand->batchItemId() === 77 + && !hash_equals( + $batchCommand->fingerprint(), + $otherParent->fingerprint() + ) + && Capsule::table('cloud_public_network_transitions')->count() + === $beforeBatchTransitions + && Capsule::table('cloud_jobs')->count() === $beforeBatchJobs, + 'Pool-replacement parent identity was mutable or left writes.'); echo "Public-network transition begin workflow tests passed.\n"; } diff --git a/web/tests/CloudRescueCatalogSchemaContractTest.php b/web/tests/CloudRescueCatalogSchemaContractTest.php index a84749d8..5fb12860 100644 --- a/web/tests/CloudRescueCatalogSchemaContractTest.php +++ b/web/tests/CloudRescueCatalogSchemaContractTest.php @@ -56,7 +56,7 @@ $assert($replica !== '' && str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'), 'Rescue replica cannot prove exact identity or retain cleanup debt.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") + "SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'") && str_contains($setup, "'cloud_rescue_artifact_delete_due'") && str_contains($setup, "'cloud_rescue_replica_cleanup'"), 'CloudSetup version or rescue catalog indexes are incomplete.'); diff --git a/web/tests/CloudTemplateImportIntentContractTest.php b/web/tests/CloudTemplateImportIntentContractTest.php index 8068f3a9..41173adc 100644 --- a/web/tests/CloudTemplateImportIntentContractTest.php +++ b/web/tests/CloudTemplateImportIntentContractTest.php @@ -63,7 +63,7 @@ $assert(str_contains($schema, && str_contains($schema, 'CONSTRAINT chk_cloud_template_import_completion CHECK (') && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'"), + "SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'"), 'Template imports are missing durable identity or terminal-state constraints.'); $assert(str_contains($routes, "'/admin/cloud-template-imports'") && str_contains($routes, "'/admin/cloud-template-imports/{id}'") diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index 47aae80e..79a6302d 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -71,7 +71,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") + "SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'") && str_contains($setup, "'chk_cloud_traffic_entitlement_balance'") && str_contains($setup, "'cloud_traffic_ledger_sequence'"), 'CloudSetup schema version or named-object validation is incomplete.'); diff --git a/web/tests/CloudVpcSchemaContractTest.php b/web/tests/CloudVpcSchemaContractTest.php index 0beb84eb..5e5eda66 100644 --- a/web/tests/CloudVpcSchemaContractTest.php +++ b/web/tests/CloudVpcSchemaContractTest.php @@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL') 'Cloud jobs cannot be correlated to VPC or VPC-port work.'); $assert(str_contains($setup, - "private const SCHEMA_VERSION = 'go-agent-wss-v29-active-public-network-claims'") + "private const SCHEMA_VERSION = 'go-agent-wss-v30-public-network-batch-identity'") && str_contains($setup, "'name' => 'cloud_vpc_enabled'") && str_contains($setup, "'value' => 'false'") && str_contains($setup,