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/vpcs.js', import.meta.url), 'utf8')) .split('const requestUserConfirmation')[1]; const template = await readFile(new URL('../resources/views/venix/cloud/pages/vpcs.tpl', import.meta.url), 'utf8'); class Node { constructor(tag, document) { Object.assign(this, { tagName: tag.toUpperCase(), document, children: [], attributes: new Map(), dataset: {}, listeners: new Map(), className: '', value: '', hidden: false, disabled: false, checked: false, open: false, text: '' }); this.classList = { contains: name => this.className.split(/\s+/).includes(name), toggle: (name, force) => { const names = new Set(this.className.split(/\s+/).filter(Boolean)); const on = force ?? !names.has(name); if (on) names.add(name); else names.delete(name); this.className = [...names].join(' '); }, add: name => this.classList.toggle(name, true), remove: name => this.classList.toggle(name, false), }; } set textContent(value) { this.text = String(value); this.replaceChildren(); } get textContent() { return this.text + this.children.map(child => child.textContent).join(''); } append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } } replaceChildren(...children) { for (const child of this.children) child.parent = null; this.children = []; this.append(...children); } setAttribute(name, value) { this.attributes.set(name, String(value)); } getAttribute(name) { return this.attributes.get(name) ?? null; } removeAttribute(name) { this.attributes.delete(name); } querySelectorAll(selector) { const matches = node => { if (selector === '[data-vpc-focus]') return Boolean(node.dataset.vpcFocus); if (selector.startsWith('.')) return node.classList.contains(selector.slice(1)); if (selector === 'th:last-child') return node.tagName === 'TH' && node.parent.children.at(-1) === node; return node.tagName === selector.toUpperCase(); }; return this.children.flatMap(child => [...(matches(child) ? [child] : []), ...child.querySelectorAll(selector)]); } querySelector(selector) { return this.querySelectorAll(selector)[0] || null; } addEventListener(name, listener) { if (!this.listeners.has(name)) this.listeners.set(name, []); this.listeners.get(name).push(listener); } async fire(name) { const event = { target: this, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, }; await Promise.all((this.listeners.get(name) || []).map(fn => fn(event))); await tick(); if (name === 'click' && !event.defaultPrevented && this.tagName === 'A' && this.href) { await this.document.navigate(this.href); } return event; } focus() { this.document.activeElement = this; } scrollIntoView() {} get isConnected() { return Boolean(this.parent); } showModal() { this.open = true; } close() { this.open = false; } } const tick = () => new Promise(resolve => setImmediate(resolve)); const A = 'a'.repeat(32), B = 'b'.repeat(32), C = 'c'.repeat(32); const href = key => `#/${key}/instances`; const network = (key, overrides = {}) => ({ vpc_key: key, name: key === A ? 'production' : 'staging', region_id: 1, region_name: '香港', cidr: '10.0.1.0/24', gateway: '10.0.1.1', state: 'active', port_count: 2, can_delete: false, ...overrides, }); const member = (id, overrides = {}) => ({ id: String(id), name: `vm-${id}`, region_id: 1, public_ipv4: `192.0.2.${id}`, can_detach: true, can_attach: false, port: { vpc_key: A, state: 'attached', private_ip: `10.0.1.${id}`, mac_address: '02:11:22:33:44:55' }, ...overrides, }); const candidate = (id, overrides = {}) => member(id, { port: null, can_detach: false, can_attach: true, ...overrides }); function fixtures() { return { user: { id: 7 }, maximum: 16, used: 2, items: [network(A), network(B, { port_count: 0, can_delete: true })], regions: [{ id: 1, name: '香港', available: 200 }, { id: 2, name: '新加坡' }], instances: [member(1), member(2), ...[3, 4, 5, 6, 7].map(id => candidate(id)), candidate(8, { can_attach: false, action_unavailable_reason: '实例服务已到期' }), candidate(9, { region_id: 2 })], membership_batches: [], }; } async function setup(hash = '#/', payload = fixtures()) { const document = {}; document.createElement = tag => new Node(tag, document); document.documentElement = document.createElement('html'); const nodes = new Map(); for (const match of template.matchAll(/<([a-z][a-z0-9]*)\b[^>]*\bid="([^"]+)"[^>]*>/g)) { const node = document.createElement(match[1]); nodes.set(match[2], node); document.documentElement.append(node); } document.activeElement = document.documentElement; const calls = [], observations = [], storage = new Map(), events = new Map(); const location = new URL(`https://panel.example.test/user/cloud/vpcs${hash}`); const window = { location, VenixDialog: { confirm: async () => true }, addEventListener: (name, listener) => events.set(name, listener) }; let fullPageNavigations = 0; document.navigate = async target => { const next = new URL(target, location.href); if (next.origin === location.origin && next.pathname === location.pathname && next.search === location.search) { if (next.hash !== location.hash) { location.hash = next.hash; events.get('hashchange')?.(); await tick(); } return; } fullPageNavigations += 1; }; let data = structuredClone(payload); let respond = async (url, options) => { if (!options.method) return structuredClone(data); throw Error(`Unexpected mutation ${url}`); }; const context = vm.createContext({ window, document, URL, AbortController, console, sessionStorage: { getItem: key => storage.get(key) || null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) }, byId: id => nodes.get(id), readBootstrap: () => structuredClone(data), initializeSession: async () => true, api: async (url, options = {}) => { calls.push({ url, ...options }); return respond(url, options); }, showError: (id, message) => { assert.ok(nodes.has(id), `Unexpected page initialization error: ${message}`); nodes.get(id).textContent = message; nodes.get(id).hidden = !message; }, toast() {}, announceTaskAccepted() {}, taskUrl: receipt => receipt?.task_id && receipt?.status_url ? receipt.status_url : '', observeTask: (receipt, options) => { const handle = { url: receipt.status_url, done: new Promise(() => {}), stop() {} }; observations.push({ receipt, options, handle }); return handle; }, recoveryTaskFailureNotice: () => '', resolvedTaskFailureNotice: () => '', taskSucceededWithoutRecovery: task => task.status === 'succeeded' && task.terminal === true, }); vm.runInContext(('const requestUserConfirmation' + source) .replace('export async function initialize()', 'async function initialize()') + '\nglobalThis.page = { initialize, apply, routeChanged };', context, { filename: 'vpcs.js' }); await context.page.initialize(); return { nodes, calls, observations, storage, location, data: () => data, fullPageNavigations: () => fullPageNavigations, update: next => { data = structuredClone(next); context.page.apply(structuredClone(next)); }, respond: fn => { respond = fn; }, event: (name, event = {}) => events.get(name)?.(event), async go(hash) { location.hash = hash; events.get('hashchange')(); await tick(); }, async confirm(accept = true) { if (accept) { nodes.get('cloud-vpc-confirm-restart').checked = true; await nodes.get('cloud-vpc-confirm-restart').fire('change'); await nodes.get('cloud-vpc-confirm-form').fire('submit'); } else await nodes.get('cloud-vpc-confirm-cancel').fire('click'); await tick(); }, }; } const checks = t => t.nodes.get('cloud-vpc-instance-manager').querySelectorAll('input'); const control = (t, focus) => t.nodes.get('cloud-vpc-instance-manager') .querySelectorAll('[data-vpc-focus]').find(node => node.dataset.vpcFocus === focus); const mutations = t => t.calls.filter(call => call.method); const plain = value => JSON.parse(JSON.stringify(value)); async function select(t, id) { const node = control(t, `select-${id}`); node.checked = true; await node.fire('change'); } async function submit(t) { await control(t, 'submit-selection').fire('click'); } for (const [query, page, joining] of [ ['?view=create', 'create', false], [`?vpc=${A}`, 'members', false], [`?vpc=${A}&view=join`, 'members', true], ['?vpc=invalid', 'missing', false], ['?vpc[]=invalid', 'missing', false], ['?view=join', 'missing', false], ]) { const t = await setup(query); assert.equal(t.nodes.get(`cloud-vpcs-${page}`).hidden, false, `Query route is not hydrated: ${query}`); if (page === 'members') assert.equal(t.nodes.get('cloud-vpc-instance-manager').querySelector('section').classList.contains('joining'), joining); assert.equal(t.calls.length, 0, 'A valid embedded library triggered an extra list request.'); } { const t = await setup(); assert.equal(t.nodes.get('cloud-vpcs-home').hidden, false); assert.equal(t.nodes.get('cloud-vpcs-create').hidden, true); const networkCards = t.nodes.get('cloud-vpcs-list').querySelectorAll('.cloud-vpc-network-card'); assert.equal(networkCards.length, 2); assert.match(networkCards[0].textContent, /production.*香港.*10\.0\.1\.0\/24.*2 台.*运行正常/s); assert.equal(t.nodes.get('cloud-vpcs-list').textContent.includes('管理实例'), false); assert.equal(t.nodes.get('cloud-vpcs-list').querySelectorAll('details').length, 0); await networkCards[0].fire('click'); assert.equal(t.fullPageNavigations(), 0, 'Opening a VPC card must stay in the workspace'); assert.equal(t.nodes.get('cloud-vpcs-members').hidden, false); await t.go('#/create'); assert.equal(t.nodes.get('cloud-vpcs-create').hidden, false); assert.equal(t.nodes.get('cloud-vpc-region').textContent.includes('200'), false); await t.go(href(A)); assert.equal(t.nodes.get('cloud-vpcs-members').hidden, false); assert.equal(t.nodes.get('cloud-vpc-network-summary').children.length, 4); assert.match(t.nodes.get('cloud-vpc-network-summary').textContent, /地区香港私网网段10\.0\.1\.0\/24默认网关10\.0\.1\.1已加入实例2 台/); assert.match(t.nodes.get('cloud-vpc-members-link').textContent, /2/); assert.match(t.nodes.get('cloud-vpc-join-link').textContent, /5/); assert.equal(t.nodes.get('cloud-vpc-instance-manager') .querySelectorAll('.cloud-vpc-instance-card').length, 2); assert.match(t.nodes.get('cloud-vpc-instance-manager').textContent, /vm-1.*192\.0\.2\.1.*10\.0\.1\.1.*02:11:22:33:44:55.*已连接/s); assert.equal(t.nodes.get('cloud-vpc-delete').disabled, true); await t.go(`${href(B)}/join`); assert.equal(t.nodes.get('cloud-vpc-join-link').getAttribute('aria-current'), 'page'); assert.equal(t.nodes.get('cloud-vpc-delete').disabled, false); for (const route of ['#/does-not-exist', href(C)]) { await t.go(route); assert.equal(t.nodes.get('cloud-vpcs-missing').hidden, false); } await t.go('#/'); assert.equal(t.nodes.get('cloud-vpcs-home').hidden, false); assert.equal(mutations(t).length, 0, 'Navigation must never mutate a VPC'); } { const t = await setup(`?vpc=${A}`); await t.nodes.get('cloud-vpc-join-link').fire('click'); assert.equal(t.fullPageNavigations(), 0, 'Switching to joinable instances must not trigger a full-page navigation'); assert.equal(t.nodes.get('cloud-vpc-instance-manager').querySelector('section') .classList.contains('joining'), true); await t.nodes.get('cloud-vpc-members-link').fire('click'); assert.equal(t.fullPageNavigations(), 0, 'Switching to attached instances must not trigger a full-page navigation'); assert.equal(t.nodes.get('cloud-vpc-instance-manager').querySelector('section') .classList.contains('joining'), false); assert.equal(mutations(t).length, 0, 'Tab switching must not mutate a VPC'); } { const t = await setup(`${href(A)}/join`); const search = control(t, 'instance-search'); assert.equal(search.placeholder, '搜索实例或公网 IP'); search.value = '192.0.2.4'; await search.fire('input'); const rows = t.nodes.get('cloud-vpc-instance-manager') .querySelectorAll('.cloud-vpc-instance-row'); assert.deepEqual(rows.filter(row => !row.hidden) .map(row => row.querySelector('input').value), ['4']); const selectAll = control(t, 'select-all'); selectAll.checked = true; await selectAll.fire('change'); assert.deepEqual(checks(t).filter(node => node.value && node.checked) .map(node => node.value), ['4'], 'Select all must apply only to filtered results'); t.update(t.data()); assert.equal(control(t, 'instance-search').value, '192.0.2.4', 'The search query must survive a status refresh'); const refreshedSearch = control(t, 'instance-search'); refreshedSearch.value = 'not-found'; await refreshedSearch.fire('input'); assert.equal(t.nodes.get('cloud-vpc-instance-manager') .querySelector('.cloud-vpc-search-empty').hidden, false); assert.equal(control(t, 'submit-selection').disabled, false, 'A filtered-out prior selection must remain explicit and actionable'); } { const t = await setup(`${href(A)}/join`); assert.deepEqual(checks(t).filter(node => node.value).map(node => node.value), ['3', '4', '5', '6', '7', '8']); assert.equal(control(t, 'select-8').disabled, true); await select(t, 'all'); assert.equal(checks(t).filter(node => node.value && node.checked).length, 5, 'No four-instance limit'); await submit(t); assert.equal(t.nodes.get('cloud-vpc-confirm').open, true); await t.nodes.get('cloud-vpc-confirm-form').fire('submit'); assert.equal(mutations(t).length, 0, 'Restart must be acknowledged'); await t.confirm(false); assert.equal(mutations(t).length, 0, 'Cancel must not dispatch'); t.respond(async (url, options) => !options.method ? t.data() : { task_id: '500', status_url: '/api/v1/tasks/500' }); await submit(t); await t.confirm(); const [request] = mutations(t); assert.equal(request.url, `/api/v1/vpcs/${A}/ports/batch`); assert.deepEqual(plain(request.body), { action: 'attach', instance_ids: [3, 4, 5, 6, 7], confirm_restart: true }); assert.match(request.headers['Idempotency-Key'], /^[a-zA-Z0-9_.-]{16,128}$/); assert.equal(request.expectedStatus, 202); assert.equal(request.requireTaskReceipt, true); assert.equal(t.location.search, `?vpc=${A}`); assert.equal(t.observations.length, 1); await t.go('#/'); await t.go(`${href(B)}/join`); assert.equal(t.observations.length, 1, 'Navigation must not duplicate observers'); } { const t = await setup(href(A)); await select(t, 1); await submit(t); const changed = t.data(); changed.instances[0].can_detach = false; t.update(changed); await t.confirm(); assert.equal(mutations(t).length, 0, 'Eligibility must be rechecked after confirmation'); assert.match(t.nodes.get('cloud-vpcs-status').textContent, /状态已变化/); } { const data = fixtures(); data.items[1].port_count = 1; data.items[1].can_delete = false; data.instances.push(member(10, { port: { vpc_key: B, state: 'preparing' }, can_detach: false, can_retry_attach: true, })); data.membership_batches = [{ vpc_key: A, state: 'blocked', total: 2, succeeded: 1, failed: 0, unknown: 1, action: 'attach', task_id: '501', status_url: '/api/v1/tasks/501', can_cancel: true, batch_key: 'd'.repeat(32) }]; const t = await setup(href(A), data); assert.equal(checks(t).every(node => node.disabled), true); assert.match(t.nodes.get('cloud-vpc-batch-status').textContent, /1 台待核对/); assert.match(t.nodes.get('cloud-vpc-batch-status').textContent, /继续撤销并清理/); assert.equal(t.observations.length, 0, 'Blocked batch must not be replayed'); await t.go(`${href(B)}/join`); assert.equal(control(t, 'select-3').disabled, false, 'Other VPCs remain usable'); await t.go(href(B)); assert.match(t.nodes.get('cloud-vpc-instance-manager').textContent, /重试连接/); assert.equal(mutations(t).length, 0); } { const data = fixtures(); data.membership_batches = [{ vpc_key: A, state: 'ports', total: 2, succeeded: 0, failed: 0, action: 'detach', task_id: '503', status_url: '/api/v1/tasks/503' }]; const t = await setup(href(A), data); assert.equal(t.observations.length, 1, 'Reload must resume the original batch'); assert.equal(t.observations[0].receipt.task_id, '503'); assert.equal(mutations(t).length, 0, 'Resuming observation must not dispatch a new operation'); assert.equal(checks(t).every(node => node.disabled), true); await t.go('#/'); await t.go(href(A)); assert.equal(t.observations.length, 1); t.event('pagehide'); t.event('pageshow', { persisted: true }); await tick(); assert.equal(t.observations.length, 2, 'Back-forward cache restoration must resume observation'); assert.equal(t.observations[1].receipt.task_id, '503'); assert.equal(mutations(t).length, 0); } { const itemStates = ['waiting_route', 'queued', 'succeeded', 'failed']; const data = fixtures(); data.instances = itemStates.map((itemState, index) => member(index + 1, { can_retry_attach: index === 0, active_task: { task_id: String(600 + index), status_url: `/api/v1/tasks/${600 + index}`, }, })); data.items[0].port_count = itemStates.length; data.membership_batches = [{ vpc_key: A, state: 'ports', total: itemStates.length, succeeded: 1, failed: 1, unknown: 0, action: 'attach', task_id: '599', status_url: '/api/v1/tasks/599', items: itemStates.map((itemState, index) => ({ instance_id: String(index + 1), state: itemState, })), }]; const t = await setup(href(A), data); const manager = t.nodes.get('cloud-vpc-instance-manager'); const rowTaskButtons = manager.querySelectorAll('button') .filter(button => button.textContent === '查看任务'); assert.equal(rowTaskButtons.length, 0, 'Batch rows must not duplicate the batch task-center action'); assert.equal(manager.querySelectorAll('button').filter(button => ['重试连接', '重试清理'].includes(button.textContent)).length, 0, 'Batch rows must not expose per-instance retry actions'); for (const label of ['等待中', '执行中', '已完成', '失败']) { assert.match(manager.textContent, new RegExp(label), `Batch rows must render ${label}`); } assert.equal(t.nodes.get('cloud-vpc-batch-status').querySelectorAll('button') .filter(button => button.textContent === '查看任务').length, 1, 'The batch must retain one task-center action'); } { const data = fixtures(); data.membership_batches = [{ vpc_key: A, batch_key: 'd'.repeat(32), state: 'blocked', action: 'attach', task_id: '504', status_url: '/api/v1/tasks/504', can_cancel: true }]; const t = await setup(href(A), data); t.respond(async (url, options) => !options.method ? t.data() : { task_id: '504', status_url: '/api/v1/tasks/504' }); const cleanup = t.nodes.get('cloud-vpc-batch-status').querySelectorAll('[data-vpc-focus]')[0]; await cleanup.fire('click'); assert.equal(mutations(t)[0].url, `/api/v1/vpcs/${A}/ports/batches/${'d'.repeat(32)}/cancel`); assert.equal(mutations(t)[0].requireTaskReceipt, true); } { const data = fixtures(); data.instances[0].can_detach = false; data.instances[0].can_retry_attach = true; data.instances[0].port.state = 'preparing'; const t = await setup(href(A), data); t.respond(async (url, options) => !options.method ? t.data() : { task_id: '505', status_url: '/api/v1/tasks/505' }); await control(t, 'retry-1').fire('click'); assert.equal(mutations(t)[0].url, '/api/v1/vms/1/vpc'); assert.equal(mutations(t)[0].method, 'PUT'); assert.deepEqual(plain(mutations(t)[0].body), { vpc_key: A, confirm_restart: true }); } { const t = await setup(`${href(A)}/join`); t.respond(async (url, options) => { if (!options.method) return t.data(); throw Object.assign(Error('Network timeout'), { mutationMayHaveApplied: true }); }); for (let attempt = 0; attempt < 2; attempt++) { await select(t, 3); await submit(t); await t.confirm(); } const requests = mutations(t); assert.equal(requests.length, 2); assert.equal(requests[0].headers['Idempotency-Key'], requests[1].headers['Idempotency-Key'], 'An explicit retry after an uncertain response must reuse the original key'); assert.equal(t.storage.size, 1); } { const t = await setup(href(A)); t.respond(async (url, options) => !options.method ? t.data() : { task_id: '502', status_url: '/api/v1/tasks/502' }); await select(t, 1); await submit(t); await t.confirm(); assert.deepEqual(plain(mutations(t)[0].body), { action: 'detach', instance_ids: [1], confirm_restart: true }); t.observations[0].options.onTerminal({ status: 'failed', terminal: true, error: '连接结果待核对', effect_may_have_applied: true, safe_to_resubmit: false }); await tick(); assert.match(t.nodes.get('cloud-vpcs-status').textContent, /请勿重复提交/); assert.equal(mutations(t).length, 1); } { const t = await setup('#/create'); const created = network(C, { name: 'new-vpc', port_count: 0, can_delete: true }); t.respond(async (url, options) => { if (options.method === 'POST') { const next = t.data(); next.items.push(created); next.used++; return { vpc: created }; } return t.data(); }); t.nodes.get('cloud-vpc-name').value = 'new-vpc'; t.nodes.get('cloud-vpc-region').value = '1'; await t.nodes.get('cloud-vpc-create-form').fire('submit'); assert.equal(t.location.search, `?vpc=${C}&view=join`); assert.equal(mutations(t).length, 1, 'Creation must not attach or restart instances'); assert.deepEqual(plain(mutations(t)[0].body), { name: 'new-vpc', region_id: 1 }); } { const t = await setup(href(B)); t.respond(async (url, options) => options.method === 'DELETE' ? { deleted: true } : { ...t.data(), items: t.data().items.filter(item => item.vpc_key !== B), used: 1 }); await t.nodes.get('cloud-vpc-delete').fire('click'); assert.equal(t.location.pathname, '/user/cloud/vpcs'); assert.equal(t.location.search, ''); assert.equal(mutations(t)[0].url, `/api/v1/vpcs/${B}`); } { const data = fixtures(); data.used = data.maximum; const t = await setup('#/create', data); assert.equal(t.nodes.get('cloud-vpc-create-submit').disabled, true); assert.match(t.nodes.get('cloud-vpc-create-availability').textContent, /配额/); t.update({ ...data, used: 0, regions: [] }); assert.match(t.nodes.get('cloud-vpc-create-availability').textContent, /暂无可用地区/); } console.log('VPC frontend navigation, selection, confirmation, task isolation, idempotency and lifecycle behavior passed.');