You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/instances.js

775 lines
30 KiB
JavaScript

const assetVersion = new URL(import.meta.url).searchParams.get('v');
function versionedModuleUrl(path) {
const url = new URL(path, import.meta.url);
url.search = '';
if (assetVersion) url.searchParams.set('v', assetVersion);
return url.href;
}
const [toastModule, instanceService] = await Promise.all([
import(versionedModuleUrl('./toast.js')),
import(versionedModuleUrl('./instance-service.js')),
]);
const { toast } = toastModule;
const { formatServiceExpiry, servicePaused } = instanceService;
const i18n = globalThis.VenixUserCopy;
const t = (key, parameters = {}) => i18n.text(key, parameters);
// The first twenty instances are rendered by PHP. This lightweight module only
// handles local filtering, pagination and batched live-state refreshes.
const byId = id => document.getElementById(id);
const POLL_INTERVAL = 15000;
const TRANSITION_POLL_INTERVAL = 3000;
const MAX_POLL_INTERVAL = 120000;
const MAX_CONVERGENCE_PROBES = 4;
const state = {
vms: [],
stats: { total: 0, running: 0, stopped: 0 },
pagination: {
page: 1, per_page: 20, total: 0, total_pages: 1,
page_count: 0, has_previous: false, has_next: false, from: 0, to: 0,
},
user: {},
loading: false,
metadataLoading: false,
statusLoading: false,
liveStatsReady: false,
pageActive: true,
pollTimer: null,
pollFailures: 0,
convergenceCursor: 0,
};
function showError(message = '') {
const target = byId('cloud-page-error');
if (!target) return;
target.textContent = message;
target.hidden = !message;
}
async function api(path) {
const response = await fetch(path, {
method: 'GET', headers: { Accept: 'application/json' },
credentials: 'same-origin', cache: 'no-store',
});
let payload;
try { payload = await response.json(); }
catch { throw new Error(t('instances.error.non_json')); }
if (response.status === 401) {
location.assign('/auth/login');
throw new Error(t('instances.error.login_expired'));
}
if (!response.ok || payload?.ret === 0) {
throw new Error(response.status === 422
? t('instances.error.input')
: t('instances.error.request', { status: response.status }));
}
return payload;
}
function makeElement(tag, className = '', content) {
const element = document.createElement(tag);
if (className) element.className = className;
if (content !== undefined) element.textContent = String(content);
return element;
}
function firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') {
return String(value).trim();
}
}
return '';
}
function normalizeVm(vm) {
const source = vm && typeof vm === 'object' ? vm : {};
const fresh = source.state_fresh === true || source.fresh === true
|| source.fresh === 1 || source.fresh === '1' || source.fresh === 'true';
return {
...source,
uuid: String(source.uuid || source.id || ''),
api_id: String(source.api_id || source.id || source.uuid || ''),
vcpu: source.vcpu ?? source.cpu_cores,
memory_mib: source.memory_mib ?? source.ram_mib,
public_network_valid: source.public_network_valid === true,
public_ipv4: source.public_network_valid === true ? String(source.public_ipv4 || '') : '',
public_ipv6: source.public_network_valid === true ? String(source.public_ipv6 || '') : '',
state_fresh: fresh,
state_observed_at: source.state_observed_at ?? source.last_success_at ?? null,
state_sync_status: String(source.state_sync_status ?? source.sync_status
?? (fresh ? 'fresh' : 'pending')).toLowerCase(),
};
}
function stateCategory(value) {
const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, '');
if (normalized === 'running' || normalized === 'blocked') return 'running';
if (['shutoff', 'stopped', 'crashed'].includes(normalized)) return 'stopped';
return 'other';
}
function stateLabel(value) {
const normalized = String(value || 'unknown').toLowerCase().replace(/[_\s-]+/g, '');
const labels = {
running: t('instances.state.running'), blocked: t('instances.state.running'),
shutoff: t('instances.state.stopped'), stopped: t('instances.state.stopped'),
shutdown: t('instances.state.shutting_down'), crashed: t('instances.state.crashed'),
paused: t('instances.state.paused'), pmsuspended: t('instances.state.suspended'),
nostate: t('instances.state.awaiting_sync'), unknown: t('instances.state.awaiting_sync'),
};
return labels[normalized] || t('instances.state.awaiting_sync');
}
function runtimeStateReady(vm) {
return !operationTransition(vm) && hasKnownState(vm)
&& (String(vm?.state_sync_status || '').toLowerCase() === ''
|| String(vm?.state_sync_status || '').toLowerCase() === 'fresh');
}
function activeOperationTransition(vm) {
const transition = String(vm?.operation_transition || '').toLowerCase();
return ['start', 'shutdown', 'reinstall', 'upgrade', 'locked'].includes(transition) ? transition : '';
}
function operationTransition(vm) {
const active = activeOperationTransition(vm);
if (active) return active;
if (vm?.state_transitioning !== true) return '';
const transition = String(vm?.state_transition || '').toLowerCase();
return transition === 'shutdown' ? transition : '';
}
function shutdownConverging(vm) {
const deadline = Number(vm?.shutdown_convergence_until);
return operationTransition(vm) === 'shutdown'
&& !activeOperationTransition(vm)
&& deadline >= Math.floor(Date.now() / 1000);
}
function hasKnownState(vm) {
const state = String(vm?.state || '').toLowerCase();
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['pending', 'never'].includes(sync)) return false;
return state !== '' && state !== 'unknown' && state !== 'nostate'
&& !['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync);
}
function stateCategoryForVm(vm) {
if (vm?.network_status === 'configuration_invalid') return 'other';
if (operationTransition(vm)) return 'other';
if (servicePaused(vm)) return 'other';
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) {
return 'other';
}
if (!hasKnownState(vm)) return 'other';
return stateCategory(vm?.state);
}
function stateDisplay(vm) {
if (vm?.network_status === 'configuration_invalid') {
return { label: t('instances.state.network_invalid'), category: 'other', note: '', noteClass: '' };
}
const transition = operationTransition(vm);
if (transition) {
const labels = {
start: t('instances.state.starting'), shutdown: t('instances.state.shutting_down'),
reinstall: t('instances.state.reinstalling'), upgrade: t('instances.state.upgrading'),
locked: t('instances.state.reconciling'),
};
return { label: labels[transition], category: 'other', note: '', noteClass: '' };
}
if (servicePaused(vm)) {
return { label: t('instances.state.paused'), category: 'other', note: '', noteClass: '' };
}
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) {
return { label: t('instances.state.sync_unavailable'), category: 'other', note: '', noteClass: 'offline' };
}
if (!hasKnownState(vm)) {
const label = ['creating', 'provisioning', 'deploying']
.includes(String(vm?.instance_status || ''))
? t('instances.state.deploying') : t('instances.state.awaiting_sync');
return { label, category: 'other', note: '', noteClass: '' };
}
const category = stateCategory(vm.state);
return {
label: stateLabel(vm.state),
category,
note: runtimeStateReady(vm) ? '' : t('instances.state.syncing'),
noteClass: runtimeStateReady(vm) ? '' : 'stale',
};
}
function vmRegion(vm) {
return firstText(vm.region, vm.location, t('instances.value.not_set'));
}
function vmIp(vm) {
if (vm?.public_network_valid !== true) return t('instances.value.not_available');
return firstText(vm.public_ipv4) || t('instances.value.not_available');
}
function vmSystemInfo(vm) {
if (vm.os_source === 'iso') return { label: t('instances.system.iso'), value: firstText(vm.install_iso, t('instances.value.unrecognized')) };
if (vm.os_source === 'cloud_template') return { label: t('instances.system.template'), value: firstText(vm.os_name, t('instances.value.unrecognized')) };
return { label: t('instances.system.other'), value: firstText(vm.os_name, vm.install_iso, t('instances.value.unrecognized')) };
}
function diskLabel(vm) {
if (Array.isArray(vm.disks) && vm.disks.length) {
const size = vm.disks.reduce((total, disk) => {
const capacity = Number(disk?.capacity_gib ?? disk?.size_gib ?? 0);
return total + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0);
}, 0);
if (size > 0) return `${Math.round(size * 100) / 100} GiB`;
}
const size = Number(vm.disk_gib);
return Number.isFinite(size) && size > 0 ? `${size} GiB` : '—';
}
function normalizeStats(value, vms = []) {
const source = value && typeof value === 'object' ? value : {};
const pageRunning = vms.filter(vm => stateCategoryForVm(vm) === 'running').length;
const pageStopped = vms.filter(vm => stateCategoryForVm(vm) === 'stopped').length;
const number = (candidate, fallback) => {
const parsed = Number(candidate);
return Number.isFinite(parsed) && parsed >= 0 ? Math.trunc(parsed) : fallback;
};
return {
total: number(source.total, vms.length),
running: number(source.running, pageRunning),
stopped: number(source.stopped, pageStopped),
};
}
function normalizePagination(value, fallbackPage = 1, fallbackTotal = 0) {
const source = value && typeof value === 'object' ? value : {};
const page = Math.max(1, Math.trunc(Number(source.page) || fallbackPage));
const totalPages = Math.max(1, Math.trunc(Number(source.total_pages) || 1));
const total = Math.max(0, Math.trunc(Number(source.total) || fallbackTotal));
return {
page,
per_page: Math.max(1, Math.trunc(Number(source.per_page) || 20)),
total,
page_count: Math.max(0, Math.trunc(Number(source.page_count) || 0)),
total_pages: totalPages,
has_previous: source.has_previous === true || page > 1,
has_next: source.has_next === true || page < totalPages,
from: Math.max(0, Math.trunc(Number(source.from) || 0)),
to: Math.max(0, Math.trunc(Number(source.to) || 0)),
};
}
function renderStats() {
if (byId('stat-total')) byId('stat-total').textContent = String(state.stats.total);
// The PHP bootstrap and the cache-only status endpoint already provide the
// last known counts. Render them immediately, including while a host is
// being re-synchronised; a stale row is explicitly marked in its status
// cell and must not make the whole summary look like it is still loading.
const liveValue = value => String(value);
if (byId('stat-running')) byId('stat-running').textContent = liveValue(state.stats.running);
if (byId('stat-stopped')) byId('stat-stopped').textContent = liveValue(state.stats.stopped);
}
async function copyText(value) {
if (navigator.clipboard?.writeText) {
try { await navigator.clipboard.writeText(value); return; } catch {}
}
const area = document.createElement('textarea');
area.value = value;
area.style.position = 'fixed';
area.style.opacity = '0';
document.body.append(area);
area.select();
try {
if (!document.execCommand('copy')) throw new Error(t('instances.error.copy'));
} finally { area.value = ''; area.remove(); }
}
function copyIconButton(value, label) {
const button = makeElement('button', 'vm-copy-icon');
button.type = 'button';
button.dataset.copyValue = value;
button.dataset.copyLabel = label;
button.title = t('instances.copy.value', { label });
button.setAttribute('aria-label', t('instances.copy.value', { label }));
const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
icon.setAttribute('viewBox', '0 0 24 24');
icon.setAttribute('aria-hidden', 'true');
const back = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
for (const [name, valuePart] of Object.entries({ x: '8', y: '8', width: '12', height: '12', rx: '2' })) {
back.setAttribute(name, valuePart);
}
const front = document.createElementNS('http://www.w3.org/2000/svg', 'path');
front.setAttribute('d', 'M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2');
icon.append(back, front);
button.append(icon);
return button;
}
function makeCell(row, label) {
const cell = document.createElement('td');
cell.dataset.label = label;
row.append(cell);
return cell;
}
function matchingVms() {
const query = (byId('search-input')?.value || '').trim().toLocaleLowerCase();
const filter = byId('state-filter')?.value || 'all';
return state.vms.filter(vm => {
const textMatches = !query || [vm.name, vm.uuid, vm.public_ipv4, vm.public_ipv6,
vm.region, vm.location, vm.os_name, vm.install_iso]
.some(value => String(value || '').toLocaleLowerCase().includes(query));
const statusMatches = filter === 'all' || stateCategoryForVm(vm) === filter;
return textMatches && statusMatches;
});
}
function renderCount(filteredCount = state.vms.length) {
const target = byId('inventory-count');
if (!target) return;
const filtering = Boolean((byId('search-input')?.value || '').trim())
|| (byId('state-filter')?.value || 'all') !== 'all';
target.textContent = filtering
? t('instances.list.count_filtered', {
filtered: filteredCount, page_count: state.vms.length, total: state.pagination.total,
})
: t('instances.list.count', {
page_count: state.vms.length, total: state.pagination.total,
});
}
function renderVms(connectionError = false) {
const filtered = matchingVms();
renderCount(filtered.length);
const tbody = byId('vm-table-body');
const empty = byId('empty-state');
if (!tbody || !empty) return;
tbody.replaceChildren();
empty.hidden = filtered.length !== 0;
if (!filtered.length) {
if (connectionError) {
byId('empty-title').textContent = t('instances.empty.failed.title');
byId('empty-description').textContent = t('instances.empty.failed.body');
} else if (state.vms.length) {
byId('empty-title').textContent = t('instances.empty.filtered.title');
byId('empty-description').textContent = t('instances.empty.filtered.body');
} else {
byId('empty-title').textContent = t('instances.empty.none.title');
byId('empty-description').textContent = t('instances.empty.none.body');
}
return;
}
const fragment = document.createDocumentFragment();
for (const vm of filtered) {
const row = document.createElement('tr');
row.dataset.vmId = vm.api_id;
row.dataset.vmUuid = vm.uuid;
const identity = makeElement('div', 'vm-identity');
identity.append(makeElement('div', 'vm-icon', '▣'));
const identityText = document.createElement('div');
const name = makeElement('a', 'vm-name-link', vm.name || t('instances.value.unnamed'));
name.href = `/user/cloud/instances/${encodeURIComponent(vm.api_id)}`;
name.dataset.vmUuid = vm.uuid;
name.setAttribute('aria-label', t('instances.manage.aria', { name: vm.name || vm.uuid }));
const uuidRow = makeElement('span', 'vm-uuid-row');
const uuid = makeElement('span', 'vm-id', vm.uuid || t('instances.value.uuid_unknown'));
if (vm.uuid) uuid.title = vm.uuid;
uuidRow.append(uuid);
if (vm.uuid) uuidRow.append(copyIconButton(vm.uuid, 'UUID'));
identityText.append(name, uuidRow);
identity.append(identityText);
makeCell(row, t('instances.column.instance')).append(identity);
const display = stateDisplay(vm);
const status = makeElement('span', `state-pill ${display.category} vm-state-pill`, display.label);
const statusCell = makeCell(row, t('instances.column.status'));
statusCell.append(status);
if (display.note) {
statusCell.append(makeElement('small', `vm-state-sync ${display.noteClass}`, display.note));
}
makeCell(row, t('instances.column.expiry')).append(makeElement(
'span', 'vm-metadata vm-expiry', formatServiceExpiry(vm),
));
makeCell(row, t('instances.column.region')).append(makeElement('span', 'vm-metadata', vmRegion(vm)));
const system = vmSystemInfo(vm);
makeCell(row, system.label).append(makeElement('span', 'vm-metadata', system.value));
const addresses = makeElement('div', 'vm-public-addresses');
const ip = vmIp(vm);
const ipRow = makeElement('span', 'vm-ip-copy-row');
ipRow.append(makeElement('span', 'vm-metadata vm-ip', ip));
if (ip !== t('instances.value.not_available')) {
ipRow.append(copyIconButton(ip, t('instances.address.ipv4')));
}
addresses.append(ipRow);
makeCell(row, t('instances.column.address')).append(addresses);
const spec = makeElement('div', 'vm-spec');
const specLabel = makeElement('small', '', t('instances.spec.compute'));
i18n.bind(specLabel, 'instances.spec.compute');
spec.append(makeElement('strong', '', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`),
specLabel);
makeCell(row, t('instances.column.spec')).append(spec);
makeCell(row, t('instances.column.disk')).append(makeElement('span', 'vm-spec', diskLabel(vm)));
fragment.append(row);
}
tbody.append(fragment);
}
function renderPagination() {
const navigation = byId('instances-pagination');
if (!navigation) return;
const { page, total_pages: totalPages, total, has_previous: previous, has_next: next } = state.pagination;
navigation.hidden = total === 0;
const busy = state.loading || state.metadataLoading || state.statusLoading;
navigation.setAttribute('aria-busy', String(busy));
if (byId('instances-page-label')) {
byId('instances-page-label').textContent = t('instances.pagination.label', {
page, pages: totalPages, total,
});
}
if (byId('instances-previous')) {
byId('instances-previous').disabled = busy || !previous;
}
if (byId('instances-next')) {
byId('instances-next').disabled = busy || !next;
}
if (byId('refresh-button')) {
byId('refresh-button').disabled = busy;
byId('refresh-button').setAttribute('aria-busy', String(busy));
}
}
function updatePageUrl(page) {
const url = new URL(location.href);
if (page > 1) url.searchParams.set('page', String(page));
else url.searchParams.delete('page');
history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`);
}
function stopPolling() {
if (state.pollTimer !== null) window.clearTimeout(state.pollTimer);
state.pollTimer = null;
}
function nextPollDelay() {
const base = state.vms.some(vm => activeOperationTransition(vm)
|| shutdownConverging(vm))
? TRANSITION_POLL_INTERVAL : POLL_INTERVAL;
if (!state.pollFailures) return base;
return Math.min(MAX_POLL_INTERVAL, base * (2 ** Math.min(state.pollFailures, 3)));
}
function schedulePolling(delay = nextPollDelay()) {
stopPolling();
if (!state.pageActive || document.hidden || !state.vms.length) return;
state.pollTimer = window.setTimeout(() => {
state.pollTimer = null;
void refreshStatuses(true);
}, delay);
}
function statusItems(payload) {
if (Array.isArray(payload?.vms)) return payload.vms;
if (Array.isArray(payload?.statuses)) return payload.statuses;
if (Array.isArray(payload?.items)) return payload.items;
if (payload?.statuses && typeof payload.statuses === 'object') {
return Object.entries(payload.statuses).map(([id, value]) => (
value && typeof value === 'object' ? { id, ...value } : { id, state: value }
));
}
return [];
}
function vmMatchesUpdate(vm, update) {
const candidates = [update?.api_id, update?.id, update?.uuid].map(value => String(value || ''));
return candidates.includes(vm.api_id) || candidates.includes(vm.uuid);
}
const VM_METADATA_FIELDS = Object.freeze([
'region', 'location', 'os_source', 'os_name', 'install_iso',
'public_network_valid', 'public_network', 'public_ipv4', 'public_ipv4_cidr',
'public_ipv6', 'public_ipv6_cidr', 'public_ip_cidr', 'public_ip',
'login_name', 'vcpu', 'cpu_cores', 'memory_mib',
'ram_mib', 'disks', 'disk_gib', 'agent_metadata_version',
]);
function needsVmMetadata(vm) {
if (Number(vm?.agent_metadata_version) >= 1) return false;
const source = firstText(vm?.os_source);
if (!source) return true;
if (source === 'cloud_template') {
// Public addressing is a frozen panel snapshot. The Agent metadata API
// cannot repair it, so an invalid snapshot must not trigger endless
// metadata probes or be replaced by host-reported network values.
return !firstText(vm.os_name) || !firstText(vm.login_name);
}
if (source === 'iso') return !firstText(vm.install_iso);
return true;
}
function metadataItems(payload) {
if (Array.isArray(payload?.vms)) return payload.vms;
if (Array.isArray(payload?.items)) return payload.items;
return [];
}
function applyMetadata(payload) {
for (const update of metadataItems(payload)) {
if (!update || typeof update !== 'object') continue;
const vm = state.vms.find(item => vmMatchesUpdate(item, update));
if (!vm) continue;
const updateUuid = String(update.uuid || '').toLowerCase();
if (!updateUuid || updateUuid !== String(vm.uuid || '').toLowerCase()) continue;
for (const field of VM_METADATA_FIELDS) {
if (Object.prototype.hasOwnProperty.call(update, field)) vm[field] = update[field];
}
Object.assign(vm, normalizeVm(vm));
}
renderVms();
}
/** Fetch host-derived static fields only once for the currently visible page. */
async function refreshMetadata() {
if (!state.pageActive || state.metadataLoading || !state.vms.length) return;
const ids = state.vms.filter(needsVmMetadata).map(vm => vm.api_id).filter(Boolean);
if (!ids.length) return;
state.metadataLoading = true;
renderPagination();
try {
const payload = await api(`/api/v1/vms/metadata?ids=${encodeURIComponent(ids.join(','))}`);
applyMetadata(payload);
} catch {
// Keep the database-backed first paint usable. The independent status
// request below still runs, and a manual page refresh can retry metadata.
} finally {
state.metadataLoading = false;
renderPagination();
}
}
function applyStatuses(payload) {
const updates = statusItems(payload);
let statusFilterChanged = false;
let displayNameChanged = false;
for (const update of updates) {
const vm = state.vms.find(item => vmMatchesUpdate(item, update));
if (!vm) continue;
const candidateState = firstText(update.state, update.status);
const normalizedState = candidateState.toLowerCase().replace(/[_\s-]+/g, '');
const hasState = candidateState !== '' && normalizedState !== 'unknown'
&& normalizedState !== 'nostate';
const previousCategory = stateCategoryForVm(vm);
const previousName = String(vm.name || '');
const liveState = update?.live_state_available === true;
const nextState = hasState ? candidateState : vm.state;
const nextSync = firstText(update.state_sync_status, update.sync_status,
liveState ? 'fresh' : vm.state_sync_status || 'pending').toLowerCase();
const nextFresh = update.state_fresh === true || update.fresh === true
|| update.fresh === 1 || update.fresh === '1' || liveState;
Object.assign(vm, update, {
state: nextState,
state_fresh: nextFresh,
state_sync_status: nextSync,
state_observed_at: update.state_observed_at ?? update.last_success_at
?? (liveState ? Math.floor(Date.now() / 1000) : vm.state_observed_at),
});
if (String(vm.name || '') !== previousName) displayNameChanged = true;
const nextCategory = stateCategoryForVm(vm);
if (previousCategory !== nextCategory) {
if (previousCategory === 'running') state.stats.running = Math.max(0, state.stats.running - 1);
if (previousCategory === 'stopped') state.stats.stopped = Math.max(0, state.stats.stopped - 1);
if (nextCategory === 'running') state.stats.running += 1;
if (nextCategory === 'stopped') state.stats.stopped += 1;
statusFilterChanged = true;
}
const row = Array.from(document.querySelectorAll('#vm-table-body tr[data-vm-id]'))
.find(item => item.dataset.vmId === vm.api_id || item.dataset.vmUuid === vm.uuid);
const pill = row?.querySelector('.vm-state-pill');
if (pill) {
const display = stateDisplay(vm);
pill.className = `state-pill ${display.category} vm-state-pill`;
pill.textContent = display.label;
const statusCell = pill.parentElement;
let note = statusCell?.querySelector('.vm-state-sync');
if (display.note) {
if (!note) {
note = makeElement('small', 'vm-state-sync');
statusCell?.append(note);
}
note.className = `vm-state-sync ${display.noteClass}`;
note.textContent = display.note;
} else if (note) {
note.remove();
}
}
}
if (payload?.stats && typeof payload.stats === 'object') {
state.stats = normalizeStats(payload.stats, state.vms);
}
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
renderStats();
if (displayNameChanged
|| (statusFilterChanged && (byId('state-filter')?.value || 'all') !== 'all')) {
renderVms();
}
}
async function refreshConvergingStatuses() {
const candidates = state.vms.filter(shutdownConverging)
.map(vm => vm.api_id).filter(Boolean);
if (!candidates.length) {
state.convergenceCursor = 0;
return;
}
const start = state.convergenceCursor % candidates.length;
const ids = [];
for (let offset = 0; offset < Math.min(MAX_CONVERGENCE_PROBES, candidates.length); offset++) {
ids.push(candidates[(start + offset) % candidates.length]);
}
state.convergenceCursor = (start + ids.length) % candidates.length;
try {
const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}&live=1`);
applyStatuses(payload);
} catch {
// Preserve the last identity-checked state and retry while the transition
// remains active; a host outage must not become a fabricated shutdown.
}
}
async function refreshStatuses(scheduleNext = true) {
if (!state.pageActive || state.statusLoading || document.hidden || !state.vms.length) {
if (scheduleNext) schedulePolling();
return;
}
const ids = state.vms.map(vm => vm.api_id).filter(Boolean);
if (!ids.length) return;
state.statusLoading = true;
renderPagination();
try {
const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids.join(','))}`);
applyStatuses(payload);
await refreshConvergingStatuses();
state.pollFailures = 0;
showError();
} catch (error) {
state.pollFailures += 1;
if (state.pollFailures >= 2) {
showError(t('instances.error.live_retry'));
}
} finally {
state.statusLoading = false;
renderPagination();
if (scheduleNext) schedulePolling();
}
}
async function loadPage(page = state.pagination.page, updateUrl = true) {
if (state.loading || state.metadataLoading) return;
const requestedPage = Math.max(1, Math.trunc(Number(page) || 1));
state.loading = true;
state.liveStatsReady = false;
stopPolling();
renderPagination();
let pageLoaded = false;
try {
const payload = await api(`/api/v1/vms/page?page=${encodeURIComponent(requestedPage)}`);
state.vms = (Array.isArray(payload?.vms) ? payload.vms : []).map(normalizeVm);
state.pagination = normalizePagination(payload?.pagination, requestedPage, state.vms.length);
state.stats = normalizeStats(payload?.stats, state.vms);
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
state.pollFailures = 0;
renderStats();
renderVms();
renderPagination();
if (updateUrl) updatePageUrl(state.pagination.page);
showError();
pageLoaded = true;
} catch (error) {
showError(t('instances.error.load'));
if (!state.vms.length) renderVms(true);
} finally {
state.loading = false;
renderPagination();
}
if (pageLoaded) {
await Promise.all([refreshMetadata(), refreshStatuses(true)]);
}
}
function hydrate() {
const source = byId('instances-bootstrap');
if (!source) return false;
try {
const payload = JSON.parse(source.textContent || '{}');
if (!Array.isArray(payload?.vms)) return false;
state.vms = payload.vms.map(normalizeVm);
state.pagination = normalizePagination(payload.pagination, 1, state.vms.length);
state.stats = normalizeStats(payload.stats, state.vms);
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
state.user = payload.user && typeof payload.user === 'object' ? payload.user : {};
renderStats();
// Replace the PHP timezone fallback synchronously from the canonical
// timestamps embedded in the bootstrap. This must not wait for a live
// Agent/status request, otherwise a failed refresh leaves panel-time
// values visible to users in other timezones.
renderVms();
renderPagination();
updatePageUrl(state.pagination.page);
return true;
} catch { return false; }
}
function bindEvents() {
byId('refresh-button')?.addEventListener('click', () => {
void loadPage(state.pagination.page, false);
});
byId('search-input')?.addEventListener('input', renderVms);
byId('state-filter')?.addEventListener('change', renderVms);
byId('instances-previous')?.addEventListener('click', () => {
if (!state.loading && !state.statusLoading && state.pagination.has_previous) {
void loadPage(state.pagination.page - 1);
}
});
byId('instances-next')?.addEventListener('click', () => {
if (!state.loading && !state.statusLoading && state.pagination.has_next) {
void loadPage(state.pagination.page + 1);
}
});
byId('vm-table-body')?.addEventListener('click', event => {
const button = event.target.closest?.('[data-copy-value]');
if (!button) return;
void copyText(button.dataset.copyValue || '')
.catch(() => toast(t('instances.error.copy_short'), 'error'));
});
window.addEventListener('pagehide', () => {
state.pageActive = false;
stopPolling();
});
window.addEventListener('pageshow', event => {
state.pageActive = true;
if (event.persisted) void refreshStatuses(true);
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopPolling();
else void refreshStatuses(true);
});
}
export async function initialize() {
const hydrated = hydrate();
bindEvents();
if (!hydrated) await loadPage(1, false);
else {
await Promise.all([refreshMetadata(), refreshStatuses(true)]);
}
}