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

183 lines
6.9 KiB
PHP

<?php
declare(strict_types=1);
$root = dirname(__DIR__);
$source = file_get_contents(
$root . '/app/Services/Cloud/CloudServiceCompensationExecutionService.php'
);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$section = static function (
string $source,
string $start,
string $next
): string {
$offset = strpos($source, $start);
$end = $offset === false ? false : strpos($source, $next, $offset + 1);
if ($offset === false || $end === false || $end <= $offset) {
throw new RuntimeException('Unable to isolate execution contract section.');
}
return substr($source, $offset, $end - $offset);
};
$assert($source !== false, 'Compensation execution source could not be read.');
$apply = $section(
$source,
'public function applyClaim(',
'public function tick('
);
$ownerLock = strpos($apply, 'User::where(');
$instanceLock = strpos($apply, 'CloudInstance::where(');
$batchLock = strpos($apply, 'CloudServiceCompensation::where(');
$itemLock = strpos($apply, 'CloudServiceCompensationItem::where(');
$assert($ownerLock !== false && $instanceLock !== false
&& $batchLock !== false && $itemLock !== false
&& $ownerLock < $instanceLock && $instanceLock < $batchLock
&& $batchLock < $itemLock,
'Apply lost the canonical owner-instance-batch-item lock order.');
$assert(str_contains($apply,
'// Canonical compensation lock order: owner -> instance ->')
&& str_contains($apply, '->lockForUpdate()->first();'),
'The canonical compensation lock order is no longer explicit.');
$assert(substr_count($apply, "->orderByDesc('ends_at')") >= 2
&& substr_count($apply, "->orderByDesc('id')") >= 2
&& str_contains($apply, "'service_period_changed'"),
'Compensation no longer revalidates the latest tail service period.');
foreach ([
'CloudInstanceMigrationService::hasOpenMigration(',
'CloudJobService::blockingQueryForInstance(',
"'finalization_incident'",
"'instance_operation_open'",
"'instance_operation_uncertain'",
'CloudJobService::blockingQueryForInvoice(',
"['creating', 'pending']",
"['failed', 'expired', 'not_created']",
"'renewal_payment_open'",
"'renewal_payment_uncertain'",
] as $fence) {
$assert(str_contains($source, $fence),
'Compensation execution lost fence: ' . $fence);
}
foreach ([
'instance_deleting',
'migration_open',
'instance_operation_open',
'renewal_payment_job_open',
'renewal_payment_open',
'renewal_mail_sending',
] as $externalWaitCode) {
$assert(preg_match(
"/'deferred',\\s*'" . preg_quote($externalWaitCode, '/')
. "'.*?false\\s*\\)/s",
$source
) === 1,
'External wait consumes technical retry budget: ' . $externalWaitCode);
}
$assert(preg_match(
'/\'service_period_changed\'.*?\$now,\s*false\s*\)/s',
$apply
) === 1
&& str_contains($source, 'private const EXTERNAL_WAIT_SECONDS = 300;')
&& str_contains(
$source,
'$item->attempts = max(0, (int) $item->attempts - 1);'
),
'External service-period wait lost its bounded non-consuming transition.');
$assert(str_contains(
$source,
'CloudInvoiceService::fenceRenewalMailForCompensationLocked('
), 'Compensation no longer fences an in-flight renewal reminder.');
$invoiceProjection = strpos($apply,
'reconcileRenewalAfterCompensationLocked(');
$trafficProjection = strpos($apply,
'extendEntitlementWindowForCompensationLocked(',
(int) $invoiceProjection);
$backupProjection = $trafficProjection === false ? false : strpos(
$apply,
'extendEntitlementWindowForCompensationLocked(',
$trafficProjection + 1
);
$periodSave = strpos($apply, '$lockedPeriod->save();');
$instanceSave = strpos($apply, '$instance->save();');
$audit = strpos($apply, '$job = $this->auditJob(');
$itemSave = strpos($apply, '$item->save();', (int) $audit);
$recalculate = strpos($apply, '->recalculateLocked($batch, $now);');
$assert($invoiceProjection !== false && $trafficProjection !== false
&& $backupProjection !== false && $periodSave !== false
&& $instanceSave !== false && $audit !== false
&& $itemSave !== false && $recalculate !== false
&& $invoiceProjection < $trafficProjection
&& $trafficProjection < $backupProjection
&& $backupProjection < $periodSave
&& $periodSave < $instanceSave
&& $instanceSave < $audit && $audit < $itemSave
&& $itemSave < $recalculate,
'Commercial projections, core rows and audit do not converge in order.');
$assert(str_contains($apply, "DB::connection('default')->transaction(")
&& str_contains($apply, "\$item->state = 'applied'")
&& str_contains($apply, '$item->audit_job_id = (int) $job->id'),
'The atomic compensation transaction lost its applied audit linkage.');
$auditMethod = $section(
$source,
'private function auditJob(',
'private function finishLocked('
);
foreach ([
"\$job->kind = 'service_compensation'",
"\$job->execution_mode = 'local'",
"\$job->host_id = null",
'CloudJobService::completeWithoutDispatchLocked($job, [',
"'seconds_added' => (int) \$item->requested_seconds",
"'previous_expires_at' => \$oldExpiry",
"'new_expires_at' => \$newExpiry",
] as $auditContract) {
$assert(str_contains($auditMethod, $auditContract),
'Local audit contract is missing: ' . $auditContract);
}
$recovery = $section(
$source,
'private function recoverAfterApplyError(',
'private function decision('
);
$latest = strpos($recovery,
'$latest = CloudServiceCompensationItem::find($itemId);');
$applied = strpos($recovery,
"(string) \$latest->state === 'applied'");
$transition = strpos($recovery, 'return $this->transitionClaim(');
$assert($latest !== false && $applied !== false && $transition !== false
&& $latest < $applied && $applied < $transition,
'Error recovery may replay before checking for an already committed item.');
foreach ([
'public const MAX_ATTEMPTS = 8;',
'public const LEASE_SECONDS = 120;',
"->where('attempts', '<', self::MAX_ATTEMPTS)",
"? 'retry_exhausted' : 'worker_lease_expired'",
"'deferred', 'rejected', 'attention'",
'min(3600, 30 * (2 ** max(0, min(7, $attempts - 1))))',
] as $leaseContract) {
$assert(str_contains($source, $leaseContract),
'Bounded retry contract is missing: ' . $leaseContract);
}
$assert(!str_contains($source, 'new CloudTrafficEntitlement')
&& !str_contains($source, 'new CloudBackupPeriodEntitlement')
&& !str_contains($source, 'new CloudBackupSubscription')
&& !str_contains($source, 'granted_bytes =')
&& !str_contains($source, 'traffic_quota_bytes =')
&& !str_contains($source, '->money =')
&& !str_contains($source, 'Wallet'),
'Compensation execution may grant traffic/backup cover or mutate wallet.');
echo "Service compensation execution contracts passed.\n";