|
|
const root = document.querySelector('[data-admin-operations]');
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const filterNames = ['q', 'status', 'kind', 'host_id', 'per_page'];
|
|
|
const columns = ['任务', '关联实例', '用户', '宿主机', '状态', '执行与调度', '更新与异常', '操作'];
|
|
|
const state = {
|
|
|
page: null, loadedUrl: null, request: null, serial: 0, loading: false,
|
|
|
active: true, healthRequest: null, healthTimer: null, health: null,
|
|
|
detailRequest: null, detailId: null, detailJob: null, detailClosing: false, opener: null, scroll: null,
|
|
|
cancelRequest: null, cancelingId: null,
|
|
|
};
|
|
|
|
|
|
function el(tag, className = '', content) {
|
|
|
const node = document.createElement(tag);
|
|
|
node.className = className;
|
|
|
if (content !== undefined) node.textContent = String(content);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function text(value, fallback = '未记录') {
|
|
|
return value === null || value === undefined || String(value).trim() === '' ? fallback : String(value);
|
|
|
}
|
|
|
|
|
|
function date(value) {
|
|
|
if (!value || !Number.isFinite(Number(value))) return '时间未记录';
|
|
|
const parsed = new Date(Number(value) * 1000);
|
|
|
if (!Number.isFinite(parsed.getTime())) return '时间未记录';
|
|
|
const pad = number => String(number).padStart(2, '0');
|
|
|
return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}:${pad(parsed.getSeconds())}`;
|
|
|
}
|
|
|
|
|
|
function stack(primary, ...secondary) {
|
|
|
const node = el('span', 'admin-checkout-user');
|
|
|
node.append(primary instanceof Node ? primary : el('strong', '', primary));
|
|
|
for (const value of secondary.filter(Boolean)) node.append(value instanceof Node ? value : el('span', '', value));
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function notice(message, error = false) {
|
|
|
const node = byId('operations-notice');
|
|
|
node.textContent = message;
|
|
|
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`;
|
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
function historyData(changes = {}) {
|
|
|
return { ...(history.state && typeof history.state === 'object' ? history.state : {}), ...changes };
|
|
|
}
|
|
|
|
|
|
async function api(path, controller, timeoutMs = 30000, options = {}) {
|
|
|
const timer = setTimeout(() => controller.abort('timeout'), timeoutMs);
|
|
|
try {
|
|
|
const method = String(options.method || 'GET').toUpperCase();
|
|
|
const headers = { Accept: 'application/json', ...(options.headers || {}) };
|
|
|
const request = { method, headers, credentials: 'same-origin',
|
|
|
cache: 'no-store', signal: controller.signal };
|
|
|
if (!['GET', 'HEAD'].includes(method)) {
|
|
|
if (!window.ADMIN_CSRF_TOKEN) throw new Error('页面安全令牌缺失,请刷新页面后重试。');
|
|
|
headers['X-CSRF-Token'] = window.ADMIN_CSRF_TOKEN;
|
|
|
headers['Content-Type'] = 'application/json';
|
|
|
request.body = options.body === undefined ? '{}' : options.body;
|
|
|
}
|
|
|
const response = await fetch(path, {
|
|
|
...request,
|
|
|
});
|
|
|
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
|
|
|
let payload;
|
|
|
try { payload = await response.json(); }
|
|
|
catch { throw new Error('服务器返回异常,请稍后重试。'); }
|
|
|
if (!response.ok || payload?.ret === 0) {
|
|
|
throw new Error(typeof payload?.detail === 'string' ? payload.detail
|
|
|
: (payload?.message || payload?.error || `请求失败 (${response.status})`));
|
|
|
}
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。');
|
|
|
throw error;
|
|
|
} finally { clearTimeout(timer); }
|
|
|
}
|
|
|
|
|
|
function listUrl(input = new URL(location.href)) {
|
|
|
const url = new URL('/admin/operations', location.origin);
|
|
|
for (const key of [...filterNames, 'page']) {
|
|
|
const value = input.searchParams.get(key);
|
|
|
if (value && !(key === 'status' && value === 'attention') && !(key === 'page' && value === '1')) url.searchParams.set(key, value);
|
|
|
}
|
|
|
return url;
|
|
|
}
|
|
|
|
|
|
function formUrl() {
|
|
|
const url = new URL('/admin/operations', location.origin);
|
|
|
for (const key of filterNames) {
|
|
|
const value = byId('operations-filter').elements.namedItem(key).value.trim();
|
|
|
if (value && !(key === 'status' && value === 'attention')) url.searchParams.set(key, value);
|
|
|
}
|
|
|
return url;
|
|
|
}
|
|
|
|
|
|
function readForm(url) {
|
|
|
const form = byId('operations-filter');
|
|
|
for (const key of filterNames) {
|
|
|
const control = form.elements.namedItem(key);
|
|
|
const value = url.searchParams.get(key) || ({ status: 'attention', per_page: '20' })[key] || '';
|
|
|
if (control instanceof HTMLSelectElement && value && !Array.from(control.options).some(option => option.value === value)) {
|
|
|
control.add(new Option(value, value));
|
|
|
}
|
|
|
control.value = value;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function syncOptions(page) {
|
|
|
const kind = byId('operations-kind');
|
|
|
kind.replaceChildren(new Option('全部类型', ''));
|
|
|
for (const item of page.kinds || []) kind.add(new Option(item.label, item.value));
|
|
|
const host = byId('operations-host');
|
|
|
host.replaceChildren(new Option('全部宿主机', ''));
|
|
|
for (const item of page.hosts || []) host.add(new Option(`${item.name}${item.region ? ` · ${item.region}` : ''}`, item.id));
|
|
|
}
|
|
|
|
|
|
function payloadUrl(page) {
|
|
|
const url = new URL('/admin/operations', location.origin);
|
|
|
for (const key of [...filterNames, 'page']) {
|
|
|
const value = key === 'page' || key === 'per_page' ? page.pagination[key] : page.filters?.[key];
|
|
|
if (value !== null && value !== undefined && value !== '') url.searchParams.set(key, String(value));
|
|
|
}
|
|
|
return listUrl(url);
|
|
|
}
|
|
|
|
|
|
function shownFilters() {
|
|
|
if (!state.page) return '尚未读取任务数据。';
|
|
|
const filters = state.page.filters || {};
|
|
|
const labels = [({ attention: '需要关注', all: '全部状态', queued: '已排队', running: '执行中', uncertain: '待核对', failed: '失败', succeeded: '已完成', cancelled: '已中止' })[filters.status] || filters.status];
|
|
|
if (filters.kind) labels.push((state.page.kinds || []).find(item => item.value === filters.kind)?.label || filters.kind);
|
|
|
if (filters.host_id) labels.push((state.page.hosts || []).find(item => String(item.id) === String(filters.host_id))?.name || `宿主机 #${filters.host_id}`);
|
|
|
if (filters.q) labels.push(`关键词「${filters.q}」`);
|
|
|
return `已显示:${labels.filter(Boolean).join(' · ')} · 第 ${state.page.pagination.page} 页。`;
|
|
|
}
|
|
|
|
|
|
function renderRows() {
|
|
|
const body = byId('operations-body');
|
|
|
body.replaceChildren();
|
|
|
for (const job of state.page.items) {
|
|
|
const tr = el('tr');
|
|
|
tr.dataset.operationId = String(job.id);
|
|
|
const detailButton = el('button', 'btn btn-primary btn-sm', '查看详情');
|
|
|
detailButton.type = 'button'; detailButton.dataset.operationDetail = String(job.id);
|
|
|
detailButton.setAttribute('aria-label', `查看任务 #${job.id} 的详情`);
|
|
|
const actions = el('div', 'd-flex flex-wrap gap-1'); actions.append(detailButton);
|
|
|
if (canCancel(job)) {
|
|
|
const cancelButton = el('button', 'btn btn-outline-danger btn-sm', '中止任务');
|
|
|
cancelButton.type = 'button'; cancelButton.dataset.operationCancel = String(job.id);
|
|
|
cancelButton.setAttribute('aria-label', `中止任务 #${job.id}`);
|
|
|
cancelButton.disabled = state.cancelingId === String(job.id);
|
|
|
actions.append(cancelButton);
|
|
|
}
|
|
|
const status = el('strong', job.status === 'failed' ? 'text-danger' : (job.attention ? 'text-warning' : (job.status === 'succeeded' ? 'text-success' : '')), text(job.display?.status));
|
|
|
const cells = [
|
|
|
stack(`#${job.id} · ${text(job.display?.kind)}`, job.created_at ? `创建 ${date(job.created_at)}` : '创建时间未记录'),
|
|
|
stack(text(job.instance_name, '无关联实例'), job.instance_id ? `实例 #${job.instance_id}` : '', job.order_id ? `订单 #${job.order_id}` : ''),
|
|
|
stack(`操作人:${text(job.actor_name)}${job.actor_id ? ` #${job.actor_id}` : ''}`, job.owner_id ? `所属:${text(job.owner_name)} #${job.owner_id}` : ''),
|
|
|
stack(text(job.host_name), text(job.region, '地区未记录')),
|
|
|
stack(status, job.attention ? el('span', 'text-warning', text(job.display?.attention)) : ''),
|
|
|
stack(`尝试 ${job.attempts} 次`, text(job.display?.lease)),
|
|
|
stack(job.updated_at ? date(job.updated_at) : '更新时间未记录', job.error ? el('span', 'text-danger', job.error) : '未记录错误'),
|
|
|
actions,
|
|
|
];
|
|
|
cells.forEach((content, index) => { const td = el('td'); td.dataset.label = columns[index]; td.append(content); tr.append(td); });
|
|
|
body.append(tr);
|
|
|
}
|
|
|
if (!state.page.items.length) {
|
|
|
const row = el('tr'); const cell = el('td', 'text-center text-muted py-4', '没有符合条件的任务。');
|
|
|
cell.colSpan = columns.length; row.append(cell); body.append(row);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function canCancel(job) {
|
|
|
if (!job || typeof job !== 'object') return false;
|
|
|
if (root?.dataset.canManage !== '1') return false;
|
|
|
if (job.can_cancel !== undefined) return job.can_cancel === true;
|
|
|
const status = String(job.status || '');
|
|
|
if (job.kind === 'action') {
|
|
|
return ['start', 'shutdown', 'reboot', 'poweroff', 'reset'].includes(job.action)
|
|
|
&& status === 'uncertain';
|
|
|
}
|
|
|
return ['snapshot_create', 'snapshot_restore', 'snapshot_delete', 'delete', 'expiry_delete'].includes(job.kind)
|
|
|
&& ['queued', 'running', 'uncertain'].includes(status);
|
|
|
}
|
|
|
|
|
|
function renderPagination() {
|
|
|
const page = state.page?.pagination;
|
|
|
byId('operations-count').textContent = page ? `共 ${page.total} 条` : '数据未获取';
|
|
|
byId('operations-pagination').hidden = !page || !page.total;
|
|
|
byId('operations-page-label').textContent = page ? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 条` : '任务数据暂不可用';
|
|
|
byId('operations-previous').disabled = state.loading || !page || page.page <= 1;
|
|
|
byId('operations-next').disabled = state.loading || !page || page.page >= page.total_pages;
|
|
|
byId('operations-refresh').disabled = state.loading;
|
|
|
byId('operations-body').setAttribute('aria-busy', String(state.loading));
|
|
|
}
|
|
|
|
|
|
function applyPage(page, replaceRows = true) {
|
|
|
if (!Array.isArray(page?.items) || !page.pagination || !page.filters || !page.summary) throw new Error('任务数据格式无效,请重试。');
|
|
|
state.page = page; state.loadedUrl = payloadUrl(page);
|
|
|
syncOptions(page); readForm(state.loadedUrl);
|
|
|
for (const key of ['total', 'failed', 'uncertain', 'delayed']) {
|
|
|
const value = key === 'delayed' ? Number(page.summary.queued_delayed) + Number(page.summary.lease_expired) : page.summary[key];
|
|
|
byId(`operations-summary-${key}`).textContent = value === null || value === undefined || !Number.isFinite(Number(value)) ? '—' : Number(value).toLocaleString('zh-CN');
|
|
|
}
|
|
|
if (replaceRows) renderRows();
|
|
|
byId('operations-shown-filters').textContent = shownFilters();
|
|
|
renderPagination();
|
|
|
}
|
|
|
|
|
|
async function loadPage(input, historyMode = 'push') {
|
|
|
const url = listUrl(input);
|
|
|
state.request?.abort();
|
|
|
const controller = new AbortController(); state.request = controller;
|
|
|
const serial = ++state.serial; state.loading = true;
|
|
|
renderPagination(); notice('正在读取任务记录…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/operations${url.search}`, controller);
|
|
|
if (controller.signal.aborted || serial !== state.serial) return;
|
|
|
applyPage(payload);
|
|
|
if (historyMode === 'push' && state.loadedUrl.href !== location.href) history.pushState(historyData(), '', state.loadedUrl);
|
|
|
notice(`已读取 ${payload.pagination.total} 条任务 · ${date(payload.generated_at)}`);
|
|
|
} catch (error) {
|
|
|
if ((controller.signal.aborted && controller.signal.reason !== 'timeout') || serial !== state.serial) return;
|
|
|
notice(`${error.message}${state.page ? ' 已保留上次读取的任务记录。' : ''}`, true);
|
|
|
byId('operations-shown-filters').textContent = `${state.page ? '刷新未成功,' : ''}${shownFilters()}`;
|
|
|
} finally {
|
|
|
if (serial === state.serial) { state.loading = false; state.request = null; renderPagination(); }
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function healthNotice(message, error = false) {
|
|
|
const node = byId('operations-health-state');
|
|
|
node.textContent = message; node.className = `fs-13 mb-0 ${error ? 'text-danger' : 'text-muted'}`;
|
|
|
}
|
|
|
|
|
|
function renderHealth(payload) {
|
|
|
if (!Array.isArray(payload?.checks) || !payload.checked_at) throw new Error('运行状态数据格式无效。');
|
|
|
const body = byId('operations-health-body'); body.replaceChildren();
|
|
|
const statuses = { ok: ['正常', 'success'], busy: ['运行中', 'primary'], warning: ['需关注', 'warning'], error: ['异常', 'danger'], unknown: ['未知', 'secondary'], disabled: ['未启用', 'secondary'] };
|
|
|
for (const check of payload.checks) {
|
|
|
const [label, tone] = statuses[check.status] || statuses.unknown;
|
|
|
const column = el('div', 'col-md-6 col-xl-4');
|
|
|
const title = el('div', 'd-flex align-items-center gap-2 mb-1');
|
|
|
title.append(el('h3', 'fs-14 fw-semibold mb-0', text(check.label)), el('span', `badge bg-${tone}-subtle text-${tone}-emphasis`, label));
|
|
|
column.append(title, el('p', 'text-muted fs-13 mb-1 text-break', text(check.message)));
|
|
|
if (check.last_seen_at) column.append(el('p', 'text-muted fs-12 mb-0', `最近活动 ${date(check.last_seen_at)}`));
|
|
|
if (check.last_success_at) column.append(el('p', 'text-muted fs-12 mb-0', `最近成功 ${date(check.last_success_at)}`));
|
|
|
if (check.active_count !== undefined && check.active_count !== null) column.append(el('p', 'text-muted fs-12 mb-0', `近期上报 ${check.active_count} 个进程`));
|
|
|
body.append(column);
|
|
|
}
|
|
|
state.health = payload;
|
|
|
healthNotice(`检查于 ${date(payload.checked_at)} · 页面可见时每 30 秒检查;引擎连通不代表宿主机均正常。`);
|
|
|
}
|
|
|
|
|
|
function stopHealth() {
|
|
|
clearTimeout(state.healthTimer); state.healthTimer = null;
|
|
|
state.healthRequest?.abort();
|
|
|
}
|
|
|
|
|
|
function scheduleHealth() {
|
|
|
clearTimeout(state.healthTimer);
|
|
|
if (state.active && !document.hidden) state.healthTimer = setTimeout(refreshHealth, 30000);
|
|
|
}
|
|
|
|
|
|
async function refreshHealth() {
|
|
|
if (!state.active || document.hidden || state.healthRequest) return;
|
|
|
clearTimeout(state.healthTimer);
|
|
|
const controller = new AbortController(); state.healthRequest = controller;
|
|
|
byId('operations-health-refresh').disabled = true;
|
|
|
byId('operations-health-body').setAttribute('aria-busy', 'true');
|
|
|
healthNotice(state.health ? `正在检查;暂显示 ${date(state.health.checked_at)} 的状态。` : '正在检查运行状态…');
|
|
|
try {
|
|
|
const payload = await api('/api/v1/admin/operations/health', controller, 15000);
|
|
|
if (!controller.signal.aborted && state.active) renderHealth(payload);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
healthNotice(`${error.message}${state.health ? ` 保留 ${date(state.health.checked_at)} 的旧状态,当前状态尚未确认。` : ' 当前运行状态未知。'}`, true);
|
|
|
} finally {
|
|
|
if (state.healthRequest === controller) {
|
|
|
state.healthRequest = null; byId('operations-health-refresh').disabled = false;
|
|
|
byId('operations-health-body').setAttribute('aria-busy', 'false'); scheduleHealth();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function safeLink(value, label) {
|
|
|
if (!value) return null;
|
|
|
try {
|
|
|
const url = new URL(value, location.origin);
|
|
|
if (url.origin !== location.origin || !/^https?:$/.test(url.protocol)) return null;
|
|
|
const link = el('a', 'btn btn-light btn-sm', label); link.href = url.pathname + url.search + url.hash;
|
|
|
return link;
|
|
|
} catch { return null; }
|
|
|
}
|
|
|
|
|
|
function infoList(entries) {
|
|
|
const list = el('dl', 'admin-instance-details');
|
|
|
for (const [label, value] of entries) list.append(el('dt', '', label), el('dd', '', text(value)));
|
|
|
return list;
|
|
|
}
|
|
|
|
|
|
function detailNotice(message, error = false) {
|
|
|
const node = byId('operation-detail-state');
|
|
|
node.textContent = message; node.hidden = !message; node.className = `alert alert-${error ? 'danger' : 'info'}`;
|
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
function renderDetail(payload) {
|
|
|
const job = payload?.job;
|
|
|
if (!job || String(job.id) !== state.detailId) throw new Error('任务详情与请求不一致,请重新打开。');
|
|
|
state.detailJob = job;
|
|
|
byId('operation-detail-title').textContent = `#${job.id} · ${text(job.display?.kind)}`;
|
|
|
const body = byId('operation-detail-body');
|
|
|
body.replaceChildren(infoList([
|
|
|
['任务状态', text(job.display?.status)], ['关注原因', text(job.display?.attention, '当前无异常标记')],
|
|
|
['操作标识', job.operation_id], ['处理阶段', job.phase], ['尝试次数', job.attempts],
|
|
|
['操作人', `${text(job.actor_name)}${job.actor_id ? ` #${job.actor_id}` : ''}`],
|
|
|
['实例所属用户', job.owner_id ? `${text(job.owner_name)} #${job.owner_id}` : '未关联或无法确认'],
|
|
|
['宿主机', `${text(job.host_name)}${job.host_id ? ` #${job.host_id}` : ''}`], ['地区', job.region],
|
|
|
['关联实例', job.instance_id ? `${text(job.instance_name)} #${job.instance_id}` : '无关联实例'],
|
|
|
['实例 UUID', job.instance_uuid], ['实例记录状态', ({ active: '在管', creating: '创建中', deleting: '删除中', deleted: '已删除', failed: '失败', reinstalling: '重装中' })[job.instance_status] || job.instance_status], ['关联订单', job.order_id ? `#${job.order_id}` : '无关联订单'],
|
|
|
['创建时间', date(job.created_at)], ['更新时间', date(job.updated_at)],
|
|
|
['首次派发时间', date(job.dispatched_at)], ['最早可调度时间', date(job.available_at)],
|
|
|
['执行租约', text(job.display?.lease)], ['租约截止时间', date(job.lease_until)],
|
|
|
]));
|
|
|
body.append(el('h3', 'h6 mt-4', '错误摘要'), el('p', job.error ? 'text-danger text-break' : 'text-muted', text(job.error, '未记录错误')));
|
|
|
for (const note of payload.notes || []) body.append(el('p', 'text-muted fs-13 mt-3 mb-0', note));
|
|
|
const links = byId('operation-detail-links'); links.replaceChildren();
|
|
|
const cancelButton = byId('operation-detail-cancel');
|
|
|
cancelButton.hidden = !canCancel(job);
|
|
|
cancelButton.disabled = state.cancelingId === String(job.id);
|
|
|
cancelButton.textContent = state.cancelingId === String(job.id) ? '正在中止…' : '中止任务';
|
|
|
for (const [key, label] of [['instance', '查看实例'], ['billing', '按订单号查账']]) {
|
|
|
const link = safeLink(job.links?.[key], label); if (link) links.append(link);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function cancelOperation(id, sourceButton = null) {
|
|
|
if (!/^[1-9][0-9]*$/.test(String(id)) || state.cancelRequest) return;
|
|
|
const job = state.detailId === String(id)
|
|
|
? state.detailJob
|
|
|
: state.page?.items?.find(item => String(item.id) === String(id));
|
|
|
if (job && !canCancel(job)) {
|
|
|
notice('任务当前不可中止,请先刷新任务状态。', true);
|
|
|
if (state.detailId === String(id)) detailNotice('任务当前不可中止,请先刷新任务状态。', true);
|
|
|
return;
|
|
|
}
|
|
|
if (!window.confirm('确认中止这个后台任务?\n\n这只会停止后续领取与重试,不会回滚已经发出的宿主机操作;完成后请核对实例实际状态。')) return;
|
|
|
const controller = new AbortController(); state.cancelRequest = controller;
|
|
|
state.cancelingId = String(id);
|
|
|
if (sourceButton) { sourceButton.disabled = true; sourceButton.textContent = '正在中止…'; }
|
|
|
if (state.detailId === String(id)) {
|
|
|
const detailButton = byId('operation-detail-cancel');
|
|
|
detailButton.hidden = false; detailButton.disabled = true; detailButton.textContent = '正在中止…';
|
|
|
detailNotice('正在中止任务…');
|
|
|
}
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/cancel`, controller, 30000, {
|
|
|
method: 'POST', body: '{}',
|
|
|
});
|
|
|
if (String(payload?.job?.id) !== String(id) || payload?.job?.status !== 'cancelled') {
|
|
|
throw new Error('中止结果未确认,请刷新任务详情核对。');
|
|
|
}
|
|
|
if (state.detailId === String(id) && byId('operation-detail').open) renderDetail(payload);
|
|
|
await loadPage(listUrl(), 'none');
|
|
|
if (state.detailId === String(id) && byId('operation-detail').open) {
|
|
|
await openDetail(String(id), state.opener);
|
|
|
}
|
|
|
notice(`任务 #${id} 已中止,后续不会再领取或重试。`);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
notice(`中止任务失败:${error.message}`, true);
|
|
|
if (state.detailId === String(id)) detailNotice(`中止任务失败:${error.message}`, true);
|
|
|
} finally {
|
|
|
if (state.cancelRequest === controller) {
|
|
|
state.cancelRequest = null; state.cancelingId = null;
|
|
|
if (state.page) renderRows();
|
|
|
if (state.detailId === String(id) && state.detailRequest === null && byId('operation-detail').open) {
|
|
|
const detailButton = byId('operation-detail-cancel');
|
|
|
detailButton.hidden = !canCancel(state.detailJob);
|
|
|
detailButton.disabled = false; detailButton.textContent = '中止任务';
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function finishDetailClose(id) {
|
|
|
state.detailClosing = false;
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
if (state.scroll) { window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' }); state.scroll = null; }
|
|
|
const opener = state.opener?.isConnected ? state.opener : (id ? root.querySelector(`[data-operation-detail="${id}"]`) : null);
|
|
|
opener?.focus({ preventScroll: true }); state.opener = null;
|
|
|
if (history.state?.operationsDetailScroll) history.replaceState(historyData({ operationsDetailScroll: undefined }), '', location.href);
|
|
|
}
|
|
|
|
|
|
function closeDetail() {
|
|
|
if (state.detailClosing) return;
|
|
|
const id = state.detailId;
|
|
|
state.detailRequest?.abort(); state.detailRequest = null; state.detailId = null; state.detailJob = null;
|
|
|
state.detailClosing = true;
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(byId('operation-detail')).then(closed => {
|
|
|
if (closed) finishDetailClose(id);
|
|
|
else state.detailClosing = false;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function openDetail(id, opener) {
|
|
|
if (!/^[1-9][0-9]*$/.test(id) || state.detailClosing) return;
|
|
|
state.detailRequest?.abort(); state.detailId = id; state.detailJob = null; state.opener = opener;
|
|
|
const controller = new AbortController(); state.detailRequest = controller;
|
|
|
byId('operation-detail-title').textContent = `任务 #${id}`;
|
|
|
byId('operation-detail-body').replaceChildren(); byId('operation-detail-links').replaceChildren();
|
|
|
byId('operation-detail-cancel').hidden = true;
|
|
|
detailNotice('正在读取任务详情…');
|
|
|
if (!byId('operation-detail').open) {
|
|
|
state.scroll = { x: window.scrollX, y: window.scrollY };
|
|
|
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.scroll.y}px`);
|
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
|
window.VenixDrawerMotion.openDrawerWithMotion(byId('operation-detail'));
|
|
|
}
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/operations/jobs/${id}`, controller);
|
|
|
if (controller.signal.aborted || state.detailId !== id) return;
|
|
|
renderDetail(payload); detailNotice('');
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (state.detailId === id) detailNotice(`${error.message} 请关闭后重试。`, true);
|
|
|
} finally { if (state.detailRequest === controller) state.detailRequest = null; }
|
|
|
}
|
|
|
|
|
|
if (root) {
|
|
|
try {
|
|
|
const payload = JSON.parse(byId('admin-operations-bootstrap').textContent);
|
|
|
if (payload) applyPage(payload, false); else readForm(listUrl());
|
|
|
} catch { notice('初始任务数据无效,请点击刷新重试。', true); readForm(listUrl()); }
|
|
|
byId('operations-filter').addEventListener('submit', event => { event.preventDefault(); void loadPage(formUrl()); });
|
|
|
byId('operations-reset').addEventListener('click', event => {
|
|
|
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
|
|
event.preventDefault(); readForm(new URL('/admin/operations', location.origin)); void loadPage(new URL('/admin/operations', location.origin));
|
|
|
});
|
|
|
byId('operations-refresh').addEventListener('click', () => { void loadPage(listUrl(), 'none'); });
|
|
|
for (const [id, delta] of [['operations-previous', -1], ['operations-next', 1]]) byId(id).addEventListener('click', () => {
|
|
|
if (!state.page) return;
|
|
|
const url = new URL(state.loadedUrl); url.searchParams.set('page', state.page.pagination.page + delta); void loadPage(url);
|
|
|
});
|
|
|
root.addEventListener('click', event => {
|
|
|
const cancelButton = event.target.closest('[data-operation-cancel]');
|
|
|
if (cancelButton) {
|
|
|
event.preventDefault();
|
|
|
void cancelOperation(cancelButton.dataset.operationCancel, cancelButton);
|
|
|
return;
|
|
|
}
|
|
|
const button = event.target.closest('[data-operation-detail]');
|
|
|
if (button) void openDetail(button.dataset.operationDetail, button);
|
|
|
});
|
|
|
byId('operations-health-refresh').addEventListener('click', () => { void refreshHealth(); });
|
|
|
const dialog = byId('operation-detail');
|
|
|
byId('operation-detail-close').addEventListener('click', closeDetail);
|
|
|
byId('operation-detail-cancel').addEventListener('click', event => {
|
|
|
event.preventDefault();
|
|
|
if (state.detailId) void cancelOperation(state.detailId, event.currentTarget);
|
|
|
});
|
|
|
dialog.addEventListener('cancel', event => { event.preventDefault(); closeDetail(); });
|
|
|
dialog.addEventListener('click', event => {
|
|
|
if (event.target === dialog) {
|
|
|
const rect = dialog.getBoundingClientRect();
|
|
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closeDetail();
|
|
|
}
|
|
|
const link = event.target.closest('a[href]');
|
|
|
if (link && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey && !event.defaultPrevented) closeDetail();
|
|
|
});
|
|
|
// Native showModal confines keyboard focus; the separate body lock covers mobile scrolling.
|
|
|
window.addEventListener('popstate', () => { closeDetail(); readForm(listUrl()); void loadPage(listUrl(), 'none'); });
|
|
|
document.addEventListener('visibilitychange', () => { if (document.hidden) stopHealth(); else void refreshHealth(); });
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
state.active = false; stopHealth(); state.request?.abort(); state.detailRequest?.abort(); state.cancelRequest?.abort();
|
|
|
if (state.scroll) history.replaceState(historyData({ operationsDetailScroll: state.scroll }), '', location.href);
|
|
|
});
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
state.active = true;
|
|
|
if (event.persisted) { closeDetail(); void refreshHealth(); }
|
|
|
});
|
|
|
const stored = history.state?.operationsDetailScroll;
|
|
|
if (stored && Number.isFinite(stored.y) && Number.isFinite(stored.x)) {
|
|
|
requestAnimationFrame(() => { window.scrollTo({ left: stored.x, top: stored.y, behavior: 'instant' }); history.replaceState(historyData({ operationsDetailScroll: undefined }), '', location.href); });
|
|
|
}
|
|
|
renderPagination(); void refreshHealth();
|
|
|
}
|