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.
268 lines
11 KiB
JavaScript
268 lines
11 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 state = {
|
|
items: [], page: 1, totalPages: 1, total: 0, loading: false,
|
|
controller: null, promoting: new Set(), promotionKeys: new Map(),
|
|
};
|
|
|
|
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 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('backups.value.date_missing');
|
|
}
|
|
|
|
function formatBytes(value) {
|
|
let amount = Number(value);
|
|
return Number.isFinite(amount) && amount >= 0
|
|
? i18n.bytes(amount) : t('backups.value.pending');
|
|
}
|
|
|
|
function backupState(value) {
|
|
const normalized = String(value || '').toLowerCase();
|
|
const values = {
|
|
ready: ['backups.state.ready', 'running'],
|
|
creating: ['backups.state.creating', 'warning'],
|
|
queued: ['backups.state.queued', 'warning'],
|
|
failed: ['backups.state.failed', 'stopped'],
|
|
uncertain: ['backups.state.uncertain', 'warning'],
|
|
deleting: ['backups.state.deleting', 'warning'],
|
|
delete_uncertain: ['backups.state.delete_uncertain', 'warning'],
|
|
delete_attention: ['backups.state.delete_attention', 'stopped'],
|
|
};
|
|
const [key, className] = values[normalized] || ['backups.state.unknown', 'other'];
|
|
return [t(key), className];
|
|
}
|
|
|
|
function normalizeItems(payload) {
|
|
const values = Array.isArray(payload?.items) ? payload.items
|
|
: Array.isArray(payload?.backups) ? payload.backups : [];
|
|
return values.filter(item => item && typeof item === 'object'
|
|
&& /^[1-9]\d*$/.test(String(item.id ?? item.backup_id ?? '')));
|
|
}
|
|
|
|
function sourceInstance(backup) {
|
|
const source = backup?.source_instance && typeof backup.source_instance === 'object'
|
|
? backup.source_instance
|
|
: backup?.source && typeof backup.source === 'object' ? backup.source : {};
|
|
return {
|
|
id: String(source.id ?? source.instance_id ?? backup.source_instance_id ?? ''),
|
|
name: firstText(source.instance_name, source.name, backup.source_instance_name),
|
|
deleted: source.deleted === true || source.status === 'deleted'
|
|
|| source.status === 'missing' || backup.source_instance_deleted === true,
|
|
};
|
|
}
|
|
|
|
function cloudSnapshot(backup) {
|
|
const value = backup?.cloud_snapshot;
|
|
if (!value || typeof value !== 'object') return null;
|
|
const key = String(value.snapshot_key ?? value.key ?? '');
|
|
return /^[a-f0-9]{32}$/.test(key) ? { ...value, key } : null;
|
|
}
|
|
|
|
function promotionKey(id) {
|
|
const existing = String(state.promotionKeys.get(id) || '');
|
|
if (/^[A-Za-z0-9_.-]{16,128}$/.test(existing)) return existing;
|
|
const key = crypto.randomUUID();
|
|
state.promotionKeys.set(id, key);
|
|
return key;
|
|
}
|
|
|
|
function render() {
|
|
const container = byId('cloud-backups-list');
|
|
container.replaceChildren();
|
|
if (!state.items.length) {
|
|
const empty = makeElement('div', 'cloud-backups-empty');
|
|
empty.append(makeElement('strong', '', t('backups.empty.title')),
|
|
makeElement('span', '', t('backups.empty.body')));
|
|
container.append(empty);
|
|
}
|
|
for (const backup of state.items) {
|
|
const id = String(backup.id ?? backup.backup_id);
|
|
const source = sourceInstance(backup);
|
|
const [stateLabel, stateClass] = backupState(backup.state ?? backup.status);
|
|
const card = makeElement('article', 'cloud-backup-card');
|
|
const heading = makeElement('div', 'cloud-backup-card-heading');
|
|
const title = makeElement('div', 'cloud-backup-title');
|
|
title.append(makeElement('span', 'cloud-backup-icon', '☁'),
|
|
makeElement('div', '', firstText(backup.name,
|
|
t('backups.name.fallback', { id: Number(id) }))));
|
|
title.lastElementChild.append(makeElement('small', '', source.deleted
|
|
? t('backups.source.deleted')
|
|
: source.name
|
|
? t('backups.source.named', { name: source.name })
|
|
: source.id
|
|
? t('backups.source.id', { id: Number(source.id) })
|
|
: t('backups.value.instance_missing')));
|
|
heading.append(title, makeElement('span', `state-pill ${stateClass}`, stateLabel));
|
|
const facts = makeElement('dl', 'cloud-backup-facts');
|
|
const rows = [
|
|
['backups.facts.created', formatDate(backup.ready_at ?? backup.created_at)],
|
|
['backups.facts.consistency', String(backup.consistency || '') === 'filesystem'
|
|
? t('backups.consistency.filesystem') : t('backups.consistency.crash')],
|
|
['backups.facts.object_size', formatBytes(backup.object_size_bytes)],
|
|
['backups.facts.disk_capacity', formatBytes(backup.virtual_size_bytes)],
|
|
];
|
|
for (const [labelKey, value] of rows) {
|
|
const row = document.createElement('div');
|
|
const label = makeElement('dt', '', t(labelKey));
|
|
i18n.bind(label, labelKey);
|
|
row.append(label, makeElement('dd', '', value));
|
|
facts.append(row);
|
|
}
|
|
const actions = makeElement('div', 'cloud-backup-actions');
|
|
if (backup.can_restore_original === true && !source.deleted
|
|
&& /^[1-9]\d*$/.test(source.id)) {
|
|
const restore = makeElement('a', 'button button-outline small', t('backups.action.restore'));
|
|
i18n.bind(restore, 'backups.action.restore');
|
|
restore.href = `/user/cloud/instances/${encodeURIComponent(source.id)}?tab=settings&setting=automatic_backup`;
|
|
actions.append(restore);
|
|
}
|
|
const snapshot = cloudSnapshot(backup);
|
|
if (snapshot) {
|
|
const view = makeElement('a', 'button button-primary small', t('backups.action.view_snapshot'));
|
|
i18n.bind(view, 'backups.action.view_snapshot');
|
|
view.href = `/user/cloud/cloud-snapshots#cloud-snapshot-${encodeURIComponent(snapshot.key)}`;
|
|
actions.append(view);
|
|
} else if (backup.can_promote === true) {
|
|
const promote = makeElement('button', 'button button-primary small',
|
|
state.promoting.has(id) ? t('backups.action.promoting') : t('backups.action.promote'));
|
|
if (!state.promoting.has(id)) i18n.bind(promote, 'backups.action.promote');
|
|
promote.type = 'button';
|
|
promote.disabled = state.loading || state.promoting.has(id);
|
|
promote.addEventListener('click', () => void promoteBackup(backup));
|
|
actions.append(promote);
|
|
}
|
|
card.append(heading, facts, actions);
|
|
container.append(card);
|
|
}
|
|
byId('cloud-backups-count').textContent = t('backups.count', { count: state.total });
|
|
byId('cloud-backups-page').textContent = t('backups.pagination.label', {
|
|
page: state.page, pages: state.totalPages,
|
|
});
|
|
byId('cloud-backups-previous').disabled = state.loading || state.page <= 1;
|
|
byId('cloud-backups-next').disabled = state.loading || state.page >= state.totalPages;
|
|
}
|
|
|
|
async function promoteBackup(backup) {
|
|
const id = String(backup?.id ?? backup?.backup_id ?? '');
|
|
if (!/^[1-9]\d*$/.test(id) || state.loading || state.promoting.has(id)) return;
|
|
state.promoting.add(id);
|
|
render();
|
|
const name = firstText(backup?.name,
|
|
t('backups.snapshot_name.fallback', { id: Number(id) })).slice(0, 64);
|
|
const idempotencyKey = promotionKey(id);
|
|
try {
|
|
await api('/api/v1/cloud-snapshots', {
|
|
method: 'POST',
|
|
body: { backup_id: Number(id), name, idempotency_key: idempotencyKey },
|
|
});
|
|
state.promotionKeys.delete(id);
|
|
toast(t('backups.toast.promote_success.body'), 'success',
|
|
t('backups.toast.promote_success.title'));
|
|
await load(state.page);
|
|
} catch {
|
|
const status = byId('cloud-backups-status');
|
|
status.hidden = false;
|
|
status.className = 'vm-settings-status error';
|
|
status.textContent = t('backups.status.promote_failed');
|
|
} finally {
|
|
state.promoting.delete(id);
|
|
render();
|
|
}
|
|
}
|
|
|
|
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;
|
|
byId('cloud-backups-status').hidden = false;
|
|
byId('cloud-backups-status').className = 'vm-settings-status';
|
|
byId('cloud-backups-status').textContent = t('backups.status.loading');
|
|
render();
|
|
try {
|
|
const payload = await api(`/api/v1/backups?page=${encodeURIComponent(Math.max(1, page))}&per_page=20`, {
|
|
signal: controller.signal,
|
|
});
|
|
if (controller.signal.aborted) return;
|
|
applyPayload(payload);
|
|
byId('cloud-backups-status').hidden = true;
|
|
} catch {
|
|
if (controller.signal.aborted) return;
|
|
byId('cloud-backups-status').className = 'vm-settings-status error';
|
|
byId('cloud-backups-status').textContent = t('backups.status.load_failed');
|
|
} finally {
|
|
if (state.controller === controller) state.controller = null;
|
|
state.loading = false;
|
|
render();
|
|
}
|
|
}
|
|
|
|
export async function initialize() {
|
|
try {
|
|
const bootstrap = readBootstrap('cloud-backups-bootstrap');
|
|
const hasBootstrap = Array.isArray(bootstrap?.items)
|
|
|| Array.isArray(bootstrap?.backups);
|
|
// 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-backups-status').hidden = true;
|
|
}
|
|
if (!await initializeSession('backups', bootstrap?.user)) return;
|
|
if (!hasBootstrap) {
|
|
await load(1);
|
|
}
|
|
byId('cloud-backups-refresh')?.addEventListener('click', () => void load(state.page));
|
|
byId('cloud-backups-previous')?.addEventListener('click', () => void load(state.page - 1));
|
|
byId('cloud-backups-next')?.addEventListener('click', () => void load(state.page + 1));
|
|
window.addEventListener('pagehide', () => state.controller?.abort());
|
|
} catch {
|
|
showError('cloud-page-error', t('backups.status.page_load_failed'));
|
|
}
|
|
}
|