You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudPublicNetworkTransitio...

1579 lines
63 KiB
PHP

<?php
namespace App\Services\Cloud {
final class CloudSecrets
{
private static array $values = [];
public static function encrypt(array $value, string $purpose): string
{
$key = bin2hex(random_bytes(16));
self::$values[$key] = $value;
return 'network-transition-test:' . $key;
}
public static function decrypt(string $value, string $purpose): array
{
$prefix = 'network-transition-test:';
return self::$values[substr($value, strlen($prefix))] ?? [];
}
}
final class CloudPanelUsageService
{
public static ?string $managementAddress = null;
public static function managementAddress($host): ?string
{
return self::$managementAddress;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudError;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Services\Cloud\CloudActivePublicNetworkClaimSet;
use App\Services\Cloud\CloudPublicNetworkClaimSetIdentity;
use App\Services\Cloud\CloudPublicNetworkSnapshot;
use App\Services\Cloud\CloudPublicNetworkTransitionCommand;
use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudPanelUsageService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$rejects = static function (callable $callback, string $message): void {
try {
$callback();
} catch (CloudError) {
return;
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $t): void {
$t->increments('id');
$t->string('money');
$t->boolean('enable');
});
$schema->create('configurations', static function (Blueprint $t): void {
$t->increments('id');
$t->string('name')->unique();
$t->text('value');
});
$schema->create('cloud_hosts', static function (Blueprint $t): void {
$t->increments('id');
$t->string('name');
$t->boolean('enabled');
});
$schema->create('cloud_host_agents', static function (Blueprint $t): void {
$t->integer('host_id')->primary();
$t->text('sealed_api_secret');
$t->boolean('enabled');
$t->integer('revision');
$t->integer('tested_revision');
$t->string('last_test_status');
$t->string('last_error_code');
$t->string('last_agent_version');
$t->text('network_selectors_json');
$t->text('public_network_capabilities_json');
$t->integer('last_tested_at');
$t->integer('created_at');
$t->integer('updated_at');
});
$schema->create('cloud_resource_pools', static function (Blueprint $t): void {
$t->increments('id');
$t->integer('line_id');
$t->string('code');
$t->string('name');
$t->string('status');
});
$schema->create('cloud_host_network_attachments', static function (
Blueprint $t
): void {
$t->increments('id');
$t->string('attachment_key');
$t->integer('host_id');
$t->integer('line_id');
$t->string('name');
$t->string('network_selector');
$t->string('state');
$t->integer('priority');
$t->integer('verified_agent_revision');
$t->string('verification_state');
$t->integer('last_verified_at');
});
$schema->create('cloud_public_ip_pools', static function (
Blueprint $t
): void {
$t->increments('id');
$t->string('pool_key');
$t->integer('host_id');
$t->integer('network_attachment_id');
$t->integer('address_family');
$t->string('name');
$t->string('cidr');
$t->string('gateway');
$t->boolean('gateway_on_link');
$t->integer('guest_prefix_length');
$t->text('dns_servers_json');
$t->text('reserved_ips_json');
$t->string('allocation_start')->nullable();
$t->string('allocation_end')->nullable();
$t->string('allocation_cursor')->nullable();
$t->integer('max_allocations');
$t->string('state');
$t->integer('priority');
$t->integer('desired_revision');
$t->integer('observed_revision');
$t->string('sync_state');
});
$schema->create('cloud_public_ips', static function (Blueprint $t): void {
$t->increments('id');
$t->integer('host_id');
$t->integer('public_ip_pool_id');
$t->integer('address_family');
$t->string('address');
$t->binary('address_binary');
$t->integer('prefix_length');
$t->string('state');
$t->integer('reservation_id')->nullable();
$t->integer('reservation_ip_claim_id')->nullable();
$t->integer('instance_id')->nullable();
$t->string('operation_id')->nullable();
$t->integer('created_at');
$t->integer('updated_at');
$t->unique(['address_family', 'address_binary']);
$t->unique('reservation_ip_claim_id');
});
$schema->create('cloud_resource_reservations', static function (
Blueprint $t
): void {
$t->increments('id');
$t->string('reservation_key');
$t->string('operation_id');
$t->integer('order_id')->nullable();
$t->integer('backup_restore_id')->nullable();
$t->integer('offer_id')->nullable();
$t->integer('resource_pool_id');
$t->integer('host_id');
$t->integer('user_id');
$t->integer('instance_id')->nullable();
$t->integer('network_attachment_id')->nullable();
$t->integer('public_ip_pool_id')->nullable();
$t->integer('public_ip_id')->nullable();
$t->integer('cpu_cores');
$t->integer('memory_mib');
$t->integer('disk_gib');
$t->string('state');
$t->integer('expires_at')->nullable();
$t->integer('released_at')->nullable();
$t->string('release_reason');
$t->integer('created_at');
$t->integer('updated_at');
});
$schema->create('cloud_resource_reservation_ips', static function (
Blueprint $t
): void {
$t->increments('id');
$t->integer('reservation_id');
$t->integer('address_family');
$t->integer('claim_generation');
$t->integer('active_claim')->nullable();
$t->integer('network_attachment_id');
$t->integer('public_ip_pool_id');
$t->integer('public_ip_id');
$t->string('operation_id');
$t->string('state');
$t->integer('released_at')->nullable();
$t->string('release_reason');
$t->integer('created_at');
$t->integer('updated_at');
$t->unique(['reservation_id', 'address_family', 'active_claim']);
$t->unique(['reservation_id', 'claim_generation', 'address_family']);
});
$schema->create('cloud_instances', static function (Blueprint $t): void {
$t->increments('id');
$t->integer('host_id');
$t->integer('user_id');
$t->integer('order_id')->nullable();
$t->integer('plan_id')->nullable();
$t->integer('offer_id')->nullable();
$t->integer('resource_pool_id');
$t->integer('reservation_id');
$t->string('uuid');
$t->string('name');
$t->string('status');
$t->string('service_status');
$t->string('network_status');
$t->integer('expires_at')->nullable();
$t->text('spec_json');
$t->integer('created_at');
$t->integer('updated_at');
});
$schema->create('cloud_public_network_transitions', static function (
Blueprint $t
): void {
$t->increments('id');
$t->string('transition_key')->unique();
$t->string('operation_id')->unique();
$t->string('kind');
$t->integer('instance_id');
$t->integer('host_id');
$t->integer('reservation_id');
$t->integer('invoice_id')->nullable()->unique();
$t->integer('pool_replacement_batch_item_id')->nullable()->unique();
$t->integer('requested_by_user_id');
$t->integer('source_network_attachment_id');
$t->integer('target_network_attachment_id');
$t->string('source_claim_set_sha256');
$t->string('target_claim_set_sha256');
$t->text('source_public_network_json');
$t->string('source_public_network_sha256');
$t->text('target_public_network_json');
$t->string('target_public_network_sha256');
$t->string('state');
$t->string('effect_resolution');
$t->integer('active_transition')->nullable();
$t->string('last_error_code');
$t->integer('effect_resolved_at')->nullable();
$t->integer('terminal_at')->nullable();
$t->integer('created_at');
$t->integer('updated_at');
$t->unique(['instance_id', 'active_transition']);
$t->unique(['reservation_id', 'active_transition']);
});
$schema->create('cloud_public_network_transition_ips', static function (
Blueprint $t
): void {
$t->increments('id');
$t->integer('transition_id');
$t->integer('address_family');
$t->integer('source_claim_id');
$t->integer('target_claim_id')->nullable()->unique();
$t->boolean('changed');
$t->integer('created_at');
$t->integer('updated_at');
$t->unique(['transition_id', 'address_family']);
});
$schema->create('cloud_invoices', static function (Blueprint $t): void {
$t->increments('id');
$t->string('invoice_no')->unique();
$t->string('purpose');
$t->integer('instance_id')->nullable();
$t->integer('order_id')->nullable();
$t->integer('user_id');
$t->integer('plan_id')->nullable();
$t->integer('offer_id')->nullable();
$t->integer('renewal_id')->nullable();
$t->integer('renews_expires_at')->nullable();
$t->integer('due_at');
$t->string('amount');
$t->string('currency');
$t->integer('validity_days');
$t->integer('traffic_quota_bytes');
$t->string('status');
$t->string('paid_via')->nullable();
$t->string('payment_reference')->nullable();
$t->integer('paid_at')->nullable();
$t->integer('created_at');
$t->integer('updated_at');
});
$schema->create('cloud_jobs', static function (Blueprint $t): void {
$t->increments('id');
$t->string('operation_id')->unique();
$t->string('request_idempotency_key');
$t->string('request_fingerprint');
foreach (['parent_job_id', 'supersedes_job_id',
'vpc_repair_root_job_id', 'order_id', 'invoice_id',
'instance_id', 'snapshot_id', 'backup_id', 'backup_restore_id',
'backup_recovery_id', 'public_network_transition_id', 'vpc_id',
'vpc_port_id', 'vpc_batch_id'] as $column) {
$t->integer($column)->nullable();
}
$t->integer('user_id');
$t->integer('host_id')->nullable();
$t->string('kind');
$t->string('execution_mode');
$t->string('phase');
$t->string('outcome')->nullable();
$t->string('status');
$t->text('sealed_payload');
$t->integer('attempts');
$t->integer('dispatch_attempts');
$t->integer('dispatch_deadline_at');
$t->integer('dispatch_started_at')->nullable();
$t->integer('agent_accepted_at')->nullable();
$t->integer('receipt_deadline_at')->nullable();
$t->integer('terminal_at')->nullable();
$t->boolean('effect_may_have_applied')->nullable();
$t->boolean('safe_to_resubmit')->nullable();
$t->string('effect_resolution');
$t->integer('effect_resolved_at')->nullable();
$t->integer('effect_resolved_by')->nullable();
$t->text('effect_resolution_reason')->nullable();
$t->boolean('finalization_incident');
$t->string('finalization_error_code')->nullable();
$t->string('completion_event_id')->nullable();
$t->integer('read_at')->nullable();
$t->integer('dispatched_at')->nullable();
$t->string('lease_token')->nullable();
$t->integer('lease_until')->default(0);
$t->integer('available_at');
$t->string('error_code')->nullable();
$t->text('result_json')->nullable();
$t->integer('created_at');
$t->integer('updated_at');
$t->unique(['user_id', 'request_idempotency_key']);
});
$schema->create('cloud_instance_migrations', static function (
Blueprint $t
): void {
$t->increments('id');
$t->integer('instance_id');
$t->string('state');
});
$schema->create('cloud_peer_migration_artifacts', static function (
Blueprint $t
): void {
$t->increments('id');
});
$schema->create('cloud_backup_recoveries', static function (
Blueprint $t
): void {
$t->increments('id');
$t->integer('instance_id');
$t->string('state');
});
$now = time();
Capsule::table('configurations')->insert([
'name' => 'cloud_ip_change_price',
'value' => '5.00',
]);
Capsule::table('user')->insert([
['id' => 10, 'money' => '20.00', 'enable' => 1],
['id' => 99, 'money' => '0.00', 'enable' => 1],
]);
Capsule::table('cloud_hosts')->insert([
'id' => 1, 'name' => 'HKG-A', 'enabled' => 1,
]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1,
'sealed_api_secret' => 'unused',
'enabled' => 1,
'revision' => 3,
'tested_revision' => 3,
'last_test_status' => 'healthy',
'last_error_code' => '',
'last_agent_version' => 'test',
'network_selectors_json' => '["bridge:br0","bridge:br1"]',
'public_network_capabilities_json' => json_encode([
'contract' => 1,
'dual_stack_required' => true,
'project_owned_filter' => true,
'ndp_guard' => true,
], JSON_THROW_ON_ERROR),
'last_tested_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
Capsule::table('cloud_resource_pools')->insert([
'id' => 1, 'line_id' => 7, 'code' => 'hkg',
'name' => 'Hong Kong', 'status' => 'active',
]);
foreach ([
[1, 'a1', 'bridge:br0', 0],
[2, 'a2', 'bridge:br1', 1],
] as [$id, $key, $selector, $priority]) {
Capsule::table('cloud_host_network_attachments')->insert([
'id' => $id,
'attachment_key' => str_repeat($key[0], 32),
'host_id' => 1,
'line_id' => 7,
'name' => strtoupper($key),
'network_selector' => $selector,
'state' => 'active',
'priority' => $priority,
'verified_agent_revision' => 3,
'verification_state' => 'verified',
'last_verified_at' => $now,
]);
}
$pool = static function (int $id, int $attachmentId, int $family,
string $key, string $cidr, string $gateway, int $priority = 0
) use ($now): array {
return [
'id' => $id,
'pool_key' => str_repeat($key, 32),
'host_id' => 1,
'network_attachment_id' => $attachmentId,
'address_family' => $family,
'name' => 'pool-' . $id,
'cidr' => $cidr,
'gateway' => $gateway,
'gateway_on_link' => $family === 6 ? 1 : 0,
'guest_prefix_length' => $family === 6 ? 64 : 24,
'dns_servers_json' => $family === 6
? '["2606:4700:4700::1111"]' : '["1.1.1.1"]',
'reserved_ips_json' => '[]',
'allocation_start' => $family === 6
? str_replace('::/64', '::1000', $cidr) : null,
'allocation_end' => $family === 6
? str_replace('::/64', '::10ff', $cidr) : null,
'allocation_cursor' => $family === 6
? str_replace('::/64', '::1000', $cidr) : null,
'max_allocations' => $family === 6 ? 64 : 0,
'state' => 'active',
'priority' => $priority,
'desired_revision' => 1,
'observed_revision' => 1,
'sync_state' => 'applied',
];
};
Capsule::table('cloud_public_ip_pools')->insert([
$pool(11, 1, 4, 'a', '8.8.8.0/24', '8.8.8.1', 10),
$pool(12, 1, 6, 'b', '2404:c140:156:3a::/64',
'2404:c140:156::1', 10),
$pool(13, 1, 4, 'c', '8.8.9.0/24', '8.8.9.1'),
$pool(14, 1, 6, 'd', '2404:c140:156:3b::/64',
'2404:c140:156::1'),
$pool(21, 2, 4, 'e', '9.9.9.0/24', '9.9.9.1'),
$pool(22, 2, 6, 'f', '2404:c140:156:3c::/64',
'2404:c140:156::1'),
]);
Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([
'dns_servers_json' => '["2404:c140:156:3c::1001"]',
'reserved_ips_json' => '["2404:c140:156:3c::1002"]',
]);
$addIp = static function (int $id, int $poolId, int $family,
string $address, string $state = 'available', ?int $reservationId = null,
?int $claimId = null, ?int $instanceId = null,
?string $operationId = null) use ($now): void {
Capsule::table('cloud_public_ips')->insert([
'id' => $id,
'host_id' => 1,
'public_ip_pool_id' => $poolId,
'address_family' => $family,
'address' => $address,
'address_binary' => inet_pton($address),
'prefix_length' => $family === 6 ? 64 : 24,
'state' => $state,
'reservation_id' => $reservationId,
'reservation_ip_claim_id' => $claimId,
'instance_id' => $instanceId,
'operation_id' => $operationId,
'created_at' => $now,
'updated_at' => $now,
]);
};
// Available transition targets.
$addIp(201, 13, 4, '8.8.9.20');
$addIp(202, 13, 4, '8.8.9.21');
$addIp(203, 13, 4, '8.8.9.22');
$addIp(204, 13, 4, '8.8.9.23');
$addIp(301, 21, 4, '9.9.9.30');
$addIp(302, 21, 4, '9.9.9.31');
$addIp(401, 22, 6, '2404:c140:156:3c::1000');
$addIp(402, 22, 6, '2404:c140:156:3c::1001');
$addIp(403, 22, 6, '2404:c140:156:3c::1003');
$sourceSnapshot = static function (string $ipv4, string $ipv6): array {
return [
'contract' => 1,
'network_selector' => 'bridge:br0',
'ipv4' => [
'pool_key' => str_repeat('a', 32),
'pool_cidr' => '8.8.8.0/24',
'address_cidr' => $ipv4 . '/24',
'gateway' => '8.8.8.1',
'gateway_on_link' => false,
],
'ipv6' => [
'pool_key' => str_repeat('b', 32),
'pool_cidr' => '2404:c140:156:3a::/64',
'address_cidr' => $ipv6 . '/64',
'gateway' => '2404:c140:156::1',
'gateway_on_link' => true,
],
'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'],
];
};
$addInstance = static function (int $instanceId, int $reservationId,
int $claim4, int $claim6, int $ip4, int $ip6,
string $address4, string $address6, int $userId
) use ($now, $addIp, $sourceSnapshot): void {
$op4 = str_pad(dechex($instanceId), 32, 'a', STR_PAD_LEFT);
$op6 = str_pad(dechex($instanceId), 32, 'b', STR_PAD_LEFT);
Capsule::table('cloud_resource_reservations')->insert([
'id' => $reservationId,
'reservation_key' => str_pad((string) $reservationId, 32, '0',
STR_PAD_LEFT),
'operation_id' => str_repeat('9', 28)
. str_pad((string) $reservationId, 4, '0', STR_PAD_LEFT),
'order_id' => $reservationId,
'backup_restore_id' => null,
'offer_id' => 1,
'resource_pool_id' => 1,
'host_id' => 1,
'user_id' => $userId,
'instance_id' => $instanceId,
// Deliberately wrong legacy singular mirrors: current authority
// must be the active pair below.
'network_attachment_id' => 999,
'public_ip_pool_id' => 999,
'public_ip_id' => 999,
'cpu_cores' => 1,
'memory_mib' => 1024,
'disk_gib' => 20,
'state' => 'committed',
'expires_at' => null,
'released_at' => null,
'release_reason' => '',
'created_at' => $now,
'updated_at' => $now,
]);
$addIp($ip4, 11, 4, $address4, 'assigned', $reservationId,
$claim4, $instanceId, $op4);
$addIp($ip6, 12, 6, $address6, 'assigned', $reservationId,
$claim6, $instanceId, $op6);
Capsule::table('cloud_resource_reservation_ips')->insert([
[
'id' => $claim4,
'reservation_id' => $reservationId,
'address_family' => 4,
'claim_generation' => 1,
'active_claim' => 1,
'network_attachment_id' => 1,
'public_ip_pool_id' => 11,
'public_ip_id' => $ip4,
'operation_id' => $op4,
'state' => 'committed',
'released_at' => null,
'release_reason' => '',
'created_at' => $now,
'updated_at' => $now,
],
[
'id' => $claim6,
'reservation_id' => $reservationId,
'address_family' => 6,
'claim_generation' => 3,
'active_claim' => 1,
'network_attachment_id' => 1,
'public_ip_pool_id' => 12,
'public_ip_id' => $ip6,
'operation_id' => $op6,
'state' => 'committed',
'released_at' => null,
'release_reason' => '',
'created_at' => $now,
'updated_at' => $now,
],
]);
Capsule::table('cloud_instances')->insert([
'id' => $instanceId,
'host_id' => 1,
'user_id' => $userId,
'order_id' => $reservationId,
'plan_id' => 1,
'offer_id' => 1,
'resource_pool_id' => 1,
'reservation_id' => $reservationId,
'uuid' => sprintf('00000000-0000-4000-8000-%012d', $instanceId),
'name' => 'vm-' . $instanceId,
'status' => 'active',
'service_status' => 'active',
'network_status' => 'active',
'expires_at' => $now + 86400,
'spec_json' => json_encode([
'managed' => true,
'os_source' => 'cloud_template',
'public_network' => $sourceSnapshot($address4, $address6),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
'created_at' => $now,
'updated_at' => $now,
]);
};
$addInstance(1, 101, 1001, 1002, 101, 102,
'8.8.8.10', '2404:c140:156:3a::1000', 10);
$addInstance(2, 102, 1003, 1004, 103, 104,
'8.8.8.11', '2404:c140:156:3a::1001', 10);
$addInstance(3, 103, 1005, 1006, 105, 106,
'8.8.8.12', '2404:c140:156:3a::1002', 10);
$addInstance(4, 104, 1007, 1008, 107, 108,
'8.8.8.13', '2404:c140:156:3a::1003', 10);
$addInstance(5, 105, 1009, 1010, 109, 110,
'8.8.8.14', '2404:c140:156:3a::1004', 10);
$addInstance(6, 106, 1011, 1012, 111, 112,
'8.8.8.15', '2404:c140:156:3a::1005', 10);
$addInstance(7, 107, 1013, 1014, 113, 114,
'8.8.8.16', '2404:c140:156:3a::1006', 10);
$addInstance(8, 108, 1015, 1016, 115, 116,
'8.8.8.17', '2404:c140:156:3a::1007', 10);
$addInstance(9, 109, 1017, 1018, 117, 118,
'8.8.8.18', '2404:c140:156:3a::1008', 10);
$addInstance(10, 110, 1019, 1020, 119, 120,
'8.8.8.19', '2404:c140:156:3a::1009', 10);
$addInstance(11, 111, 1021, 1022, 121, 122,
'8.8.8.20', '2404:c140:156:3a::100a', 10);
$addInstance(12, 112, 1023, 1024, 123, 124,
'8.8.8.21', '2404:c140:156:3a::100b', 10);
$sourceClaims = Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 101)->where('active_claim', 1)
->orderBy('address_family')->get()->all();
$sourceClaimsByFamily = [];
foreach ($sourceClaims as $claim) {
$sourceClaimsByFamily[(int) $claim->address_family] = $claim;
}
$sourceAddresses = CloudPublicIp::whereIn('id', [101, 102])
->get()->keyBy('id')->all();
$sourceNetwork = CloudPublicNetworkSnapshot::fromArray($sourceSnapshot(
'8.8.8.10',
'2404:c140:156:3a::1000'
));
$activeDigest = CloudActivePublicNetworkClaimSet::fromLedger(
101,
$sourceClaims,
$sourceAddresses,
$sourceNetwork
)->digest();
$genericDigest = CloudPublicNetworkClaimSetIdentity::fromLedger(
101,
$sourceClaimsByFamily,
$sourceAddresses,
$sourceNetwork
)->digest();
$assert(hash_equals($activeDigest, $genericDigest),
'Active and transition claim-set digest algorithms drifted.');
$admin = CloudPublicNetworkTransitionCommand::adminExact(
1,
99,
'admin-network-0001',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.20/24',
]]
);
$reservationOperation = Capsule::table('cloud_resource_reservations')
->where('id', 101)->value('operation_id');
$dispatch = CloudPublicNetworkTransitionWorkflow::begin($admin);
$assert(!$dispatch->replayed()
&& $dispatch->target()->address(4) === '8.8.9.20/24'
&& $dispatch->target()->address(6)
=== '2404:c140:156:3a::1000/64',
'Same-attachment IPv4 transition did not preserve IPv6.');
$transition = Capsule::table('cloud_public_network_transitions')
->where('id', $dispatch->transitionId())->first();
$legs = Capsule::table('cloud_public_network_transition_ips')
->where('transition_id', $dispatch->transitionId())
->orderBy('address_family')->get();
$targetClaim = Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 101)->where('address_family', 4)
->whereNull('active_claim')->first();
$targetIp = Capsule::table('cloud_public_ips')->where('id', 201)->first();
$job = Capsule::table('cloud_jobs')->where('id', $dispatch->jobId())->first();
$payload = CloudSecrets::decrypt((string) $job->sealed_payload, 'job-payload');
$assert($transition !== null && $transition->state === 'queued'
&& $transition->source_network_attachment_id === 1
&& $transition->target_network_attachment_id === 1
&& $transition->source_claim_set_sha256 !== str_repeat('0', 64)
&& $transition->target_claim_set_sha256 !== str_repeat('0', 64)
&& $legs->count() === 2
&& (int) $legs[0]->changed === 1
&& (int) $legs[1]->changed === 0
&& $targetClaim !== null
&& (int) $targetClaim->claim_generation === 2
&& $targetClaim->active_claim === null
&& $targetClaim->state === 'reserved'
&& (int) $targetIp->reservation_ip_claim_id === (int) $targetClaim->id
&& $targetIp->state === 'reserved'
&& (int) $job->public_network_transition_id
=== $dispatch->transitionId()
&& $job->kind === 'network_change'
&& ($payload['body']['public_network'] ?? null)
=== $dispatch->target()->toArray()
&& array_key_exists('price_cents', $payload)
&& $payload['price_cents'] === null
&& $payload['charged_amount'] === null
&& Capsule::table('cloud_resource_reservations')->where('id', 101)
->value('operation_id') === $reservationOperation
&& !isset($payload['source_public_ip_id']),
'Transition, target claim, IP fence, or complete job contract is invalid.');
Capsule::table('cloud_public_ip_pools')->where('id', 13)
->update(['state' => 'disabled']);
$replay = CloudPublicNetworkTransitionWorkflow::begin($admin);
$assert($replay->replayed()
&& $replay->transitionId() === $dispatch->transitionId()
&& Capsule::table('cloud_jobs')->count() === 1
&& Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 101)->count() === 3,
'Exact replay consulted mutable target catalog or duplicated resources.');
Capsule::table('cloud_hosts')->where('id', 1)
->update(['enabled' => 0]);
Capsule::table('cloud_instances')->where('id', 1)->update([
'status' => 'suspended',
'service_status' => 'expired_grace',
'spec_json' => '{}',
]);
$mutableReplay = CloudPublicNetworkTransitionWorkflow::begin($admin);
$assert($mutableReplay->replayed()
&& $mutableReplay->transitionId() === $dispatch->transitionId()
&& Capsule::table('cloud_jobs')->count() === 1,
'Exact replay was coupled to mutable host or instance eligibility.');
Capsule::table('cloud_hosts')->where('id', 1)
->update(['enabled' => 1]);
Capsule::table('cloud_instances')->where('id', 1)->update([
'status' => 'active',
'service_status' => 'active',
'spec_json' => json_encode([
'managed' => true,
'os_source' => 'cloud_template',
'public_network' => $sourceSnapshot(
'8.8.8.10',
'2404:c140:156:3a::1000'
),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
]);
Capsule::table('cloud_instances')->where('id', 1)
->update(['host_id' => 2]);
$rejects(
static fn () => CloudPublicNetworkTransitionWorkflow::begin($admin),
'Exact replay accepted a drifted immutable host association.'
);
Capsule::table('cloud_instances')->where('id', 1)
->update(['host_id' => 1]);
Capsule::table('cloud_public_network_transitions')
->where('id', $dispatch->transitionId())->update([
'state' => 'succeeded',
'effect_resolution' => 'applied',
]);
Capsule::table('cloud_instances')->where('id', 1)
->update(['host_id' => 2]);
$rejects(
static fn () => CloudPublicNetworkTransitionWorkflow::begin($admin),
'Corrupt terminal-shaped replay bypassed the active host fence.'
);
Capsule::table('cloud_instances')->where('id', 1)
->update(['host_id' => 1]);
Capsule::table('cloud_public_network_transitions')
->where('id', $dispatch->transitionId())->update([
'state' => 'queued',
'effect_resolution' => 'not_applicable',
]);
Capsule::table('cloud_public_ip_pools')->where('id', 13)
->update(['state' => 'active']);
$beforeActiveTransition = [
'transitions' => Capsule::table(
'cloud_public_network_transitions'
)->count(),
'jobs' => Capsule::table('cloud_jobs')->count(),
'claims' => Capsule::table(
'cloud_resource_reservation_ips'
)->count(),
'target_state' => Capsule::table('cloud_public_ips')
->where('id', 201)->value('state'),
];
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
1,
99,
'admin-network-active-transition-0001',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.20/24',
]]
)
), 'A second request bypassed an unrelated active transition.');
$assert($beforeActiveTransition === [
'transitions' => Capsule::table(
'cloud_public_network_transitions'
)->count(),
'jobs' => Capsule::table('cloud_jobs')->count(),
'claims' => Capsule::table(
'cloud_resource_reservation_ips'
)->count(),
'target_state' => Capsule::table('cloud_public_ips')
->where('id', 201)->value('state'),
], 'Active-transition admission rejection left durable writes.');
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
1,
99,
'admin-network-0001',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.21/24',
]]
)
), 'Same idempotency key accepted a different target.');
$beforeSameKey = Capsule::table('cloud_public_network_transitions')->count();
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
4,
99,
'admin-network-0001',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'One actor reused a transition idempotency key on another instance.');
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeSameKey
&& Capsule::table('cloud_public_ips')->where('id', 203)
->value('state') === 'available',
'Cross-instance idempotency conflict left side effects.');
$beforeTransitions = Capsule::table('cloud_public_network_transitions')
->count();
$beforeJobs = Capsule::table('cloud_jobs')->count();
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
2,
99,
'admin-network-0002',
[4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.30/24',
]]
)
), 'Cross-attachment single-family transition was accepted.');
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeTransitions
&& Capsule::table('cloud_jobs')->count() === $beforeJobs
&& Capsule::table('cloud_public_ips')->where('id', 301)
->value('state') === 'available',
'Rejected cross-attachment transition left side effects.');
$beforeDriftTransitions = Capsule::table(
'cloud_public_network_transitions'
)->count();
$beforeDriftJobs = Capsule::table('cloud_jobs')->count();
Capsule::table('cloud_public_ip_pools')->whereIn('id', [21, 22])
->update(['observed_revision' => 2]);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
2,
99,
'admin-network-revision-drift',
[
4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.30/24',
],
6 => [
'pool_key' => str_repeat('f', 32),
'address_cidr' => '2404:c140:156:3c::1000/64',
],
]
)
), 'A pool with observed revision ahead of desired was accepted.');
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeDriftTransitions
&& Capsule::table('cloud_jobs')->count() === $beforeDriftJobs
&& Capsule::table('cloud_public_ips')->where('id', 301)
->value('state') === 'available'
&& Capsule::table('cloud_public_ips')->where('id', 401)
->value('state') === 'available',
'Revision-drift rejection left transition, job, or IP writes.');
Capsule::table('cloud_public_ip_pools')->whereIn('id', [21, 22])
->update(['observed_revision' => 1]);
$validTargetPools = [
21 => [
'cidr' => '9.9.9.0/24', 'gateway' => '9.9.9.1',
'gateway_on_link' => 0, 'guest_prefix_length' => 24,
'dns_servers_json' => '["1.1.1.1"]',
'reserved_ips_json' => '[]',
'allocation_start' => null, 'allocation_end' => null,
'allocation_cursor' => null, 'max_allocations' => 0,
],
22 => [
'cidr' => '2404:c140:156:3c::/64',
'gateway' => '2404:c140:156::1', 'gateway_on_link' => 1,
'guest_prefix_length' => 64,
'dns_servers_json' => '["2404:c140:156:3c::1001"]',
'reserved_ips_json' => '["2404:c140:156:3c::1002"]',
'allocation_start' => '2404:c140:156:3c::1000',
'allocation_end' => '2404:c140:156:3c::10ff',
'allocation_cursor' => '2404:c140:156:3c::1000',
'max_allocations' => 64,
],
];
$corruptPoolCases = [
'guest prefix drift' => [22, ['guest_prefix_length' => 65]],
'IPv4 on-link gateway' => [21, ['gateway_on_link' => 1]],
'IPv4 invalid boolean gateway flag' => [21, [
'gateway_on_link' => 2,
]],
'IPv4 /23 prefix' => [21, [
'cidr' => '9.9.8.0/23', 'guest_prefix_length' => 23,
]],
'IPv6 /121 prefix' => [22, [
'cidr' => '2404:c140:156:3c::/121',
'guest_prefix_length' => 121,
]],
'private DNS' => [21, [
'dns_servers_json' => '["10.0.0.1"]',
]],
'duplicate DNS' => [21, [
'dns_servers_json' => '["1.1.1.1","1.1.1.1"]',
]],
'empty DNS' => [21, ['dns_servers_json' => '[]']],
'five DNS addresses' => [21, [
'dns_servers_json' => '["1.1.1.1","8.8.8.8",'
. '"9.9.9.9","2606:4700:4700::1111",'
. '"2001:4860:4860::8888"]',
]],
'private reserved address' => [21, [
'reserved_ips_json' => '["10.0.0.1"]',
]],
'duplicate reserved address' => [21, [
'reserved_ips_json' => '["9.9.9.2","9.9.9.2"]',
]],
'off-pool reserved address' => [21, [
'reserved_ips_json' => '["8.8.8.2"]',
]],
'network reserved address' => [21, [
'reserved_ips_json' => '["9.9.9.0"]',
]],
'off-prefix gateway without on-link' => [22, [
'gateway_on_link' => 0,
]],
'IPv6 invalid boolean gateway flag' => [22, [
'gateway_on_link' => 'false',
]],
'zero sparse allocation limit' => [22, [
'max_allocations' => 0,
]],
'excess sparse allocation limit' => [22, [
'max_allocations' => 65536,
]],
'insufficient sparse range' => [22, [
'allocation_end' => '2404:c140:156:3c::1002',
'max_allocations' => 2,
]],
'cursor outside sparse range' => [22, [
'allocation_cursor' => '2404:c140:156:3c::1100',
]],
];
$beforeCorruptClaims = Capsule::table(
'cloud_resource_reservation_ips'
)->count();
$beforeCorruptIps = Capsule::table('cloud_public_ips')->count();
$beforeCorruptInvoices = Capsule::table('cloud_invoices')->count();
$beforeCorruptMoney = (string) Capsule::table('user')->where('id', 10)
->value('money');
$caseNumber = 0;
foreach ($corruptPoolCases as $label => [$poolId, $corruption]) {
$caseNumber++;
Capsule::table('cloud_public_ip_pools')->where('id', $poolId)
->update($corruption);
$requestKey = sprintf('admin-network-corrupt-%02d', $caseNumber);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
2,
99,
$requestKey,
[
4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.30/24',
],
6 => [
'pool_key' => str_repeat('f', 32),
'address_cidr' => '2404:c140:156:3c::1000/64',
],
]
)
), 'A corrupt public-IP pool entered transition writes: ' . $label);
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeDriftTransitions
&& Capsule::table('cloud_jobs')->count() === $beforeDriftJobs
&& Capsule::table('cloud_resource_reservation_ips')->count()
=== $beforeCorruptClaims
&& Capsule::table('cloud_public_ips')->count()
=== $beforeCorruptIps
&& Capsule::table('cloud_invoices')->count()
=== $beforeCorruptInvoices
&& (string) Capsule::table('user')->where('id', 10)
->value('money') === $beforeCorruptMoney
&& Capsule::table('cloud_public_ips')->where('id', 301)
->value('state') === 'available'
&& Capsule::table('cloud_public_ips')->where('id', 401)
->value('state') === 'available',
'Corrupt-pool rejection left durable writes: ' . $label);
Capsule::table('cloud_public_ip_pools')->where('id', $poolId)
->update($validTargetPools[$poolId]);
}
CloudPanelUsageService::$managementAddress =
'2404:c140:156:3c::1003';
$beforeManagementTransitions = Capsule::table(
'cloud_public_network_transitions'
)->count();
$beforeManagementJobs = Capsule::table('cloud_jobs')->count();
$beforeManagementClaims = Capsule::table(
'cloud_resource_reservation_ips'
)->count();
$beforeManagementIps = Capsule::table('cloud_public_ips')->count();
$beforeManagementInvoices = Capsule::table('cloud_invoices')->count();
$beforeManagementMoney = (string) Capsule::table('user')
->where('id', 10)->value('money');
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
2,
99,
'admin-network-management-blocked',
[
4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.30/24',
],
6 => [
'pool_key' => str_repeat('f', 32),
'address_cidr' => '2404:c140:156:3c::1003/64',
],
]
)
), 'The host management address entered sparse transition writes.');
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeManagementTransitions
&& Capsule::table('cloud_jobs')->count() === $beforeManagementJobs
&& Capsule::table('cloud_resource_reservation_ips')->count()
=== $beforeManagementClaims
&& Capsule::table('cloud_public_ips')->count()
=== $beforeManagementIps
&& Capsule::table('cloud_invoices')->count()
=== $beforeManagementInvoices
&& (string) Capsule::table('user')->where('id', 10)
->value('money') === $beforeManagementMoney
&& Capsule::table('cloud_public_ips')->where('id', 403)
->value('state') === 'available',
'Management-address rejection left durable writes.');
CloudPanelUsageService::$managementAddress = null;
Capsule::table('cloud_host_network_attachments')->where('id', 1)
->update(['state' => 'draining']);
$cross = CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
2,
99,
'admin-network-0003',
[
4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.30/24',
],
6 => [
'pool_key' => str_repeat('f', 32),
'address_cidr' => '2404:c140:156:3c::1000/64',
],
]
)
);
$assert($cross->target()->toArray()['network_selector'] === 'bridge:br1'
&& $cross->target()->address(4) === '9.9.9.30/24'
&& $cross->target()->address(6)
=== '2404:c140:156:3c::1000/64',
'Draining-source cross-attachment dual-stack target was not prepared.');
Capsule::table('cloud_host_network_attachments')->where('id', 1)
->update(['state' => 'active']);
$blocker = new CloudJob();
$blocker->operation_id = str_repeat('7', 32);
$blocker->request_idempotency_key = 'other-instance-job-0004';
$blocker->request_fingerprint = hash('sha256', 'blocking-job');
$blocker->instance_id = 4;
$blocker->user_id = 10;
$blocker->host_id = 1;
$blocker->kind = 'restart';
$blocker->execution_mode = 'agent';
$blocker->sealed_payload = CloudSecrets::encrypt([], 'job-payload');
$blocker->lease_until = 0;
$blocker->available_at = $now;
$blocker->created_at = $blocker->updated_at = $now;
$blocker->save();
$beforeTransitions = Capsule::table('cloud_public_network_transitions')
->count();
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
4,
99,
'admin-network-0004',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'A blocking instance task did not fence network transition begin.');
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeTransitions
&& Capsule::table('cloud_public_ips')->where('id', 203)
->value('state') === 'available',
'Blocking task rejection left transition side effects.');
$blocker->delete();
Capsule::table('cloud_instance_migrations')->insert([
'id' => 1,
'instance_id' => 5,
'state' => 'preparing_source',
]);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
5,
99,
'admin-network-0005',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'An open maintenance migration did not fence network transition begin.');
Capsule::table('cloud_instance_migrations')->delete();
Capsule::table('cloud_backup_recoveries')->insert([
'id' => 1,
'instance_id' => 11,
'state' => 'uncertain',
]);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
11,
99,
'admin-network-0011',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'An open backup recovery did not fence network transition begin.');
Capsule::table('cloud_backup_recoveries')->delete();
Capsule::table('cloud_instances')->where('id', 6)
->update(['expires_at' => $now - 1]);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
6,
99,
'admin-network-0006',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'An expired instance entered network transition begin.');
Capsule::table('cloud_instances')->where('id', 9)
->update(['status' => 'stopped']);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
9,
99,
'admin-network-0009',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'A non-active lifecycle instance entered network transition begin.');
Capsule::table('cloud_instances')->where('id', 7)->update([
'spec_json' => json_encode([
'managed' => false,
'os_source' => 'cloud_template',
'public_network' => $sourceSnapshot(
'8.8.8.16',
'2404:c140:156:3a::1006'
),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
]);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
7,
99,
'admin-network-0007',
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.22/24',
]]
)
), 'An unmanaged instance entered transition writes.');
$assert(Capsule::table('cloud_public_ips')->where('id', 203)
->value('state') === 'available',
'Managed-cloud-template gate fenced an address despite rejection.');
$beforeTransitions = Capsule::table('cloud_public_network_transitions')
->count();
$beforeJobs = Capsule::table('cloud_jobs')->count();
$beforeIps = Capsule::table('cloud_public_ips')->count();
// Establish the sparse-capacity precondition explicitly instead of
// depending on later readers inferring it from the cross-attachment case:
// pool 22 already owns one reserved slot while address 403 is a distinct,
// valid, pre-materialized available address.
Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([
'max_allocations' => 1,
]);
$assert((int) Capsule::table('cloud_public_ip_pools')->where('id', 22)
->value('max_allocations') === 1
&& Capsule::table('cloud_public_ips')->where('id', 401)
->value('state') === 'reserved'
&& Capsule::table('cloud_public_ips')->where('id', 403)
->value('state') === 'available',
'Sparse-capacity fixture did not establish one occupied slot and one '
. 'separate available address.');
$attemptSparse = static function (string $requestKey,
string $targetIpv6): void {
CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
10,
99,
$requestKey,
[
4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.31/24',
],
6 => [
'pool_key' => str_repeat('f', 32),
'address_cidr' => $targetIpv6,
],
]
)
);
};
$rejects(
static fn () => $attemptSparse(
'admin-network-ipv6-full',
'2404:c140:156:3c::1003/64'
),
'A full sparse pool reused a materialized available row.'
);
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeTransitions
&& Capsule::table('cloud_jobs')->count() === $beforeJobs
&& Capsule::table('cloud_public_ips')->count() === $beforeIps,
'Full sparse pool rejection left durable writes.');
Capsule::table('cloud_public_ip_pools')->where('id', 22)->update([
'max_allocations' => 64,
]);
foreach ([
'admin-network-ipv6-dns' => '2404:c140:156:3c::1001/64',
'admin-network-ipv6-reserved' => '2404:c140:156:3c::1002/64',
'admin-network-ipv6-range' => '2404:c140:156:3c::1100/64',
] as $requestKey => $targetIpv6) {
$rejects(
static fn () => $attemptSparse($requestKey, $targetIpv6),
'A blocked or out-of-range sparse IPv6 target was accepted.'
);
}
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeTransitions
&& Capsule::table('cloud_jobs')->count() === $beforeJobs
&& Capsule::table('cloud_public_ips')->count() === $beforeIps
&& Capsule::table('cloud_public_ips')->where('id', 302)
->value('state') === 'available',
'Rejected sparse IPv6 input left target, job, or transition writes.');
$sparse = CloudPublicNetworkTransitionWorkflow::begin(
CloudPublicNetworkTransitionCommand::adminExact(
8,
99,
'admin-network-0008',
[
4 => [
'pool_key' => str_repeat('e', 32),
'address_cidr' => '9.9.9.31/24',
],
6 => [
'pool_key' => str_repeat('f', 32),
'address_cidr' => '2404:c140:156:3c::10ff/64',
],
]
)
);
$sparseIp = Capsule::table('cloud_public_ips')
->where('address', '2404:c140:156:3c::10ff')->first();
$assert($sparse->target()->address(6)
=== '2404:c140:156:3c::10ff/64'
&& $sparseIp !== null
&& (int) $sparseIp->public_ip_pool_id === 22
&& $sparseIp->state === 'reserved',
'Explicit sparse IPv6 target was not materialized and fenced.');
$paid = CloudPublicNetworkTransitionCommand::userPaidAutomatic(
3,
10,
'tenant-network-0001',
'5.00'
);
Capsule::table('user')->where('id', 10)->update(['enable' => 0]);
$beforeTransitions = Capsule::table('cloud_public_network_transitions')
->count();
$beforeInvoices = Capsule::table('cloud_invoices')->count();
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
$paid
), 'A disabled account entered a paid public-network transition.');
$assert(Capsule::table('cloud_public_network_transitions')->count()
=== $beforeTransitions
&& Capsule::table('cloud_invoices')->count() === $beforeInvoices
&& (string) Capsule::table('user')->where('id', 10)
->value('money') === '20.00',
'Disabled-account rejection left financial or transition side effects.');
Capsule::table('user')->where('id', 10)->update(['enable' => 1]);
$paidDispatch = CloudPublicNetworkTransitionWorkflow::begin($paid);
$paidTransition = Capsule::table('cloud_public_network_transitions')
->where('id', $paidDispatch->transitionId())->first();
$invoice = Capsule::table('cloud_invoices')
->where('id', $paidTransition->invoice_id)->first();
$paidJob = Capsule::table('cloud_jobs')
->where('id', $paidDispatch->jobId())->first();
$paidPayload = CloudSecrets::decrypt(
(string) $paidJob->sealed_payload,
'job-payload'
);
$assert((string) Capsule::table('user')->where('id', 10)->value('money')
=== '15.00'
&& $invoice !== null && $invoice->status === 'paid'
&& $invoice->payment_reference ===
'public-network-transition-' . $paid->transitionKey()
&& (int) Capsule::table('cloud_jobs')
->where('id', $paidDispatch->jobId())->value('invoice_id')
=== (int) $invoice->id,
'Paid transition was not charged and associated atomically.');
$assert(($paidPayload['price_cents'] ?? null) === 500
&& ($paidPayload['charged_amount'] ?? null) === '5.00'
&& ($paidPayload['currency'] ?? null) === 'USD',
'Paid transition did not freeze its exact settlement contract.');
Capsule::table('configurations')->where('name', 'cloud_ip_change_price')
->update(['value' => '9.00']);
$paidReplay = CloudPublicNetworkTransitionWorkflow::begin($paid);
$assert($paidReplay->replayed()
&& (string) Capsule::table('user')->where('id', 10)->value('money')
=== '15.00'
&& Capsule::table('cloud_invoices')->count() === 1,
'Paid replay consulted mutable price or duplicated settlement.');
Capsule::table('configurations')->where('name', 'cloud_ip_change_price')
->update(['value' => '5.00']);
Capsule::table('cloud_invoices')->where('id', $invoice->id)
->update(['amount' => '4.00']);
$rejects(static fn () => CloudPublicNetworkTransitionWorkflow::begin(
$paid
), 'Paid replay accepted a corrupted invoice association.');
Capsule::table('cloud_invoices')->where('id', $invoice->id)
->update(['amount' => '5.00']);
// The private reservation seam must share begin()'s one transaction. A
// failure at the final job insert rolls back wallet, invoice, transition,
// target claim and address fencing as one unit.
$rollbackCommand = CloudPublicNetworkTransitionCommand::userPaidAutomatic(
12,
10,
'tenant-network-rollback-0012',
'5.00'
);
$rollbackBefore = [
'money' => (string) Capsule::table('user')->where('id', 10)
->value('money'),
'invoices' => Capsule::table('cloud_invoices')->count(),
'transitions' => Capsule::table(
'cloud_public_network_transitions'
)->count(),
'legs' => Capsule::table(
'cloud_public_network_transition_ips'
)->count(),
'jobs' => Capsule::table('cloud_jobs')->count(),
'claims' => Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 112)->count(),
];
Capsule::connection()->statement(
'CREATE TRIGGER fail_transition_job_insert '
. 'BEFORE INSERT ON cloud_jobs '
. "WHEN NEW.request_idempotency_key = "
. "'tenant-network-rollback-0012' "
. "BEGIN SELECT RAISE(ABORT, 'fault injection'); END"
);
$rollbackRejected = false;
try {
CloudPublicNetworkTransitionWorkflow::begin($rollbackCommand);
} catch (Throwable) {
$rollbackRejected = true;
}
Capsule::connection()->statement('DROP TRIGGER fail_transition_job_insert');
$assert($rollbackRejected
&& (string) Capsule::table('user')->where('id', 10)->value('money')
=== $rollbackBefore['money']
&& Capsule::table('cloud_invoices')->count()
=== $rollbackBefore['invoices']
&& Capsule::table('cloud_public_network_transitions')->count()
=== $rollbackBefore['transitions']
&& Capsule::table('cloud_public_network_transition_ips')->count()
=== $rollbackBefore['legs']
&& Capsule::table('cloud_jobs')->count() === $rollbackBefore['jobs']
&& Capsule::table('cloud_resource_reservation_ips')
->where('reservation_id', 112)->count()
=== $rollbackBefore['claims']
&& Capsule::table('cloud_public_ips')->whereIn('id', [203, 204])
->where('state', 'available')
->whereNull('reservation_id')
->whereNull('reservation_ip_claim_id')
->whereNull('instance_id')
->whereNull('operation_id')->count() === 2,
'Extracted reservation seam committed a partial transition.');
$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',
]]
);
$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.');
// The internal batch caller may replay only the exact locked parent. A
// drifted parent FK must fail even when the frozen request fingerprint is
// otherwise unchanged.
$seedJob = CloudJob::find($dispatch->jobId());
$parentA = $seedJob->replicate();
$parentA->operation_id = str_repeat('d', 32);
$parentA->request_idempotency_key = 'pool-parent-replay-a-0001';
$parentA->request_fingerprint = hash('sha256', 'parent-a');
$parentA->parent_job_id = null;
$parentA->instance_id = null;
$parentA->host_id = null;
$parentA->public_network_transition_id = null;
$parentA->kind = 'public_ip_pool_replacement_batch';
$parentA->execution_mode = 'local';
$parentA->created_at = $parentA->updated_at = time();
$parentA->save();
$parentB = $parentA->replicate();
$parentB->operation_id = str_repeat('e', 32);
$parentB->request_idempotency_key = 'pool-parent-replay-b-0001';
$parentB->request_fingerprint = hash('sha256', 'parent-b');
$parentB->created_at = $parentB->updated_at = time();
$parentB->save();
$batchReplayCommand = CloudPublicNetworkTransitionCommand::poolReplacement(
1,
99,
'admin-network-0001',
(int) $parentA->id,
77,
[4 => [
'pool_key' => str_repeat('c', 32),
'address_cidr' => '8.8.9.20/24',
]]
);
Capsule::table('cloud_public_network_transitions')
->where('id', $dispatch->transitionId())->update([
'kind' => 'pool_replacement',
'pool_replacement_batch_item_id' => 77,
]);
Capsule::table('cloud_jobs')->where('id', $dispatch->jobId())->update([
'parent_job_id' => (int) $parentA->id,
'request_fingerprint' => $batchReplayCommand->fingerprint(),
]);
$reserve = new ReflectionMethod(
CloudPublicNetworkTransitionWorkflow::class,
'reserveTransitionLocked'
);
$invokeBatchReplay = static function () use (
$reserve,
$batchReplayCommand
) {
return Capsule::connection()->transaction(static function () use (
$reserve,
$batchReplayCommand
) {
$actor = \App\Models\User::where('id', 99)
->lockForUpdate()->first();
return $reserve->invoke(null, $batchReplayCommand, $actor);
});
};
$batchReplay = $invokeBatchReplay();
$assert($batchReplay->replayed()
&& $batchReplay->transitionId() === $dispatch->transitionId(),
'Exact batch parent replay did not return its frozen dispatch.');
Capsule::table('cloud_jobs')->where('id', $dispatch->jobId())
->update(['parent_job_id' => (int) $parentB->id]);
$rejects(
$invokeBatchReplay,
'Batch replay accepted a drifted parent job association.'
);
Capsule::table('cloud_jobs')->where('id', $dispatch->jobId())->update([
'parent_job_id' => null,
'request_fingerprint' => $admin->fingerprint(),
]);
Capsule::table('cloud_public_network_transitions')
->where('id', $dispatch->transitionId())->update([
'kind' => 'admin_manual',
'pool_replacement_batch_item_id' => null,
]);
CloudJob::whereIn('id', [(int) $parentA->id, (int) $parentB->id])
->delete();
echo "Public-network transition begin workflow tests passed.\n";
}