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.
172 lines
12 KiB
JavaScript
172 lines
12 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { readFile } from 'node:fs/promises';
|
|
import vm from 'node:vm';
|
|
|
|
const source = await readFile(new URL('../public/cloud/admin-host-inventory.js', import.meta.url), 'utf8');
|
|
class Node {
|
|
constructor(tag = 'div') {
|
|
this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {}; this.attributes = new Map();
|
|
this.listeners = new Map(); this.hidden = false; this.disabled = false; this.isConnected = true;
|
|
this.open = false; this.value = ''; this._text = ''; this.style = { setProperty() {}, removeProperty() {} };
|
|
const classes = new Set(); this.classList = { add: x => classes.add(x), remove: x => classes.delete(x) };
|
|
}
|
|
set textContent(value) { this._text = String(value); this.children = []; }
|
|
get textContent() { return this._text + this.children.map(item => item.textContent).join(''); }
|
|
set innerHTML(_) { throw new Error('Never interpret diagnostic content as HTML.'); }
|
|
get options() { return this.children; }
|
|
append(...values) { this.children.push(...values); }
|
|
add(option) { this.children.push(option); }
|
|
replaceChildren(...values) { this._text = ''; this.children = values; }
|
|
setAttribute(key, value) { this.attributes.set(key, String(value)); }
|
|
addEventListener(key, handler) { const listeners = this.listeners.get(key) || []; listeners.push(handler); this.listeners.set(key, listeners); }
|
|
dispatch(key, fields = {}) {
|
|
const event = { target: this, button: 0, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...fields };
|
|
for (const listener of this.listeners.get(key) || []) listener(event);
|
|
}
|
|
closest(selector) { return selector === '[data-inventory-detail]' && this.dataset.inventoryDetail ? this : null; }
|
|
focus() {}
|
|
getBoundingClientRect() { return { left: 0, right: 500, top: 0, bottom: 800 }; }
|
|
}
|
|
class Option extends Node { constructor(label, value) { super('option'); this.textContent = label; this.value = String(value); } }
|
|
const flush = async () => { for (let i = 0; i < 20; i += 1) await Promise.resolve(); };
|
|
const firstId = 'a'.repeat(32);
|
|
const secondId = 'b'.repeat(32);
|
|
function attempt(id = firstId, changes = {}) {
|
|
return { attempt_id: id, host_id: 7, host_name: '示例宿主机', source: 'manual', source_label: '管理员手动同步',
|
|
started_at: 1234, finished_at: 1242, duration_ms: 8000, duration_is_final: true,
|
|
outcome: 'timeout', outcome_label: '超时', stage: 'capacity_request', stage_label: '请求容量数据',
|
|
error_code: 'engine_http_timeout', error_message: '超时;引擎阶段未确认', applied: false,
|
|
timeout_ms: 8000, http_status: null, panel_version: 'inventory-v1', php_version: '8.5.0', generation: 1, stages: [], ...changes };
|
|
}
|
|
function page(items = [attempt()], pageNumber = 1) {
|
|
return { items, pagination: { page: pageNumber, per_page: 20, total: 21, total_pages: 2 },
|
|
filters: { host_id: '7', outcome: 'all', page: pageNumber, per_page: 20 },
|
|
hosts: [{ id: '7', name: '示例宿主机' }],
|
|
summary: { last_attempt_at: 1234, last_success_at: 1230, last_failure_at: 1242, in_progress: 0, consecutive_failures: 1 } };
|
|
}
|
|
function fixture(initial = page()) {
|
|
const ids = [...source.matchAll(/byId\('([^']+)'\)/g)].map(match => match[1]);
|
|
ids.push('inventory-previous', 'inventory-next', 'inventory-outcome', 'inventory-per-page', ...['last_attempt_at', 'last_success_at', 'last_failure_at'].map(key => `inventory-summary-${key}`));
|
|
const nodes = Object.fromEntries([...new Set(ids)].map(id => [id, new Node()]));
|
|
nodes['admin-inventory-bootstrap'].textContent = JSON.stringify(initial);
|
|
nodes['inventory-body'].textContent = 'SSR records';
|
|
nodes['inventory-filter'].elements = { namedItem: key => nodes[({ host_id: 'inventory-host', outcome: 'inventory-outcome', per_page: 'inventory-per-page' })[key]] };
|
|
const root = new Node(); const document = new Node(); document.documentElement = new Node(); document.body = new Node();
|
|
document.getElementById = id => nodes[id]; document.createElement = tag => new Node(tag);
|
|
document.querySelector = selector => selector === '[data-admin-host-inventory]' ? root : null;
|
|
const window = new Node(); window.scrollX = 0; window.scrollY = 100; window.scrollTo = () => {};
|
|
window.VenixDrawerMotion = {
|
|
openDrawerWithMotion: dialog => { dialog.open = true; },
|
|
closeDrawerWithMotion: dialog => { dialog.open = false; return Promise.resolve(true); },
|
|
};
|
|
const location = { origin: 'https://example.test', href: 'https://example.test/admin/host-inventory?host_id=7' };
|
|
const history = { state: null, pushState(value, _, url) { this.state = value; location.href = String(url); } };
|
|
let now = 0; let lastTimer = 0; const timers = new Map(); const requests = [];
|
|
const setTimeout = (callback, delay) => { const id = ++lastTimer; timers.set(id, { callback, due: now + delay }); return id; };
|
|
const fetch = (url, options) => new Promise((resolve, reject) => { requests.push({ url, options, resolve, reject, settled: false }); });
|
|
vm.runInNewContext(source, { document, window, location, history, URL, Node, Option, Date, AbortController,
|
|
fetch, setTimeout, clearTimeout: id => timers.delete(id), console }, { filename: 'admin-host-inventory.js' });
|
|
return {
|
|
nodes, root, window, requests, location,
|
|
async click(id) { if (!nodes[id].disabled) nodes[id].dispatch('click'); await flush(); },
|
|
async open(id = firstId) { const button = new Node('button'); button.dataset.inventoryDetail = id; root.dispatch('click', { target: button }); await flush(); },
|
|
async respond(payload, request = requests.find(item => !item.settled), status = 200) {
|
|
assert.ok(request); request.settled = true; request.resolve({ ok: status < 300, status, json: async () => payload }); await flush();
|
|
},
|
|
async advance(ms) {
|
|
const end = now + ms;
|
|
while (true) {
|
|
const next = [...timers.entries()].filter(([, timer]) => timer.due <= end).sort((a, b) => a[1].due - b[1].due)[0];
|
|
if (!next) break;
|
|
now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush();
|
|
}
|
|
now = end; await flush();
|
|
},
|
|
};
|
|
}
|
|
|
|
// SSR and idle pages never trigger requests. Refresh reads only history, and
|
|
// opening a detail does not retrieve engine evidence until the explicit click.
|
|
{
|
|
const test = fixture(); await test.advance(120000);
|
|
assert.equal(test.requests.length, 0, 'The SSR page must not refetch or poll.');
|
|
assert.equal(test.nodes['inventory-body'].textContent, 'SSR records');
|
|
await test.click('inventory-refresh'); assert.equal(test.requests.length, 1);
|
|
assert.match(test.requests[0].url, /^\/api\/v1\/admin\/host-inventory\?host_id=7$/);
|
|
const unsafe = attempt(firstId, { host_name: '<img src=x onerror=alert(1)>', error_message: '<script>bad()</script>' });
|
|
await test.respond(page([unsafe]));
|
|
assert.match(test.nodes['inventory-body'].textContent, /<script>bad\(\)<\/script>/);
|
|
assert.match(test.nodes['inventory-body'].textContent, /容量未更新/);
|
|
await test.open(); assert.equal(test.requests.length, 2);
|
|
await test.respond({ attempt: unsafe, notes: [] }); await test.advance(100000);
|
|
assert.equal(test.requests.length, 2, 'Details must not auto-fetch or poll the engine.');
|
|
assert.match(test.nodes['inventory-detail-body'].textContent, /超时/);
|
|
await test.click('inventory-engine-refresh'); await test.click('inventory-engine-refresh');
|
|
assert.equal(test.requests.length, 3, 'Repeated evidence clicks must share a single read.');
|
|
assert.equal(test.requests[2].url, `/api/v1/admin/host-inventory/${firstId}/engine`);
|
|
await test.respond({ available: true, attempt_id: firstId, traces: [{ resource: 'capacity', state: 'succeeded', stage: 'response',
|
|
started_at: 1234, finished_at: 1245, duration_ms: 11000, error_code: '', http_status: 200, engine_version: 'a'.repeat(40), stages: [] }] });
|
|
assert.match(test.nodes['inventory-engine-body'].textContent, /采集成功/);
|
|
assert.match(test.nodes['inventory-engine-body'].textContent, /父阶段包含子阶段耗时/);
|
|
assert.match(test.nodes['inventory-detail-body'].textContent, /超时/);
|
|
assert.match(test.nodes['inventory-detail-body'].textContent, /容量未更新/, 'Late engine success must not rewrite panel application state.');
|
|
assert.equal(test.requests.every(request => request.options.method === undefined), true, 'Diagnostics only uses GET.');
|
|
}
|
|
|
|
// Late detail/evidence responses cannot populate a different or closed drawer.
|
|
{
|
|
const test = fixture(); await test.open(firstId); const oldDetail = test.requests[0];
|
|
await test.open(secondId); await test.respond({ attempt: attempt(secondId), notes: [] }, test.requests[1]);
|
|
await test.respond({ attempt: attempt(firstId, { host_name: 'obsolete' }), notes: [] }, oldDetail);
|
|
assert.doesNotMatch(test.nodes['inventory-detail-body'].textContent, /obsolete/);
|
|
await test.click('inventory-engine-refresh'); const evidence = test.requests[2];
|
|
await test.click('inventory-detail-close'); assert.equal(evidence.options.signal.aborted, true);
|
|
await test.open(firstId); await test.respond({ attempt: attempt(), notes: [] }, test.requests[3]);
|
|
await test.respond({ available: false, attempt_id: secondId, traces: [], message: 'stale evidence' }, evidence);
|
|
assert.doesNotMatch(test.nodes['inventory-engine-state'].textContent, /stale evidence/);
|
|
}
|
|
|
|
// Empty evidence and failed reads must remain honest, with no implicit rescan.
|
|
{
|
|
const test = fixture(); await test.open(); await test.respond({ attempt: attempt(), notes: [] });
|
|
await test.click('inventory-engine-refresh');
|
|
await test.respond({ available: true, attempt_id: firstId, traces: [] });
|
|
assert.match(test.nodes['inventory-engine-body'].textContent, /不能据此认定宿主机故障/);
|
|
await test.click('inventory-engine-refresh');
|
|
await test.respond({ available: false, attempt_id: firstId, traces: [], error_code: 'engine_connect_failed', message: '诊断存储不可用' });
|
|
assert.match(test.nodes['inventory-engine-state'].textContent, /诊断存储不可用/);
|
|
assert.doesNotMatch(test.nodes['inventory-engine-body'].textContent, /没有对应引擎记录/);
|
|
await test.advance(120000); assert.equal(test.requests.length, 3);
|
|
}
|
|
|
|
// Pagination and browser history requests stay DB-only; older list responses
|
|
// cannot overwrite a newer filter result, even if abort is not honored.
|
|
{
|
|
const test = fixture(); await test.click('inventory-refresh'); const oldList = test.requests[0];
|
|
test.nodes['inventory-filter'].dispatch('submit'); await flush();
|
|
await test.respond(page([attempt(secondId)]), test.requests[1]);
|
|
await test.respond(page([attempt(firstId, { host_name: 'obsolete list' })]), oldList);
|
|
assert.doesNotMatch(test.nodes['inventory-body'].textContent, /obsolete list/);
|
|
await test.click('inventory-next'); assert.match(test.requests[2].url, /page=2/);
|
|
await test.respond(page([attempt(secondId)], 2));
|
|
assert.match(test.nodes['inventory-page-label'].textContent, /第 2 \/ 2 页/);
|
|
assert.equal(test.nodes['inventory-next'].disabled, true);
|
|
test.window.dispatch('popstate'); await flush();
|
|
assert.equal(test.requests[3].url.includes('/engine'), false);
|
|
}
|
|
|
|
// A bounded diagnostic lookup timeout remains an unknown diagnostic read, not
|
|
// a newly failed inventory, and does not retry itself.
|
|
{
|
|
const test = fixture(); await test.open(); await test.respond({ attempt: attempt(), notes: [] });
|
|
await test.click('inventory-engine-refresh'); const request = test.requests[1];
|
|
await test.advance(5000); assert.equal(request.options.signal.aborted, true);
|
|
request.reject(new Error('aborted')); await flush();
|
|
assert.match(test.nodes['inventory-engine-state'].textContent, /读取诊断超时/);
|
|
assert.match(test.nodes['inventory-engine-state'].textContent, /内部阶段尚未确认/);
|
|
assert.match(test.nodes['inventory-detail-body'].textContent, /容量未更新/);
|
|
await test.advance(120000); assert.equal(test.requests.length, 2);
|
|
}
|
|
|
|
console.log('Inventory UI SSR/no-scan, escaping, manual evidence, late-result isolation and pagination passed.');
|