perf: render deployment workflows on first response

dev
admin 2 months ago
parent dad9fa6ad2
commit b82abf5547

@ -3,6 +3,7 @@ namespace App\Controllers;
use App\Models\CloudHost;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
@ -182,9 +183,13 @@ final class CloudAdminController
if (isset($args['job_id'])) {
$path .= '/import-jobs/' . rawurlencode($args['job_id']);
}
return $response->withJson(
(new CloudEngineClient())->request($method, $path, $actor, $body)
);
$result = (new CloudEngineClient())->request($method, $path, $actor, $body);
if ($method === 'GET' && !isset($args['job_id']) && !isset($args['id'])) {
CloudDeploymentPageService::rememberTemplateCatalog($result);
} elseif (is_array($result['template'] ?? null)) {
CloudDeploymentPageService::rememberTemplate($result['template']);
}
return $response->withJson($result);
}
// Rescue ISOs remain deliberately scoped to one host and its separate

@ -14,6 +14,7 @@ use App\Services\Auth;
use App\Services\AdminCsrf;
use App\Services\Config;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
@ -130,30 +131,7 @@ final class CloudApiController
public function plans($request, $response)
{
$plans = [];
$available = Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get();
$hostIds = $available->pluck('host_id')->map(static fn ($id) => (int) $id)
->filter(static fn ($id) => $id > 0)->unique()->values()->all();
$hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds)
->where('enabled', 1)->get()->keyBy('id');
foreach ($available as $plan) {
if ((int) $plan->stock === 0) {
continue;
}
$host = $hosts->get((int) $plan->host_id);
if ($host !== null) {
$plans[] = ['id' => (int) $plan->id, 'name' => $plan->name, 'price' => (string) $plan->price,
'cpu_cores' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'disk_gib' => (int) $plan->disk_gib,
'validity_days' => (int) $plan->validity_days,
'traffic_quota_bytes' => (int) $plan->traffic_quota_bytes,
'traffic_gib' => $plan->trafficGiB(),
'stock' => (int) $plan->stock, 'host_id' => (int) $host->id,
'host_name' => $host->name, 'country_code' => strtoupper((string) ($host->country_code ?? '')),
'region' => $host->region];
}
}
return $this->json($response, ['plans' => $plans]);
return $this->json($response, ['plans' => CloudDeploymentPageService::plans()]);
}
public function orders($request, $response)
@ -861,9 +839,9 @@ final class CloudApiController
$key->save();
return $this->json($response, ['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint], 201);
}
$keys = CloudSSHKey::where('user_id', $actor['user_id'])->orderBy('id')->get()->map(fn ($key) =>
['id' => (int) $key->id, 'name' => $key->name, 'fingerprint' => $key->fingerprint, 'created_at' => (int) $key->created_at])->all();
return $this->json($response, ['keys' => $keys]);
return $this->json($response, [
'keys' => CloudDeploymentPageService::sshKeys((int) $actor['user_id']),
]);
}
public function deleteKey($request, $response, $args)
@ -881,7 +859,7 @@ final class CloudApiController
// Cloud images are a panel-wide catalog. Host-specific replication is
// owned by the private engine and must not make the browser reload or
// replace the catalog whenever a customer changes region or plan.
$catalog = $engine->request('GET', '/internal/v1/vm-templates', $actor);
$catalog = CloudDeploymentPageService::freshTemplateCatalog($actor);
$templatePayload = [
'templates' => is_array($catalog['templates'] ?? null)
? $catalog['templates'] : [],

@ -5,6 +5,7 @@ namespace App\Controllers;
use App\Services\AdminCsrf;
use App\Services\Auth;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInvoicePageService;
@ -72,7 +73,36 @@ final class CloudPageController
public function deploy($request, $response, $args)
{
return $this->render($response, 'deploy', '部署实例');
$actor = CloudAccess::actor(false);
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
$plans = CloudDeploymentPageService::publicPagePlans();
$regions = CloudDeploymentPageService::regions($plans);
$catalog = CloudDeploymentPageService::templateCatalogForPage($actor);
$templates = is_array($catalog['templates'] ?? null)
? $catalog['templates'] : [];
$catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true;
$keys = $this->sshKeyOptions((int) $actor['user_id']);
$defaultHostId = $regions === [] ? 0 : (int) $regions[0]['host_id'];
$bootstrapRegions = array_map(static fn (array $region): array =>
array_diff_key($region, ['plans' => true]), $regions);
$payload = [
'user' => $this->userBootstrap($user, $actor),
'plans' => $plans,
'regions' => $bootstrapRegions,
'templates' => $templates,
'ssh_keys' => $keys,
'default_host_id' => $defaultHostId,
'catalog_unavailable' => $catalogUnavailable,
];
return $this->render($response, 'deploy', '部署实例', '', '', [
'cloud_deploy_regions' => $regions,
'cloud_deploy_template_groups' => CloudDeploymentPageService::templateGroups($templates),
'cloud_deploy_ssh_keys' => $keys,
'cloud_deploy_default_host_id' => $defaultHostId,
'cloud_deploy_catalog_unavailable' => $catalogUnavailable,
'cloud_deploy_bootstrap_json' => $this->safeJson($payload),
]);
}
public function isoImages($request, $response, $args)
@ -124,7 +154,42 @@ final class CloudPageController
public function reinstall($request, $response, $args)
{
return $this->renderVmPage($response, $args, 'reinstall', '重装系统');
$vmId = $this->vmId($args);
if ($vmId === null) {
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
}
$actor = CloudAccess::actor(false);
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
try {
$vm = CloudInstancePageService::detailForActor($actor, $vmId);
} catch (CloudError $error) {
if ($error->httpStatus === 404) {
return $response->withHeader('Location', '/user/cloud/instances')
->withStatus(302);
}
throw $error;
}
$vm = $this->reinstallVm($vm);
$catalog = CloudDeploymentPageService::templateCatalogForPage($actor);
$templates = is_array($catalog['templates'] ?? null)
? $catalog['templates'] : [];
$catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true;
$keys = $this->sshKeyOptions((int) $actor['user_id']);
$payload = [
'user' => $this->userBootstrap($user, $actor),
'vm' => $vm,
'templates' => $templates,
'ssh_keys' => $keys,
'catalog_unavailable' => $catalogUnavailable,
];
return $this->render($response, 'reinstall', '重装系统', $vmId, '', [
'cloud_reinstall_vm' => $vm,
'cloud_reinstall_template_groups' => CloudDeploymentPageService::templateGroups($templates),
'cloud_reinstall_ssh_keys' => $keys,
'cloud_reinstall_catalog_unavailable' => $catalogUnavailable,
'cloud_reinstall_bootstrap_json' => $this->safeJson($payload),
]);
}
public function rescue($request, $response, $args)
@ -139,8 +204,8 @@ final class CloudPageController
private function renderVmPage($response, $args, $page, $title)
{
$vmId = isset($args['id']) ? (string) $args['id'] : '';
if (!preg_match('/^[1-9][0-9]*$/', $vmId)) {
$vmId = $this->vmId($args);
if ($vmId === null) {
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
}
@ -173,6 +238,17 @@ final class CloudPageController
$smarty->assign('cloud_vm_view', []);
$smarty->assign('cloud_vm_scope_label', '我的实例');
$smarty->assign('cloud_vm_bootstrap_json', '{}');
$smarty->assign('cloud_deploy_regions', []);
$smarty->assign('cloud_deploy_template_groups', []);
$smarty->assign('cloud_deploy_ssh_keys', []);
$smarty->assign('cloud_deploy_default_host_id', 0);
$smarty->assign('cloud_deploy_catalog_unavailable', false);
$smarty->assign('cloud_deploy_bootstrap_json', '{}');
$smarty->assign('cloud_reinstall_vm', []);
$smarty->assign('cloud_reinstall_template_groups', []);
$smarty->assign('cloud_reinstall_ssh_keys', []);
$smarty->assign('cloud_reinstall_catalog_unavailable', false);
$smarty->assign('cloud_reinstall_bootstrap_json', '{}');
foreach ($values as $name => $value) {
$smarty->assign($name, $value);
}
@ -260,6 +336,35 @@ final class CloudPageController
return $json === false ? '{}' : $json;
}
private function vmId(array $args): ?string
{
$vmId = isset($args['id']) ? (string) $args['id'] : '';
return preg_match('/^[1-9][0-9]*$/D', $vmId) === 1 ? $vmId : null;
}
/** Deployment forms need only opaque key identifiers and user labels. */
private function sshKeyOptions(int $userId): array
{
return array_map(static fn (array $key): array => [
'id' => $key['id'],
'name' => $key['name'],
], CloudDeploymentPageService::sshKeys($userId));
}
/** Keep reinstall bootstrap small and free of internal host identifiers. */
private function reinstallVm(array $vm): array
{
$keys = [
'id', 'api_id', 'uuid', 'name', 'state', 'public_ip_cidr', 'public_ip',
'instance_status', 'service_status', 'network_status', 'can_operate',
'can_delete', 'is_owner',
];
$result = array_intersect_key($vm, array_flip($keys));
$address = trim((string) ($result['public_ip_cidr'] ?? $result['public_ip'] ?? ''));
$result['public_ip'] = $address === '' ? '' : (explode('/', $address, 2)[0] ?: '');
return $result;
}
private function vmListRow(array $vm): array
{
[$stateLabel, $stateClass] = $this->vmState((string) ($vm['state'] ?? 'unknown'));

@ -0,0 +1,382 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudSSHKey;
use App\Models\Configurations;
use App\Models\Shop;
/**
* Database-backed first-paint data for instance deployment and reinstall.
*
* The template snapshot deliberately contains only public catalog labels and
* identifiers. Host paths, replica locations, credentials and checksums never
* cross this boundary or enter the configurations table.
*/
final class CloudDeploymentPageService
{
private const TEMPLATE_SNAPSHOT_KEY = 'cloud_public_template_catalog_v1';
private const TEMPLATE_SNAPSHOT_VERSION = 1;
private const TEMPLATE_SNAPSHOT_REFRESH_SECONDS = 300;
public static function plans(): array
{
$plans = [];
$available = Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get();
$hostIds = $available->pluck('host_id')->map(static fn ($id): int => (int) $id)
->filter(static fn (int $id): bool => $id > 0)->unique()->values()->all();
$hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds)
->where('enabled', 1)->get(['id', 'name', 'country_code', 'region'])->keyBy('id');
foreach ($available as $plan) {
if ((int) $plan->stock === 0) {
continue;
}
$host = $hosts->get((int) $plan->host_id);
if ($host === null) {
continue;
}
$plans[] = [
'id' => (int) $plan->id,
'name' => (string) $plan->name,
'price' => (string) $plan->price,
'cpu_cores' => (int) $plan->cpu_cores,
'memory_mib' => (int) $plan->memory_mib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps,
'disk_gib' => (int) $plan->disk_gib,
'validity_days' => (int) $plan->validity_days,
'traffic_quota_bytes' => (int) $plan->traffic_quota_bytes,
'traffic_gib' => $plan->trafficGiB(),
'stock' => (int) $plan->stock,
'host_id' => (int) $host->id,
'host_name' => (string) $host->name,
'country_code' => strtoupper(trim((string) ($host->country_code ?? ''))),
'region' => trim((string) $host->region),
];
}
return $plans;
}
/** Plans embedded in user HTML omit the administrator-facing host label. */
public static function publicPagePlans(): array
{
return array_map(static function (array $plan): array {
unset($plan['host_name']);
return $plan;
}, self::plans());
}
public static function regions(array $plans): array
{
$regions = [];
foreach ($plans as $plan) {
$hostId = max(0, (int) ($plan['host_id'] ?? 0));
if ($hostId === 0) {
continue;
}
if (!isset($regions[$hostId])) {
$countryCode = strtoupper(trim((string) ($plan['country_code'] ?? '')));
$regions[$hostId] = [
'host_id' => $hostId,
'country_code' => $countryCode,
'flag' => self::countryFlag($countryCode),
'region' => trim((string) ($plan['region'] ?? '')) ?: '地区未设置',
'plans' => [],
];
}
$regions[$hostId]['plans'][] = $plan;
}
return array_values($regions);
}
public static function sshKeys(int $userId): array
{
return CloudSSHKey::where('user_id', $userId)->orderBy('id')->get([
'id', 'name', 'fingerprint', 'created_at',
])->map(static fn ($key): array => [
'id' => (int) $key->id,
'name' => (string) $key->name,
'fingerprint' => (string) $key->fingerprint,
'created_at' => (int) $key->created_at,
])->all();
}
/**
* Return a complete public catalog for SSR. A durable last-known snapshot
* avoids an engine dependency on every page view. On a fresh installation
* the first request waits briefly for the loopback engine and still returns
* one complete HTML response instead of an empty browser shell.
*/
public static function templateCatalogForPage(array $actor): array
{
$snapshot = self::templateSnapshot();
if ($snapshot !== null
&& time() - (int) $snapshot['checked_at'] < self::TEMPLATE_SNAPSHOT_REFRESH_SECONDS) {
return self::pageCatalog($snapshot);
}
try {
return self::freshTemplateCatalog($actor, 2.0);
} catch (CloudError $error) {
error_log('Unable to refresh the public cloud template catalog: '
. get_class($error));
$snapshot ??= [
'version' => self::TEMPLATE_SNAPSHOT_VERSION,
'updated_at' => 0,
'templates' => [],
];
$snapshot['checked_at'] = time();
$snapshot['refresh_failed'] = true;
self::saveTemplateSnapshot($snapshot);
return self::pageCatalog($snapshot);
}
}
/** Fetch the authoritative engine-global catalog and refresh the snapshot. */
public static function freshTemplateCatalog(array $actor, float $timeoutSeconds = 20.0): array
{
$payload = (new CloudEngineClient(null, $timeoutSeconds))->request(
'GET', '/internal/v1/vm-templates', $actor
);
$payload['templates'] = self::sanitizeTemplates($payload['templates'] ?? []);
self::rememberTemplateCatalog($payload);
return $payload;
}
/** Persist only the public subset needed to draw an image picker. */
public static function rememberTemplateCatalog(array $payload): void
{
$templates = self::sanitizeTemplates($payload['templates'] ?? []);
$snapshot = [
'version' => self::TEMPLATE_SNAPSHOT_VERSION,
'updated_at' => time(),
'checked_at' => time(),
'refresh_failed' => false,
'templates' => array_map(static fn (array $template): array => [
'id' => $template['id'],
'name' => $template['name'],
'os_family' => $template['os_family'],
'os_version' => $template['os_version'],
], $templates),
];
self::saveTemplateSnapshot($snapshot);
}
private static function saveTemplateSnapshot(array $snapshot): void
{
$json = json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
// configurations.value is TEXT. Refuse an accidental oversized write
// instead of truncating the JSON into a misleading partial catalog.
if (strlen($json) > 60000) {
error_log('Public cloud template catalog snapshot exceeds the storage limit');
return;
}
try {
$row = Configurations::where('name', self::TEMPLATE_SNAPSHOT_KEY)->first();
if ($row === null) {
$row = new Configurations();
$row->name = self::TEMPLATE_SNAPSHOT_KEY;
}
$row->value = $json;
$row->save();
} catch (\Throwable $error) {
// A public API read must not fail merely because its optional
// first-paint snapshot could not be refreshed.
error_log('Unable to save the public cloud template catalog snapshot: '
. get_class($error));
}
}
/** Update a cached rename/import result without ever fabricating a catalog. */
public static function rememberTemplate(array $template): void
{
$snapshot = self::templateSnapshot();
$records = self::sanitizeTemplates([$template]);
if ($snapshot === null || $records === []) {
return;
}
$replacement = $records[0];
$templates = [];
$found = false;
foreach ($snapshot['templates'] as $existing) {
if ((string) $existing['id'] === (string) $replacement['id']) {
$templates[] = $replacement;
$found = true;
} else {
$templates[] = $existing;
}
}
if (!$found) {
$templates[] = $replacement;
}
self::rememberTemplateCatalog(['templates' => $templates]);
}
public static function templateGroups(array $templates): array
{
$groups = [];
foreach (self::sanitizeTemplates($templates) as $template) {
[$family, $version] = self::templateSystem($template);
if (!isset($groups[$family])) {
$groups[$family] = [
'family' => $family,
'icon_path' => self::templateIcon($family),
'templates' => [],
];
}
$template['display_version'] = $version;
$groups[$family]['templates'][] = $template;
}
foreach ($groups as &$group) {
usort($group['templates'], static function (array $left, array $right): int {
$version = version_compare(
(string) ($right['display_version'] ?? '0'),
(string) ($left['display_version'] ?? '0')
);
return $version !== 0 ? $version
: strnatcasecmp((string) $left['name'], (string) $right['name']);
});
}
unset($group);
$order = ['AlmaLinux' => 0, 'Debian' => 1, 'CentOS Stream' => 2, 'Ubuntu' => 3];
uasort($groups, static fn (array $left, array $right): int =>
($order[$left['family']] ?? 100) <=> ($order[$right['family']] ?? 100)
?: strcasecmp($left['family'], $right['family']));
return array_values($groups);
}
private static function templateSnapshot(): ?array
{
try {
$raw = Configurations::where('name', self::TEMPLATE_SNAPSHOT_KEY)->value('value');
} catch (\Throwable $error) {
return null;
}
if (!is_string($raw) || $raw === '' || strlen($raw) > 65535) {
return null;
}
$decoded = json_decode($raw, true);
if (!is_array($decoded) || (int) ($decoded['version'] ?? 0) !== self::TEMPLATE_SNAPSHOT_VERSION
|| !is_array($decoded['templates'] ?? null)) {
return null;
}
$templates = self::sanitizeTemplates($decoded['templates']);
// Do not accept a partially corrupted non-empty snapshot as an empty
// authoritative catalog; recover it from the engine instead.
if ($decoded['templates'] !== [] && $templates === []) {
return null;
}
return [
'version' => self::TEMPLATE_SNAPSHOT_VERSION,
'updated_at' => max(0, (int) ($decoded['updated_at'] ?? 0)),
'checked_at' => max(0, (int) ($decoded['checked_at']
?? $decoded['updated_at'] ?? 0)),
'refresh_failed' => ($decoded['refresh_failed'] ?? false) === true,
'templates' => $templates,
];
}
private static function pageCatalog(array $snapshot): array
{
$templates = is_array($snapshot['templates'] ?? null)
? $snapshot['templates'] : [];
$failed = ($snapshot['refresh_failed'] ?? false) === true;
return [
'templates' => $templates,
'catalog_stale' => $failed && $templates !== [],
'catalog_unavailable' => $failed && $templates === [],
];
}
private static function sanitizeTemplates($values): array
{
if (!is_array($values)) {
return [];
}
$templates = [];
foreach (array_slice($values, 0, 256) as $value) {
if (!is_array($value)) {
continue;
}
$id = $value['id'] ?? null;
$name = $value['name'] ?? null;
$family = $value['os_family'] ?? '';
$version = $value['os_version'] ?? '';
if (!is_string($id)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $id) !== 1
|| !self::plainLabel($name, 64)
|| !self::plainLabel($family, 40)
|| !is_string($version)
|| preg_match('/^[0-9]{1,4}(?:\.[0-9]{1,4}){0,2}$/D', $version) !== 1) {
continue;
}
$templates[$id] = [
'id' => $id,
'name' => trim($name),
'os_family' => trim($family),
'os_version' => $version,
];
}
return array_values($templates);
}
private static function plainLabel($value, int $maximum): bool
{
return is_string($value) && trim($value) !== '' && mb_strlen($value) <= $maximum
&& preg_match('//u', $value) === 1
&& preg_match('/[\x00-\x1F\x7F]/u', $value) !== 1;
}
private static function templateSystem(array $template): array
{
$familyKey = strtolower((string) preg_replace(
'/[\s_-]+/', '', (string) ($template['os_family'] ?? '')
));
$family = [
'alma' => 'AlmaLinux', 'almalinux' => 'AlmaLinux',
'debian' => 'Debian', 'centos' => 'CentOS Stream',
'centosstream' => 'CentOS Stream', 'ubuntu' => 'Ubuntu',
][$familyKey] ?? '';
$idVersion = '';
if (preg_match('/^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/i',
(string) $template['id'], $match) === 1) {
$family = $family ?: [
'alma' => 'AlmaLinux', 'debian' => 'Debian',
'ubuntu' => 'Ubuntu', 'centosstream' => 'CentOS Stream',
][strtolower($match[1])];
$idVersion = $match[2];
if (strtolower($match[1]) === 'ubuntu' && strlen($idVersion) === 4) {
$idVersion = substr($idVersion, 0, 2) . '.' . substr($idVersion, 2);
}
}
return [
$family ?: '其他系统',
(string) ($template['os_version'] ?: $idVersion),
];
}
private static function templateIcon(string $family): string
{
return [
'AlmaLinux' => '/cloud/almalinux-icon.svg',
'Debian' => '/cloud/debian-icon.svg',
'CentOS Stream' => '/cloud/centos-icon.svg',
'Ubuntu' => '/cloud/ubuntu-icon.svg',
][$family] ?? '';
}
private static function countryFlag(string $countryCode): string
{
if (preg_match('/^[A-Z]{2}$/D', $countryCode) !== 1) {
return '🌐';
}
return mb_chr(127397 + ord($countryCode[0]), 'UTF-8')
. mb_chr(127397 + ord($countryCode[1]), 'UTF-8');
}
}

@ -3,14 +3,15 @@ const assetVersion = new URL(import.meta.url).searchParams.get('v');
if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion);
const {
bindPageCleanup, buy, byId, initializeSession, openCreate,
showError,
readBootstrap, showError,
} = await import(runtimeUrl.href);
export async function initialize() {
try {
if (!await initializeSession('create')) return;
const bootstrap = readBootstrap('deploy-bootstrap');
if (!await initializeSession('create', bootstrap?.user)) return;
bindPageCleanup();
byId('create-form')?.addEventListener('submit', buy);
await openCreate();
await openCreate(bootstrap);
} catch (error) { showError('cloud-page-error', error.message); }
}

@ -3,15 +3,16 @@ const assetVersion = new URL(import.meta.url).searchParams.get('v');
if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion);
const {
bindPageCleanup, byId, initializeSession, openReinstall, reinstall,
selectVmByApiId, showError,
readBootstrap, selectVmByApiId, showError,
} = await import(runtimeUrl.href);
export async function initialize() {
try {
if (!await initializeSession('reinstall')) return;
const bootstrap = readBootstrap('reinstall-bootstrap');
if (!await initializeSession('reinstall', bootstrap?.user)) return;
bindPageCleanup();
const vm = await selectVmByApiId(document.body.dataset.vmId || '');
const vm = await selectVmByApiId(document.body.dataset.vmId || '', bootstrap?.vm);
byId('reinstall-form')?.addEventListener('submit', reinstall);
await openReinstall(vm);
await openReinstall(vm, bootstrap);
} catch (error) { showError('cloud-page-error', error.message); }
}

@ -1,7 +1,7 @@
// PHP owns authentication, authorisation, ownership and purchasing. No engine
// address, token, host credential or unrestricted create API exists in this UI.
const byId = (id) => document.getElementById(id);
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], invoiceBalance: '0.00', selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], invoiceBalance: '0.00', selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
// Keep the historical storage key so an interrupted deployment made just
// before an online update can still reconcile to the same opening invoice.
const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:';
@ -17,6 +17,19 @@ const invoicePagePath = (id) => `${CLOUD_PATHS.invoices}/${encodeURIComponent(St
const navigate = (path) => location.assign(path);
const text = (id, value) => { byId(id).textContent = value ?? '—'; };
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
function readBootstrap(id) {
const source = byId(id);
if (!source) return null;
let payload;
try { payload = JSON.parse(source.textContent || '{}'); }
catch { throw new Error('页面初始数据无效,请刷新后重试。'); }
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('页面初始数据缺失,请刷新后重试。');
return payload;
}
function bootstrapItems(payload, ...names) {
for (const name of names) if (Array.isArray(payload?.[name])) return payload[name];
return [];
}
function showError(id, message) { text(id, message); byId(id).hidden = !message; }
let toastTimer;
function toast(message, kind = '') { const element = byId('toast'); element.textContent = message; element.className = `toast ${kind}`; element.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { element.hidden = true; }, 5000); }
@ -340,6 +353,15 @@ function flagForCountry(code) {
}
function saleRegions() {
const regions = new Map();
for (const region of state.regions) {
const hostId = String(region?.host_id ?? region?.id ?? '');
if (!/^\d+$/.test(hostId) || regions.has(hostId)) continue;
regions.set(hostId, {
hostId,
countryCode: String(region.country_code || '').trim().toUpperCase(),
region: String(region.region || region.name || '地区未设置').trim() || '地区未设置',
});
}
for (const plan of state.plans) {
const hostId = String(plan?.host_id || '');
if (!/^\d+$/.test(hostId) || regions.has(hostId)) continue;
@ -477,9 +499,39 @@ async function selectPlan(planId) {
showError('create-error', '');
updateCreateAvailability();
}
async function openCreate() {
async function openCreate(bootstrap = null) {
state.view = 'create'; state.selectedVmId = null; showError('create-error', '');
state.selectedRegionHostId = ''; byId('vm-region-host').value = ''; byId('vm-plan').value = '';
byId('vm-plan').value = '';
if (bootstrap && Array.isArray(bootstrap.plans) && Array.isArray(bootstrap.templates)) {
state.regions = bootstrapItems(bootstrap, 'regions');
state.plans = bootstrapItems(bootstrap, 'plans');
if (!state.plans.length) state.plans = state.regions.flatMap(region => Array.isArray(region?.plans) ? region.plans : []);
state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates');
state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true;
state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys');
state.resources = { templates: state.templates };
state.selectedKeys.create = '';
const regions = saleRegions();
const requestedDefault = bootstrap.default_host_id ?? bootstrap.default_region?.host_id ?? bootstrap.default_region;
const requestedHostId = String(requestedDefault ?? '');
state.selectedRegionHostId = regions.some(region => region.hostId === requestedHostId)
? requestedHostId : (regions[0]?.hostId || '');
byId('vm-region-host').value = state.selectedRegionHostId;
renderRegionPicker();
renderPlanPicker();
renderTemplateCatalog('vm-template');
renderKeyCards('create');
byId('vm-template').disabled = !state.templates.some(item => item?.id);
byId('vm-name').disabled = false;
byId('vm-root-password').disabled = false;
setDeploymentStepEnabled('vm-plan-step', Boolean(state.selectedRegionHostId));
setDeploymentStepEnabled('vm-source-step', true);
setDeploymentStepEnabled('vm-config-step', true);
updateCreateAvailability();
return;
}
state.regions = [];
state.selectedRegionHostId = ''; byId('vm-region-host').value = '';
setDeploymentStepEnabled('vm-plan-step', false); resetInstallChoices();
const results = await Promise.allSettled([
api('/api/v1/plans').then(plans => { state.plans = items(plans); renderRegionPicker(); }),
@ -499,6 +551,7 @@ async function loadGlobalTemplates() {
const resources = await api('/api/v1/resources', { signal: controller.signal });
if (controller !== state.resourceController) return;
state.resources = resources;
state.templateCatalogUnavailable = false;
state.templates = items(resources.templates || resources.cloud_templates);
renderTemplateCatalog('vm-template');
byId('vm-template').disabled = !state.templates.some(item => item?.id);
@ -1184,9 +1237,27 @@ async function loadInvoices(page = state.invoicePage) {
renderInvoicePagination();
}
}
async function openReinstall(vm) {
if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error');
async function openReinstall(vm, bootstrap = null) {
state.view = 'reinstall'; text('reinstall-subtitle', `${vm.name} · 保留原有公网网络参数,重新创建系统盘。`); text('reinstall-public-ip', vmIp(vm)); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false;
if (!vm?.can_operate) {
byId('reinstall-fields').inert = true;
byId('reinstall-fields').setAttribute('aria-disabled', 'true');
byId('reinstall-submit').disabled = true;
showError('reinstall-error', '实例服务已到期或正在执行策略,当前不能重装系统。');
return;
}
byId('reinstall-fields').inert = false;
byId('reinstall-fields').removeAttribute('aria-disabled');
byId('reinstall-submit').disabled = false;
if (bootstrap && Array.isArray(bootstrap.templates)) {
state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates');
state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true;
state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys');
state.selectedKeys.reinstall = '';
renderTemplateCatalog('reinstall-template');
renderKeyCards('reinstall');
return;
}
try { const resources = await api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`); state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('reinstall-template'); await loadKeys(); } catch (error) { showError('reinstall-error', error.message); }
}
async function pollJob(kind, id, phaseId, errorId) {
@ -1922,9 +1993,12 @@ function renderTemplateCatalog(inputId) {
}
if (!groups.size) {
input.value = "";
container.replaceChildren(makeElement("p", "template-catalog-empty", state.admin
? "暂无云镜像,请先到“云镜像模板”页面导入。"
: "暂无可用云镜像,请联系管理员导入模板。"));
container.replaceChildren(makeElement("p", "template-catalog-empty",
state.templateCatalogUnavailable
? "系统镜像目录暂时无法读取,请稍后刷新。"
: state.admin
? "暂无云镜像,请先到“云镜像模板”页面导入。"
: "暂无可用云镜像,请联系管理员导入模板。"));
return;
}
if (!state.templates.some((item) => String(item.id) === input.value)) input.value = "";
@ -1965,8 +2039,14 @@ function renderTemplateCatalog(inputId) {
}
container.replaceChildren(...cards);
}
async function initializeSession(view) {
async function initializeSession(view, bootstrapUser = null) {
state.view = view;
if (bootstrapUser && typeof bootstrapUser === 'object') {
if (bootstrapUser.authenticated === false) { location.assign('/auth/login'); return false; }
applyCloudUser(bootstrapUser);
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
return true;
}
const session = await api('/api/v1/session');
if (session.authenticated === false) { location.assign('/auth/login'); return false; }
applyCloudUser(session);
@ -1974,7 +2054,14 @@ async function initializeSession(view) {
return true;
}
async function selectVmByApiId(apiId) {
async function selectVmByApiId(apiId, bootstrapVm = null) {
if (bootstrapVm && typeof bootstrapVm === 'object') {
const vm = normalizeVm(bootstrapVm);
if (!vm.api_id || String(vm.api_id) !== String(apiId || '')) throw new Error('实例初始数据与当前地址不匹配,请刷新后重试。');
state.vms = [vm];
state.selectedVmId = vm.uuid;
return vm;
}
const vm = await loadVm(apiId, true);
if (!vm) throw new Error('虚拟机不存在或当前账户无权访问。');
return vm;
@ -1997,7 +2084,7 @@ export {
drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, invoicePagePath,
loadGlobalTemplates, loadInvoiceDetail, loadInvoices, loadKeys, loadVmMetrics, loadVmTrafficDaily,
loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall,
renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm,
readBootstrap, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm,
scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics,
stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp,
vmPagePath,

@ -6,23 +6,73 @@
<div class="workspace-form-body deploy-flow">
<section class="deployment-step" aria-labelledby="deploy-region-title">
<div class="deployment-step-heading"><span>1</span><h2 id="deploy-region-title">选择地区</h2></div>
<input id="vm-region-host" type="hidden" value="" />
<div id="vm-region-picker" class="region-picker" role="group" aria-labelledby="deploy-region-title"></div>
<input id="vm-region-host" type="hidden" value="{$cloud_deploy_default_host_id|default:''|escape:"html"}" />
<div id="vm-region-picker" class="region-picker" role="group" aria-labelledby="deploy-region-title">
{if empty($cloud_deploy_regions)}
<p class="template-catalog-empty">暂无可部署地区,请联系管理员配置在售商品。</p>
{else}
{foreach $cloud_deploy_regions as $region}
<button class="region-option" type="button" data-host-id="{$region.host_id|escape:"html"}" aria-pressed="{if $region.host_id == $cloud_deploy_default_host_id}true{else}false{/if}" aria-label="选择地区 {$region.region|escape:"html"}">
<span class="region-flag" aria-hidden="true">{$region.flag|default:'🌐'|escape:"html"}</span>
<strong>{$region.region|escape:"html"}</strong>
</button>
{/foreach}
{/if}
</div>
</section>
<section id="vm-plan-step" class="deployment-step is-disabled" aria-labelledby="deploy-plan-title">
<section id="vm-plan-step" class="deployment-step{if empty($cloud_deploy_regions)} is-disabled{/if}" aria-labelledby="deploy-plan-title" aria-disabled="{if empty($cloud_deploy_regions)}true{else}false{/if}">
<div class="deployment-step-heading"><span>2</span><h2 id="deploy-plan-title">选择实例规格</h2></div>
<input id="vm-plan" type="hidden" value="" />
<div id="vm-plan-picker" class="plan-picker" role="group" aria-labelledby="deploy-plan-title"><p class="template-catalog-empty">请先选择地区。</p></div>
<div id="vm-plan-picker" class="plan-picker" role="group" aria-labelledby="deploy-plan-title">
{assign var=default_region_has_plans value=false}
{foreach $cloud_deploy_regions as $region}
{if $region.host_id == $cloud_deploy_default_host_id && !empty($region.plans)}
{assign var=default_region_has_plans value=true}
<div class="plan-table-head"><span>名称</span><span>CPU</span><span>内存</span><span>硬盘</span><span>每月流量</span><span>价格</span></div>
{foreach $region.plans as $plan}
{assign var=plan_memory_gib value=$plan.memory_mib/1024}
{assign var=plan_traffic_tib value=$plan.traffic_gib/1024}
<button class="plan-option" type="button" data-plan-id="{$plan.id|escape:"html"}" aria-pressed="false" aria-label="选择实例规格 {$plan.name|escape:"html"}">
<strong class="plan-option-name">{$plan.name|escape:"html"}</strong>
<span class="plan-option-value">{$plan.cpu_cores|escape:"html"} vCPU</span>
<span class="plan-option-value">{$plan_memory_gib|string_format:"%g"|escape:"html"} GB</span>
<span class="plan-option-value">{$plan.disk_gib|escape:"html"} GB</span>
<span class="plan-option-value">{if $plan.traffic_gib == 0}不限{else}{$plan_traffic_tib|string_format:"%g"|escape:"html"} TB{/if}</span>
<strong class="plan-option-price">${$plan.price|string_format:"%.2f"|escape:"html"}</strong>
</button>
{/foreach}
{/if}
{/foreach}
{if !$default_region_has_plans}<p class="template-catalog-empty">当前地区暂无可用实例规格。</p>{/if}
</div>
</section>
<section id="vm-source-step" class="deployment-step is-disabled" aria-labelledby="deploy-source-title">
<section id="vm-source-step" class="deployment-step" aria-labelledby="deploy-source-title" aria-disabled="false">
<div class="deployment-step-heading"><span>3</span><h2 id="deploy-source-title">选择系统镜像</h2></div>
<div class="field full" id="vm-template-field"><input id="vm-template" name="template_id" type="hidden" value="" disabled /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="deploy-source-title" aria-required="true"></div></div>
<div class="field full" id="vm-template-field"><input id="vm-template" name="template_id" type="hidden" value=""{if empty($cloud_deploy_template_groups)} disabled{/if} /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="deploy-source-title" aria-required="true">
{if empty($cloud_deploy_template_groups)}
<p class="template-catalog-empty">{if !empty($cloud_deploy_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}</p>
{else}
{foreach $cloud_deploy_template_groups as $group}
<details class="template-family-card" data-family="{$group.family|escape:"html"}">
<summary class="template-family-summary">
<span class="template-family-icon{if !empty($group.icon_path)} system{/if}" aria-hidden="true">{if !empty($group.icon_path)}<img class="template-system-logo" src="{$group.icon_path|escape:"html"}" alt="" />{else}&#x25C8;{/if}</span>
<strong>{$group.family|escape:"html"}</strong><span class="template-family-arrow">&#x2304;</span>
</summary>
<div class="template-versions" role="group" aria-label="{$group.family|escape:"html"} 可用版本">
{foreach $group.templates as $template}
<button class="template-version-option" type="button" data-template-id="{$template.id|escape:"html"}" aria-pressed="false" aria-label="选择模板 {$template.name|escape:"html"}"><strong>{$template.name|escape:"html"}</strong></button>
{/foreach}
</div>
</details>
{/foreach}
{/if}
</div></div>
</section>
<section id="vm-config-step" class="deployment-step is-disabled" aria-labelledby="deploy-config-title">
<section id="vm-config-step" class="deployment-step" aria-labelledby="deploy-config-title" aria-disabled="false">
<div class="deployment-step-heading"><span>4</span><h2 id="deploy-config-title">实例信息</h2></div>
<div class="form-grid">
<div class="field full"><label for="vm-name">实例名称 <span>*</span></label><input id="vm-name" name="name" type="text" required minlength="1" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" placeholder="例如 web-prod-01" disabled /></div>
<div class="cloud-fields full" id="vm-cloud-fields"><div class="form-grid vm-cloud-auth-fields"><div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="部署实例时选择 SSH 公钥"></div><a id="vm-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div><div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" disabled /></div></div></div>
<div class="field full"><label for="vm-name">实例名称 <span>*</span></label><input id="vm-name" name="name" type="text" required minlength="1" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" placeholder="例如 web-prod-01" /></div>
<div class="cloud-fields full" id="vm-cloud-fields"><div class="form-grid vm-cloud-auth-fields"><div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="部署实例时选择 SSH 公钥">{if empty($cloud_deploy_ssh_keys)}<p class="muted">暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。</p>{else}{foreach $cloud_deploy_ssh_keys as $key}<button class="ssh-key-option" type="button" aria-pressed="false" data-key-id="{$key.id|escape:"html"}"><strong class="ssh-key-choice-label">{$key.name|escape:"html"}</strong></button>{/foreach}{/if}</div><a id="vm-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div><div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" /></div></div></div>
</div>
</section>
<p id="create-error" class="form-error" role="alert" hidden></p>
@ -31,3 +81,4 @@
</form>
</section>
</div>
<script id="deploy-bootstrap" type="application/json">{$cloud_deploy_bootstrap_json nofilter}</script>

@ -1,24 +1,26 @@
<div id="vm-workspace">
<section id="reinstall-view" class="workspace-form-page" aria-labelledby="reinstall-title">
<a id="reinstall-back" class="button button-ghost workspace-form-back" href="/user/cloud/instances/{$cloud_vm_id|escape:"url"}">← 返回实例详情</a>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow danger-text">REINSTALL SYSTEM</span><h1 id="reinstall-title" tabindex="-1">重装云镜像系统</h1><p id="reinstall-subtitle">保留原有公网网络参数,重新创建系统盘。</p></div></div>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow danger-text">REINSTALL SYSTEM</span><h1 id="reinstall-title" tabindex="-1">重装云镜像系统</h1><p id="reinstall-subtitle">{$cloud_reinstall_vm.name|default:'实例'|escape:"html"} · 保留原有公网网络参数,重新创建系统盘。</p></div></div>
<form id="reinstall-form" class="inventory-panel workspace-form-card">
<div class="workspace-form-body">
<div id="reinstall-fields">
<div id="reinstall-fields"{if !$cloud_reinstall_vm.can_operate|default:false} inert aria-disabled="true"{/if}>
{if !$cloud_reinstall_vm.can_operate|default:false}<p class="reinstall-warning"><strong>当前实例暂时不能重装。</strong>实例服务已到期或正在执行平台策略,请先恢复服务状态后再操作。</p>{/if}
<p class="reinstall-warning"><strong>重装将永久清除原系统盘中的全部数据。</strong>面板会先请求虚拟机正常关机;若关机超时,重装会停止,不会强制断电。libvirt/QEMU 报告虚拟机已从新盘启动后,原系统盘将自动删除。这个“启动”不保证客户机系统、网络或 SSH 已经可用,请确认模板和网络配置。</p>
<p class="reinstall-network">沿用首次创建的公网网络信息:<strong id="reinstall-public-ip"></strong>。网桥、MAC、网关和 DNS 也会保持原配置。</p>
<p class="reinstall-network">沿用首次创建的公网网络信息:<strong id="reinstall-public-ip">{if !empty($cloud_reinstall_vm.public_ip)}{$cloud_reinstall_vm.public_ip|escape:"html"}{elseif !empty($cloud_reinstall_vm.public_ip_cidr)}{$cloud_reinstall_vm.public_ip_cidr|escape:"html"}{else}未记录{/if}</strong>。网桥、MAC、网关和 DNS 也会保持原配置。</p>
<div class="form-grid">
<div class="field full"><span id="reinstall-template-label" class="template-field-label">重装镜像 <span>*</span></span><input id="reinstall-template" name="template_id" type="hidden" value="" /><div id="reinstall-template-catalog" class="template-catalog" role="group" aria-labelledby="reinstall-template-label" aria-describedby="reinstall-template-hint" aria-required="true"></div><small id="reinstall-template-hint">点击系统图标下方的箭头展开版本,选择当前宿主机已导入的云镜像。</small></div>
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="reinstall-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="重装系统时选择 SSH 公钥"></div><small>直接选择“公钥管理”中保存的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><a id="reinstall-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div>
<div class="field full"><span id="reinstall-template-label" class="template-field-label">重装镜像 <span>*</span></span><input id="reinstall-template" name="template_id" type="hidden" value="" /><div id="reinstall-template-catalog" class="template-catalog" role="group" aria-labelledby="reinstall-template-label" aria-describedby="reinstall-template-hint" aria-required="true">{if empty($cloud_reinstall_template_groups)}<p class="template-catalog-empty">{if !empty($cloud_reinstall_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}</p>{else}{foreach $cloud_reinstall_template_groups as $group}<details class="template-family-card" data-family="{$group.family|escape:"html"}"><summary class="template-family-summary"><span class="template-family-icon{if !empty($group.icon_path)} system{/if}" aria-hidden="true">{if !empty($group.icon_path)}<img class="template-system-logo" src="{$group.icon_path|escape:"html"}" alt="" />{else}&#x25C8;{/if}</span><strong>{$group.family|escape:"html"}</strong><span class="template-family-arrow">&#x2304;</span></summary><div class="template-versions" role="group" aria-label="{$group.family|escape:"html"} 可用版本">{foreach $group.templates as $template}<button class="template-version-option" type="button" data-template-id="{$template.id|escape:"html"}" aria-pressed="false" aria-label="选择模板 {$template.name|escape:"html"}"><strong>{$template.name|escape:"html"}</strong></button>{/foreach}</div></details>{/foreach}{/if}</div><small id="reinstall-template-hint">点击系统图标下方的箭头展开版本,选择全局云镜像版本。</small></div>
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="reinstall-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="重装系统时选择 SSH 公钥">{if empty($cloud_reinstall_ssh_keys)}<p class="muted">暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。</p>{else}{foreach $cloud_reinstall_ssh_keys as $key}<button class="ssh-key-option" type="button" aria-pressed="false" data-key-id="{$key.id|escape:"html"}"><strong class="ssh-key-choice-label">{$key.name|escape:"html"}</strong></button>{/foreach}{/if}</div><small>直接选择“公钥管理”中保存的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><a id="reinstall-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div>
<div class="field full" id="reinstall-root-password-field"><label for="reinstall-root-password">初始 root 密码(可选)</label><input id="reinstall-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="reinstall-root-password-hint" placeholder="留空时自动生成强密码" /><small id="reinstall-root-password-hint" aria-live="polite">留空时自动生成强密码,即使选择了公钥;自行设置需至少 12 个字符,包含大写字母、小写字母、数字和符号。</small></div>
<div class="field full"><label for="reinstall-confirm-name">输入虚拟机名称以确认删除旧系统盘 <span>*</span></label><input id="reinstall-confirm-name" name="confirmation_name" type="text" required autocomplete="off" spellcheck="false" placeholder="请输入完整的虚拟机名称" /><small id="reinstall-confirm-hint"></small></div>
</div>
</div>
<div id="reinstall-progress" class="reinstall-progress" role="status" aria-live="polite" hidden><span class="console-spinner" aria-hidden="true"></span><div><strong>正在重装,请保持此页面打开</strong><p id="reinstall-phase">准备重装任务…</p><small>刷新此标签页后会自动恢复任务;如有初始密码,将加密保存在面板数据库中。</small></div></div>
<div id="reinstall-result" class="reinstall-result" role="status" aria-live="polite" hidden><h3 id="reinstall-result-title"></h3><p id="reinstall-result-message"></p><div id="reinstall-password-box" class="reinstall-password-box" hidden><span>新系统的 root 初始密码</span><div><code id="reinstall-generated-password"></code><button id="reinstall-copy-password" class="button button-outline small" type="button">复制</button></div><small>请先保存到安全位置,再点击“已保存密码,完成”。页面中的明文届时会清除,面板记录的初始密码仍可在虚拟机详情页按需查看。</small></div><p id="reinstall-result-warning" class="reinstall-result-warning" hidden></p></div>
<p id="reinstall-error" class="form-error" role="alert" hidden></p>
<p id="reinstall-error" class="form-error" role="alert"{if $cloud_reinstall_vm.can_operate|default:false} hidden{/if}>{if !$cloud_reinstall_vm.can_operate|default:false}实例服务已到期或正在执行策略,当前不能重装系统。{/if}</p>
</div>
<div class="workspace-form-actions"><a id="reinstall-cancel" class="button button-outline" href="/user/cloud/instances/{$cloud_vm_id|escape:"url"}">取消</a><button id="reinstall-submit" class="button button-danger" type="submit">确认重装并删除旧盘</button><button id="reinstall-forget" class="button button-outline" type="button" hidden>放弃恢复任务</button><button id="reinstall-retry" class="button button-outline" type="button" hidden>重新查询任务</button><button id="reinstall-done" class="button button-primary" type="button" hidden>完成</button></div>
<div class="workspace-form-actions"><a id="reinstall-cancel" class="button button-outline" href="/user/cloud/instances/{$cloud_vm_id|escape:"url"}">取消</a><button id="reinstall-submit" class="button button-danger" type="submit"{if !$cloud_reinstall_vm.can_operate|default:false} disabled{/if}>确认重装并删除旧盘</button><button id="reinstall-forget" class="button button-outline" type="button" hidden>放弃恢复任务</button><button id="reinstall-retry" class="button button-outline" type="button" hidden>重新查询任务</button><button id="reinstall-done" class="button button-primary" type="button" hidden>完成</button></div>
</form>
</section>
</div>
<script id="reinstall-bootstrap" type="application/json">{$cloud_reinstall_bootstrap_json nofilter}</script>

@ -1 +1 @@
{assign var=venix_asset_version value='2026092810' scope='global'}
{assign var=venix_asset_version value='2026092811' scope='global'}

@ -0,0 +1,194 @@
<?php
// Static regression contract for deployment/reinstall first paint. The HTML
// response owns all data needed to draw the form; JavaScript only hydrates
// interactions and must not briefly replace the catalog with loading states.
$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);
};
$controller = file_get_contents($root . '/app/Controllers/CloudPageController.php');
$service = file_get_contents($root . '/app/Services/Cloud/CloudDeploymentPageService.php');
$deployTemplate = file_get_contents($root . '/resources/views/venix/cloud/pages/deploy.tpl');
$reinstallTemplate = file_get_contents($root . '/resources/views/venix/cloud/pages/reinstall.tpl');
$deployModule = file_get_contents($root . '/public/cloud/deploy.js');
$reinstallModule = file_get_contents($root . '/public/cloud/reinstall.js');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$cloudShell = file_get_contents($root . '/resources/views/venix/cloud/page.tpl');
$layoutAssets = file_get_contents($root . '/resources/views/venix/layout_assets.tpl');
$deployController = $section($controller, 'public function deploy(',
'public function isoImages(');
$reinstallController = $section($controller, 'public function reinstall(',
'public function rescue(');
$openCreate = $section($runtime, 'async function openCreate(',
'async function loadGlobalTemplates(');
$openReinstall = $section($runtime, 'async function openReinstall(',
'async function pollJob(');
$selectRegion = $section($runtime, 'async function selectRegion(',
'async function selectPlan(');
$selectPlan = $section($runtime, 'async function selectPlan(',
'async function openCreate(');
$sshKeyOptions = $section($controller, 'private function sshKeyOptions(',
'private function reinstallVm(');
$assert(str_contains($deployController, 'CloudAccess::actor(false)')
&& str_contains($deployController, 'CloudDeploymentPageService::publicPagePlans()')
&& str_contains($deployController, 'CloudDeploymentPageService::regions($plans)')
&& str_contains($deployController, 'CloudDeploymentPageService::templateCatalogForPage($actor)')
&& str_contains($deployController, '$this->sshKeyOptions((int) $actor[\'user_id\'])')
&& str_contains($deployController,
'$defaultHostId = $regions === [] ? 0 : (int) $regions[0][\'host_id\']')
&& str_contains($deployController, "'catalog_unavailable' => \$catalogUnavailable")
&& str_contains($deployController,
"'cloud_deploy_catalog_unavailable' => \$catalogUnavailable")
&& str_contains($deployController, "'cloud_deploy_bootstrap_json' => \$this->safeJson(\$payload)"),
'Deployment controller must build one complete, actor-scoped first-paint payload.');
$assert(str_contains($sshKeyOptions, "'id' => \$key['id']")
&& str_contains($sshKeyOptions, "'name' => \$key['name']")
&& str_contains($sshKeyOptions, 'CloudDeploymentPageService::sshKeys($userId)')
&& !str_contains($sshKeyOptions, 'fingerprint')
&& !str_contains($sshKeyOptions, 'created_at'),
'Deployment bootstraps must expose only the saved key identifier and display name.');
$assert(str_contains($service, "->orderBy('sort')->orderBy('id')")
&& str_contains($service, "->where('enabled', 1)")
&& str_contains($service, 'if ((int) $plan->stock === 0)')
&& str_contains($service, 'return array_values($regions);')
&& str_contains($service, "unset(\$plan['host_name'])"),
'Available plans and regions must retain administrator sale order and omit private host labels.');
$assert(str_contains($service, "private const TEMPLATE_SNAPSHOT_KEY")
&& str_contains($service, 'TEMPLATE_SNAPSHOT_REFRESH_SECONDS')
&& str_contains($service, "'checked_at' => time()")
&& str_contains($service, "'catalog_unavailable' =>")
&& str_contains($service, 'Configurations::where(')
&& str_contains($service, 'self::sanitizeTemplates(')
&& str_contains($service, "'id' => \$template['id']")
&& str_contains($service, "'os_family' => \$template['os_family']")
&& str_contains($service, "'os_version' => \$template['os_version']"),
'The first-paint image catalog must use a durable, sanitized public snapshot.');
$assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/json"')
&& str_contains($deployTemplate, '{$cloud_deploy_bootstrap_json nofilter}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_regions as $region}')
&& str_contains($deployTemplate, '$region.host_id == $cloud_deploy_default_host_id')
&& str_contains($deployTemplate, '{foreach $region.plans as $plan}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}')
&& str_contains($deployTemplate, '$cloud_deploy_catalog_unavailable')
&& str_contains($deployTemplate, '系统镜像目录暂时无法读取')
&& !str_contains($deployTemplate, '请先选择地区')
&& !str_contains($deployTemplate, '正在加载'),
'Deployment HTML must immediately show regions, first-region plans, images and saved keys.');
$assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')")
&& str_contains($deployModule, "initializeSession('create', bootstrap?.user)")
&& str_contains($deployModule, 'openCreate(bootstrap)')
&& !str_contains($deployModule, '/api/v1/session')
&& !str_contains($deployModule, '/api/v1/plans')
&& !str_contains($deployModule, '/api/v1/resources')
&& !str_contains($deployModule, '/api/v1/ssh-keys'),
'Deployment page initialization must hydrate embedded data without a second data request.');
$deployHydrationEnd = strpos($openCreate, ' return;');
$deployFallback = strpos($openCreate, 'Promise.allSettled([');
$assert($openCreate !== ''
&& str_contains($openCreate, 'Array.isArray(bootstrap.plans)')
&& str_contains($openCreate, 'Array.isArray(bootstrap.templates)')
&& str_contains($openCreate, "bootstrapItems(bootstrap, 'regions')")
&& str_contains($openCreate, 'bootstrap.catalog_unavailable === true')
&& str_contains($openCreate, 'bootstrap.default_host_id')
&& str_contains($openCreate, "(regions[0]?.hostId || '')")
&& str_contains($openCreate, "renderTemplateCatalog('vm-template')")
&& $deployHydrationEnd !== false && $deployFallback !== false
&& $deployHydrationEnd < $deployFallback
&& !str_contains(substr($openCreate, 0, $deployHydrationEnd), "api('/api/v1/"),
'Deployment hydration must select the requested/first region and paint all data before any fallback.');
$assert($selectRegion !== '' && $selectPlan !== ''
&& !str_contains($selectRegion, 'resetInstallChoices()')
&& !str_contains($selectRegion, 'renderTemplateCatalog(')
&& !str_contains($selectRegion, 'loadGlobalTemplates(')
&& !str_contains($selectRegion, "byId('vm-template').value")
&& !str_contains($selectPlan, 'resetInstallChoices()')
&& !str_contains($selectPlan, 'renderTemplateCatalog(')
&& !str_contains($selectPlan, 'loadGlobalTemplates(')
&& !str_contains($selectPlan, "byId('vm-template').value"),
'Changing a region or plan must never clear or reload the global image selection.');
$assert(str_contains($reinstallController, 'CloudAccess::actor(false)')
&& str_contains($reinstallController, 'CloudInstancePageService::detailForActor($actor, $vmId)')
&& str_contains($reinstallController, '$vm = $this->reinstallVm($vm)')
&& str_contains($reinstallController, 'CloudDeploymentPageService::templateCatalogForPage($actor)')
&& str_contains($reinstallController, '$this->sshKeyOptions((int) $actor[\'user_id\'])')
&& str_contains($reinstallController, "'catalog_unavailable' => \$catalogUnavailable")
&& str_contains($reinstallController,
"'cloud_reinstall_catalog_unavailable' => \$catalogUnavailable")
&& str_contains($reinstallController, "'cloud_reinstall_bootstrap_json' => \$this->safeJson(\$payload)"),
'Reinstall controller must embed an owner-scoped VM plus its image and key choices.');
$assert(str_contains($reinstallTemplate, 'id="reinstall-bootstrap" type="application/json"')
&& str_contains($reinstallTemplate, '{$cloud_reinstall_bootstrap_json nofilter}')
&& str_contains($reinstallTemplate, '$cloud_reinstall_vm.name')
&& str_contains($reinstallTemplate, '$cloud_reinstall_vm.public_ip')
&& str_contains($reinstallTemplate, '{foreach $cloud_reinstall_template_groups as $group}')
&& str_contains($reinstallTemplate, '{foreach $cloud_reinstall_ssh_keys as $key}')
&& str_contains($reinstallTemplate, '$cloud_reinstall_catalog_unavailable')
&& str_contains($reinstallTemplate, '系统镜像目录暂时无法读取')
&& !str_contains($reinstallTemplate, '正在加载'),
'Reinstall HTML must immediately show the VM, network, image catalog and saved keys.');
$assert(str_contains($reinstallTemplate, '$cloud_reinstall_vm.can_operate')
&& str_contains($reinstallTemplate, 'inert aria-disabled="true"')
&& str_contains($reinstallTemplate, '当前不能重装系统')
&& str_contains($openReinstall, "byId('reinstall-submit').disabled = true"),
'A policy-blocked instance must expose reinstall information without an actionable destructive form.');
$assert(str_contains($reinstallModule, "readBootstrap('reinstall-bootstrap')")
&& str_contains($reinstallModule, "initializeSession('reinstall', bootstrap?.user)")
&& str_contains($reinstallModule,
'selectVmByApiId(document.body.dataset.vmId || \'\', bootstrap?.vm)')
&& str_contains($reinstallModule, 'openReinstall(vm, bootstrap)')
&& !str_contains($reinstallModule, '/api/v1/session')
&& !str_contains($reinstallModule, '/api/v1/vms')
&& !str_contains($reinstallModule, '/api/v1/resources')
&& !str_contains($reinstallModule, '/api/v1/ssh-keys'),
'Reinstall initialization must use embedded VM/catalog data without initial data APIs.');
$reinstallBootstrapStart = strpos($openReinstall,
'if (bootstrap && Array.isArray(bootstrap.templates))');
$reinstallHydrationEnd = $reinstallBootstrapStart === false ? false
: strpos($openReinstall, ' return;', $reinstallBootstrapStart);
$reinstallFallback = strpos($openReinstall, 'api(`/api/v1/resources?vm_id=');
$assert($openReinstall !== ''
&& str_contains($openReinstall, 'Array.isArray(bootstrap.templates)')
&& str_contains($openReinstall, 'bootstrap.catalog_unavailable === true')
&& str_contains($openReinstall, "bootstrapItems(bootstrap, 'ssh_keys', 'keys')")
&& str_contains($openReinstall, "renderTemplateCatalog('reinstall-template')")
&& str_contains($openReinstall, "renderKeyCards('reinstall')")
&& $reinstallHydrationEnd !== false && $reinstallFallback !== false
&& $reinstallHydrationEnd < $reinstallFallback
&& !str_contains(substr($openReinstall, 0, $reinstallHydrationEnd), '/api/v1/resources'),
'Reinstall hydration must paint embedded choices before its compatibility fallback.');
$assert(str_contains($controller, 'JSON_HEX_TAG')
&& str_contains($controller, "'csrf_token' => AdminCsrf::token()")
&& str_contains($controller, "withHeader('Cache-Control', 'private, no-store')"),
'Embedded deployment data must remain script-safe, authenticated and non-cacheable.');
$assert(preg_match("/venix_asset_version value='[0-9]+'/", $layoutAssets) === 1
&& str_contains($cloudShell, "{include file='layout_assets.tpl'}")
&& str_contains($cloudShell, '?v={$venix_asset_version}')
&& str_contains($cloudShell, 'data-asset-version="{$venix_asset_version|escape:"html"}"')
&& str_contains($deployModule,
"const assetVersion = new URL(import.meta.url).searchParams.get('v');")
&& str_contains($deployModule, "runtimeUrl.searchParams.set('v', assetVersion)")
&& str_contains($reinstallModule,
"const assetVersion = new URL(import.meta.url).searchParams.get('v');")
&& str_contains($reinstallModule, "runtimeUrl.searchParams.set('v', assetVersion)"),
'Cloud page and dynamically imported runtime assets must share one cache-busting version.');
echo "Deployment and reinstall server-rendered first-paint contract passed.\n";

@ -17,6 +17,7 @@ $adminController = file_get_contents($web . '/app/Controllers/CloudAdminControll
$feature = file_get_contents($web . '/app/Services/Cloud/CloudUserIsoFeature.php');
$view = file_get_contents($web . '/app/Services/View.php');
$client = file_get_contents($web . '/app/Services/Cloud/CloudEngineClient.php');
$deploymentPages = file_get_contents($web . '/app/Services/Cloud/CloudDeploymentPageService.php');
$orders = file_get_contents($web . '/app/Services/Cloud/CloudOrderService.php');
$runtime = file_get_contents($web . '/public/cloud/runtime.js');
$isoClient = file_get_contents($web . '/public/cloud/iso-images.js');
@ -74,9 +75,11 @@ $assert(str_contains($orders, "if (\$source !== 'cloud')")
&& !str_contains($runtime, 'body.iso_path ='),
'Provisioning must be cloud-template-only on both browser and server boundaries.');
$assert(str_contains($controller, "\$available->pluck('host_id')")
&& str_contains($controller, "CloudHost::whereIn('id', \$hostIds)")
&& str_contains($controller, "'/internal/v1/vm-templates'")
$assert(str_contains($deploymentPages, "\$available->pluck('host_id')")
&& str_contains($deploymentPages, "CloudHost::whereIn('id', \$hostIds)")
&& str_contains($controller, 'CloudDeploymentPageService::plans()')
&& str_contains($controller, 'CloudDeploymentPageService::freshTemplateCatalog($actor)')
&& str_contains($deploymentPages, "'/internal/v1/vm-templates'")
&& str_contains($controller, "return \$this->json(\$response, \$templatePayload);")
&& !str_contains($controller, "\$engine->host(\$hostId, 'GET', 'vm-templates', \$actor)"),
'Plan listing must preload hosts and deployment resources must return the global cloud-template catalog.');

@ -52,6 +52,11 @@ $clientStyles = file_get_contents($public . '/client.css');
$baseStyles = file_get_contents($public . '/styles.css');
$routes = file_get_contents($root . '/config/routes.php');
$cloudPageController = file_get_contents($root . '/app/Controllers/CloudPageController.php');
$deploymentPageService = file_get_contents($root . '/app/Services/Cloud/CloudDeploymentPageService.php');
$deployTemplate = file_get_contents($views . '/cloud/pages/deploy.tpl');
$reinstallTemplate = file_get_contents($views . '/cloud/pages/reinstall.tpl');
$deployModule = file_get_contents($public . '/deploy.js');
$reinstallModule = file_get_contents($public . '/reinstall.js');
$shopFormScript = file_get_contents($views . '/admin/shop/form_js.tpl');
$templateAdmin = file_get_contents($views . '/admin/cloud/templates.tpl');
$rescueAdmin = file_get_contents($views . '/admin/cloud/rescue.tpl');
@ -137,11 +142,6 @@ $assert(str_contains($planRenderer, "'plan-table-head'")
&& !str_contains($cloudTemplate, 'id="create-iso-tip"'),
'Deployment plans must use selectable specification rows without obsolete helper panels.');
$runtimeDeployScript = file_get_contents($public . '/runtime.js');
$resetStart = strpos($runtimeDeployScript, 'function resetInstallChoices()');
$resetEnd = $resetStart === false ? false
: strpos($runtimeDeployScript, 'function renderRegionPicker()', $resetStart);
$resetInstall = $resetStart === false || $resetEnd === false ? ''
: substr($runtimeDeployScript, $resetStart, $resetEnd - $resetStart);
$selectRegionStart = strpos($runtimeDeployScript, 'async function selectRegion(');
$selectRegionEnd = $selectRegionStart === false ? false
: strpos($runtimeDeployScript, 'async function selectPlan(', $selectRegionStart);
@ -149,55 +149,72 @@ $selectRegion = $selectRegionStart === false || $selectRegionEnd === false ? ''
: substr($runtimeDeployScript, $selectRegionStart, $selectRegionEnd - $selectRegionStart);
$selectPlanStart = strpos($runtimeDeployScript, 'async function selectPlan(');
$selectPlanEnd = $selectPlanStart === false ? false
: strpos($runtimeDeployScript, 'async function openCreate()', $selectPlanStart);
: strpos($runtimeDeployScript, 'async function openCreate(', $selectPlanStart);
$selectPlan = $selectPlanStart === false || $selectPlanEnd === false ? ''
: substr($runtimeDeployScript, $selectPlanStart, $selectPlanEnd - $selectPlanStart);
$openCreateStart = strpos($runtimeDeployScript, 'async function openCreate()');
$openCreateStart = strpos($runtimeDeployScript, 'async function openCreate(');
$openCreateEnd = $openCreateStart === false ? false
: strpos($runtimeDeployScript, 'async function loadGlobalTemplates()', $openCreateStart);
$openCreate = $openCreateStart === false || $openCreateEnd === false ? ''
: substr($runtimeDeployScript, $openCreateStart, $openCreateEnd - $openCreateStart);
$resourcesStart = strpos($runtimeDeployScript, 'async function loadGlobalTemplates()');
$resourcesEnd = $resourcesStart === false ? false
: strpos($runtimeDeployScript, 'function provisionInvoiceStorageKey()', $resourcesStart);
$resourceLoader = $resourcesStart === false || $resourcesEnd === false ? ''
: substr($runtimeDeployScript, $resourcesStart, $resourcesEnd - $resourcesStart);
$statusStart = strpos($runtimeDeployScript, 'function renderTemplateCatalogStatus(');
$statusEnd = $statusStart === false ? false
: strpos($runtimeDeployScript, 'function renderTemplateCatalog(', $statusStart);
$templateStatus = $statusStart === false || $statusEnd === false ? ''
: substr($runtimeDeployScript, $statusStart, $statusEnd - $statusStart);
$loadingPosition = strpos($resourceLoader,
"renderTemplateCatalogStatus('vm-template', '正在加载系统镜像…', true)");
$requestPosition = strpos($resourceLoader,
"const resources = await api('/api/v1/resources'");
$templatesPosition = strpos($resourceLoader,
'state.templates = items(resources.templates || resources.cloud_templates)');
$catalogPosition = strpos($resourceLoader, "renderTemplateCatalog('vm-template')");
$assert($resetInstall !== ''
&& !str_contains($resetInstall, "renderTemplateCatalog('vm-template')")
&& str_contains($resetInstall, 'templateInput.disabled = true')
&& str_contains($resetInstall, 'templateCatalog.replaceChildren()')
&& $loadingPosition !== false && $requestPosition !== false
&& $templatesPosition !== false && $catalogPosition !== false
&& $loadingPosition < $requestPosition
&& $requestPosition < $templatesPosition
&& $templatesPosition < $catalogPosition
&& !str_contains($resourceLoader, 'resetInstallChoices()')
&& str_contains($templateStatus, 'container.setAttribute("aria-busy", String(busy))')
&& str_contains($templateStatus, '"template-catalog-status"')
&& !str_contains($templateStatus, 'template-catalog-empty')
&& str_contains($resourceLoader, '系统镜像加载失败,请刷新页面后重试。')
&& str_contains($resourceLoader, 'controller === state.resourceController')
&& str_contains($resourceLoader, "error.name !== 'AbortError'")
&& str_contains($runtimeDeployScript, '暂无可用云镜像,请联系管理员导入模板。'),
'Global cloud-image loading must distinguish loading, failure and true-empty states.');
$assert(str_contains($openCreate, 'Promise.allSettled([')
&& str_contains($openCreate, "api('/api/v1/plans')")
&& str_contains($openCreate, 'loadKeys()')
&& str_contains($openCreate, 'loadGlobalTemplates()')
&& substr_count($runtimeDeployScript, "api('/api/v1/resources'") === 1,
'Deployment must load plans, keys and the global image directory in parallel exactly once.');
$openReinstallStart = strpos($runtimeDeployScript, 'async function openReinstall(');
$openReinstallEnd = $openReinstallStart === false ? false
: strpos($runtimeDeployScript, 'async function pollJob(', $openReinstallStart);
$openReinstall = $openReinstallStart === false || $openReinstallEnd === false ? ''
: substr($runtimeDeployScript, $openReinstallStart, $openReinstallEnd - $openReinstallStart);
$deployHydrationReturn = strpos($openCreate, ' return;');
$deployFallbackRequest = strpos($openCreate, 'Promise.allSettled([');
$reinstallBootstrapStart = strpos($openReinstall,
'if (bootstrap && Array.isArray(bootstrap.templates))');
$reinstallHydrationReturn = $reinstallBootstrapStart === false ? false
: strpos($openReinstall, ' return;', $reinstallBootstrapStart);
$reinstallFallbackRequest = strpos($openReinstall, "api(`/api/v1/resources?vm_id=");
$assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/json"')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_regions as $region}')
&& str_contains($deployTemplate, '$region.host_id == $cloud_deploy_default_host_id')
&& str_contains($deployTemplate, '{foreach $region.plans as $plan}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}')
&& !str_contains($deployTemplate, '正在加载系统镜像'),
'Deployment HTML must contain regions, first-region plans, images and SSH keys before hydration.');
$assert(str_contains($deploymentPageService, "->orderBy('sort')->orderBy('id')")
&& str_contains($deploymentPageService, "->where('enabled', 1)")
&& str_contains($deploymentPageService, "'plans' => []")
&& str_contains($cloudPageController, '$defaultHostId = $regions === [] ? 0 : (int) $regions[0][\'host_id\']')
&& str_contains($cloudPageController, "'cloud_deploy_bootstrap_json' => \$this->safeJson(\$payload)"),
'Deployment SSR must preserve sale order and select the first available host region by default.');
$assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')")
&& str_contains($deployModule, "initializeSession('create', bootstrap?.user)")
&& str_contains($deployModule, 'openCreate(bootstrap)')
&& !str_contains($deployModule, '/api/v1/session')
&& !str_contains($deployModule, '/api/v1/plans')
&& !str_contains($deployModule, '/api/v1/resources')
&& !str_contains($deployModule, '/api/v1/ssh-keys'),
'Deployment first paint must hydrate its embedded payload without initial data API requests.');
$assert(str_contains($openCreate, 'Array.isArray(bootstrap.plans)')
&& str_contains($openCreate, 'Array.isArray(bootstrap.templates)')
&& str_contains($openCreate, "bootstrapItems(bootstrap, 'regions')")
&& str_contains($openCreate, 'bootstrap.default_host_id')
&& str_contains($openCreate, "(regions[0]?.hostId || '')")
&& str_contains($openCreate, "renderTemplateCatalog('vm-template')")
&& $deployHydrationReturn !== false && $deployFallbackRequest !== false
&& $deployHydrationReturn < $deployFallbackRequest,
'Deployment hydration must use the embedded full catalog and first valid region before any compatibility fallback.');
$assert(str_contains($reinstallTemplate, 'id="reinstall-bootstrap" type="application/json"')
&& str_contains($reinstallTemplate, '$cloud_reinstall_vm.name')
&& str_contains($reinstallTemplate, '{foreach $cloud_reinstall_template_groups as $group}')
&& str_contains($reinstallTemplate, '{foreach $cloud_reinstall_ssh_keys as $key}')
&& str_contains($reinstallModule, "readBootstrap('reinstall-bootstrap')")
&& str_contains($reinstallModule, "initializeSession('reinstall', bootstrap?.user)")
&& str_contains($reinstallModule, 'selectVmByApiId(document.body.dataset.vmId || \'\', bootstrap?.vm)')
&& str_contains($reinstallModule, 'openReinstall(vm, bootstrap)')
&& !str_contains($reinstallModule, '/api/v1/session')
&& !str_contains($reinstallModule, '/api/v1/resources')
&& !str_contains($reinstallModule, '/api/v1/ssh-keys')
&& str_contains($openReinstall, 'Array.isArray(bootstrap.templates)')
&& $reinstallHydrationReturn !== false && $reinstallFallbackRequest !== false
&& $reinstallHydrationReturn < $reinstallFallbackRequest,
'Reinstall HTML must embed VM, image and key data and hydrate without initial data API requests.');
$assert($selectRegion !== '' && $selectPlan !== ''
&& !str_contains($selectRegion, 'resetInstallChoices()')
&& !str_contains($selectRegion, 'renderTemplateCatalog(')

Loading…
Cancel
Save