perf: server-render instance pages
parent
1e1f68d503
commit
ea84d9519e
@ -0,0 +1,460 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudHost;
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudServicePeriod;
|
||||
use App\Services\Config;
|
||||
|
||||
/**
|
||||
* Database-only, actor-scoped instance snapshots for user-facing pages.
|
||||
*
|
||||
* This service must never contact the private engine. It deliberately gives
|
||||
* the browser a useful first paint even when one or more libvirt hosts are
|
||||
* slow or unavailable; live power state is layered on through the dedicated
|
||||
* status endpoints after the HTML is visible.
|
||||
*/
|
||||
final class CloudInstancePageService
|
||||
{
|
||||
public static function forActor(array $actor, int $page = 1, int $perPage = 20): array
|
||||
{
|
||||
$page = max(1, $page);
|
||||
$perPage = max(1, min(100, $perPage));
|
||||
$base = self::visibleQuery($actor);
|
||||
$total = (int) (clone $base)->count();
|
||||
$totalPages = max(1, (int) ceil($total / $perPage));
|
||||
$page = min($page, $totalPages);
|
||||
$records = (clone $base)->orderByDesc('id')
|
||||
->offset(($page - 1) * $perPage)
|
||||
->limit($perPage)
|
||||
->get(self::listColumns());
|
||||
$snapshots = self::listSnapshots($records);
|
||||
$counts = ['running' => 0, 'stopped' => 0, 'other' => 0];
|
||||
foreach ($snapshots as $vm) {
|
||||
$counts[self::stateCategory((string) ($vm['state'] ?? 'unknown'))]++;
|
||||
}
|
||||
// Power state is not persisted in cloud_instances. Any records outside
|
||||
// the visible page are therefore unknown until the lightweight live
|
||||
// status request completes; never invent a running/stopped count.
|
||||
$counts['other'] += max(0, $total - count($snapshots));
|
||||
$vms = $snapshots;
|
||||
|
||||
return [
|
||||
'vms' => $vms,
|
||||
'stats' => [
|
||||
'total' => $total,
|
||||
'running' => $counts['running'],
|
||||
'stopped' => $counts['stopped'],
|
||||
'other' => $counts['other'],
|
||||
],
|
||||
'pagination' => self::pagination($page, $perPage, $total, count($vms)),
|
||||
];
|
||||
}
|
||||
|
||||
public static function detailForActor(array $actor, $id): array
|
||||
{
|
||||
$instance = self::visibleInstanceQuery($actor, $id)->first(self::columns());
|
||||
if ($instance === null) {
|
||||
throw new CloudError('虚拟机不存在或无权访问', 404);
|
||||
}
|
||||
return self::snapshots(
|
||||
new \Illuminate\Database\Eloquent\Collection([$instance]), $actor
|
||||
)[0];
|
||||
}
|
||||
|
||||
/** Mutable database state for the detail poll, without static VM metadata. */
|
||||
public static function statusForActor(array $actor, $id): array
|
||||
{
|
||||
$instance = self::visibleInstanceQuery($actor, $id)->first([
|
||||
'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name',
|
||||
'status', 'service_status', 'network_status', 'expires_at',
|
||||
'traffic_quota_bytes', 'traffic_download_bytes',
|
||||
'traffic_upload_bytes',
|
||||
]);
|
||||
if ($instance === null) {
|
||||
throw new CloudError('虚拟机不存在或无权访问', 404);
|
||||
}
|
||||
$period = null;
|
||||
if ($instance->current_period_id !== null) {
|
||||
$period = CloudServicePeriod::where('id', $instance->current_period_id)
|
||||
->where('instance_id', $instance->id)
|
||||
->first(['starts_at', 'ends_at']);
|
||||
}
|
||||
$owner = (int) $instance->user_id === (int) $actor['user_id'];
|
||||
$global = ($actor['is_admin'] ?? false)
|
||||
&& ($actor['is_super_admin'] ?? false)
|
||||
&& ($actor['can_manage'] ?? false);
|
||||
$lifecycleActive = (string) $instance->status === 'active';
|
||||
$canDelete = $lifecycleActive && ($owner || $global);
|
||||
$download = max(0, (int) $instance->traffic_download_bytes);
|
||||
$upload = max(0, (int) $instance->traffic_upload_bytes);
|
||||
$used = $download + $upload;
|
||||
$quota = max(0, (int) $instance->traffic_quota_bytes);
|
||||
return [
|
||||
'id' => (string) $instance->id,
|
||||
'api_id' => (string) $instance->id,
|
||||
'uuid' => (string) $instance->uuid,
|
||||
'host_id' => (int) $instance->host_id,
|
||||
'name' => (string) $instance->name,
|
||||
'state' => 'unknown',
|
||||
'instance_status' => (string) $instance->status,
|
||||
'service_status' => (string) $instance->service_status,
|
||||
'network_status' => (string) $instance->network_status,
|
||||
'service_expires_at' => $instance->expires_at === null
|
||||
? null : (int) $instance->expires_at,
|
||||
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
|
||||
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
|
||||
'traffic_download_bytes' => $download,
|
||||
'traffic_upload_bytes' => $upload,
|
||||
'traffic_used_bytes' => $used,
|
||||
'traffic_quota_bytes' => $quota,
|
||||
'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used),
|
||||
'is_owner' => $owner,
|
||||
'can_operate' => $canDelete && $instance->serviceAvailable(),
|
||||
'can_delete' => $canDelete,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return actor-visible snapshots in the caller's requested id order.
|
||||
* Ordinary users stay owner scoped; read-only administrators retain the
|
||||
* historical all-instance view without inheriting mutation permissions.
|
||||
*/
|
||||
public static function forActorIds(array $actor, array $ids): array
|
||||
{
|
||||
$ordered = [];
|
||||
foreach ($ids as $id) {
|
||||
$number = filter_var($id, FILTER_VALIDATE_INT,
|
||||
['options' => ['min_range' => 1]]);
|
||||
if ($number !== false) {
|
||||
if (!isset($ordered[(int) $number])) {
|
||||
$ordered[(int) $number] = count($ordered);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($ordered === []) {
|
||||
return [];
|
||||
}
|
||||
$records = self::visibleQuery($actor)
|
||||
->whereIn('id', array_keys($ordered))
|
||||
->get(['id', 'uuid', 'host_id', 'name']);
|
||||
$vms = [];
|
||||
foreach ($records as $instance) {
|
||||
$vms[] = [
|
||||
'id' => (string) $instance->id,
|
||||
'api_id' => (string) $instance->id,
|
||||
'uuid' => (string) $instance->uuid,
|
||||
'host_id' => (int) $instance->host_id,
|
||||
'name' => (string) $instance->name,
|
||||
'state' => 'unknown',
|
||||
];
|
||||
}
|
||||
usort($vms, static fn (array $left, array $right): int =>
|
||||
($ordered[(int) $left['id']] ?? PHP_INT_MAX)
|
||||
<=> ($ordered[(int) $right['id']] ?? PHP_INT_MAX));
|
||||
return $vms;
|
||||
}
|
||||
|
||||
/** A deliberately small mutable status view merged with live engine data. */
|
||||
public static function status(array $snapshot, array $live = []): array
|
||||
{
|
||||
$liveUuid = is_string($live['uuid'] ?? null)
|
||||
? strtolower(trim($live['uuid'])) : '';
|
||||
$liveMatches = $liveUuid !== '' && hash_equals(
|
||||
strtolower((string) $snapshot['uuid']), $liveUuid
|
||||
);
|
||||
if (!$liveMatches) {
|
||||
$live = [];
|
||||
}
|
||||
$liveStateAvailable = $liveMatches
|
||||
&& is_string($live['state'] ?? null)
|
||||
&& trim($live['state']) !== '';
|
||||
$state = is_string($live['state'] ?? null) && trim($live['state']) !== ''
|
||||
? trim($live['state']) : (string) ($snapshot['state'] ?? 'unknown');
|
||||
$name = is_string($live['name'] ?? null) && trim($live['name']) !== ''
|
||||
? trim($live['name']) : (string) ($snapshot['name'] ?? '');
|
||||
return [
|
||||
'id' => (string) $snapshot['id'],
|
||||
'api_id' => (string) $snapshot['api_id'],
|
||||
'uuid' => (string) $snapshot['uuid'],
|
||||
'name' => $name,
|
||||
'state' => $state,
|
||||
'live_state_available' => $liveStateAvailable,
|
||||
'instance_status' => (string) $snapshot['instance_status'],
|
||||
'service_status' => (string) $snapshot['service_status'],
|
||||
'network_status' => (string) $snapshot['network_status'],
|
||||
'service_expires_at' => $snapshot['service_expires_at'],
|
||||
'current_period_started_at' => $snapshot['current_period_started_at'],
|
||||
'current_period_ends_at' => $snapshot['current_period_ends_at'],
|
||||
'traffic_download_bytes' => (int) $snapshot['traffic_download_bytes'],
|
||||
'traffic_upload_bytes' => (int) $snapshot['traffic_upload_bytes'],
|
||||
'traffic_used_bytes' => (int) $snapshot['traffic_used_bytes'],
|
||||
'traffic_quota_bytes' => (int) $snapshot['traffic_quota_bytes'],
|
||||
'traffic_remaining_bytes' => (int) $snapshot['traffic_remaining_bytes'],
|
||||
'is_owner' => (bool) $snapshot['is_owner'],
|
||||
'can_operate' => (bool) $snapshot['can_operate'],
|
||||
'can_delete' => (bool) $snapshot['can_delete'],
|
||||
];
|
||||
}
|
||||
|
||||
/** Minimal list-poll payload; billing and permissions belong to detail. */
|
||||
public static function powerStatus(array $snapshot, array $live = []): array
|
||||
{
|
||||
$liveUuid = is_string($live['uuid'] ?? null)
|
||||
? strtolower(trim($live['uuid'])) : '';
|
||||
$matches = $liveUuid !== '' && hash_equals(
|
||||
strtolower((string) $snapshot['uuid']), $liveUuid
|
||||
);
|
||||
$available = $matches && is_string($live['state'] ?? null)
|
||||
&& trim($live['state']) !== '';
|
||||
return [
|
||||
'id' => (string) $snapshot['id'],
|
||||
'api_id' => (string) $snapshot['api_id'],
|
||||
'uuid' => (string) $snapshot['uuid'],
|
||||
'name' => $matches && is_string($live['name'] ?? null)
|
||||
&& trim($live['name']) !== ''
|
||||
? trim($live['name']) : (string) $snapshot['name'],
|
||||
'state' => $available ? trim($live['state']) : 'unknown',
|
||||
'live_state_available' => $available,
|
||||
];
|
||||
}
|
||||
|
||||
/** Keep the paginated list bootstrap intentionally smaller than detail. */
|
||||
private static function listItem(array $snapshot): array
|
||||
{
|
||||
$keys = [
|
||||
'id', 'api_id', 'uuid', 'name', 'state', 'region', 'location',
|
||||
'os_source', 'os_name', 'install_iso', 'public_ip_cidr', 'public_ip',
|
||||
'vcpu', 'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib',
|
||||
];
|
||||
return array_intersect_key($snapshot, array_flip($keys));
|
||||
}
|
||||
|
||||
private static function listSnapshots($instances): array
|
||||
{
|
||||
if ($instances->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
$hosts = self::hostMap($instances);
|
||||
$result = [];
|
||||
foreach ($instances as $instance) {
|
||||
$decoded = json_decode((string) $instance->spec_json, true);
|
||||
$spec = CloudInput::safeResult(is_array($decoded) ? $decoded : []);
|
||||
$host = $hosts[(int) $instance->host_id] ?? null;
|
||||
$region = trim((string) ($host?->region ?? ''));
|
||||
if ($region === '') {
|
||||
$region = trim((string) ($spec['region'] ?? $spec['location'] ?? ''));
|
||||
}
|
||||
$result[] = self::listItem(array_merge($spec, [
|
||||
'id' => (string) $instance->id,
|
||||
'api_id' => (string) $instance->id,
|
||||
'uuid' => (string) $instance->uuid,
|
||||
'name' => (string) $instance->name,
|
||||
'state' => 'unknown',
|
||||
'region' => $region,
|
||||
]));
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function hostMap($instances): array
|
||||
{
|
||||
$hostIds = $instances->pluck('host_id')->map(
|
||||
static fn ($id): int => (int) $id
|
||||
)->unique()->values()->all();
|
||||
$hosts = [];
|
||||
if ($hostIds !== []) {
|
||||
foreach (CloudHost::whereIn('id', $hostIds)
|
||||
->get(['id', 'region', 'country_code']) as $host) {
|
||||
$hosts[(int) $host->id] = $host;
|
||||
}
|
||||
}
|
||||
return $hosts;
|
||||
}
|
||||
|
||||
private static function snapshots($instances, array $actor): array
|
||||
{
|
||||
if ($instances->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
$instanceIds = $instances->pluck('id')->map(static fn ($id): int => (int) $id)->all();
|
||||
$periodIds = $instances->pluck('current_period_id')->filter(
|
||||
static fn ($id): bool => $id !== null
|
||||
)->map(static fn ($id): int => (int) $id)->unique()->values()->all();
|
||||
|
||||
$hosts = self::hostMap($instances);
|
||||
$periods = [];
|
||||
if ($periodIds !== []) {
|
||||
foreach (CloudServicePeriod::whereIn('id', $periodIds)
|
||||
->whereIn('instance_id', $instanceIds)
|
||||
->get(['id', 'instance_id', 'starts_at', 'ends_at', 'status']) as $period) {
|
||||
$periods[(int) $period->id] = $period;
|
||||
}
|
||||
}
|
||||
$futurePeriods = [];
|
||||
foreach (CloudServicePeriod::whereIn('instance_id', $instanceIds)
|
||||
->where('status', 'scheduled')
|
||||
->selectRaw('instance_id, COUNT(*) AS period_count')
|
||||
->groupBy('instance_id')->get() as $row) {
|
||||
$futurePeriods[(int) $row->instance_id] = (int) $row->period_count;
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($instances as $instance) {
|
||||
$period = $instance->current_period_id === null ? null
|
||||
: ($periods[(int) $instance->current_period_id] ?? null);
|
||||
if ($period !== null && (int) $period->instance_id !== (int) $instance->id) {
|
||||
$period = null;
|
||||
}
|
||||
$result[] = self::snapshot(
|
||||
$instance,
|
||||
$actor,
|
||||
$hosts[(int) $instance->host_id] ?? null,
|
||||
$period,
|
||||
(int) ($futurePeriods[(int) $instance->id] ?? 0)
|
||||
);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function snapshot(CloudInstance $instance, array $actor,
|
||||
?CloudHost $host, ?CloudServicePeriod $period, int $futurePeriods): array
|
||||
{
|
||||
$decoded = json_decode((string) $instance->spec_json, true);
|
||||
$spec = CloudInput::safeResult(is_array($decoded) ? $decoded : []);
|
||||
$owner = (int) $instance->user_id === (int) $actor['user_id'];
|
||||
$global = ($actor['is_admin'] ?? false)
|
||||
&& ($actor['is_super_admin'] ?? false)
|
||||
&& ($actor['can_manage'] ?? false);
|
||||
$lifecycleActive = (string) $instance->status === 'active';
|
||||
$canDelete = $lifecycleActive && ($owner || $global);
|
||||
$canOperate = $canDelete && $instance->serviceAvailable();
|
||||
$quota = max(0, (int) $instance->traffic_quota_bytes);
|
||||
$download = max(0, (int) $instance->traffic_download_bytes);
|
||||
$upload = max(0, (int) $instance->traffic_upload_bytes);
|
||||
$used = $download + $upload;
|
||||
$region = trim((string) ($host?->region ?? ''));
|
||||
if ($region === '') {
|
||||
$region = trim((string) ($spec['region'] ?? $spec['location'] ?? ''));
|
||||
}
|
||||
$createdAt = (int) $instance->created_at > 0
|
||||
? gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at) : null;
|
||||
|
||||
$maximumFuturePeriods = max(1, min(120,
|
||||
(int) Config::get('cloud_max_renewal_periods_ahead', 24)));
|
||||
return array_merge($spec, [
|
||||
'id' => (string) $instance->id,
|
||||
'api_id' => (string) $instance->id,
|
||||
'uuid' => (string) $instance->uuid,
|
||||
'display_uuid' => (string) $instance->uuid,
|
||||
'name' => (string) $instance->name,
|
||||
// Power state is intentionally never trusted from the persisted
|
||||
// specification. Operations remain disabled until a fresh,
|
||||
// UUID-checked engine status response is merged by the browser.
|
||||
'state' => 'unknown',
|
||||
'host_id' => (int) $instance->host_id,
|
||||
'user_id' => (int) $instance->user_id,
|
||||
'owner_user_id' => (int) $instance->user_id,
|
||||
'region' => $region,
|
||||
'country_code' => strtoupper(trim((string) ($host?->country_code
|
||||
?? ($spec['country_code'] ?? '')))),
|
||||
'created_at' => $createdAt,
|
||||
'instance_status' => (string) $instance->status,
|
||||
'service_status' => (string) $instance->service_status,
|
||||
'network_status' => (string) $instance->network_status,
|
||||
'service_expires_at' => $instance->expires_at === null
|
||||
? null : (int) $instance->expires_at,
|
||||
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
|
||||
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
|
||||
'prepaid_periods' => max(0, $futurePeriods),
|
||||
'traffic_download_bytes' => $download,
|
||||
'traffic_upload_bytes' => $upload,
|
||||
'traffic_used_bytes' => $used,
|
||||
'traffic_quota_bytes' => $quota,
|
||||
'traffic_remaining_bytes' => $quota === 0 ? 0 : max(0, $quota - $used),
|
||||
'renewal_price' => $instance->renewal_price === null
|
||||
? null : (string) $instance->renewal_price,
|
||||
'renewal_days' => max(0, (int) $instance->renewal_days),
|
||||
'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes),
|
||||
'login_name' => (string) ($spec['login_name']
|
||||
?? (($spec['os_source'] ?? '') === 'cloud_template' ? 'root' : '')),
|
||||
'is_owner' => $owner,
|
||||
'can_operate' => $canOperate,
|
||||
'can_delete' => $canDelete,
|
||||
'can_view_credential' => $owner || $global,
|
||||
'can_renew' => $lifecycleActive && $owner
|
||||
&& $instance->expires_at !== null
|
||||
&& (int) $instance->renewal_days > 0
|
||||
&& $instance->renewal_price !== null
|
||||
&& $futurePeriods < $maximumFuturePeriods,
|
||||
'has_initial_root_password' => ($owner || $global)
|
||||
&& $instance->credential_cipher !== null,
|
||||
'password_available' => ($owner || $global)
|
||||
&& $instance->credential_cipher !== null,
|
||||
]);
|
||||
}
|
||||
|
||||
private static function visibleQuery(array $actor)
|
||||
{
|
||||
$query = CloudInstance::where('status', '<>', 'deleted');
|
||||
if (!($actor['is_admin'] ?? false)) {
|
||||
$query->where('user_id', (int) $actor['user_id']);
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
private static function visibleInstanceQuery(array $actor, $id)
|
||||
{
|
||||
$query = self::visibleQuery($actor);
|
||||
if (ctype_digit((string) $id)) {
|
||||
return $query->where('id', (int) $id);
|
||||
}
|
||||
return $query->where('uuid', (string) $id);
|
||||
}
|
||||
|
||||
private static function columns(): array
|
||||
{
|
||||
return [
|
||||
'id', 'uuid', 'host_id', 'user_id', 'current_period_id', 'name',
|
||||
'status', 'service_status', 'network_status', 'expires_at',
|
||||
'renewal_price', 'renewal_days', 'renewal_traffic_bytes',
|
||||
'traffic_quota_bytes', 'traffic_download_bytes',
|
||||
'traffic_upload_bytes', 'spec_json', 'credential_cipher',
|
||||
'created_at', 'updated_at',
|
||||
];
|
||||
}
|
||||
|
||||
private static function listColumns(): array
|
||||
{
|
||||
return ['id', 'uuid', 'host_id', 'name', 'spec_json'];
|
||||
}
|
||||
|
||||
private static function pagination(int $page, int $perPage, int $total, int $count): array
|
||||
{
|
||||
$pages = max(1, (int) ceil($total / $perPage));
|
||||
return [
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
'page_count' => $count,
|
||||
'total' => $total,
|
||||
'total_pages' => $pages,
|
||||
'has_previous' => $page > 1,
|
||||
'has_next' => $page < $pages,
|
||||
'from' => $count === 0 ? 0 : (($page - 1) * $perPage) + 1,
|
||||
'to' => $count === 0 ? 0 : (($page - 1) * $perPage) + $count,
|
||||
];
|
||||
}
|
||||
|
||||
private static function stateCategory(string $state): string
|
||||
{
|
||||
$normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $state));
|
||||
if (in_array($normalized, ['running', 'blocked'], true)) {
|
||||
return 'running';
|
||||
}
|
||||
if (in_array($normalized, ['shutoff', 'stopped', 'crashed'], true)) {
|
||||
return 'stopped';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
}
|
||||
@ -1 +1 @@
|
||||
{assign var=venix_asset_version value='2026092804' scope='global'}
|
||||
{assign var=venix_asset_version value='2026092805' scope='global'}
|
||||
|
||||
@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class Config
|
||||
{
|
||||
public static function get($name, $default = null)
|
||||
{
|
||||
return $name === 'cloud_max_renewal_periods_ahead' ? 24 : $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudInstancePageService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('cloud_hosts', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('region')->default('');
|
||||
$table->string('country_code')->default('');
|
||||
});
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('uuid');
|
||||
$table->integer('host_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('current_period_id')->nullable();
|
||||
$table->string('name');
|
||||
$table->string('status');
|
||||
$table->string('service_status');
|
||||
$table->string('network_status');
|
||||
$table->integer('expires_at')->nullable();
|
||||
$table->string('renewal_price')->nullable();
|
||||
$table->integer('renewal_days')->default(0);
|
||||
$table->integer('renewal_traffic_bytes')->default(0);
|
||||
$table->integer('traffic_quota_bytes')->default(0);
|
||||
$table->integer('traffic_download_bytes')->default(0);
|
||||
$table->integer('traffic_upload_bytes')->default(0);
|
||||
$table->text('spec_json');
|
||||
$table->text('credential_cipher')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('starts_at');
|
||||
$table->integer('ends_at');
|
||||
$table->string('status');
|
||||
});
|
||||
|
||||
Capsule::table('cloud_hosts')->insert([
|
||||
'id' => 7, 'region' => 'HongKong', 'country_code' => 'HK',
|
||||
]);
|
||||
$now = time();
|
||||
$common = [
|
||||
'host_id' => 7, 'current_period_id' => null, 'status' => 'active',
|
||||
'service_status' => 'active', 'network_status' => 'active',
|
||||
'expires_at' => $now + 86400, 'renewal_price' => '10.00',
|
||||
'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
|
||||
'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
|
||||
'traffic_upload_bytes' => 200,
|
||||
'spec_json' => json_encode(['vcpu' => 2, 'memory_mib' => 2048, 'state' => 'running',
|
||||
'disk_gib' => 40, 'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10']),
|
||||
'credential_cipher' => 'test-cipher', 'created_at' => $now - 60,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
Capsule::table('cloud_instances')->insert($common + [
|
||||
'id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111',
|
||||
'user_id' => 1, 'name' => 'owner-vm',
|
||||
]);
|
||||
Capsule::table('cloud_instances')->insert($common + [
|
||||
'id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222',
|
||||
'user_id' => 2, 'name' => 'foreign-vm',
|
||||
]);
|
||||
|
||||
$owner = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
|
||||
'can_manage' => false];
|
||||
$admin = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => false,
|
||||
'can_manage' => false];
|
||||
$global = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => true,
|
||||
'can_manage' => true];
|
||||
|
||||
Capsule::connection('default')->flushQueryLog();
|
||||
Capsule::connection('default')->enableQueryLog();
|
||||
$page = CloudInstancePageService::forActor($owner, 1, 20);
|
||||
$pageQueryCount = count(Capsule::connection('default')->getQueryLog());
|
||||
Capsule::connection('default')->disableQueryLog();
|
||||
$assert($page['stats']['total'] === 1 && count($page['vms']) === 1
|
||||
&& $page['pagination']['page_count'] === 1
|
||||
&& $page['vms'][0]['name'] === 'owner-vm',
|
||||
'Ordinary user instance first page crossed the owner boundary.');
|
||||
$assert($pageQueryCount <= 3,
|
||||
'Instance first page regressed beyond count, rows and host batch queries.');
|
||||
$assert($page['vms'][0]['state'] === 'unknown',
|
||||
'Persisted specification power state was trusted before a live UUID check.');
|
||||
$assert(!array_key_exists('traffic_quota_bytes', $page['vms'][0])
|
||||
&& !array_key_exists('password_available', $page['vms'][0]),
|
||||
'Paginated instance rows leaked detail-only billing or credential metadata.');
|
||||
$ownedDetail = CloudInstancePageService::detailForActor($owner, 1);
|
||||
$assert($ownedDetail['can_operate'] && $ownedDetail['can_delete']
|
||||
&& $ownedDetail['password_available'] && $ownedDetail['can_renew'],
|
||||
'Owner lost expected instance capabilities.');
|
||||
$assert(count(CloudInstancePageService::forActorIds($owner, [1, 2])) === 1,
|
||||
'Ordinary user batch status scope disclosed a foreign instance.');
|
||||
|
||||
$adminPage = CloudInstancePageService::forActor($admin, 1, 20);
|
||||
$assert($adminPage['stats']['total'] === 2,
|
||||
'Read-only administrator lost the historical all-instance view.');
|
||||
$foreign = CloudInstancePageService::detailForActor($admin, 2);
|
||||
$assert(!$foreign['is_owner'] && !$foreign['can_operate']
|
||||
&& !$foreign['can_delete'] && !$foreign['can_view_credential']
|
||||
&& !$foreign['password_available'] && !$foreign['can_renew'],
|
||||
'Read-only administrator inherited foreign instance mutation or credential access.');
|
||||
|
||||
$managed = CloudInstancePageService::detailForActor($global, 2);
|
||||
$assert(!$managed['is_owner'] && $managed['can_operate']
|
||||
&& $managed['can_delete'] && $managed['can_view_credential']
|
||||
&& $managed['password_available'] && !$managed['can_renew'],
|
||||
'Super administrator capabilities no longer match the legacy VM boundary.');
|
||||
Capsule::connection('default')->flushQueryLog();
|
||||
Capsule::connection('default')->enableQueryLog();
|
||||
$mutable = CloudInstancePageService::statusForActor($global, 2);
|
||||
$statusQueryCount = count(Capsule::connection('default')->getQueryLog());
|
||||
Capsule::connection('default')->disableQueryLog();
|
||||
$assert($statusQueryCount <= 1 && $mutable['host_id'] === 7
|
||||
&& !array_key_exists('credential_cipher', $mutable)
|
||||
&& !array_key_exists('renewal_price', $mutable),
|
||||
'Detail status poll loaded static host, credential or renewal metadata.');
|
||||
$status = CloudInstancePageService::status($managed,
|
||||
['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']);
|
||||
$assert($status['state'] === 'running' && $status['traffic_used_bytes'] === 500
|
||||
&& $status['traffic_remaining_bytes'] === 1500
|
||||
&& $status['live_state_available'] === true,
|
||||
'Lightweight status did not merge live state with the database billing snapshot.');
|
||||
$unavailable = CloudInstancePageService::status($managed);
|
||||
$assert($unavailable['state'] === 'unknown'
|
||||
&& $unavailable['live_state_available'] === false,
|
||||
'Unavailable hosts were presented as confirmed live power state.');
|
||||
$power = CloudInstancePageService::powerStatus($managed,
|
||||
['uuid' => $managed['uuid'], 'name' => 'foreign-vm', 'state' => 'running']);
|
||||
$assert($power['state'] === 'running' && $power['live_state_available'] === true
|
||||
&& !array_key_exists('traffic_quota_bytes', $power)
|
||||
&& !array_key_exists('can_delete', $power),
|
||||
'List polling returned detail-only billing or permission fields.');
|
||||
|
||||
echo "Cloud instance page service ownership and administrator permissions passed.\n";
|
||||
}
|
||||
@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
// Static regression contract for the instance list/detail hybrid SSR boundary.
|
||||
// PHP and database snapshots own first paint; libvirt is consulted only by
|
||||
// the small status endpoints after the page is already usable.
|
||||
$root = dirname(__DIR__);
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$section = static function (string $source, string $start, string $end): string {
|
||||
$offset = strpos($source, $start);
|
||||
if ($offset === false) {
|
||||
return '';
|
||||
}
|
||||
$limit = strpos($source, $end, $offset + strlen($start));
|
||||
return $limit === false ? substr($source, $offset)
|
||||
: substr($source, $offset, $limit - $offset);
|
||||
};
|
||||
|
||||
$page = file_get_contents($root . '/app/Controllers/CloudPageController.php');
|
||||
$api = file_get_contents($root . '/app/Controllers/CloudApiController.php');
|
||||
$service = file_get_contents($root . '/app/Services/Cloud/CloudInstancePageService.php');
|
||||
$middleware = file_get_contents($root . '/app/Middleware/CloudApi.php');
|
||||
$routes = file_get_contents($root . '/config/routes_cloud.php');
|
||||
$pageService = $section($service, 'public static function forActor(',
|
||||
'public static function detailForActor(');
|
||||
|
||||
$assert(str_contains($service, "CloudInstance::where('status', '<>', 'deleted')")
|
||||
&& str_contains($service, "if (!(\$actor['is_admin'] ?? false))")
|
||||
&& str_contains($service, "->where('user_id', (int) \$actor['user_id'])")
|
||||
&& str_contains($service, '->limit($perPage)')
|
||||
&& str_contains($service, '->get(self::listColumns())')
|
||||
&& str_contains($service, "'per_page' => \$perPage")
|
||||
&& str_contains($service, "'page_count' => \$count")
|
||||
&& !str_contains($service, 'CloudEngineClient'),
|
||||
'Instance first-paint service must remain actor scoped, bounded and engine free.');
|
||||
$assert(str_contains($pageService, 'self::listSnapshots($records)')
|
||||
&& !str_contains($pageService, 'self::snapshots($records, $actor)'),
|
||||
'Instance list first paint must not load detail-only billing and credential data.');
|
||||
$assert(str_contains($service, "\$canDelete = \$lifecycleActive && (\$owner || \$global)")
|
||||
&& str_contains($service, "'can_view_credential' => \$owner || \$global")
|
||||
&& str_contains($service, "'can_renew' => \$lifecycleActive && \$owner")
|
||||
&& str_contains($service, "'state' => 'unknown'"),
|
||||
'Read-only administrators must not inherit owner or super-admin instance operations.');
|
||||
$assert(str_contains($service, 'CloudHost::whereIn')
|
||||
&& str_contains($service, 'CloudServicePeriod::whereIn')
|
||||
&& str_contains($service, "->groupBy('instance_id')"),
|
||||
'Instance page dependencies must remain bulk loaded instead of queried per row.');
|
||||
$assert(str_contains($service, 'private static function listItem(')
|
||||
&& str_contains($service, 'private static function listSnapshots(')
|
||||
&& str_contains($service, "->get(['id', 'uuid', 'host_id', 'name'])")
|
||||
&& str_contains($service, 'public static function powerStatus(')
|
||||
&& str_contains($service, "'live_state_available'")
|
||||
&& str_contains($service, "array_intersect_key"),
|
||||
'Instance list bootstrap and polling payloads must remain detail-free and bounded.');
|
||||
$assert(str_contains($service, 'public static function statusForActor(')
|
||||
&& str_contains($service, "'traffic_upload_bytes',")
|
||||
&& !str_contains($section($service, 'public static function statusForActor(',
|
||||
'public static function forActorIds('), 'credential_cipher'),
|
||||
'Detail status polling must load only mutable database state.');
|
||||
|
||||
$instances = $section($page, 'public function instances(', 'public function detail(');
|
||||
$detail = $section($page, 'public function detail(', 'public function deploy(');
|
||||
$assert(str_contains($instances, 'CloudAccess::actor(false)')
|
||||
&& str_contains($instances, 'CloudInstancePageService::forActor')
|
||||
&& str_contains($instances, "'cloud_vm_rows'")
|
||||
&& str_contains($instances, "'cloud_vm_bootstrap_json'"),
|
||||
'Instance list HTML must embed its owner-scoped database first page without a cloud session.');
|
||||
$assert(str_contains($detail, 'CloudAccess::actor(false)')
|
||||
&& str_contains($detail, 'CloudInstancePageService::detailForActor')
|
||||
&& str_contains($detail, "'cloud_vm_view'")
|
||||
&& str_contains($detail, "'cloud_vm_bootstrap_json'"),
|
||||
'Instance detail HTML must embed a useful owner-scoped database snapshot.');
|
||||
$assert(str_contains($page, 'JSON_HEX_TAG')
|
||||
&& str_contains($page, "'csrf_token' => AdminCsrf::token()")
|
||||
&& str_contains($page, "withHeader('Cache-Control', 'private, no-store')"),
|
||||
'Embedded instance state must be script-safe, authenticated and non-cacheable.');
|
||||
|
||||
$pageRoute = strpos($routes, "'/vms/page'");
|
||||
$statusesRoute = strpos($routes, "'/vms/statuses'");
|
||||
$statusRoute = strpos($routes, "'/vms/{id:[0-9]+}/status'");
|
||||
$legacyRoute = strpos($routes, "'/vms/{id}'");
|
||||
$assert($pageRoute !== false && $statusesRoute !== false && $statusRoute !== false
|
||||
&& $legacyRoute !== false && $pageRoute < $legacyRoute
|
||||
&& $statusesRoute < $legacyRoute && $statusRoute < $legacyRoute,
|
||||
'Lightweight fixed VM routes must precede the legacy dynamic VM route.');
|
||||
|
||||
$pageApi = $section($api, 'public function vmPage(', 'public function vmStatuses(');
|
||||
$statusesApi = $section($api, 'public function vmStatuses(', 'public function vmStatus(');
|
||||
$statusApi = $section($api, 'public function vmStatus(', 'public function vm(');
|
||||
$assert(str_contains($pageApi, '$this->billingActor($request)')
|
||||
&& str_contains($pageApi, 'CloudInstancePageService::forActor')
|
||||
&& !str_contains($pageApi, 'CloudEngineClient'),
|
||||
'Paginated VM rows must not create an engine session or contact libvirt.');
|
||||
$assert(str_contains($statusesApi, 'CloudInstancePageService::forActorIds')
|
||||
&& str_contains($statusesApi, 'CloudInstancePageService::powerStatus')
|
||||
&& str_contains($statusesApi, "'GET', 'vm-states'")
|
||||
&& str_contains($statusesApi, 'isset($allowed[$uuid])')
|
||||
&& !str_contains($statusesApi, "'GET', 'vms'"),
|
||||
'Batch VM status must intersect owner UUIDs and use only the lightweight engine resource.');
|
||||
$assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor')
|
||||
&& str_contains($statusApi, ". '/state'")
|
||||
&& str_contains($statusApi, 'hash_equals('),
|
||||
'Single VM status must be owner scoped, UUID checked and avoid the full VM detail resource.');
|
||||
$assert(str_contains($middleware, "\$path === '/api/v1/vms/page'")
|
||||
&& str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'),
|
||||
'Database-only VM pagination must not allocate a private-engine cloud session.');
|
||||
|
||||
echo "Instance list/detail SSR and lightweight live-status contract passed.\n";
|
||||
Loading…
Reference in New Issue