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.
245 lines
10 KiB
JavaScript
245 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 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())
|
|
? 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 backupState(value) {
|
|
const normalized = String(value || '').toLowerCase();
|
|
const values = {
|
|
ready: ['可用', 'running'], creating: ['正在备份', 'warning'], queued: ['等待备份', 'warning'],
|
|
failed: ['备份失败', 'stopped'], uncertain: ['等待核对', 'warning'], deleting: ['正在删除', 'warning'],
|
|
delete_uncertain: ['删除待核对', 'warning'], delete_attention: ['清理需人工处理', 'stopped'],
|
|
};
|
|
return values[normalized] || [normalized || '状态未知', 'other'];
|
|
}
|
|
|
|
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', '', '还没有云备份'),
|
|
makeElement('span', '', '购买自动备份后,可在实例详情中设置备份计划。'));
|
|
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, `云备份 #${id}`)));
|
|
title.lastElementChild.append(makeElement('small', '', source.deleted
|
|
? '源实例已删除' : `来源:${source.name || (source.id ? `实例 #${source.id}` : '实例未记录')}`));
|
|
heading.append(title, makeElement('span', `state-pill ${stateClass}`, stateLabel));
|
|
const facts = makeElement('dl', 'cloud-backup-facts');
|
|
const rows = [
|
|
['创建时间', formatDate(backup.ready_at ?? backup.created_at)],
|
|
['一致性', String(backup.consistency || '') === 'filesystem' ? '文件系统一致' : '崩溃一致'],
|
|
['对象大小', formatBytes(backup.object_size_bytes)],
|
|
['磁盘容量', formatBytes(backup.virtual_size_bytes)],
|
|
];
|
|
for (const [label, value] of rows) {
|
|
const row = document.createElement('div');
|
|
row.append(makeElement('dt', '', 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', '恢复原实例');
|
|
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', '查看云快照');
|
|
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) ? '正在保存…' : '保存为云快照');
|
|
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 = `${state.total} 个`;
|
|
byId('cloud-backups-page').textContent = `第 ${state.page} / ${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, `云快照 #${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('云快照已保存,可前往“云快照”创建新实例。', 'success');
|
|
await load(state.page);
|
|
} catch (error) {
|
|
const status = byId('cloud-backups-status');
|
|
status.hidden = false;
|
|
status.className = 'vm-settings-status error';
|
|
status.textContent = error?.message || '保存云快照失败,请稍后重试。';
|
|
} 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 = '正在读取云备份…';
|
|
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 (error) {
|
|
if (controller.signal.aborted) return;
|
|
byId('cloud-backups-status').className = 'vm-settings-status error';
|
|
byId('cloud-backups-status').textContent = error?.message || '云备份读取失败,请稍后重试。';
|
|
} finally {
|
|
if (state.controller === controller) state.controller = null;
|
|
state.loading = false;
|
|
render();
|
|
}
|
|
}
|
|
|
|
export async function initialize() {
|
|
try {
|
|
const bootstrap = readBootstrap('cloud-backups-bootstrap');
|
|
if (!await initializeSession('backups', bootstrap?.user)) return;
|
|
if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.backups)) {
|
|
applyPayload(bootstrap);
|
|
byId('cloud-backups-status').hidden = true;
|
|
} else {
|
|
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 (error) {
|
|
showError('cloud-page-error', error?.message || '云备份页面加载失败,请刷新后重试。');
|
|
}
|
|
}
|