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

278 lines
11 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudPublicNetworkTransitionCommand;
use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$method = static function (string $contents, string $start, string $end) use (
$assert
): string {
$offset = strpos($contents, $start);
$limit = $offset === false ? false : strpos($contents, $end, $offset + 1);
$assert($offset !== false && $limit !== false && $limit > $offset,
'Workflow method source is missing: ' . $start);
return substr($contents, $offset, $limit - $offset);
};
$root = dirname(__DIR__);
$source = file_get_contents(
$root . '/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php'
);
$billing = file_get_contents(
$root . '/app/Services/Cloud/CloudIpChangeBillingService.php'
);
$activeIdentity = file_get_contents(
$root . '/app/Services/Cloud/CloudActivePublicNetworkClaimSet.php'
);
$worker = file_get_contents(
$root . '/app/Services/Cloud/CloudWorkerService.php'
);
$recovery = file_get_contents(
$root . '/app/Services/Cloud/CloudOperationRecoveryService.php'
);
$tenantController = file_get_contents(
$root . '/app/Controllers/CloudApiController.php'
);
$adminController = file_get_contents(
$root . '/app/Controllers/CloudAdminInstanceController.php'
);
$assert(is_string($source) && is_string($billing)
&& is_string($activeIdentity) && is_string($worker)
&& is_string($recovery) && is_string($tenantController)
&& is_string($adminController), 'Transition workflow sources are missing.');
$workflow = new ReflectionClass(CloudPublicNetworkTransitionWorkflow::class);
$public = array_values(array_map(
static fn (ReflectionMethod $method): string => $method->getName(),
array_filter(
$workflow->getMethods(ReflectionMethod::IS_PUBLIC),
static fn (ReflectionMethod $method): bool =>
$method->getDeclaringClass()->getName()
=== CloudPublicNetworkTransitionWorkflow::class
)
));
$assert($workflow->isFinal() && $public === [
'begin',
'beginPoolReplacementBatch',
'markDispatched',
'markJobUncertain',
'recordEvidence',
'finishJobLocked',
'publishPreparedLocked',
'retryPendingFinalization',
], 'Stage 4 transition seam drifted.');
$command = new ReflectionClass(CloudPublicNetworkTransitionCommand::class);
foreach (['userPaidAutomatic', 'adminExact', 'poolReplacement'] as $factory) {
$assert($command->hasMethod($factory)
&& $command->getMethod($factory)->isStatic(),
'Transition command factory is missing: ' . $factory);
}
$begin = $method(
$source,
'public static function begin(',
'public static function beginPoolReplacementBatch('
);
$batchBegin = $method(
$source,
'public static function beginPoolReplacementBatch(',
'private static function reserveTransitionLocked('
);
$reserve = $method(
$source,
'private static function reserveTransitionLocked(',
'private static function freezeTransitionLocked('
);
$ordered = static function (string $body, array $needles) use ($assert): void {
$cursor = -1;
foreach ($needles as $needle) {
$position = strpos($body, $needle);
$assert($position !== false && $position > $cursor,
'Transition lock order drifted at: ' . $needle);
$cursor = $position;
}
};
$ordered($begin, [
"User::where('id', \$command->actorUserId())",
'self::reserveTransitionLocked($command, $actorUser)',
]);
$assert(substr_count($begin, 'transaction(') === 1
&& !str_contains($reserve, 'transaction(')
&& !str_contains($batchBegin, 'transaction(')
&& !str_contains($batchBegin, 'lockForUpdate(')
&& !preg_match('/::(?:find|where|whereIn)\(/', $batchBegin),
'Reservation seam introduced a nested transaction.');
$assert(str_contains($batchBegin,
'CloudPublicNetworkTransitionBatchPlan $plan')
&& str_contains($batchBegin, '$item->state = \'queued\'')
&& str_contains($batchBegin, '$item->child_job_id = $dispatch->jobId()'),
'Batch transition seam no longer consumes only a caller-locked plan.');
$ordered($reserve, [
'$jobHint = CloudJob::where(',
'$existingParent = CloudJob::where(',
'$existingJob = CloudJob::where(',
'$instance = CloudInstance::where(',
'[$replayHost] = self::lockHostBoundaryLocked(',
'$existing = CloudPublicNetworkTransition::where(',
]);
$assert(str_contains($source,
'(int) $parent->id !== (int) $command->parentJobId()')
&& str_contains($source,
'(int) ($job->parent_job_id ?? 0)')
&& str_contains($source,
'!== (int) $command->parentJobId()'),
'Batch replay no longer binds the locked parent identity.');
$ordered($reserve, [
'$priorJob = CloudJob::where(',
'$instance = CloudInstance::where(',
'[$host, $agent] = self::lockHostBoundaryLocked(',
'$active = CloudPublicNetworkTransition::where(',
'$resourcePool = CloudResourcePool::where(',
'$attachments = CloudHostNetworkAttachment::whereIn(',
'$pools = CloudPublicIpPool::whereIn(\'id\', $poolIds)',
'$reservation = CloudResourceReservation::where(',
'$allClaims = DB::table(\'cloud_resource_reservation_ips\')',
'$ips = CloudPublicIp::where(\'host_id\', (int) $instance->host_id)',
]);
foreach ([
['public static function markJobUncertain(',
'public static function recordEvidence('],
['public static function recordEvidence(',
'public static function finishJobLocked('],
['public static function finishJobLocked(',
'public static function publishPreparedLocked('],
['public static function publishPreparedLocked(',
'public static function retryPendingFinalization('],
] as [$start, $end]) {
$ordered($method($source, $start, $end), [
'$instance = CloudInstance::where(',
'self::lockHostBoundaryLocked(',
'$transition = CloudPublicNetworkTransition::where(',
]);
}
$retry = $method(
$source,
'public static function retryPendingFinalization(',
'private static function lockHostBoundaryLocked('
);
$ordered($retry, [
'$actor = User::where(\'id\', $userId)',
'$parent = $parentId > 0',
'$job = CloudJob::where(\'id\', $jobId)',
'self::finishJobLocked(',
]);
$topology = $method(
$source,
'private static function lockFrozenTopologyLocked(',
'private static function assertFrozenRowIdentity('
);
$ordered($topology, [
'$attachments = CloudHostNetworkAttachment::whereIn(',
"->orderBy('id')->lockForUpdate()->get()",
'$pools = CloudPublicIpPool::where(',
"->whereIn('pool_key', \$poolKeys)->orderBy('id')",
]);
$assert(str_contains($source, "\$transition->state = 'reserved';")
&& str_contains($source, "'active_claim' => null")
&& str_contains($source, "'state' => 'reserved'")
&& str_contains($source, "\$transition->state = 'queued';")
&& strpos($source, "\$transition->state = 'reserved';")
< strpos($source, "\$transition->state = 'queued';"),
'Transition must fence targets before atomically becoming queued.');
$replayPosition = strpos($reserve, 'return self::replayLocked(');
$admissionPosition = strpos(
$reserve,
'CloudPublicNetworkMutationAdmission::assertCanBegin($instance)'
);
$activeTransitionPosition = strpos(
$reserve,
"->where('active_transition', 1)->lockForUpdate()->first()"
);
$assert($replayPosition !== false && $admissionPosition !== false
&& $activeTransitionPosition !== false
&& $replayPosition < $admissionPosition
&& $admissionPosition < $activeTransitionPosition,
'Exact replay, shared admission, or locked transition recheck drifted.');
$assert(str_contains($source, "(\$spec['managed'] ?? false) !== true")
&& str_contains($source,
"(\$spec['os_source'] ?? null) !== 'cloud_template'"),
'The deep workflow seam does not enforce managed cloud-template admission.');
$assert(str_contains($source, "\$job->kind = 'network_change';")
&& str_contains($source,
"\$job->public_network_transition_id = (int) \$transition->id;")
&& str_contains($source,
"'public_network' => \$targetSnapshot->toArray()")
&& str_contains($source, "'price_cents' => \$command->priceCents()")
&& str_contains($source, "'charged_amount' => \$invoice === null")
&& !str_contains($source, "'source_public_ip_id' =>")
&& !str_contains($source, "'target_public_ip_id' =>"),
'Queued job does not freeze the complete transition contract.');
$assert(str_contains($billing,
'CloudPublicNetworkTransitionCommand $command')
&& str_contains($billing, "\$command->kind() !== 'user_paid'")
&& str_contains($activeIdentity,
'CloudPublicNetworkClaimSetIdentity::fromLedger('),
'Billing or claim-set identity is not delegated through the deep seam.');
$assert(str_contains($worker, 'markDispatched($job)')
&& str_contains($worker, 'recordEvidence(')
&& str_contains($worker, 'finishJobLocked(')
&& str_contains($worker, 'markJobUncertain(')
&& str_contains($recovery, 'publishPreparedLocked('),
'Worker or recovery coordinator bypasses the Stage 4 transition seam.');
$allowedBeginCallers = [
realpath($root . '/app/Controllers/CloudApiController.php'),
realpath($root . '/app/Controllers/CloudAdminInstanceController.php'),
];
$actualBeginCallers = [];
foreach ([$root . '/app', $root . '/config'] as $directory) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$directory,
FilesystemIterator::SKIP_DOTS
)
);
foreach ($iterator as $file) {
if (!$file->isFile() || $file->getExtension() !== 'php'
|| $file->getPathname()
=== $root
. '/app/Services/Cloud/'
. 'CloudPublicNetworkTransitionWorkflow.php') {
continue;
}
$contents = file_get_contents($file->getPathname());
if (is_string($contents) && str_contains(
$contents,
'CloudPublicNetworkTransitionWorkflow::begin('
)) {
$actualBeginCallers[] = realpath($file->getPathname());
}
}
}
$actualBeginCallers = array_values(array_unique($actualBeginCallers));
sort($actualBeginCallers);
sort($allowedBeginCallers);
$assert($actualBeginCallers === $allowedBeginCallers,
'Production workflow callers escaped the two Stage 5 controller seams.');
$assert(str_contains($tenantController,
'CloudPublicNetworkTransitionCommand::')
&& str_contains($tenantController, 'userPaidAutomatic(')
&& str_contains($tenantController,
'CloudPublicNetworkTransitionWorkflow::begin($command)')
&& !str_contains($tenantController,
"CloudJobService::enqueue(\n \$instance,\n \$actor,\n 'network_change'")
&& str_contains($adminController,
'CloudPublicNetworkTransitionCommand::adminExact(')
&& str_contains($adminController,
'CloudPublicNetworkTransitionWorkflow::begin($command)'),
'A Stage 5 controller bypasses the command plus transition seam.');
echo "Public-network transition workflow contract tests passed.\n";