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.
169 lines
7.9 KiB
JavaScript
169 lines
7.9 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { readFile } from 'node:fs/promises';
|
|
import vm from 'node:vm';
|
|
|
|
// Run the shipped command, job polling, status merging and button rendering.
|
|
// Only browser I/O is replaced so delayed reads cannot be hidden by a mock loader.
|
|
const moduleSource = await readFile(new URL('../public/cloud/runtime.js', import.meta.url), 'utf8');
|
|
const source = moduleSource.replace(/^import[^\n]+\n/u, '')
|
|
.replace(/^export \{[\s\S]*?\};\s*$/mu, '')
|
|
+ '\n;globalThis.__power = { state, selectedVm, renderVmDetail, powerAction, loadVmStatus };\n';
|
|
|
|
class Element {
|
|
constructor() {
|
|
this.children = []; this.textContent = ''; this.hidden = false; this.disabled = false;
|
|
this.dataset = {}; this.attributes = new Map(); this.listeners = new Map();
|
|
this.style = {}; this.classList = { add() {}, remove() {}, toggle() {} };
|
|
}
|
|
append(...children) { this.children.push(...children); }
|
|
replaceChildren(...children) { this.children = children; }
|
|
setAttribute(name, value) { this.attributes.set(name, String(value)); }
|
|
removeAttribute(name) { this.attributes.delete(name); }
|
|
addEventListener(name, callback) { this.listeners.set(name, callback); }
|
|
closest() { return this; }
|
|
}
|
|
|
|
const flush = async () => { for (let turn = 0; turn < 30; turn += 1) await Promise.resolve(); };
|
|
|
|
function fixture() {
|
|
const elements = new Map();
|
|
elements.set('cloud-page-error', new Element());
|
|
const requests = [];
|
|
const notices = [];
|
|
const timers = [];
|
|
const context = {
|
|
document: {
|
|
visibilityState: 'visible', body: { dataset: { vmId: '17' } },
|
|
getElementById(id) {
|
|
if (!elements.has(id)) elements.set(id, new Element());
|
|
return elements.get(id);
|
|
},
|
|
createElement() { return new Element(); },
|
|
querySelectorAll() { return []; },
|
|
addEventListener() {},
|
|
},
|
|
location: { protocol: 'https:', hostname: 'panel.test' },
|
|
Headers, AbortController, URL,
|
|
confirm() { return true; },
|
|
toast(...args) { notices.push(args); },
|
|
setTimeout(callback, delay) { timers.push({ callback, delay }); return timers.length; },
|
|
fetch(path, options = {}) {
|
|
return new Promise((resolve, reject) => requests.push({ path, ...options, resolve, reject, settled: false }));
|
|
},
|
|
};
|
|
vm.runInNewContext(source, context, { filename: 'runtime.js' });
|
|
const runtime = context.__power;
|
|
const machine = { id: '17', api_id: '17', uuid: 'vm-uuid', name: 'test-vm',
|
|
can_operate: true, can_delete: true, state: 'running', state_fresh: true,
|
|
os_source: 'cloud_template' };
|
|
Object.assign(runtime.state, { csrfToken: 'test-csrf', vms: [machine], selectedVmId: machine.uuid, view: 'detail' });
|
|
runtime.renderVmDetail(machine);
|
|
return {
|
|
...runtime, requests, notices, timers, elements,
|
|
button(label) {
|
|
const buttons = ['vm-detail-primary-actions', 'vm-detail-danger-actions']
|
|
.flatMap(id => elements.get(id).children);
|
|
const button = buttons.find(item => item.textContent === label);
|
|
assert.ok(button, `Missing button: ${label}`);
|
|
return button;
|
|
},
|
|
pending(path) {
|
|
const request = requests.find(item => !item.settled && item.path === path);
|
|
assert.ok(request, `Missing request: ${path}`);
|
|
return request;
|
|
},
|
|
async respond(request, payload, status = 200) {
|
|
request.settled = true;
|
|
request.resolve({ status, ok: status >= 200 && status < 300, json: async () => payload });
|
|
await flush();
|
|
},
|
|
};
|
|
}
|
|
|
|
async function accept(h, action, jobId = '41') {
|
|
const promise = h.powerAction(action, action === 'poweroff');
|
|
await h.respond(h.pending('/api/v1/vms/17/actions'), { job_id: jobId, action_label: '电源' });
|
|
return { promise, request: h.pending(`/api/v1/jobs/${jobId}`) };
|
|
}
|
|
|
|
// A request is not a command receipt: keep all power mutations serialized
|
|
// until the existing job has actually confirmed execution.
|
|
{
|
|
const h = fixture();
|
|
const pending = await accept(h, 'shutdown');
|
|
assert.equal(h.button('强制断电').disabled, true);
|
|
await h.powerAction('poweroff', true);
|
|
assert.equal(h.requests.filter(item => item.method === 'POST').length, 1);
|
|
assert.equal(h.notices.some(([, kind]) => kind === 'success'), false);
|
|
await h.respond(pending.request, { status: 'succeeded' });
|
|
await pending.promise;
|
|
assert.equal(h.state.powerMutation, null);
|
|
assert.equal(h.button('强制断电').disabled, false, 'A pending observation must not retain the power lock');
|
|
assert.equal(h.selectedVm().state, 'running', 'The receipt does not invent a stopped state');
|
|
assert.equal(h.timers.length, 0, 'No special shutdown convergence timer remains');
|
|
|
|
const observation = h.pending('/api/v1/vms/17/status?live=1');
|
|
await h.respond(observation, { state: 'running', state_fresh: true });
|
|
assert.equal(h.elements.get('vm-detail-state').textContent, '运行中');
|
|
const forced = await accept(h, 'poweroff', '42');
|
|
assert.equal(h.requests.filter(item => item.method === 'POST').length, 2);
|
|
await h.respond(forced.request, { status: 'succeeded' });
|
|
await forced.promise;
|
|
await h.respond(h.pending('/api/v1/vms/17/status?live=1'), { state: 'shutoff', state_fresh: true });
|
|
assert.equal(h.selectedVm().state, 'shutoff');
|
|
}
|
|
|
|
// A slow observation is invalidated when a newer action starts, even if fetch
|
|
// ignores abort and returns before the new command's post-completion refresh.
|
|
for (const lateError of [false, true]) {
|
|
const h = fixture();
|
|
const shutdown = await accept(h, 'shutdown');
|
|
await h.respond(shutdown.request, { status: 'succeeded' });
|
|
await shutdown.promise;
|
|
const oldRead = h.pending('/api/v1/vms/17/status?live=1');
|
|
const forced = await accept(h, 'poweroff', '42');
|
|
assert.equal(oldRead.signal.aborted, true);
|
|
await h.respond(oldRead, lateError ? { message: 'stale observation error' }
|
|
: { state: 'shutoff', state_fresh: true }, lateError ? 502 : 200);
|
|
assert.equal(h.selectedVm().state, 'running', 'An old observation cannot update the newer command');
|
|
assert.equal(h.elements.get('cloud-page-error').textContent, '');
|
|
assert.equal(h.state.powerMutation.action, 'poweroff');
|
|
await h.respond(forced.request, { status: 'succeeded' });
|
|
await forced.promise;
|
|
await h.respond(h.pending('/api/v1/vms/17/status?live=1'), { state: 'shutoff', state_fresh: true });
|
|
assert.equal(h.selectedVm().state, 'shutoff');
|
|
}
|
|
|
|
// Observation failure remains an observation error after a successful command;
|
|
// it neither changes the receipt nor disables a subsequent force-poweroff.
|
|
{
|
|
const h = fixture();
|
|
const shutdown = await accept(h, 'shutdown');
|
|
await h.respond(shutdown.request, { status: 'succeeded' });
|
|
await shutdown.promise;
|
|
await h.respond(h.pending('/api/v1/vms/17/status?live=1'), { message: '状态暂不可用' }, 502);
|
|
assert.equal(h.button('强制断电').disabled, false);
|
|
assert.equal(h.selectedVm().state, 'running');
|
|
assert.equal(h.notices.filter(([, kind]) => kind === 'success').length, 1);
|
|
assert.equal(h.elements.get('cloud-page-error').textContent, '状态暂不可用');
|
|
}
|
|
|
|
// A genuinely unknown job is never presented as command success or replayed.
|
|
// Existing server-side admission still rejects a later explicit mutation.
|
|
{
|
|
const h = fixture();
|
|
const shutdown = await accept(h, 'shutdown');
|
|
await h.respond(shutdown.request, { status: 'uncertain', error: '命令回执未知,请核对原操作' });
|
|
await shutdown.promise;
|
|
assert.equal(h.notices.some(([, kind]) => kind === 'success'), false);
|
|
assert.equal(h.notices.at(-1)[1], 'error');
|
|
assert.equal(h.requests.filter(item => item.method === 'POST').length, 1);
|
|
const forced = h.powerAction('poweroff', true);
|
|
await h.respond(h.pending('/api/v1/vms/17/actions'), { message: '已有待核对的任务' }, 409);
|
|
await forced;
|
|
assert.equal(h.notices.at(-1)[0], '已有待核对的任务');
|
|
assert.equal(h.requests.filter(item => item.path.startsWith('/api/v1/jobs/')).length, 1);
|
|
}
|
|
|
|
console.log('Cloud power command completion, independent observations and stale response checks passed.');
|