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.
298 lines
12 KiB
JavaScript
298 lines
12 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 {
|
|
api, byId, initializeSession, readBootstrap, showError, toast,
|
|
} = await import(versionedModuleUrl('./runtime.js'));
|
|
const i18n = globalThis.VenixUserCopy;
|
|
const t = (key, parameters = {}) => i18n.text(key, parameters);
|
|
|
|
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options)
|
|
?? Promise.resolve(false);
|
|
|
|
const state = {
|
|
items: [], page: 1, totalPages: 1, total: 0, loading: false,
|
|
controller: null, deleting: new Set(), deleteUncertain: new Set(),
|
|
hashFocused: false,
|
|
};
|
|
|
|
function element(tag, className = '', content) {
|
|
const value = document.createElement(tag);
|
|
if (className) value.className = className;
|
|
if (content !== undefined) value.textContent = String(content);
|
|
return value;
|
|
}
|
|
|
|
function firstText(...values) {
|
|
for (const value of values) {
|
|
if (value !== null && value !== undefined && String(value).trim() !== '') {
|
|
return String(value).trim();
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function formatDate(value) {
|
|
const raw = Number(value);
|
|
const timestamp = Number.isFinite(raw) && raw > 0
|
|
? (raw < 1e12 ? raw * 1000 : raw) : Date.parse(String(value || ''));
|
|
const date = new Date(timestamp);
|
|
return Number.isFinite(date.getTime())
|
|
? i18n.date(timestamp) : t('snapshots.value.date_missing');
|
|
}
|
|
|
|
function formatBytes(value) {
|
|
let amount = Number(value);
|
|
return Number.isFinite(amount) && amount >= 0
|
|
? i18n.bytes(amount) : t('snapshots.value.pending');
|
|
}
|
|
|
|
function snapshotState(value) {
|
|
const normalized = String(value || '').toLowerCase();
|
|
const values = {
|
|
ready: ['snapshots.state.ready', 'running'],
|
|
promoting: ['snapshots.state.promoting', 'warning'],
|
|
deleting: ['snapshots.state.deleting', 'warning'],
|
|
delete_uncertain: ['snapshots.state.delete_uncertain', 'warning'],
|
|
failed: ['snapshots.state.failed', 'stopped'],
|
|
};
|
|
const [key, className] = values[normalized] || ['snapshots.state.unknown', 'other'];
|
|
return [t(key), className];
|
|
}
|
|
|
|
function normalizeItems(payload) {
|
|
const values = Array.isArray(payload?.items) ? payload.items
|
|
: Array.isArray(payload?.snapshots) ? payload.snapshots : [];
|
|
return values.filter(item => item && typeof item === 'object'
|
|
&& /^[a-f0-9]{32}$/.test(String(item.snapshot_key ?? item.key ?? '')));
|
|
}
|
|
|
|
function sourceInstance(snapshot) {
|
|
const source = snapshot?.source_instance && typeof snapshot.source_instance === 'object'
|
|
? snapshot.source_instance : {};
|
|
return {
|
|
id: String(source.id ?? source.instance_id ?? snapshot.source_instance_id ?? ''),
|
|
name: firstText(source.name, source.instance_name, snapshot.source_instance_name),
|
|
};
|
|
}
|
|
|
|
function render() {
|
|
const container = byId('cloud-snapshots-list');
|
|
container.replaceChildren();
|
|
if (!state.items.length) {
|
|
const empty = element('div', 'cloud-backups-empty cloud-snapshots-empty');
|
|
empty.append(element('strong', '', t('snapshots.empty.title')),
|
|
element('span', '', t('snapshots.empty.body')));
|
|
container.append(empty);
|
|
}
|
|
for (const snapshot of state.items) {
|
|
const key = String(snapshot.snapshot_key ?? snapshot.key);
|
|
const source = sourceInstance(snapshot);
|
|
const [stateLabel, stateClass] = snapshotState(snapshot.state ?? snapshot.status);
|
|
const card = element('article', 'cloud-backup-card cloud-snapshot-card');
|
|
card.id = `cloud-snapshot-${key}`;
|
|
const heading = element('div', 'cloud-backup-card-heading');
|
|
const title = element('div', 'cloud-backup-title');
|
|
const pendingInvoices = Math.max(0, Number(snapshot.active_invoice_count) || 0);
|
|
title.append(element('span', 'cloud-backup-icon cloud-snapshot-icon', '◆'),
|
|
element('div', '', firstText(snapshot.name,
|
|
t('snapshots.name.fallback', { id: key.slice(0, 8) }))));
|
|
const sourceLabel = source.name
|
|
? t('snapshots.source.named', { name: source.name })
|
|
: source.id
|
|
? t('snapshots.source.id', { id: Number(source.id) })
|
|
: t('snapshots.value.source_missing');
|
|
title.lastElementChild.append(element('small', '', pendingInvoices > 0
|
|
? t('snapshots.source.with_invoices', { source: sourceLabel, count: pendingInvoices })
|
|
: sourceLabel));
|
|
heading.append(title, element('span', `state-pill ${stateClass}`, stateLabel));
|
|
|
|
const facts = element('dl', 'cloud-backup-facts cloud-snapshot-facts');
|
|
const rows = [
|
|
['snapshots.facts.saved', formatDate(snapshot.ready_at ?? snapshot.created_at)],
|
|
['snapshots.facts.os', firstText(snapshot.os_name, t('snapshots.value.os_missing'))],
|
|
['snapshots.facts.object_size', formatBytes(snapshot.object_size_bytes)],
|
|
['snapshots.facts.disk_capacity', formatBytes(snapshot.virtual_size_bytes)],
|
|
];
|
|
for (const [labelKey, value] of rows) {
|
|
const row = document.createElement('div');
|
|
const label = element('dt', '', t(labelKey));
|
|
i18n.bind(label, labelKey);
|
|
row.append(label, element('dd', '', value));
|
|
facts.append(row);
|
|
}
|
|
|
|
const actions = element('div', 'cloud-backup-actions cloud-snapshot-actions');
|
|
if (snapshot.can_create_instance === true) {
|
|
const create = element('a', 'button button-primary small', t('snapshots.action.create'));
|
|
i18n.bind(create, 'snapshots.action.create');
|
|
create.href = `/user/cloud/deploy?cloud_snapshot=${encodeURIComponent(key)}`;
|
|
actions.append(create);
|
|
}
|
|
const deleteUnknown = state.deleteUncertain.has(key);
|
|
const remove = element('button', 'button button-outline small danger',
|
|
deleteUnknown ? t('snapshots.action.pending_review')
|
|
: state.deleting.has(key) ? t('snapshots.action.deleting')
|
|
: t('snapshots.action.delete'));
|
|
remove.type = 'button';
|
|
if (!deleteUnknown && !state.deleting.has(key)) {
|
|
i18n.bind(remove, 'snapshots.action.delete');
|
|
}
|
|
remove.disabled = snapshot.can_delete !== true || state.deleting.has(key)
|
|
|| deleteUnknown;
|
|
if (deleteUnknown) {
|
|
remove.title = t('snapshots.delete_disabled.uncertain');
|
|
} else if (snapshot.can_delete !== true) {
|
|
remove.title = pendingInvoices > 0
|
|
? t('snapshots.delete_disabled.pending_invoice')
|
|
: t('snapshots.delete_disabled.state');
|
|
}
|
|
remove.addEventListener('click', () => void deleteSnapshot(snapshot));
|
|
actions.append(remove);
|
|
card.append(heading, facts, actions);
|
|
container.append(card);
|
|
}
|
|
byId('cloud-snapshots-count').textContent = t('snapshots.count', { count: state.total });
|
|
byId('cloud-snapshots-page').textContent = t('snapshots.pagination.label', {
|
|
page: state.page, pages: state.totalPages,
|
|
});
|
|
byId('cloud-snapshots-previous').disabled = state.loading || state.page <= 1;
|
|
byId('cloud-snapshots-next').disabled = state.loading || state.page >= state.totalPages;
|
|
if (!state.hashFocused && location.hash.startsWith('#cloud-snapshot-')) {
|
|
state.hashFocused = true;
|
|
requestAnimationFrame(() => document.getElementById(location.hash.slice(1))
|
|
?.scrollIntoView({ block: 'center' }));
|
|
}
|
|
}
|
|
|
|
function applyPayload(payload) {
|
|
state.items = normalizeItems(payload);
|
|
const pagination = payload?.pagination && typeof payload.pagination === 'object'
|
|
? payload.pagination : {};
|
|
state.page = Math.max(1, Number(pagination.page ?? payload?.page) || 1);
|
|
state.totalPages = Math.max(1,
|
|
Number(pagination.total_pages ?? payload?.total_pages) || 1);
|
|
state.total = Math.max(0,
|
|
Number(pagination.total ?? payload?.total) || state.items.length);
|
|
render();
|
|
}
|
|
|
|
async function load(page = 1) {
|
|
if (state.loading) return;
|
|
state.loading = true;
|
|
state.controller?.abort();
|
|
const controller = new AbortController();
|
|
state.controller = controller;
|
|
const status = byId('cloud-snapshots-status');
|
|
status.hidden = false;
|
|
status.className = 'vm-settings-status';
|
|
status.textContent = t('snapshots.status.loading');
|
|
render();
|
|
try {
|
|
const payload = await api(`/api/v1/cloud-snapshots?page=${encodeURIComponent(Math.max(1, page))}&per_page=20`, {
|
|
signal: controller.signal,
|
|
});
|
|
if (controller.signal.aborted) return;
|
|
applyPayload(payload);
|
|
status.hidden = true;
|
|
} catch {
|
|
if (controller.signal.aborted) return;
|
|
status.className = 'vm-settings-status error';
|
|
status.textContent = t('snapshots.status.load_failed');
|
|
} finally {
|
|
if (state.controller === controller) state.controller = null;
|
|
state.loading = false;
|
|
render();
|
|
}
|
|
}
|
|
|
|
async function deleteSnapshot(snapshot) {
|
|
const key = String(snapshot?.snapshot_key ?? snapshot?.key ?? '');
|
|
if (!/^[a-f0-9]{32}$/.test(key) || state.deleting.has(key)) return;
|
|
const name = firstText(snapshot?.name,
|
|
t('snapshots.name.fallback', { id: key.slice(0, 8) }));
|
|
const pendingInvoices = Math.max(0, Number(snapshot?.active_invoice_count) || 0);
|
|
if (pendingInvoices > 0) {
|
|
toast(t('snapshots.toast.pending_invoice.body'), 'error',
|
|
t('snapshots.toast.pending_invoice.title'));
|
|
return;
|
|
}
|
|
const confirmed = await requestUserConfirmation({
|
|
title: t('snapshots.confirm.delete.title'),
|
|
message: t('snapshots.confirm.delete.body', { name }),
|
|
confirmText: t('snapshots.confirm.delete.button'),
|
|
tone: 'danger',
|
|
});
|
|
if (!confirmed) return;
|
|
state.deleting.add(key);
|
|
render();
|
|
try {
|
|
const payload = await api(`/api/v1/cloud-snapshots/${encodeURIComponent(key)}`, {
|
|
method: 'DELETE',
|
|
expectedStatus: 200,
|
|
headers: { 'Idempotency-Key': crypto.randomUUID() },
|
|
});
|
|
const resultState = String(payload?.snapshot?.state || '').toLowerCase();
|
|
if (resultState === 'deleted') {
|
|
toast(t('snapshots.toast.deleted.body'), 'success',
|
|
t('snapshots.toast.deleted.title'));
|
|
} else if (resultState === 'delete_uncertain') {
|
|
toast(t('snapshots.toast.delete_uncertain.body'), 'warning',
|
|
t('snapshots.toast.delete_uncertain.title'));
|
|
} else {
|
|
toast(t('snapshots.toast.deleting.body'), 'warning',
|
|
t('snapshots.toast.deleting.title'));
|
|
}
|
|
await load(state.page);
|
|
} catch (error) {
|
|
const status = byId('cloud-snapshots-status');
|
|
status.hidden = false;
|
|
status.className = 'vm-settings-status error';
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
state.deleteUncertain.add(key);
|
|
status.textContent = t('snapshots.status.delete_unknown');
|
|
toast(t('snapshots.toast.delete_uncertain.body'), 'warning',
|
|
t('snapshots.toast.delete_uncertain.title'));
|
|
} else {
|
|
status.textContent = t('snapshots.status.delete_failed');
|
|
}
|
|
} finally {
|
|
state.deleting.delete(key);
|
|
render();
|
|
}
|
|
}
|
|
|
|
export async function initialize() {
|
|
try {
|
|
const bootstrap = readBootstrap('cloud-snapshots-bootstrap');
|
|
const hasBootstrap = Array.isArray(bootstrap?.items)
|
|
|| Array.isArray(bootstrap?.snapshots);
|
|
// Do not leave the panel-time SSR fallback visible while session
|
|
// confirmation is pending or unavailable; the page bootstrap already
|
|
// carries canonical owner-scoped timestamps.
|
|
if (hasBootstrap) {
|
|
applyPayload(bootstrap);
|
|
byId('cloud-snapshots-status').hidden = true;
|
|
}
|
|
if (!await initializeSession('cloud-snapshots', bootstrap?.user)) return;
|
|
if (!hasBootstrap) {
|
|
await load(1);
|
|
}
|
|
byId('cloud-snapshots-refresh')?.addEventListener('click',
|
|
() => void load(state.page));
|
|
byId('cloud-snapshots-previous')?.addEventListener('click',
|
|
() => void load(state.page - 1));
|
|
byId('cloud-snapshots-next')?.addEventListener('click',
|
|
() => void load(state.page + 1));
|
|
window.addEventListener('pagehide', () => state.controller?.abort());
|
|
} catch {
|
|
showError('cloud-page-error', t('snapshots.status.page_load_failed'));
|
|
}
|
|
}
|