refactor: establish batch transition identity contract

go
codex 3 weeks ago
parent b50da3df65
commit fa941beb3c

@ -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' => [

@ -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',

@ -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<int,array{pool_key:string,address_cidr:string}> $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; }
}

@ -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 {

@ -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;

@ -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,

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
$database = new PDO('sqlite::memory:');
$database->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";

@ -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')

@ -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'")

@ -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";
}

@ -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.');

@ -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}'")

@ -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.');

@ -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,

Loading…
Cancel
Save