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

255 lines
11 KiB
PHP

<?php
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$value = file_get_contents($root . '/' . $path);
if (!is_string($value)) {
throw new RuntimeException('Unable to read ' . $path);
}
return $value;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$routes = $read('config/routes_cloud.php');
$worker = $read('app/Services/Cloud/CloudWorkerService.php');
$jobs = $read('app/Services/Cloud/CloudJobService.php');
$controller = $read('app/Controllers/CloudApiController.php');
$adminInstanceController = $read(
'app/Controllers/CloudAdminInstanceController.php'
);
$middleware = $read('app/Middleware/CloudApi.php');
$jobModel = $read('app/Models/CloudJob.php');
$completion = $read('app/Services/Cloud/CloudOperationCompletionService.php');
$operationRecovery = $read(
'app/Services/Cloud/CloudOperationRecoveryService.php'
);
$automaticRecovery = $read(
'app/Services/Cloud/CloudAutomaticOperationRecoveryService.php'
);
$adminOperationRecovery = $read(
'app/Services/Cloud/CloudAdminOperationRecoveryService.php'
);
$adminOperations = $read('app/Services/Cloud/CloudAdminOperationsService.php');
$adminOperationsController = $read(
'app/Controllers/CloudAdminOperationsController.php'
);
$createFinalizer = $read(
'app/Services/Cloud/CloudCreateFailureFinalizer.php'
);
$paymentEffect = $read(
'app/Services/Cloud/CloudPaymentEffectResolutionService.php'
);
$schema = $read('sql/cloud.sql');
$mail = $read('app/Services/Cloud/CloudInvoiceService.php');
$lifecycle = $read('app/Services/Cloud/CloudLifecycleService.php');
$usdt = $read('app/Services/Payment/UsdtScannerService.php');
$assert(str_contains($routes, "'/tasks'")
&& str_contains($routes, "'/tasks/{id:[0-9]+}'")
&& str_contains($routes, "'/tasks/read'")
&& !str_contains($routes, "'/jobs")
&& !str_contains($routes, "'/reinstall-jobs")
&& !str_contains($routes, "'/rescue-jobs")
&& !str_contains($routes, '/stop-auto')
&& !str_contains($routes, '/abort-job')
&& !str_contains($routes, "'/cleanup'"),
'Public/admin routes retained a legacy or replay-oriented job endpoint.');
$assert(!str_contains($worker, "'/v1/operations/'")
&& !str_contains($worker, "'/reconcile'")
&& !str_contains($worker, 'automaticReconciliation')
&& !str_contains($worker, "'status' => 'queued',\n 'dispatched_at' => null"),
'Cloud worker retained mutation reconciliation or requeue behavior.');
$recoverySeam = substr(
$worker,
strpos($worker, 'public function prepareRecoveredEffect'),
1200
);
$assert(str_contains($recoverySeam,
'CloudOperationRecoveryPolicy::supportsLedgerFinalizer(')
&& str_contains($recoverySeam,
'(string) $job->kind')
&& str_contains($recoverySeam,
"throw new CloudError('任务类型不支持自动效果恢复', 409)"),
'The public recovered-effect seam does not use the explicit ledger-finalizer policy.');
$assert(str_contains($worker, "->where('dispatch_attempts', 0)")
&& str_contains($worker, "'dispatch_attempts' => 1")
&& substr_count($worker, 'self::dispatchableBeforeDeadline(') >= 3
&& str_contains($worker,
"->where('kind', '!=', 'host_storage_configure')")
&& str_contains($worker,
"->orWhere('created_at', '>', \$now - \$storageWindow)")
&& str_contains($schema,
'CONSTRAINT chk_cloud_job_dispatch_once CHECK (dispatch_attempts <= 1)'),
'Single-dispatch or effective dispatch-deadline boundary is not enforced in code and schema.');
$assert(!str_contains($controller, '/api/v1/jobs/')
&& !preg_match("/'job_id'\s*=>\s*\(string\) \$job->id/", $controller)
&& str_contains($controller, "'task_id' => (string) \$job->id")
&& str_contains($jobs, "'status_url' => '/api/v1/tasks/'"),
'Mutation acknowledgements or task DTOs retained the old job contract.');
$assert(preg_match_all(
'/\$this->json\(\$response,\s*\[([^;]*?)\]\s*,\s*202\)/s',
$controller,
$acknowledgements
) !== false, 'Unable to inspect task acknowledgement payloads.');
foreach ($acknowledgements[1] as $acknowledgement) {
if (!str_contains($acknowledgement, "'task_id'")) {
continue;
}
preg_match_all("/'([a-z_]+)'\s*=>/", $acknowledgement, $keys);
$keys = array_values(array_unique($keys[1]));
sort($keys);
$assert($keys === ['status_url', 'task_id'],
'A 202 task acknowledgement exposes fields beyond task_id/status_url.');
}
$assert(preg_match_all(
'/->withJson\(\s*\[([^;]*?)\]\s*,\s*202\)/s',
$adminInstanceController,
$adminAcknowledgements
) !== false, 'Unable to inspect administrator task acknowledgements.');
foreach ($adminAcknowledgements[1] as $acknowledgement) {
if (!str_contains($acknowledgement, "'task_id'")) {
continue;
}
preg_match_all("/'([a-z_]+)'\s*=>/", $acknowledgement, $keys);
$keys = array_values(array_unique($keys[1]));
sort($keys);
$assert($keys === ['status_url', 'task_id'],
'An administrator 202 acknowledgement exposes extra task fields.');
}
$assert(!str_contains($middleware, '(?:jobs|reinstall-jobs|rescue-jobs)')
&& str_contains($middleware,
'#^/api/v1/tasks(?:/[0-9]+|/read)?$#D'),
'Middleware retained the old task routes or omitted the task API.');
$assert(str_contains($controller,
'CloudWorkerService::expireDueTasksForOwner(')
&& str_contains($jobs,
'CloudWorkerService::expireDueTasksForOwner(')
&& str_contains($worker,
"\$query->where('user_id', \$userId)")
&& str_contains($worker,
"orderByRaw('CASE WHEN parent_job_id IS NULL THEN 1 ELSE 0 END')")
&& str_contains($worker,
'CloudOperationCompletionService::pendingForJob(')
&& str_contains($controller,
"->where('user_id', (int) \$actor['user_id'])")
&& str_contains($controller,
"->where('phase', 'terminal')->whereNull('read_at')"),
'Task GET/list fallback is not owner-scoped, receipt-first, or durable.');
$assert(str_contains($completion, "(string) \$job->phase === 'terminal'")
&& str_contains($completion, "\$job->completion_event_id")
&& str_contains($completion,
'CloudOperationRecoveryService::settleLateReceipt(')
&& str_contains($operationRecovery,
"(string) \$job->outcome === 'failed'")
&& str_contains($operationRecovery,
"if (!in_array(\$resolution, ['applied', 'not_applied'], true))")
&& str_contains($operationRecovery,
'$job->effect_resolution = $resolution;')
&& !str_contains($operationRecovery,
"\$job->outcome = 'succeeded'")
&& str_contains($completion, "['succeeded', 'failed']")
&& str_contains($completion,
"(\$input['status'] ?? null) === 'succeeded'")
&& str_contains($completion,
"(\$input['status'] ?? null) === 'failed'"),
'Late completion immutability or terminal receipt validation is missing.');
$fenceCommit = substr(
$automaticRecovery,
strpos($automaticRecovery, 'private static function resolveFenceAndCommit'),
6500
);
$pendingReceiptCheck = strpos(
$fenceCommit,
"->where('disposition', 'received')"
);
$fenceWrite = strpos(
$fenceCommit,
'CloudAdminOperationRecoveryService::resolveFenceForRecovery('
);
$effectCommit = strpos($fenceCommit, 'self::commitPrepared(');
$lockedJob = strpos($fenceCommit, '->lockForUpdate()->first()');
$leaseCheck = strpos($fenceCommit, '(int) $job->lease_until <= time()');
$jobContext = substr(
$adminOperationRecovery,
strpos($adminOperationRecovery, 'private static function jobContext'),
3500
);
$envelopeCheck = strpos(
$jobContext,
'CloudJobService::hasTerminalRecoveryStateConflict($job)'
);
$clientCreation = strpos(
$jobContext,
'CloudAgentSettingsService::clientForConfiguration('
);
$terminalStateConflict = substr(
$jobs,
strpos($jobs, 'public static function hasTerminalRecoveryStateConflict'),
2200
);
$assert($lockedJob !== false
&& $leaseCheck !== false
&& $pendingReceiptCheck !== false
&& $fenceWrite !== false
&& $effectCommit !== false
&& $envelopeCheck !== false
&& $clientCreation !== false
&& $lockedJob < $leaseCheck
&& $leaseCheck < $pendingReceiptCheck
&& $pendingReceiptCheck < $fenceWrite
&& $fenceWrite < $effectCommit
&& $envelopeCheck < $clientCreation
&& str_contains(
$terminalStateConflict,
'self::hasAgentRecoveryEnvelopeConflict($job)'
),
'Automatic fence write is not serialized after locked lease, immutable envelope, receipt, and PHP commit checks.');
$assert(!str_contains(substr($jobModel,
strpos($jobModel, "\$job->request_fingerprint = hash")),
'sealed_payload')
&& !str_contains(substr($jobModel,
strpos($jobModel, "\$job->request_fingerprint = hash"), 700),
'(string) $job->operation_id'),
'Fallback request fingerprint depends on randomized ciphertext or identity.');
$resolveEffect = substr($adminOperations,
strpos($adminOperations, 'public static function resolveEffect'), 6000);
$paymentRoute = strpos($adminOperationsController,
'CloudPaymentEffectResolutionService::handles($id)');
$agentInspect = strpos($adminOperationsController,
'CloudAdminOperationRecoveryService::inspect($actor, $id)',
$paymentRoute === false ? 0 : $paymentRoute);
$assert(str_contains($resolveEffect, "['applied', 'not_applied']")
&& str_contains($resolveEffect, "(string) \$target->kind !== 'create'")
&& str_contains($resolveEffect,
'CloudCreateFailureFinalizer::assertResolutionSupported(')
&& str_contains($resolveEffect,
'CloudCreateFailureFinalizer::resolveNotApplied(')
&& !str_contains($resolveEffect,
"'effect_resolution' => \$resolution")
&& str_contains($createFinalizer,
"(string) \$job->phase !== 'terminal'")
&& str_contains($createFinalizer,
"(string) \$job->outcome !== 'failed'")
&& str_contains($paymentEffect,
"(string) \$job->phase !== 'terminal'")
&& str_contains($paymentEffect,
"(string) \$job->outcome !== 'failed'")
&& $paymentRoute !== false && $agentInspect !== false
&& $paymentRoute < $agentInspect,
'Effect resolution lacks kind-specific atomic finalizers or can use an Agent/provider mutation for payment evidence.');
$assert(str_contains($mail, "\$message->status = 'failed'")
&& !str_contains($mail, 'min(21600, 60 *'),
'Mail delivery still schedules automatic retries.');
$assert(!str_contains($lifecycle, 'policyRetryReady'),
'Lifecycle policy still retries a failed generation automatically.');
$assert(!str_contains($usdt, 'retryStoredEvents')
&& str_contains($usdt, "status' => 'quarantined'")
&& str_contains($usdt, "'settlement_attempts' => 1"),
'USDT poison events are not isolated after one settlement attempt.');
echo "Single-dispatch architecture contract passed.\n";