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.
virt/web/tests/CloudVpcMemberChoicesTest.mjs

532 lines
23 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const moduleSource = await readFile(new URL('../public/cloud/vpc.js', import.meta.url), 'utf8');
// Execute the shipped candidate and request code, without duplicating its rules.
// Only the unrelated full detail layout is replaced with an observation hook;
// list rendering, candidate rendering, requests and state transitions stay real.
const source = moduleSource
.replace(/^import[^\n]+\n/u, '')
.replace('export async function initialize()', 'async function initialize()')
+ `\n;globalThis.__memberChoices = {
state, memberChoice, populateMemberChoices, refreshMemberChoices,
submitMember, removeMember, refreshBootstrap, mutate, selectVpc, createVpc,
hasMemberCleanup, reconcile, renderList,
observeDetailRender(callback) { renderDetail = callback; },
};\n`;
class Node {
constructor() {
this.children = [];
this.dataset = {};
this.attributes = new Map();
this.value = '';
this.textContent = '';
this.disabled = false;
this.hidden = false;
this.isConnected = true;
this.classList = { add() {}, remove() {} };
}
get options() { return this.children; }
append(...nodes) { this.children.push(...nodes); }
replaceChildren(...nodes) { this.children = nodes; }
setAttribute(name, value) { this.attributes.set(name, value); }
removeAttribute(name) { this.attributes.delete(name); }
querySelector() { return null; }
querySelectorAll() { return []; }
reset() {}
focus() {}
}
class OptionNode extends Node {
constructor(label, value, defaultSelected = false, selected = false) {
super();
Object.assign(this, { textContent: String(label), value: String(value), defaultSelected, selected });
}
}
const token = 'a'.repeat(64);
const region = { id: 7, name: 'Test region' };
const available = { state: 'available', vpc_key: null, vpc_name: null };
const attached = { state: 'attached', vpc_key: 'old-vpc', vpc_name: '原 VPC' };
const instance = (id = 11, attachment = available, overrides = {}) => ({
id, name: `vm-${id}`, region_id: 7, region: region.name,
service_available: true, vpc_attachment: attachment, ...overrides,
});
const doc = (key = 'new-vpc', members = []) => ({
vpc: { vpc_key: key, name: key, region_id: 7, cidr: '10.20.0.0/24',
state: 'active', usable: true, member_count: members.length },
members, routes: [], acl_rules: [], operations: [],
});
const bootstrap = instances => ({
user: { user_id: '9', csrf_token: token }, regions: [region], instances,
});
const response = payload => ({ status: 200, ok: true, async json() { return payload; } });
const pageResponse = instances => ({
ok: true, status: 200,
async text() { return `<script id="vpc-bootstrap">${JSON.stringify(bootstrap(instances))}</script>`; },
});
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
function harness() {
const ids = [
'vpc-member-instance', 'vpc-page-error', 'vpc-page-notice', 'vpc-detail-panel', 'vpc-detail',
'vpc-create-region', 'vpc-create-open', 'vpc-create-submit', 'vpc-create-availability',
'vpc-create-region-hint', 'vpc-create-close', 'vpc-create-cancel', 'vpc-create-error',
'vpc-create-form', 'vpc-create-modal', 'vpc-list', 'vpc-list-empty', 'vpc-list-reconcile',
'vpc-stat-total', 'vpc-stat-active', 'vpc-stat-attention', 'vpc-list-caption',
];
const nodes = Object.fromEntries(ids.map(id => [id, new Node()]));
const memberSubmit = new Node();
const emptyHint = new Node();
const aclDraft = new Node();
aclDraft.value = 'unsaved ACL draft';
const controls = [nodes['vpc-member-instance'], memberSubmit];
const requests = [];
const confirmations = [];
const timers = new Map();
let timerSequence = 0;
let handler = () => { throw new Error('Unexpected request'); };
let confirmResult = true;
const context = {
document: {
visibilityState: 'visible', body: new Node(),
getElementById(id) { return nodes[id] || null; },
createElement() { return new Node(); },
querySelector(selector) {
return ({ '[data-vpc-member-submit]': memberSubmit,
'[data-vpc-member-empty]': emptyHint, '#vpc-acl-editor': aclDraft })[selector] || null;
},
querySelectorAll() { return controls; },
},
Option: OptionNode, HTMLElement: Node, Headers, AbortController,
DOMParser: class {
parseFromString(html, contentType) {
assert.equal(contentType, 'text/html');
const match = html.match(/<script id="vpc-bootstrap">([\s\S]*)<\/script>/u);
return { getElementById(id) {
assert.equal(id, 'vpc-bootstrap');
return match ? { textContent: match[1] } : null;
} };
}
},
location: { protocol: 'https:', hostname: 'panel.test', pathname: '/user/vpcs', search: '' },
crypto: { randomUUID() { return '12345678-1234-1234-1234-123456789abc'; } },
window: { setTimeout(callback, delay) {
const id = ++timerSequence;
timers.set(id, { callback, delay });
return id;
} },
clearTimeout(id) { timers.delete(id); },
confirm(message) { confirmations.push(message); return confirmResult; }, toast() {},
async fetch(path, options = {}) {
const request = { path, ...options };
requests.push(request);
return handler(request);
},
};
vm.runInNewContext(source, context, { filename: 'vpc.js' });
const api = context.__memberChoices;
Object.assign(api.state, { csrfToken: token, userId: '9', regions: [region],
instances: [instance()], selectedKey: 'new-vpc', selected: doc(), vpcs: [doc().vpc] });
const renders = [];
api.observeDetailRender(() => {
renders.push({ busy: api.state.busy, attachment: api.state.instances[0]?.vpc_attachment?.state });
});
return { ...api, nodes, memberSubmit, emptyHint, aclDraft, requests, confirmations, renders, timers,
setConfirmResult(value) { confirmResult = value; },
fireTimeout(delay) {
const entry = [...timers].find(([, timer]) => timer.delay === delay);
assert.ok(entry, `Expected a pending ${delay} ms timeout`);
timers.delete(entry[0]);
entry[1].callback();
},
setFetch(nextHandler) { handler = nextHandler; } };
}
// Both explicit member mutations disclose the stopped prerequisite before a
// write. Cancelling the dialog must not mutate membership or refresh a form in
// progress. Accepted work contains no browser or server auto-power opt-in.
for (const action of ['attach', 'detach']) {
const h = harness();
h.setConfirmResult(false);
const submit = () => action === 'attach'
? h.submitMember({ instance_id: { value: '11' } }) : h.removeMember('member-11');
await submit();
assert.equal(h.requests.length, 0, 'Declining a stopped-only mutation must make no request.');
assert.equal(h.confirmations.length, 1);
assert.match(h.confirmations[0], /实例已完全关机/u);
assert.match(h.confirmations[0], /不会自动关机或开机/u);
assert.match(h.confirmations[0], /实例仍保持关机/u);
if (action === 'attach') assert.match(h.confirmations[0], /vm-11/u);
else assert.match(h.confirmations[0], /清理确认前.*IP 不会重新分配/u);
h.setConfirmResult(true);
h.setFetch(request => request.path === '/user/vpcs'
? pageResponse([instance()]) : response(doc()));
await submit();
assert.deepEqual(h.requests.map(request => `${request.method} ${request.path}`), [
action === 'attach' ? 'POST /api/v1/vpcs/new-vpc/members'
: 'DELETE /api/v1/vpcs/new-vpc/members/member-11',
'GET /user/vpcs',
], 'Accepted stopped-only work must stay in the durable VPC API.');
assert.equal(Object.hasOwn(JSON.parse(h.requests[0].body), 'auto_power'), false,
'New member mutations must not opt into legacy automatic power handling.');
assert.match(h.nodes['vpc-page-notice'].textContent, /实例会保持关机/u);
}
// Network readiness or an empty VPC must not hide a pending power restore.
// Explicit retry remains accessible independently of those network states.
for (const status of ['active', 'awaiting_members']) {
const h = harness();
const current = doc();
Object.assign(current.vpc, { last_operation_id: 'current', state: status,
usable: status === 'active', setup_state: status === 'awaiting_members' ? status : null });
current.operations = [{ operation_id: 'current', kind: 'member_detach',
power_workflow: { phase: 'paused', error_code: 'vpc_power_result_uncertain' } }];
h.state.selected = current;
h.state.vpcs = [current.vpc];
h.renderList();
assert.equal(h.nodes['vpc-list-reconcile'].hidden, false);
assert.equal(h.nodes['vpc-list-reconcile'].disabled, false);
h.setFetch(request => request.path === '/user/vpcs'
? pageResponse([instance()]) : response(current));
await h.reconcile();
assert.equal(h.requests[0].path, '/api/v1/vpcs/new-vpc/reconcile');
assert.equal(h.requests[0].method, 'POST');
}
// A same-region VM owned by another VPC stays visible with an explanatory label.
{
const h = harness();
const choice = h.memberChoice(instance(11, attached), doc());
assert.equal(choice.disabled, true);
assert.equal(choice.reason, '已加入 VPC:原 VPC');
h.state.instances = [instance(11, attached), instance(12)];
assert.equal(h.populateMemberChoices(h.nodes['vpc-member-instance'], doc()), 1);
const options = h.nodes['vpc-member-instance'].options;
assert.deepEqual(options.map(option => option.value), ['', '12', '11']);
assert.equal(options[1].disabled, false);
assert.equal(options[2].disabled, true);
assert.match(options[2].textContent, /已加入 VPC:原 VPC/u);
}
// Server projection merges all live ownership states into attached; the local
// current-detail guard must also win over an older available bootstrap payload.
for (const memberState of ['active', 'applying', 'waiting', 'uncertain', 'degraded', 'suspended', 'unknown']) {
const h = harness();
const currentDoc = doc('new-vpc', [{ instance_id: 11, state: memberState }]);
const choice = h.memberChoice(instance(), currentDoc);
assert.equal(choice.disabled, true, `${memberState} current member must stay unavailable`);
assert.equal(choice.reason, '已在当前 VPC');
}
for (const memberState of ['deleting', 'deleted']) {
const h = harness();
assert.match(h.memberChoice(instance(), doc('new-vpc', [
{ instance_id: 11, state: memberState },
])).reason, /仍在清理/u);
}
// A legacy deleted tombstone still owns cleanup. Keep it unselectable while
// providing an explicit reconciliation path even for an otherwise stable root.
{
const h = harness();
assert.equal(h.hasMemberCleanup(null), false);
assert.equal(h.hasMemberCleanup({}), false);
assert.equal(h.hasMemberCleanup(doc()), false);
for (const state of ['active', 'deleting', 'unknown']) {
assert.equal(h.hasMemberCleanup(doc('new-vpc', [{ instance_id: 11, state }])), false);
}
assert.equal(h.hasMemberCleanup(doc('new-vpc', [{ instance_id: 11, state: 'deleted' }])), true);
assert.equal(h.hasMemberCleanup(doc('new-vpc', [
{ instance_id: 12, state: 'active' }, { instance_id: 11, state: 'DELETED' },
])), true);
assert.match(h.memberChoice(instance(11, { state: 'cleanup_pending', vpc_name: '旧私网' }), doc()).reason,
/旧私网.*仍在清理.*核对/u);
}
for (const status of ['active', 'awaiting_members']) {
const h = harness();
const cleanupDoc = doc('new-vpc', [{ instance_id: 11, state: 'deleted' }]);
if (status === 'awaiting_members') Object.assign(cleanupDoc.vpc, {
state: 'applying', usable: false, setup_state: 'awaiting_members', member_count: 0,
});
h.state.selected = cleanupDoc;
h.renderList();
assert.equal(h.nodes['vpc-list-reconcile'].hidden, false,
`${status} with a deleted member must retain its cleanup action.`);
assert.equal(h.nodes['vpc-list-reconcile'].disabled, false);
assert.equal(h.memberChoice(instance(), cleanupDoc).disabled, true);
h.setFetch(request => request.method === 'POST'
? response(cleanupDoc) : pageResponse([instance(11, { state: 'cleanup_pending' })]));
await h.reconcile();
assert.deepEqual(h.requests.filter(request => request.method === 'POST').map(request => request.path),
['/api/v1/vpcs/new-vpc/reconcile']);
assert.equal(h.state.instances[0].vpc_attachment.state, 'cleanup_pending',
'Requesting reconciliation alone must not manufacture a cleanup receipt.');
assert.equal(h.memberSubmit.disabled, true);
}
{
const h = harness();
Object.assign(h.state.selected.vpc, { state: 'applying', usable: false,
setup_state: 'awaiting_members', member_count: 0 });
h.renderList();
assert.equal(h.nodes['vpc-list-reconcile'].hidden, true);
assert.equal(h.nodes['vpc-list-reconcile'].disabled, true);
await h.reconcile();
assert.equal(h.requests.length, 0, 'A genuinely empty VPC does not need a cleanup reconciliation.');
assert.match(h.nodes['vpc-page-notice'].textContent, /等待实例/u);
}
{
const h = harness();
const cases = [
[instance(), false, ''],
[instance(11, { ...attached, vpc_key: 'new-vpc' }), true, '已在当前 VPC'],
[instance(11, { ...attached, vpc_name: '' }), true, '已加入其他 VPC'],
[instance(11, { state: 'cleanup_pending' }), true, '仍在清理'],
[instance(11, { state: 'unavailable' }), true, '待核验'],
[instance(11, { state: 'future-unknown' }), true, '待核验'],
[instance(11, null), true, '待核验'],
[{ id: 11 }, true, '待核验'],
[undefined, true, '待核验'],
[instance(11, available, { region_id: 8 }), true, '地区不匹配'],
[instance(11, available, { region_id: null }), true, '地区待核验'],
[instance(11, available, { region_id: 'invalid' }), true, '地区待核验'],
[instance(11, available, { service_available: false }), true, '服务当前不可用'],
];
for (const [row, disabled, reason] of cases) {
const result = h.memberChoice(row, doc());
assert.equal(result.disabled, disabled);
assert.ok(result.reason.includes(reason), result.reason);
}
h.state.instances = [instance(11, available, { service_available: false })];
h.refreshMemberChoices();
assert.deepEqual(h.nodes['vpc-member-instance'].options.map(option => option.value), ['']);
assert.equal(h.memberSubmit.disabled, true);
assert.equal(h.emptyHint.hidden, false);
}
// A fresh projection revokes an existing selection; successful cleanup makes it
// selectable again but must not silently reselect the previously blocked VM.
{
const h = harness();
const select = h.nodes['vpc-member-instance'];
h.refreshMemberChoices();
select.value = '11';
h.state.instances = [instance(11, { state: 'cleanup_pending' })];
h.refreshMemberChoices();
assert.equal(select.value, '');
assert.equal(h.memberSubmit.disabled, true);
h.setFetch(() => pageResponse([instance()]));
await h.refreshBootstrap();
assert.equal(select.value, '');
assert.equal(select.options.find(option => option.value === '11').disabled, false);
assert.equal(h.memberSubmit.disabled, false);
assert.equal(h.emptyHint.hidden, true);
select.value = '11';
await h.refreshBootstrap();
assert.equal(select.value, '11', 'A still eligible selection survives refresh.');
assert.equal(h.timers.size, 0, 'Completed candidate refresh must clear its timeout.');
}
for (const row of [instance(11, attached), instance(11, { state: 'cleanup_pending' }),
instance(11, null), instance(11, available, { region_id: 8 }),
instance(11, available, { service_available: false })]) {
const h = harness();
h.state.instances = [row];
await h.submitMember({ instance_id: { value: '11' } });
assert.equal(h.requests.length, 0, 'A manually forced blocked value must not POST.');
assert.notEqual(h.nodes['vpc-page-error'].textContent, '');
}
{
const h = harness();
await h.submitMember({ instance_id: { value: '9999' } });
assert.equal(h.requests.length, 0, 'A fabricated instance id must not POST.');
}
// Read-only candidate refreshes must keep dirty ACL input nodes and values intact.
{
const h = harness();
h.state.detailDirty = true;
const draft = h.aclDraft;
h.setFetch(() => pageResponse([instance(11, attached)]));
await h.refreshBootstrap();
assert.equal(h.state.detailDirty, true);
assert.equal(h.renders.length, 0, 'Candidate refresh must not rebuild the detail editor.');
assert.equal(h.aclDraft, draft);
assert.equal(h.aclDraft.value, 'unsaved ACL draft');
assert.equal(h.memberSubmit.disabled, true);
}
for (const failure of [
() => { throw new Error('network unavailable'); },
() => ({ ok: false, status: 503 }),
() => ({ ok: true, async text() { return '<html>login</html>'; } }),
() => ({ ok: true, async text() { return '<script id="vpc-bootstrap">broken</script>'; } }),
() => ({ ok: true, async text() {
return '<script id="vpc-bootstrap">{"user":{"user_id":"10","csrf_token":"'
+ token + '"},"instances":[]}</script>';
} }),
]) {
const h = harness();
h.refreshMemberChoices();
h.nodes['vpc-member-instance'].value = '11';
h.setFetch(failure);
assert.ok(await h.refreshBootstrap(true));
assert.equal(h.state.instances[0].vpc_attachment.state, 'unavailable');
assert.equal(h.nodes['vpc-member-instance'].value, '');
assert.equal(h.memberSubmit.disabled, true, 'A failed projection refresh must fail closed.');
}
// Ignore a pre-mutation response even if transport ignores AbortController.
// Refresh ownership after the write before controls become actionable again.
{
const h = harness();
const oldRead = deferred();
let pageRequests = 0;
h.setFetch(request => {
if (request.path === '/user/vpcs') {
pageRequests += 1;
if (pageRequests === 1) return oldRead.promise;
assert.equal(h.state.busy, true, 'Fresh ownership must be read while mutation stays locked.');
return pageResponse([instance(11, attached)]);
}
assert.equal(request.method, 'POST');
return response(doc('new-vpc', [{ instance_id: 11, state: 'applying' }]));
});
const pending = h.refreshBootstrap(true);
const oldSignal = h.requests[0].signal;
await h.submitMember({ instance_id: { value: '11' } });
assert.equal(oldSignal.aborted, true);
oldRead.resolve(pageResponse([instance()]));
await pending;
assert.equal(h.state.instances[0].vpc_attachment.state, 'attached');
assert.equal(h.memberSubmit.disabled, true);
assert.equal(h.state.busy, false);
assert.deepEqual(h.requests.map(request => `${request.method} ${request.path}`), [
'GET /user/vpcs', 'POST /api/v1/vpcs/new-vpc/members', 'GET /user/vpcs',
]);
assert.equal(h.renders.at(-1).attachment, 'attached');
}
// An ambiguous failed POST still refreshes ownership; a stale error from an
// earlier refresh must not erase a newer successful projection either.
{
const h = harness();
const oldRead = deferred();
let pageRequests = 0;
h.setFetch(request => {
if (request.method === 'POST') throw new Error('response lost');
pageRequests += 1;
return pageRequests === 1 ? oldRead.promise : pageResponse([instance(11, attached)]);
});
const pending = h.refreshBootstrap(true);
await h.mutate('/api/v1/vpcs/new-vpc/members', 'POST', { instance_id: 11 });
oldRead.resolve({ ok: false, status: 503 });
await pending;
assert.equal(h.state.instances[0].vpc_attachment.state, 'attached');
assert.equal(h.memberSubmit.disabled, true);
assert.match(h.nodes['vpc-page-error'].textContent, /response lost/u);
assert.equal(h.renders.length, 0, 'A failed mutation must not overwrite an editor draft.');
}
// A successful write must not leave all controls locked when refreshing either
// response headers or the HTML body stalls. Drive the actual deadline callback
// deterministically; no real timer or remote request is used by these tests.
for (const stalledStage of ['fetch', 'body']) {
const h = harness();
const reachedStall = deferred();
h.setFetch(request => {
if (request.method === 'POST') return response(doc());
const awaitAbort = () => new Promise((resolve, reject) => {
request.signal.addEventListener('abort', () => {
const error = new Error('aborted');
error.name = 'AbortError';
reject(error);
}, { once: true });
reachedStall.resolve();
});
return stalledStage === 'fetch' ? awaitAbort() : { ok: true, text: awaitAbort };
});
const operation = h.mutate('/api/v1/vpcs/new-vpc/members', 'POST', { instance_id: 11 });
await reachedStall.promise;
assert.equal(h.state.busy, true);
h.fireTimeout(10000);
await operation;
assert.equal(h.requests.at(-1).signal.aborted, true);
assert.equal(h.state.busy, false, `A ${stalledStage} timeout must release the mutation lock.`);
assert.equal(h.state.instances[0].vpc_attachment.state, 'unavailable');
assert.equal(h.memberSubmit.disabled, true);
assert.equal([...h.timers.values()].some(timer => timer.delay === 10000), false);
}
{
const h = harness();
const oldRead = deferred();
let pageRequests = 0;
h.setFetch(() => ++pageRequests === 1 ? oldRead.promise : pageResponse([instance(11, attached)]));
const pending = h.refreshBootstrap(true);
await h.refreshBootstrap(true);
const latestSignal = h.requests.at(-1).signal;
h.fireTimeout(10000);
assert.equal(latestSignal.aborted, false, 'An old deadline must only abort its own controller.');
oldRead.resolve({ ok: false, status: 503 });
await pending;
assert.equal(h.state.instances[0].vpc_attachment.state, 'attached',
'An expired read cannot replace the newer ownership projection with unavailable.');
assert.equal(h.timers.size, 0);
}
{
const h = harness();
h.setFetch(request => request.path === '/user/vpcs'
? pageResponse([instance(11, attached)]) : response(doc('another-vpc')));
await h.selectVpc('another-vpc');
assert.deepEqual(h.requests.map(request => request.path), ['/user/vpcs', '/api/v1/vpcs/another-vpc']);
assert.equal(h.state.selectedKey, 'another-vpc');
assert.equal(h.renders.at(-1).attachment, 'attached', 'Switching must refresh ownership before rendering choices.');
}
// A detail read started before the user edits a policy must not later erase it.
{
const h = harness();
const detailRead = deferred();
const detailStarted = deferred();
h.setFetch(request => {
if (request.path === '/user/vpcs') return pageResponse([instance()]);
detailStarted.resolve();
return detailRead.promise;
});
const selection = h.selectVpc('another-vpc');
await detailStarted.promise;
h.state.detailDirty = true;
detailRead.resolve(response(doc('another-vpc')));
await selection;
assert.equal(h.state.detailDirty, true);
assert.equal(h.renders.length, 0, 'A delayed detail read must preserve newly edited policy input.');
}
{
const h = harness();
h.setFetch(request => {
if (request.method === 'POST') return response(doc('created-vpc'));
assert.equal(h.state.busy, true);
return pageResponse([instance(11, attached)]);
});
const form = h.nodes['vpc-create-form'];
Object.assign(form, { name: { value: 'created-vpc' }, region_id: { value: '7' },
checkValidity() { return true; } });
await h.createVpc({ preventDefault() {}, currentTarget: form });
assert.deepEqual(h.requests.map(request => `${request.method} ${request.path}`), [
'POST /api/v1/vpcs', 'GET /user/vpcs',
]);
assert.equal(h.state.selectedKey, 'created-vpc');
assert.equal(h.state.busy, false);
assert.equal(h.renders.at(-1).attachment, 'attached', 'Creating a VPC must not reuse the old candidate snapshot.');
}
console.log('Cloud VPC member choices, cleanup, stale-read fencing and mutation refresh behavior passed.');