import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; globalThis.location = new URL('https://panel.example.test/user/cloud'); const observerUrl = new URL('../public/cloud/task-observer.js', import.meta.url); const centerUrl = new URL('../public/cloud/task-center.js', import.meta.url); const detailUrl = new URL('../public/cloud/detail.js', import.meta.url); const adminInstancesUrl = new URL('../public/cloud/admin-instances.js', import.meta.url); const runtimeUrl = new URL('../public/cloud/runtime.js', import.meta.url); const isoImagesUrl = new URL('../public/cloud/iso-images.js', import.meta.url); const reinstallViewUrl = new URL('../resources/views/venix/cloud/pages/reinstall.tpl', import.meta.url); const { normalizeTask, observeTask, readTask, taskUrl, } = await import(`${observerUrl.href}?test=${Date.now()}`); const { dateText } = await import(`${centerUrl.href}?test=${Date.now()}`); const protocolFailure = task => { assert.equal(task.terminal, true); assert.equal(task.completed, true); assert.equal(task.status, 'failed'); assert.equal(task.error_code, 'task_protocol_invalid'); assert.equal(task.effect_may_have_applied, true); assert.equal(task.safe_to_resubmit, false); }; // The fresh public contract has exactly one active representation and two // terminal states. Legacy aliases and incomplete envelopes fail closed. { const running = normalizeTask({ id: '41', completed: false }); assert.equal(running.status, 'running'); assert.equal(running.terminal, false); for (const status of ['succeeded', 'failed']) { const task = normalizeTask({ id: '41', completed: true, status }); assert.equal(task.status, status); assert.equal(task.terminal, true); } for (const malformed of [ { completed: false }, { id: 'not-a-task', completed: false }, { id: '41' }, { id: '41', completed: false, status: 'running' }, { id: '41', completed: true }, { id: '41', completed: true, status: 'success' }, { id: '41', completed: true, status: 'completed' }, { id: '41', completed: true, status: 'done' }, { id: '41', completed: true, status: 'cancelled' }, { id: '41', completed: true, status: 'uncertain' }, { id: '41', completed: true, status: 'needs_attention' }, { id: '41', completed: true, status: 'SUCCEEDED' }, ]) protocolFailure(normalizeTask(malformed)); const failed = normalizeTask({ id: '42', completed: true, status: 'failed', error: 'host result lost', error_code: 'agent_timeout', effect_may_have_applied: true, safe_to_resubmit: true, failure: { effect_may_have_applied: false, safe_to_resubmit: true }, }); assert.equal(failed.effect_may_have_applied, true); assert.equal(failed.safe_to_resubmit, false, 'A possibly-applied task can never be resubmitted.'); assert.equal(failed.error, 'host result lost'); assert.equal(Object.prototype.hasOwnProperty.call(failed, 'failure'), false); const nestedOnly = normalizeTask({ id: '43', completed: true, status: 'failed', failure: { error: 'legacy', effect_may_have_applied: true, safe_to_resubmit: true }, }); assert.equal(nestedOnly.error, ''); assert.equal(nestedOnly.effect_may_have_applied, false); assert.equal(nestedOnly.safe_to_resubmit, false); } // Receipts accept only the two top-level fields from the fresh API. { assert.equal(taskUrl({ task_id: 'a/b' }), ''); assert.equal(taskUrl({ status_url: '/api/v1/tasks/72' }), ''); assert.equal(taskUrl({ task_id: '72', status_url: '/api/v1/tasks/72' }), '/api/v1/tasks/72'); assert.equal(taskUrl({ task_id: '72', status_url: '/api/v1/tasks/72', result: {} }), ''); assert.equal(taskUrl({ task_id: '72', status_url: '/api/v1/tasks/73' }), ''); assert.equal(taskUrl({ status_url: '/api/v1/tasks/72?legacy=1' }), ''); assert.equal(taskUrl({ status_url: 'https://other.example.test/api/v1/tasks/72' }), ''); assert.equal(taskUrl({ id: '72' }), ''); assert.equal(taskUrl({ job_id: '72' }), ''); assert.equal(taskUrl({ task: { id: '72' } }), ''); const invalidDirect = observeTask('/api/v1/tasks/not-a-task', { fetchImpl: async () => { throw new Error('invalid path must not be fetched'); }, delays: [0], maxDurationMs: 1000, requestTimeoutMs: 1000, }); assert.equal(invalidDirect.url, ''); assert.equal(await invalidDirect.done, null); } // HTTP 202 is active and HTTP 200 is terminal. A status/body mismatch becomes // a visible protocol failure instead of another poll cycle. { const response = (status, body) => ({ status, ok: status >= 200 && status < 300, json: async () => body, }); const active = await readTask('/api/v1/tasks/1', { fetchImpl: async () => response(202, { id: '1', completed: false }), }); assert.equal(active.terminal, false); protocolFailure(await readTask('/api/v1/tasks/1', { fetchImpl: async () => response(200, { id: '1', completed: false }), })); protocolFailure(await readTask('/api/v1/tasks/1', { fetchImpl: async () => response(202, { id: '1', completed: true, status: 'succeeded' }), })); protocolFailure(await readTask('/api/v1/tasks/1', { fetchImpl: async () => response(200, { ret: 0, error: 'legacy envelope' }), })); } // Reproduce hidden -> visible before the aborted request's finally block. The // observer must resume exactly once, remain GET-only, and finish at terminal. { class Surface extends EventTarget { constructor() { super(); this.visibilityState = 'visible'; } setTimeout(callback, delay) { return setTimeout(callback, delay); } clearTimeout(id) { clearTimeout(id); } } const documentRef = new Surface(); const windowRef = new Surface(); const requests = []; const fetchImpl = (url, options) => { requests.push({ url, options }); if (requests.length > 1) { return Promise.resolve({ status: 200, ok: true, json: async () => ({ id: '91', completed: true, status: 'succeeded' }), }); } return new Promise((resolve, reject) => { options.signal.addEventListener('abort', () => { queueMicrotask(() => reject(new DOMException('Aborted', 'AbortError'))); }, { once: true }); }); }; const handle = observeTask({ task_id: '91', status_url: '/api/v1/tasks/91' }, { documentRef, windowRef, fetchImpl, delays: [0], maxDurationMs: 2000, requestTimeoutMs: 1000, }); for (let turn = 0; turn < 20 && requests.length < 1; turn += 1) { await new Promise(resolve => setTimeout(resolve, 1)); } assert.equal(requests.length, 1); documentRef.visibilityState = 'hidden'; documentRef.dispatchEvent(new Event('visibilitychange')); documentRef.visibilityState = 'visible'; documentRef.dispatchEvent(new Event('visibilitychange')); const result = await Promise.race([ handle.done, new Promise((_, reject) => setTimeout(() => reject(new Error('observer did not resume')), 500)), ]); assert.equal(result.status, 'succeeded'); assert.equal(requests.length, 2); assert.ok(requests.every(request => request.options.method === 'GET')); } // Task-center dates from PHP are Unix seconds, not date strings. { const seconds = 1_600_000_000; assert.equal( dateText(seconds), new Date(seconds * 1000).toLocaleString('zh-CN', { hour12: false }), ); } // Keep the integration contract visible in a small static guard: the task // center must query both partitions and acknowledge presentation explicitly. { const source = await readFile(centerUrl, 'utf8'); assert.match(source, /requestPage\('active'/); assert.match(source, /requestPage\('completed'/); assert.match(source, /state=active&limit=1/); assert.match(source, /fetch\('\/api\/v1\/tasks\/read'/); assert.match(source, /body:\s*JSON\.stringify\(\{ ids \}\)/); assert.match(source, /\{ title: '进行中'/); assert.match(source, /\{ title: '已完成'/); assert.match(source, /if \(task\.terminal && task\.id/); assert.doesNotMatch(source, /重试任务|重新提交任务|data-task-retry/); } // A successful mutation receipt must be handled before any resource refresh, // and legacy mutation retry controls must not remain in the DOM. { const detailSource = await readFile(detailUrl, 'utf8'); const firewallReceipt = detailSource.indexOf('expectedStatus: 202', detailSource.indexOf('async function saveVmFirewall')); const firewallRefresh = detailSource.indexOf('loadVmFirewall(vmId, true, true)', detailSource.indexOf('async function saveVmFirewall')); assert.ok(firewallReceipt >= 0); assert.ok(firewallRefresh < 0 || firewallReceipt < firewallRefresh); assert.match(detailSource, /requireTaskReceipt: true/); assert.match(detailSource, /syncInstanceSettingForm\(form\)/); assert.match(detailSource, /snapshotMutation = null;[\s\S]*loadVmSnapshots\(vmId, true, false\)/); const adminInstancesSource = await readFile(adminInstancesUrl, 'utf8'); assert.doesNotMatch(adminInstancesSource, /state\.networkRequest \|\| activeJob/); assert.match(adminInstancesSource, /response\.status !== 202 \|\| !taskUrl\(payload\)/); assert.match(adminInstancesSource, /await refreshDetail\(vm\.id\)/); const runtimeSource = await readFile(runtimeUrl, 'utf8'); assert.match(runtimeSource, /expectedStatus: 202, requireTaskReceipt: true/); assert.match(runtimeSource, /syncReinstallControls\(refreshed \|\| selectedVm\(\)\)/); const isoImagesSource = await readFile(isoImagesUrl, 'utf8'); assert.match(isoImagesSource, /method: 'DELETE', expectedStatus: 202, requireTaskReceipt: true/); assert.match(isoImagesSource, /const refreshed = await loadIsos\(\{ observeActive: false \}\)/); assert.match(isoImagesSource, /const canDelete = String\(record\.state \|\| ''\) === 'active'/); const reinstallView = await readFile(reinstallViewUrl, 'utf8'); assert.doesNotMatch(reinstallView, /reinstall-(?:retry|forget)/); assert.doesNotMatch(reinstallView, />\s*重新查询任务\s*