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/app/Services/Cloud/CloudEngineReadiness.php

69 lines
2.2 KiB
PHP

<?php
namespace App\Services\Cloud;
/**
* Gate long-running control-plane consumers on the private engine's real
* application readiness, not merely on systemd having executed uvicorn.
*/
final class CloudEngineReadiness
{
private const DEFAULT_TIMEOUT_SECONDS = 45.0;
private const RETRY_MICROSECONDS = 1000000;
public static function wait(
?callable $probe = null,
float $timeoutSeconds = self::DEFAULT_TIMEOUT_SECONDS,
?callable $clock = null,
?callable $sleep = null,
): bool {
$timeoutSeconds = max(0.001, min(60.0, $timeoutSeconds));
$clock ??= static fn (): float => hrtime(true) / 1000000000;
$sleep ??= static function (int $microseconds): void {
usleep($microseconds);
};
$probe ??= self::probe(...);
$deadline = $clock() + $timeoutSeconds;
while (true) {
try {
if ($probe() === true) {
return true;
}
} catch (\Throwable $error) {
// Startup races and an engine that is not listening yet are
// expected here. Never log transport details or secrets.
}
$remaining = $deadline - $clock();
if ($remaining <= 0) {
return false;
}
$microseconds = max(1, min(
self::RETRY_MICROSECONDS,
(int) ceil($remaining * 1000000),
));
$sleep($microseconds);
}
}
private static function probe(): bool
{
// Health is an authenticated system probe, not an end-user action.
// The engine health route checks the signed request and engine stores;
// it does not authorize against a particular panel account.
$actor = [
'user_id' => 1,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'session_id' => 'cloud-engine-readiness',
];
$result = (new CloudEngineClient(null, 2.0))->request(
'GET', '/internal/v1/health', $actor
);
return ($result['status'] ?? null) === 'ok'
&& ($result['accepting_mutations'] ?? null) === true;
}
}