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/CloudPrivateCidrAllocatorTe...

244 lines
11 KiB
PHP

<?php
use App\Models\CloudPrivateCidrAllocatorConfig;
use App\Models\CloudPrivateCidrClaim;
use App\Models\CloudPrivateNetwork;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudPrivateCidrAllocator;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
// The contract portion is intentionally useful even on a checkout without a
// PHP runtime. The SQLite section below exercises canonicalisation,
// idempotency, overlap rejection, release/reuse and revision CAS when the
// project's normal PHP dependencies are available.
$root = dirname(__DIR__);
$schemaSource = file_get_contents($root . '/sql/cloud.sql');
$serviceSource = file_get_contents($root
. '/app/Services/Cloud/CloudPrivateCidrAllocator.php');
$modelSource = file_get_contents($root . '/app/Models/CloudPrivateNetwork.php');
$configModelSource = file_get_contents($root
. '/app/Models/CloudPrivateCidrAllocatorConfig.php');
$claimModelSource = file_get_contents($root
. '/app/Models/CloudPrivateCidrClaim.php');
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$assert(is_string($schemaSource)
&& str_contains($schemaSource,
'CREATE TABLE IF NOT EXISTS cloud_private_cidr_allocator_configs (')
&& str_contains($schemaSource,
'CREATE TABLE IF NOT EXISTS cloud_private_cidr_claims (')
&& str_contains($schemaSource,
'CREATE TABLE IF NOT EXISTS cloud_private_networks (')
&& str_contains($schemaSource,
'UNIQUE KEY cloud_private_network_active_cidr (active_cidr)')
&& str_contains($schemaSource,
'UNIQUE KEY cloud_private_cidr_claim_block (block_cidr)')
&& str_contains($schemaSource, 'requested_cidr VARCHAR(18)')
&& str_contains($schemaSource,
'KEY cloud_private_network_overlap (state, network_address, broadcast_address, id)')
&& str_contains($schemaSource,
"VALUES (1, '10.0.0.0/8', 24, 16, 24, 1, UNIX_TIMESTAMP())"),
'Global private CIDR schema lost its quantum claim, interval index or seed.');
$assert(is_string($serviceSource)
&& str_contains($serviceSource, 'claimCandidate')
&& str_contains($serviceSource, 'CloudPrivateCidrClaimConflict')
&& str_contains($serviceSource, '->transaction(')
&& str_contains($serviceSource, 'self::LIVE_STATES')
&& str_contains($serviceSource, '未知私网 CIDR 状态')
&& str_contains($serviceSource, 'compareAndSwapState')
&& str_contains($serviceSource, 'active_cidr')
&& str_contains($serviceSource, 'assertClaimLedger')
&& str_contains($serviceSource, 'self::normalizeCidr((string) $network->cidr, $prefix)')
&& str_contains($serviceSource,
"\$network->broadcast_address !== \$canonical['broadcast']")
&& str_contains($serviceSource,
"->orderBy('block_cidr')->lockForUpdate()->pluck('block_cidr')")
&& str_contains($serviceSource, 'CIDR 分配请求已经释放')
&& str_contains($serviceSource, 'isTransientConflict')
&& !str_contains($serviceSource, 'CloudPrivateCidrAllocatorLock')
&& !str_contains($serviceSource, "CloudPrivateCidrAllocatorConfig::where(\n 'id', self::CONFIG_ID\n )->lockForUpdate()"),
'CIDR allocation no longer uses a database transaction, overlap ledger and CAS.');
$assert(is_string($modelSource)
&& str_contains($modelSource, "protected \$table = 'cloud_private_networks';")
&& is_string($configModelSource)
&& str_contains($configModelSource,
"protected \$table = 'cloud_private_cidr_allocator_configs';")
&& is_string($claimModelSource)
&& str_contains($claimModelSource,
"protected \$table = 'cloud_private_cidr_claims';"),
'Private CIDR Eloquent boundaries are missing.');
if (!is_file($root . '/vendor/autoload.php')) {
echo "Cloud private CIDR schema and source contracts passed (runtime skipped).\n";
return;
}
require $root . '/vendor/autoload.php';
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_private_cidr_allocator_configs', static function (Blueprint $table): void {
$table->unsignedTinyInteger('id')->primary();
$table->string('pool_cidr', 18);
$table->unsignedTinyInteger('quantum_prefix_length');
$table->unsignedTinyInteger('min_prefix_length');
$table->unsignedTinyInteger('max_prefix_length');
$table->unsignedBigInteger('revision');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_private_cidr_claims', static function (Blueprint $table): void {
$table->increments('id');
$table->string('block_cidr', 18)->unique();
$table->string('allocation_key', 32);
$table->unsignedBigInteger('created_at');
$table->index(['allocation_key', 'block_cidr']);
});
$schema->create('cloud_private_networks', static function (Blueprint $table): void {
$table->increments('id');
$table->string('vpc_key', 32)->unique();
$table->string('allocation_key', 32)->unique();
$table->unsignedInteger('user_id');
$table->unsignedInteger('region_id');
$table->string('cidr', 18);
$table->string('requested_cidr', 18)->nullable();
$table->string('active_cidr', 18)->nullable()->unique();
$table->unsignedBigInteger('network_address');
$table->unsignedBigInteger('broadcast_address');
$table->unsignedTinyInteger('prefix_length');
$table->string('state', 16);
$table->unsignedBigInteger('revision');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unsignedBigInteger('released_at')->nullable();
});
$config = new CloudPrivateCidrAllocatorConfig();
$config->id = 1;
$config->pool_cidr = '10.0.0.0/8';
$config->quantum_prefix_length = 24;
$config->min_prefix_length = 16;
$config->max_prefix_length = 24;
$config->revision = 1;
$config->updated_at = time();
$config->save();
$key = str_repeat('a', 32);
$vpc = str_repeat('b', 32);
$first = CloudPrivateCidrAllocator::allocate($key, 7, 1, null, 24, $vpc);
$assert($first->cidr === '10.0.0.0/24'
&& $first->active_cidr === $first->cidr, 'First global CIDR was not canonical.');
$assert(CloudPrivateCidrClaim::where('allocation_key', $key)->count() === 1,
'The active network did not claim its /24 quantum.');
$second = CloudPrivateCidrAllocator::allocate(str_repeat('c', 32), 8, 2,
null, 24, str_repeat('d', 32));
$assert($second->cidr === '10.0.1.0/24',
'Automatic CIDR allocation did not advance to the next aligned block.');
$retry = CloudPrivateCidrAllocator::allocate($key, 7, 1, null, 24, $vpc);
$assert((int) $retry->id === (int) $first->id,
'A repeated allocation key created a second private network.');
$expectConflict = static function (callable $operation, string $message) use ($assert): void {
try {
$operation();
} catch (CloudError $error) {
$assert($error->httpStatus === 409, $message . ' returned the wrong status.');
return;
}
throw new RuntimeException($message);
};
$expectConflict(static fn () => CloudPrivateCidrAllocator::allocate(
str_repeat('e', 32), 9, 3, '10.0.0.1/24', 24, str_repeat('f', 32)
), 'Overlapping CIDR was accepted.');
$expectConflict(static fn () => CloudPrivateCidrAllocator::allocate(
$key, 99, 1, null, 24, $vpc
), 'Allocation-key parameter drift was accepted.');
$released = CloudPrivateCidrAllocator::release($key, 1);
$assert($released->state === 'released' && $released->active_cidr === null
&& (int) $released->revision === 2,
'Release did not clear the active claim and advance its revision.');
$assert(CloudPrivateCidrClaim::where('allocation_key', $key)->count() === 0,
'Release did not remove the reusable quantum claim.');
$expectConflict(static fn () => CloudPrivateCidrAllocator::allocate(
$key, 7, 1, null, 24, $vpc
), 'A released allocation key resurrected an unclaimed network row.');
$reused = CloudPrivateCidrAllocator::allocate(str_repeat('1', 32), 10, 1,
'10.0.0.0/24', 24, str_repeat('2', 32));
$assert($reused->cidr === '10.0.0.0/24',
'A released CIDR was not safely reusable under quantum claims.');
$expectConflict(static fn () => CloudPrivateCidrAllocator::release($key, 1),
'A stale revision released a CIDR a second time.');
$brokenKey = str_repeat('3', 32);
$broken = CloudPrivateCidrAllocator::allocate(
$brokenKey, 11, 1, null, 24, str_repeat('4', 32)
);
CloudPrivateCidrClaim::where('allocation_key', $brokenKey)->delete();
try {
CloudPrivateCidrAllocator::allocate(
$brokenKey, 11, 1, null, 24, str_repeat('4', 32)
);
throw new RuntimeException(
'An idempotent retry returned a live CIDR with a missing quantum claim.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 503,
'Damaged idempotent CIDR retry returned the wrong status.');
}
try {
CloudPrivateCidrAllocator::release($brokenKey, (int) $broken->revision);
throw new RuntimeException('A CIDR with a missing quantum claim was released.');
} catch (CloudError $error) {
$assert($error->httpStatus === 503,
'A damaged CIDR claim ledger returned the wrong status.');
}
$assert(CloudPrivateNetwork::where('allocation_key', $brokenKey)->value('state')
=== 'active',
'A damaged CIDR claim ledger was partially released.');
$tamperedKey = str_repeat('5', 32);
$tampered = CloudPrivateCidrAllocator::allocate(
$tamperedKey, 12, 1, null, 24, str_repeat('6', 32)
);
CloudPrivateNetwork::where('allocation_key', $tamperedKey)->update([
// Keep cidr/network_address and the matching /24 claim unchanged. The
// old release check ignored this interval-field drift and would have
// made a corrupt allocation reusable.
'broadcast_address' => (int) $tampered->broadcast_address - 1,
]);
try {
CloudPrivateCidrAllocator::allocate(
$tamperedKey, 12, 1, null, 24, str_repeat('6', 32)
);
throw new RuntimeException(
'An idempotent retry returned a CIDR with tampered interval metadata.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 503,
'Tampered idempotent CIDR retry returned the wrong status.');
}
try {
CloudPrivateCidrAllocator::release($tamperedKey, (int) $tampered->revision);
throw new RuntimeException('A CIDR with tampered interval metadata was released.');
} catch (CloudError $error) {
$assert($error->httpStatus === 503,
'Tampered CIDR interval metadata returned the wrong status.');
}
$assert(CloudPrivateNetwork::where('allocation_key', $tamperedKey)->value('state')
=== 'active'
&& CloudPrivateCidrClaim::where('allocation_key', $tamperedKey)->count() === 1,
'Tampered CIDR metadata partially released its network or exact claim.');
$normalized = CloudPrivateCidrAllocator::normalize('10.2.3.4/16', 16);
$assert($normalized['cidr'] === '10.2.0.0/16'
&& $normalized['broadcast_address'] === '10.2.255.255',
'CIDR canonicalisation or broadcast calculation is incorrect.');
echo "Cloud private CIDR allocation schema, overlap, idempotency, release and CAS tests passed.\n";