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.
263 lines
10 KiB
JavaScript
263 lines
10 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 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(), 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())
|
|
? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录';
|
|
}
|
|
|
|
function formatBytes(value) {
|
|
let amount = Number(value);
|
|
if (!Number.isFinite(amount) || amount < 0) return '等待完成';
|
|
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
|
let index = 0;
|
|
while (amount >= 1024 && index < units.length - 1) {
|
|
amount /= 1024;
|
|
index += 1;
|
|
}
|
|
const precision = index === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2;
|
|
return `${amount.toFixed(precision)} ${units[index]}`;
|
|
}
|
|
|
|
function snapshotState(value) {
|
|
const normalized = String(value || '').toLowerCase();
|
|
const values = {
|
|
ready: ['可用', 'running'], promoting: ['正在保存', 'warning'],
|
|
deleting: ['正在删除', 'warning'],
|
|
delete_uncertain: ['删除待核对', 'warning'], failed: ['保存失败', 'stopped'],
|
|
};
|
|
return values[normalized] || [normalized || '状态未知', 'other'];
|
|
}
|
|
|
|
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', '', '还没有云快照'),
|
|
element('span', '', '可前往“云备份”将一份可用备份保存为云快照。'));
|
|
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, `云快照 ${key.slice(0, 8)}`)));
|
|
const sourceLabel = source.name || (source.id ? `实例 #${source.id}` : '来源实例未记录');
|
|
title.lastElementChild.append(element('small', '', pendingInvoices > 0
|
|
? `来源:${sourceLabel} · ${pendingInvoices} 张待支付账单`
|
|
: `来源:${sourceLabel}`));
|
|
heading.append(title, element('span', `state-pill ${stateClass}`, stateLabel));
|
|
|
|
const facts = element('dl', 'cloud-backup-facts cloud-snapshot-facts');
|
|
const rows = [
|
|
['保存时间', formatDate(snapshot.ready_at ?? snapshot.created_at)],
|
|
['操作系统', firstText(snapshot.os_name, '系统未记录')],
|
|
['对象大小', formatBytes(snapshot.object_size_bytes)],
|
|
['磁盘容量', formatBytes(snapshot.virtual_size_bytes)],
|
|
];
|
|
for (const [label, value] of rows) {
|
|
const row = document.createElement('div');
|
|
row.append(element('dt', '', 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', '创建实例');
|
|
create.href = `/user/cloud/deploy?cloud_snapshot=${encodeURIComponent(key)}`;
|
|
actions.append(create);
|
|
}
|
|
const remove = element('button', 'button button-outline small danger',
|
|
state.deleting.has(key) ? '正在处理…' : '删除');
|
|
remove.type = 'button';
|
|
remove.disabled = snapshot.can_delete !== true || state.deleting.has(key);
|
|
if (snapshot.can_delete !== true) {
|
|
remove.title = pendingInvoices > 0
|
|
? '存在待支付账单,请先支付或等待账单失效后再删除。'
|
|
: '云快照当前状态不允许删除。';
|
|
}
|
|
remove.addEventListener('click', () => void deleteSnapshot(snapshot));
|
|
actions.append(remove);
|
|
card.append(heading, facts, actions);
|
|
container.append(card);
|
|
}
|
|
byId('cloud-snapshots-count').textContent = `${state.total} 个`;
|
|
byId('cloud-snapshots-page').textContent = `第 ${state.page} / ${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 = '正在读取云快照…';
|
|
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 (error) {
|
|
if (controller.signal.aborted) return;
|
|
status.className = 'vm-settings-status error';
|
|
status.textContent = error?.message || '云快照读取失败,请稍后重试。';
|
|
} 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, `云快照 ${key.slice(0, 8)}`);
|
|
const pendingInvoices = Math.max(0, Number(snapshot?.active_invoice_count) || 0);
|
|
if (pendingInvoices > 0) {
|
|
toast('云快照存在待支付账单,请先支付或等待账单失效。', 'error');
|
|
return;
|
|
}
|
|
const confirmed = await requestUserConfirmation({
|
|
title: '删除云快照',
|
|
message: `确定永久删除“${name}”?删除后不能再用它创建实例,且无法恢复。`,
|
|
confirmText: '删除云快照',
|
|
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('云快照已删除。', 'success');
|
|
} else if (resultState === 'delete_uncertain') {
|
|
toast('删除结果待核对;系统会在两次间隔证据一致后创建新的删除代次。', 'warning');
|
|
} else {
|
|
toast('云快照正在删除,请稍后刷新状态。', 'warning');
|
|
}
|
|
await load(state.page);
|
|
} catch (error) {
|
|
const status = byId('cloud-snapshots-status');
|
|
status.hidden = false;
|
|
status.className = 'vm-settings-status error';
|
|
status.textContent = error?.message || '云快照删除失败,请稍后重试。';
|
|
} finally {
|
|
state.deleting.delete(key);
|
|
render();
|
|
}
|
|
}
|
|
|
|
export async function initialize() {
|
|
try {
|
|
const bootstrap = readBootstrap('cloud-snapshots-bootstrap');
|
|
if (!await initializeSession('cloud-snapshots', bootstrap?.user)) return;
|
|
if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.snapshots)) {
|
|
applyPayload(bootstrap);
|
|
byId('cloud-snapshots-status').hidden = true;
|
|
} else {
|
|
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 (error) {
|
|
showError('cloud-page-error',
|
|
error?.message || '云快照页面加载失败,请刷新后重试。');
|
|
}
|
|
}
|