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.
323 lines
14 KiB
JavaScript
323 lines
14 KiB
JavaScript
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 appUrl = new URL('../public/cloud/app.js', import.meta.url);
|
|
const layoutAssetsUrl = new URL('../resources/views/venix/layout_assets.tpl', import.meta.url);
|
|
const adminUrl = new URL('../public/cloud/admin.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, taskTitle } = 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'));
|
|
}
|
|
|
|
// A long polling interval is clipped to the remaining absolute observation
|
|
// budget. Stopping at the deadline must not wait for the full next interval.
|
|
{
|
|
class ClockSurface extends EventTarget {
|
|
constructor(now) {
|
|
super();
|
|
this.now = now;
|
|
this.visibilityState = 'visible';
|
|
this.nextId = 1;
|
|
this.timers = new Map();
|
|
}
|
|
setTimeout(callback, delay) {
|
|
const id = this.nextId++;
|
|
this.timers.set(id, { callback, due: this.now + delay });
|
|
return id;
|
|
}
|
|
clearTimeout(id) { this.timers.delete(id); }
|
|
async runNext() {
|
|
const pending = [...this.timers.entries()]
|
|
.sort((left, right) => left[1].due - right[1].due)[0];
|
|
assert.ok(pending, 'fake clock has no pending timer');
|
|
const [id, timer] = pending;
|
|
this.timers.delete(id);
|
|
this.now = timer.due;
|
|
timer.callback();
|
|
await Promise.resolve();
|
|
await Promise.resolve();
|
|
}
|
|
}
|
|
const originalNow = Date.now;
|
|
const clock = new ClockSurface(10_000);
|
|
const documentRef = new ClockSurface(clock.now);
|
|
Object.defineProperty(documentRef, 'now', {
|
|
get: () => clock.now, set: () => {}, configurable: true,
|
|
});
|
|
Date.now = () => clock.now;
|
|
let requests = 0;
|
|
let stopped = '';
|
|
try {
|
|
const handle = observeTask({ task_id: '92', status_url: '/api/v1/tasks/92' }, {
|
|
documentRef,
|
|
windowRef: clock,
|
|
fetchImpl: async () => {
|
|
requests += 1;
|
|
return { status: 202, ok: true, json: async () => ({ id: '92', completed: false }) };
|
|
},
|
|
delays: [30_000],
|
|
maxDurationMs: 1000,
|
|
requestTimeoutMs: 1000,
|
|
onStop: reason => { stopped = reason; },
|
|
});
|
|
await clock.runNext();
|
|
await Promise.resolve();
|
|
await clock.runNext();
|
|
assert.equal(await handle.done, null);
|
|
assert.equal(stopped, 'deadline');
|
|
assert.equal(clock.now, 11_000);
|
|
assert.equal(requests, 1);
|
|
} finally {
|
|
Date.now = originalNow;
|
|
}
|
|
}
|
|
|
|
// 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 }),
|
|
);
|
|
}
|
|
|
|
// Task titles must use the server-owned Chinese presentation label. Internal
|
|
// protocol identifiers are useful for diagnostics, but must never leak into
|
|
// the ordinary drawer title when the label is absent or malformed.
|
|
{
|
|
assert.equal(taskTitle({
|
|
kind: 'instance_settings', kind_label: '实例设置',
|
|
}), '实例设置');
|
|
assert.equal(taskTitle({
|
|
kind: 'instance_settings', kind_label: '重置 root 密码',
|
|
action: 'instance_settings', action_label: null,
|
|
}), '重置 root 密码');
|
|
assert.equal(taskTitle({
|
|
kind: 'action', kind_label: '开机', action: 'start', action_label: '开机',
|
|
}), '开机');
|
|
assert.equal(taskTitle({
|
|
kind: 'unknown_internal_job', action: 'unknown_internal_action', type: 'legacy_type',
|
|
}), '后台任务');
|
|
}
|
|
|
|
// 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.match(source, /raw\?\.kind === 'host_storage_configure'/);
|
|
assert.match(source, /旧存储任务已终止且不会重放/);
|
|
assert.doesNotMatch(source, /重试任务|重新提交任务|data-task-retry/);
|
|
|
|
const appSource = await readFile(appUrl, 'utf8');
|
|
const layoutAssets = await readFile(layoutAssetsUrl, 'utf8');
|
|
const assetVersion = layoutAssets.match(/venix_asset_version value='([0-9]+)'/)?.[1];
|
|
assert.ok(assetVersion, 'The shared cloud asset version is missing.');
|
|
assert.match(appSource, new RegExp(`task-center\\.js\\?v=${assetVersion}`));
|
|
}
|
|
|
|
// Host storage observation is finite, resumes from the persisted task receipt
|
|
// when the drawer is reopened, and only refreshes with GET after it stops.
|
|
{
|
|
const source = await readFile(adminUrl, 'utf8');
|
|
assert.match(source, /payload\.state === 'applying' && payload\.task_id && payload\.status_url/);
|
|
assert.match(source, /maxDurationMs:\s*300000/);
|
|
assert.match(source, /reason !== 'deadline'/);
|
|
assert.match(source, /refreshHostStorageAfterTask/);
|
|
assert.match(source, /stopHostStorageObserver\('drawer-close'\)/);
|
|
assert.match(source, /stopHostStorageObserver\('drawer-reopen'\)/);
|
|
assert.doesNotMatch(source, /任务可能仍在后台执行;当前配置保持锁定/);
|
|
}
|
|
|
|
// 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*</);
|
|
}
|
|
|
|
console.log('Cloud task observer behavior tests passed.');
|