perf(user): render cloud pages on first paint
parent
cee8b9a1f5
commit
c46203afe9
@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Display-only first paints built from the existing actor-scoped public DTOs. */
|
||||
final class CloudUserPageView
|
||||
{
|
||||
public static function backups(array $payload): array
|
||||
{
|
||||
$items = [];
|
||||
foreach ($payload['items'] ?? [] as $backup) {
|
||||
$id = (string) ($backup['id'] ?? '');
|
||||
[$label, $class] = self::state((string) ($backup['state'] ?? ''), [
|
||||
'ready' => ['可用', 'running'], 'creating' => ['正在备份', 'warning'],
|
||||
'queued' => ['等待备份', 'warning'], 'failed' => ['备份失败', 'stopped'],
|
||||
'uncertain' => ['等待核对', 'warning'], 'deleting' => ['正在删除', 'warning'],
|
||||
'delete_uncertain' => ['删除待核对', 'warning'],
|
||||
'delete_attention' => ['清理需人工处理', 'stopped'],
|
||||
]);
|
||||
$source = $backup['source_instance'] ?? [];
|
||||
$sourceId = (string) ($source['id'] ?? '');
|
||||
$deleted = ($source['deleted'] ?? false) === true
|
||||
|| in_array($source['status'] ?? '', ['deleted', 'missing'], true);
|
||||
$snapshot = $backup['cloud_snapshot'] ?? [];
|
||||
$snapshotKey = (string) ($snapshot['snapshot_key'] ?? $snapshot['key'] ?? '');
|
||||
$items[] = [
|
||||
'id' => $id, 'name' => self::text($backup['name'] ?? '', '云备份 #' . $id),
|
||||
'source_label' => $deleted ? '源实例已删除'
|
||||
: '来源:' . self::text($source['name'] ?? '', $sourceId !== '' ? '实例 #' . $sourceId : '实例未记录'),
|
||||
'state_label' => $label, 'state_class' => $class,
|
||||
'date_display' => self::date($backup['ready_at'] ?? $backup['created_at'] ?? null),
|
||||
'consistency_display' => ($backup['consistency'] ?? '') === 'filesystem' ? '文件系统一致' : '崩溃一致',
|
||||
'object_display' => self::bytes($backup['object_size_bytes'] ?? null),
|
||||
'disk_display' => self::bytes($backup['virtual_size_bytes'] ?? null),
|
||||
'restore_href' => !$deleted && ($backup['can_restore_original'] ?? false) === true
|
||||
&& preg_match('/^[1-9][0-9]*$/D', $sourceId) === 1
|
||||
? '/user/cloud/instances/' . $sourceId . '?tab=settings&setting=automatic_backup' : '',
|
||||
'snapshot_href' => preg_match('/^[a-f0-9]{32}$/D', $snapshotKey) === 1
|
||||
? '/user/cloud/cloud-snapshots#cloud-snapshot-' . $snapshotKey : '',
|
||||
'can_promote' => ($backup['can_promote'] ?? false) === true,
|
||||
];
|
||||
}
|
||||
return ['items' => $items, 'pagination' => self::pagination($payload)];
|
||||
}
|
||||
|
||||
public static function cloudSnapshots(array $payload): array
|
||||
{
|
||||
$items = [];
|
||||
foreach ($payload['items'] ?? [] as $snapshot) {
|
||||
$key = (string) ($snapshot['snapshot_key'] ?? '');
|
||||
[$label, $class] = self::state((string) ($snapshot['state'] ?? ''), [
|
||||
'ready' => ['可用', 'running'], 'promoting' => ['正在保存', 'warning'],
|
||||
'deleting' => ['正在删除', 'warning'], 'delete_uncertain' => ['删除待核对', 'warning'],
|
||||
'failed' => ['保存失败', 'stopped'],
|
||||
]);
|
||||
$source = $snapshot['source_instance'] ?? [];
|
||||
$sourceName = self::text($source['name'] ?? '', !empty($source['id']) ? '实例 #' . $source['id'] : '来源实例未记录');
|
||||
$pending = max(0, (int) ($snapshot['active_invoice_count'] ?? 0));
|
||||
$items[] = [
|
||||
'key' => $key, 'name' => self::text($snapshot['name'] ?? '', '云快照 ' . substr($key, 0, 8)),
|
||||
'source_label' => '来源:' . $sourceName . ($pending > 0 ? ' · ' . $pending . ' 张待支付账单' : ''),
|
||||
'state_label' => $label, 'state_class' => $class,
|
||||
'date_display' => self::date($snapshot['ready_at'] ?? $snapshot['created_at'] ?? null),
|
||||
'os_display' => self::text($snapshot['os_name'] ?? '', '系统未记录'),
|
||||
'object_display' => self::bytes($snapshot['object_size_bytes'] ?? null),
|
||||
'disk_display' => self::bytes($snapshot['virtual_size_bytes'] ?? null),
|
||||
'create_href' => ($snapshot['can_create_instance'] ?? false) === true
|
||||
&& preg_match('/^[a-f0-9]{32}$/D', $key) === 1 ? '/user/cloud/deploy?cloud_snapshot=' . $key : '',
|
||||
'delete_title' => ($snapshot['can_delete'] ?? false) === true ? ''
|
||||
: ($pending > 0 ? '存在待支付账单,请先支付或等待账单失效后再删除。' : '云快照当前状态不允许删除。'),
|
||||
];
|
||||
}
|
||||
return ['items' => $items, 'pagination' => self::pagination($payload)];
|
||||
}
|
||||
|
||||
public static function vpcs(array $payload, array $query): array
|
||||
{
|
||||
$networks = [];
|
||||
$current = null;
|
||||
$key = is_string($query['vpc'] ?? null) ? $query['vpc'] : '';
|
||||
$view = is_string($query['view'] ?? null) ? $query['view'] : '';
|
||||
$page = $key !== '' ? 'members' : ($view === 'create' ? 'create' : 'home');
|
||||
if ((isset($query['vpc']) && preg_match('/^[a-f0-9]{32}$/D', $key) !== 1)
|
||||
|| (isset($query['view']) && !in_array($view, ['create', 'members', 'join'], true))
|
||||
|| ($key === '' && in_array($view, ['members', 'join'], true))) {
|
||||
$page = 'missing';
|
||||
}
|
||||
$batches = $payload['membership_batches'] ?? [];
|
||||
foreach ($payload['items'] ?? [] as $network) {
|
||||
$networkKey = (string) ($network['vpc_key'] ?? '');
|
||||
$batch = null;
|
||||
foreach ($batches as $candidate) {
|
||||
if (($candidate['vpc_key'] ?? '') === $networkKey) { $batch = $candidate; break; }
|
||||
}
|
||||
[$label, $class] = ($network['state'] ?? '') === 'active'
|
||||
? ['运行正常', 'running'] : [self::text($network['state'] ?? '', '状态未知'), 'other'];
|
||||
$network['state_label'] = $batch !== null ? '变更中' : $label;
|
||||
$network['state_class'] = $batch !== null ? 'other' : $class;
|
||||
$network['members_href'] = '/user/cloud/vpcs?vpc=' . rawurlencode($networkKey);
|
||||
$network['join_href'] = $network['members_href'] . '&view=join';
|
||||
$network['batch'] = $batch;
|
||||
$networks[] = $network;
|
||||
if ($networkKey === $key) {
|
||||
$current = $network;
|
||||
$current['state_label'] = $label;
|
||||
$current['state_class'] = $class;
|
||||
}
|
||||
}
|
||||
if ($page === 'members' && $current === null) $page = 'missing';
|
||||
$members = [];
|
||||
$candidates = [];
|
||||
foreach ($payload['instances'] ?? [] as $instance) {
|
||||
if ($current === null) break;
|
||||
$port = $instance['port'] ?? null;
|
||||
$joined = is_array($port) && ($port['vpc_key'] ?? '') === $key;
|
||||
$candidate = $port === null && (int) ($instance['region_id'] ?? 0) === (int) $current['region_id'];
|
||||
if (!$joined && !$candidate) continue;
|
||||
[$label, $class] = $candidate
|
||||
? (($instance['can_attach'] ?? false) === true ? ['可加入', 'running'] : ['暂不可加入', 'other'])
|
||||
: self::state((string) ($port['state'] ?? ''), [
|
||||
'preparing' => ['正在连接', 'other'], 'attached' => ['已连接', 'running'],
|
||||
'detaching' => ['正在断开', 'other'], 'release_pending' => ['等待清理', 'other'],
|
||||
'released' => ['已断开', 'other'], 'migrating' => ['正在迁移', 'other'],
|
||||
]);
|
||||
foreach ($current['batch']['items'] ?? [] as $batchItem) {
|
||||
if ((string) ($batchItem['instance_id'] ?? '') !== (string) $instance['id']) continue;
|
||||
[$label, $class] = self::state((string) ($batchItem['state'] ?? ''), [
|
||||
'waiting_route' => ['等待中', 'other'], 'queued' => ['执行中', 'other'],
|
||||
'succeeded' => ['已完成', 'running'], 'failed' => ['失败', 'failed'], 'unknown' => ['失败', 'failed'],
|
||||
]);
|
||||
break;
|
||||
}
|
||||
$instance['state_label'] = $label;
|
||||
$instance['state_class'] = $class;
|
||||
$instance['public_ipv4'] = self::text($instance['public_ipv4'] ?? '', '未分配');
|
||||
if ($joined) $members[] = $instance; else $candidates[] = $instance;
|
||||
}
|
||||
return [
|
||||
'page' => $page, 'joining' => $view === 'join', 'networks' => $networks,
|
||||
'regions' => $payload['regions'] ?? [], 'current' => $current,
|
||||
'members' => $view === 'join' ? $candidates : $members,
|
||||
'member_count' => count($members),
|
||||
'joinable_count' => count(array_filter($candidates, static fn (array $item): bool => ($item['can_attach'] ?? false) === true)),
|
||||
'used' => max(0, (int) ($payload['used'] ?? count($networks))),
|
||||
'maximum' => max(1, (int) ($payload['maximum'] ?? 16)),
|
||||
];
|
||||
}
|
||||
|
||||
public static function isos(array $payload): array
|
||||
{
|
||||
$items = [];
|
||||
foreach ($payload['isos'] ?? [] as $iso) {
|
||||
$iso['size_display'] = self::bytes($iso['size_bytes'] ?? null);
|
||||
$iso['fingerprint_display'] = !empty($iso['sha256']) ? ' · SHA-256 ' . substr((string) $iso['sha256'], 0, 12) . '…' : '';
|
||||
$items[] = $iso;
|
||||
}
|
||||
return ['items' => $items, 'can_import' => ($payload['can_import'] ?? false) === true,
|
||||
'import_active' => ($payload['active_import_job']['completed'] ?? true) === false];
|
||||
}
|
||||
|
||||
private static function pagination(array $payload): array
|
||||
{
|
||||
$value = $payload['pagination'] ?? [];
|
||||
$page = max(1, (int) ($value['page'] ?? 1));
|
||||
$pages = max(1, (int) ($value['total_pages'] ?? 1));
|
||||
return ['page' => $page, 'total_pages' => $pages,
|
||||
'total' => max(0, (int) ($value['total'] ?? count($payload['items'] ?? []))),
|
||||
'has_previous' => $page > 1, 'has_next' => $page < $pages];
|
||||
}
|
||||
|
||||
private static function text($value, string $fallback): string
|
||||
{
|
||||
$text = trim((string) $value);
|
||||
return $text !== '' ? $text : $fallback;
|
||||
}
|
||||
|
||||
private static function state(string $value, array $labels): array
|
||||
{
|
||||
return $labels[$value] ?? [self::text($value, '状态未知'), 'other'];
|
||||
}
|
||||
|
||||
private static function date($value): string
|
||||
{
|
||||
return is_numeric($value) && (float) $value > 0
|
||||
? date('Y/m/d H:i:s', (int) ((float) $value >= 1e12 ? (float) $value / 1000 : $value)) : '时间未记录';
|
||||
}
|
||||
|
||||
private static function bytes($value): string
|
||||
{
|
||||
if (!is_numeric($value) || (float) $value < 0) return '等待完成';
|
||||
$amount = (float) $value;
|
||||
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
||||
$index = 0;
|
||||
while ($amount >= 1024 && $index < count($units) - 1) { $amount /= 1024; ++$index; }
|
||||
$precision = $index === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2));
|
||||
return number_format($amount, $precision, '.', '') . ' ' . $units[$index];
|
||||
}
|
||||
}
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026103006' scope='global'}
|
||||
{assign var=venix_asset_version value='2026103007' scope='global'}
|
||||
|
||||
@ -0,0 +1,126 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const source = (await readFile(new URL('../public/cloud/app.js', import.meta.url), 'utf8'))
|
||||
.replaceAll('import.meta.url', JSON.stringify('https://panel.example.test/cloud/app.js?v=fixture'))
|
||||
.replaceAll('import(', 'loadModule(');
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
const deferred = () => {
|
||||
let resolve;
|
||||
const promise = new Promise(done => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
};
|
||||
|
||||
async function start(taskModule, pageModule) {
|
||||
const requested = [];
|
||||
const nodes = new Map(['cloud-page-error', 'panel-task-state'].map(id => [id, { textContent: '', hidden: true }]));
|
||||
vm.runInNewContext(source, {
|
||||
URL,
|
||||
document: { body: { dataset: { cloudPage: 'deploy' } }, getElementById: id => nodes.get(id) },
|
||||
loadModule: async href => {
|
||||
const path = new URL(href).pathname;
|
||||
requested.push(path);
|
||||
return path === '/cloud/task-center.js' ? taskModule() : pageModule();
|
||||
},
|
||||
});
|
||||
await tick();
|
||||
return { requested, nodes };
|
||||
}
|
||||
|
||||
{
|
||||
const task = deferred();
|
||||
let pageReady = false, taskReady = false;
|
||||
const test = await start(() => task.promise, () => ({ initialize() { pageReady = true; } }));
|
||||
assert.equal(pageReady, true, 'A pending task-center module blocks the page.');
|
||||
assert(test.requested.includes('/cloud/deploy.js'));
|
||||
task.resolve({ initializeTaskCenter() { taskReady = true; } });
|
||||
await tick();
|
||||
assert.equal(taskReady, true);
|
||||
}
|
||||
|
||||
{
|
||||
let pageReady = false;
|
||||
const test = await start(() => Promise.reject(new Error('fixture task download failure')),
|
||||
() => ({ initialize() { pageReady = true; } }));
|
||||
assert.equal(pageReady, true, 'A failed task-center download prevents page initialization.');
|
||||
assert.equal(test.nodes.get('cloud-page-error').textContent, '');
|
||||
assert.match(test.nodes.get('panel-task-state').textContent, /任务中心/);
|
||||
}
|
||||
|
||||
{
|
||||
let taskReady = false;
|
||||
const test = await start(() => ({ initializeTaskCenter() { taskReady = true; } }),
|
||||
() => ({ initialize: async () => { throw new Error('fixture page failure'); } }));
|
||||
assert.equal(taskReady, true);
|
||||
assert.equal(test.nodes.get('cloud-page-error').textContent, 'fixture page failure',
|
||||
'An asynchronous page initialization error escapes the shared error handler.');
|
||||
}
|
||||
|
||||
const runtime = await readFile(new URL('../public/cloud/runtime.js', import.meta.url), 'utf8');
|
||||
const session = runtime.slice(runtime.indexOf('async function initializeSession('), runtime.indexOf('async function selectVmByApiId('));
|
||||
{
|
||||
const vpcs = await readFile(new URL('../public/cloud/vpcs.js', import.meta.url), 'utf8');
|
||||
const initialize = vpcs.slice(vpcs.indexOf('export async function initialize()')).replace('export ', '');
|
||||
const bootstrap = { user: { user_id: '7', csrf_token: 'fixture' }, items: [], instances: [], regions: [] };
|
||||
let rendered = false;
|
||||
const context = vm.createContext({ state: {}, readBootstrap: () => bootstrap,
|
||||
applyCloudUser() {}, api() { throw Error('Unexpected first-paint session or library fetch'); },
|
||||
byId: () => ({ addEventListener() {} }), apply() { rendered = true; },
|
||||
setPageStatus() {}, bindBatchConfirmation() {}, createVpc() {}, routeChanged() {},
|
||||
window: { addEventListener() {} }, location: { assign() {} }, showError(id, message) { throw Error(message); },
|
||||
});
|
||||
vm.runInContext(session + '\n' + initialize, context);
|
||||
await vm.runInContext('initialize()', context);
|
||||
assert.equal(rendered, true, 'VPC bootstrap requires an additional session or library request.');
|
||||
}
|
||||
|
||||
{
|
||||
const isos = await readFile(new URL('../public/cloud/iso-images.js', import.meta.url), 'utf8');
|
||||
const apply = isos.slice(isos.indexOf('function applyIsoPayload('), isos.indexOf('function taskFailureMessage('));
|
||||
const initialize = isos.slice(isos.indexOf('export async function initialize()')).replace('export ', '');
|
||||
const bootstrap = { user: { user_id: '7' }, isos: [{ id: 'iso-one' }], can_import: false,
|
||||
active_import_job: { task_id: '41', completed: false } };
|
||||
const pageState = { isos: [], importObserver: null };
|
||||
let observed = '', rendered = false;
|
||||
const context = vm.createContext({ state: {}, pageState, readBootstrap: () => bootstrap,
|
||||
applyCloudUser() {}, api() { throw Error('Unexpected initial ISO request'); },
|
||||
byId: () => ({ addEventListener() {} }), bindPageCleanup() {},
|
||||
renderIsos() { rendered = true; }, taskUrl: receipt => receipt.status_url,
|
||||
setImportStatus() {}, updateImportAvailability() {}, watchImport(receipt) { observed = receipt.task_id; },
|
||||
importIso() {}, window: { addEventListener() {} }, location: { assign() {} },
|
||||
showError(id, message) { throw Error(message); },
|
||||
});
|
||||
vm.runInContext(session + '\n' + apply + '\n' + initialize, context);
|
||||
await vm.runInContext('initialize()', context);
|
||||
assert.equal(rendered, true);
|
||||
assert.equal(pageState.canImport, false);
|
||||
assert.equal(observed, '41', 'ISO hydration failed to observe the original in-flight task.');
|
||||
}
|
||||
|
||||
{
|
||||
const sales = runtime.slice(runtime.indexOf('function saleRegions('), runtime.indexOf('function setDeploymentStepEnabled('));
|
||||
const pricing = runtime.slice(runtime.indexOf('function selectedSaleOffer('), runtime.indexOf('function updateCreateAvailability('));
|
||||
const openCreate = runtime.slice(runtime.indexOf('async function openCreate('), runtime.indexOf('async function loadGlobalTemplates('));
|
||||
const nodes = new Map();
|
||||
const byId = id => {
|
||||
if (!nodes.has(id)) nodes.set(id, { value: '', checked: false, dataset: {}, classList: { toggle() {} }, addEventListener() {} });
|
||||
return nodes.get(id);
|
||||
};
|
||||
byId('vm-automatic-backup').checked = true;
|
||||
const bootstrap = { regions: [{ id: 1 }], lines: [{ id: 1, region_id: 1, is_default: true }],
|
||||
offers: [{ id: 1, region_id: 1, line_id: 1, currency: 'USD', sellable: true, price: '10.00', backup_price: '2.00' }],
|
||||
default_offer_id: 1, templates: [], ssh_keys: [] };
|
||||
const context = vm.createContext({ state: { regions: [], lines: [], offers: [], templates: [], selectedKeys: {} }, byId,
|
||||
bootstrapItems: (value, key) => value[key] || [], showError() {},
|
||||
renderRegionPicker() {}, renderLinePicker() {}, renderOfferPicker() {}, renderTemplateCatalog() {}, renderKeyCards() {},
|
||||
setDeploymentStepEnabled() {}, updateCreateAvailability() {}, formatUsd: value => `$${Number(value).toFixed(2)} USD`,
|
||||
});
|
||||
vm.runInContext(sales + '\n' + pricing + '\n' + openCreate, context);
|
||||
context.bootstrap = bootstrap;
|
||||
await vm.runInContext('openCreate(bootstrap)', context);
|
||||
assert.equal(byId('vm-automatic-backup').checked, true, 'Hydration clears a backup choice made while the module was loading.');
|
||||
assert.equal(byId('vm-order-total-price').textContent, '$12.00 USD');
|
||||
}
|
||||
|
||||
console.log('Independent page/task boot, embedded VPC/ISO hydration, original task resumption and deployment selection preservation passed.');
|
||||
@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudUserPageView;
|
||||
|
||||
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
|
||||
if (error_reporting() & $severity) throw new ErrorException($message, 0, $severity, $file, $line);
|
||||
return false;
|
||||
});
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) throw new RuntimeException($message);
|
||||
};
|
||||
$smarty = new Smarty();
|
||||
$compileDir = sys_get_temp_dir() . '/virt-user-first-paint-' . bin2hex(random_bytes(6));
|
||||
mkdir($compileDir);
|
||||
$smarty->setCompileDir($compileDir);
|
||||
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
|
||||
$render = static function (string $page, array $values) use ($smarty): DOMXPath {
|
||||
$smarty->clearAllAssign();
|
||||
$smarty->assign('cloud_vm_bootstrap_json', '{}');
|
||||
$smarty->assign($values);
|
||||
$html = $smarty->fetch('cloud/pages/' . $page . '.tpl');
|
||||
$dom = new DOMDocument();
|
||||
$old = libxml_use_internal_errors(true);
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($old);
|
||||
return new DOMXPath($dom);
|
||||
};
|
||||
$one = static function (DOMXPath $xpath, string $id): DOMElement {
|
||||
$node = $xpath->query('//*[@id="' . $id . '"]')->item(0);
|
||||
if (!$node instanceof DOMElement) throw new RuntimeException('Missing first-paint element ' . $id);
|
||||
return $node;
|
||||
};
|
||||
$unsafe = '<img src=x onerror=alert(1)>';
|
||||
$backup = ['id' => 9, 'name' => $unsafe, 'state' => 'ready',
|
||||
'source_instance' => ['id' => '7', 'name' => 'vm-seven', 'status' => 'active'],
|
||||
'created_at' => 1793404800, 'consistency' => 'filesystem',
|
||||
'object_size_bytes' => 1024, 'virtual_size_bytes' => 25 * 1073741824,
|
||||
'can_restore_original' => false, 'can_promote' => true];
|
||||
$payload = ['items' => [$backup], 'pagination' => ['page' => 2, 'total' => 41, 'total_pages' => 3]];
|
||||
$xpath = $render('backups', ['cloud_backup_view' => CloudUserPageView::backups($payload)]);
|
||||
$assert(str_contains($one($xpath, 'cloud-backups-list')->textContent, $unsafe)
|
||||
&& $xpath->query('//img')->length === 0, 'Backup first paint is empty or contains unescaped names.');
|
||||
$assert($one($xpath, 'cloud-backups-count')->textContent === '41 个'
|
||||
&& $one($xpath, 'cloud-backups-page')->textContent === '第 2 / 3 页'
|
||||
&& $one($xpath, 'cloud-backups-status')->hasAttribute('hidden'), 'Backup count, page or loaded state is incorrect.');
|
||||
$assert($xpath->query('//a[contains(@href,"setting=automatic_backup")]')->length === 0,
|
||||
'First paint invented original-restore permission for an ineligible backup.');
|
||||
$backup['can_restore_original'] = true;
|
||||
$xpath = $render('backups', ['cloud_backup_view' => CloudUserPageView::backups(['items' => [$backup]])]);
|
||||
$assert($xpath->query('//a[contains(@href,"/instances/7?tab=settings")]')->length === 1, 'Eligible original restore link is missing.');
|
||||
|
||||
$key = str_repeat('a', 32);
|
||||
$snapshot = ['snapshot_key' => $key, 'name' => 'snapshot-before-js', 'state' => 'ready',
|
||||
'source_instance' => ['id' => '7', 'name' => 'vm-seven'], 'created_at' => 1793404800,
|
||||
'can_create_instance' => true, 'can_delete' => false, 'active_invoice_count' => 1];
|
||||
$xpath = $render('cloud-snapshots', ['cloud_snapshot_view' => CloudUserPageView::cloudSnapshots(['items' => [$snapshot]])]);
|
||||
$assert(str_contains($one($xpath, 'cloud-snapshots-list')->textContent, 'snapshot-before-js')
|
||||
&& $xpath->query('//a[@href="/user/cloud/deploy?cloud_snapshot=' . $key . '"]')->length === 1,
|
||||
'Cloud snapshot first paint lost its name or deployment link.');
|
||||
$assert($xpath->query('//button[@title="存在待支付账单,请先支付或等待账单失效后再删除。" and @disabled]')->length === 1,
|
||||
'Snapshot first paint lost pending-invoice deletion protection.');
|
||||
|
||||
$vpc = ['vpc_key' => $key, 'name' => 'vpc-before-js', 'region_id' => 1,
|
||||
'region_name' => '香港', 'cidr' => '10.0.1.0/24', 'gateway' => '10.0.1.1', 'state' => 'active', 'port_count' => 1];
|
||||
$member = ['id' => '7', 'name' => 'vm-member', 'region_id' => 1, 'public_ipv4' => '192.0.2.7',
|
||||
'port' => ['vpc_key' => $key, 'state' => 'attached', 'private_ip' => '10.0.1.2', 'mac_address' => '02:11:22:33:44:55']];
|
||||
$candidate = ['id' => '8', 'name' => 'vm-candidate', 'region_id' => 1, 'public_ipv4' => '192.0.2.8', 'port' => null, 'can_attach' => true];
|
||||
$elsewhere = $candidate; $elsewhere['id'] = '99'; $elsewhere['name'] = 'other-region'; $elsewhere['region_id'] = 2;
|
||||
$library = ['items' => [$vpc], 'regions' => [['id' => 1, 'name' => '香港']],
|
||||
'instances' => [$member, $candidate, $elsewhere], 'used' => 1, 'maximum' => 16];
|
||||
foreach ([['query' => [], 'page' => 'home'], ['query' => ['view' => 'create'], 'page' => 'create'],
|
||||
['query' => ['vpc' => $key], 'page' => 'members'],
|
||||
['query' => ['vpc' => $key, 'view' => 'join'], 'page' => 'members'],
|
||||
['query' => ['vpc' => str_repeat('b', 32)], 'page' => 'missing'],
|
||||
['query' => ['vpc' => ['invalid']], 'page' => 'missing']] as $case) {
|
||||
$view = CloudUserPageView::vpcs($library, $case['query']);
|
||||
$xpath = $render('vpcs', ['cloud_vpc_view' => $view]);
|
||||
$assert(!$one($xpath, 'cloud-vpcs-' . $case['page'])->hasAttribute('hidden'), 'VPC initial route is hidden before JavaScript.');
|
||||
$assert($one($xpath, 'cloud-vpcs-quota')->textContent === '1 / 16 个', 'VPC first paint resets the quota to zero.');
|
||||
if ($case['page'] === 'home') $assert(str_contains($one($xpath, 'cloud-vpcs-list')->textContent, 'vpc-before-js'), 'VPC list is empty.');
|
||||
if ($case['page'] === 'create') $assert($xpath->query('//select[@id="cloud-vpc-region"]/option[@value="1"]')->length === 1, 'VPC regions wait for JavaScript.');
|
||||
if ($case['page'] === 'members') {
|
||||
$text = $one($xpath, 'cloud-vpc-instance-manager')->textContent;
|
||||
$joining = ($case['query']['view'] ?? '') === 'join';
|
||||
$assert(str_contains($text, $joining ? 'vm-candidate' : 'vm-member')
|
||||
&& !str_contains($text, 'other-region')
|
||||
&& str_contains($text, $joining ? '192.0.2.8' : '10.0.1.2'), 'VPC members or addresses do not match the requested view.');
|
||||
}
|
||||
}
|
||||
|
||||
$deploy = ['cloud_deploy_default_region_id' => 1, 'cloud_deploy_default_line_id' => 1,
|
||||
'cloud_deploy_default_offer_id' => 1, 'cloud_deploy_lines_enabled' => false,
|
||||
'cloud_deploy_regions' => [['id' => 1, 'name' => '香港']], 'cloud_deploy_lines' => [],
|
||||
'cloud_deploy_offers' => [['id' => 1, 'name' => 'plan', 'region_id' => 1, 'line_id' => 1,
|
||||
'sellable' => true, 'cpu_cores' => 1, 'memory_mib' => 1024, 'disk_gib' => 25,
|
||||
'traffic_gib' => 1024, 'traffic_tib' => '1']], 'cloud_deploy_template_groups' => [],
|
||||
'cloud_deploy_ssh_keys' => [], 'cloud_deploy_bootstrap_json' => '{}',
|
||||
'cloud_deploy_price' => '$10.00 USD', 'cloud_deploy_backup_price' => '$2.00 USD', 'cloud_deploy_snapshot' => null];
|
||||
$xpath = $render('deploy', $deploy);
|
||||
$assert(!$one($xpath, 'vm-order-summary')->hasAttribute('hidden')
|
||||
&& $one($xpath, 'vm-order-total-price')->textContent === '$10.00 USD'
|
||||
&& !$one($xpath, 'vm-automatic-backup')->hasAttribute('disabled'), 'Selected plan pricing or backup availability waits for JavaScript.');
|
||||
$deploy['cloud_deploy_snapshot'] = ['snapshot_key' => $key, 'name' => $unsafe];
|
||||
$xpath = $render('deploy', $deploy);
|
||||
$assert(!$one($xpath, 'vm-cloud-snapshot-source')->hasAttribute('hidden')
|
||||
&& $one($xpath, 'vm-template-field')->hasAttribute('hidden')
|
||||
&& $one($xpath, 'vm-cloud-fields')->hasAttribute('hidden')
|
||||
&& $one($xpath, 'vm-root-password')->hasAttribute('disabled')
|
||||
&& $one($xpath, 'vm-cloud-snapshot-key')->getAttribute('value') === $key
|
||||
&& $xpath->query('//img')->length === 0, 'Snapshot deployment first paint shows normal installation controls or unsafe names.');
|
||||
|
||||
$xpath = $render('isos', ['cloud_iso_view' => CloudUserPageView::isos(['isos' => [
|
||||
['id' => 'iso', 'name' => 'iso-before-js', 'size_bytes' => 1024, 'sha256' => str_repeat('a', 64), 'can_delete' => true],
|
||||
]])]);
|
||||
$assert(str_contains($one($xpath, 'user-iso-list')->textContent, 'iso-before-js'), 'Personal ISO library waits for JavaScript.');
|
||||
|
||||
$xpath = $render('detail', ['cloud_vm_view' => ['can_operate' => true, 'can_delete' => true],
|
||||
'cloud_detail_has_ssh_keys' => false, 'cloud_detail_no_ssh_keys' => true]);
|
||||
$assert($xpath->query('//*[@id="vm-detail-primary-actions"]/button[@disabled and @class="row-button"]')->length === 4,
|
||||
'Instance daily actions wait for JavaScript or use different first-paint styling.');
|
||||
$xpath = $render('detail', ['cloud_vm_view' => ['can_operate' => false, 'can_delete' => false],
|
||||
'cloud_detail_has_ssh_keys' => false, 'cloud_detail_no_ssh_keys' => true]);
|
||||
$assert($xpath->query('//*[@id="vm-detail-primary-actions"]/button')->length === 0,
|
||||
'Read-only first paint exposes owner power controls.');
|
||||
|
||||
echo "User backup, cloud-snapshot, VPC routes, deployment pricing/source, ISO and instance-action first paints passed without JavaScript.\n";
|
||||
Loading…
Reference in New Issue