refactor(admin): consolidate instance action lifecycle
parent
ad68a5bef1
commit
579be14f1a
@ -0,0 +1,77 @@
|
||||
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
||||
function versionedModuleUrl(path) {
|
||||
const url = new URL(path, import.meta.url);
|
||||
if (assetVersion) url.searchParams.set('v', assetVersion);
|
||||
return url.href;
|
||||
}
|
||||
const taskRuntime = await import(versionedModuleUrl('./task-observer.js'));
|
||||
|
||||
// Own the instance action contract: safe transport, receipt announcement,
|
||||
// terminal interpretation and fence messages. Polling remains in task-observer.
|
||||
export function createAdminInstanceActions({
|
||||
runtimeFactory = globalThis.VenixAdminRequestRuntime?.create,
|
||||
tasks = taskRuntime,
|
||||
...transportOptions
|
||||
} = {}) {
|
||||
if (typeof runtimeFactory !== 'function') {
|
||||
throw new TypeError('administrator request runtime is unavailable');
|
||||
}
|
||||
const runtime = runtimeFactory({ ...transportOptions, taskReceiptValidator: tasks.taskUrl });
|
||||
|
||||
function failureMessage(task, fallback) {
|
||||
const recoveryNotice = tasks.recoveryTaskFailureNotice(task);
|
||||
if (recoveryNotice) return recoveryNotice;
|
||||
const message = task?.error || fallback;
|
||||
if (task?.effect_may_have_applied) {
|
||||
return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并将任务编号交由管理员核查。`;
|
||||
}
|
||||
return task?.safe_to_resubmit === false
|
||||
? `${message} 任务已失败且相关资源已锁定,请勿再次提交,并联系管理员核查。` : message;
|
||||
}
|
||||
|
||||
function blockMessage(task, action) {
|
||||
if (task?.blocks_mutation !== true) return '';
|
||||
const id = task?.id || '—';
|
||||
if (task.completed === false && task.status === 'active') {
|
||||
return `实例已有任务 #${id}(执行中),完成前不能${action}。`;
|
||||
}
|
||||
if (task.completed === true && task.recovery?.pending === true) {
|
||||
const code = String(task.recovery?.code || task.finalization_error_code || '');
|
||||
if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') {
|
||||
return `任务 #${id} 的派发账本异常,资源保持安全锁定;修复账本并完成核验前不能${action}。`;
|
||||
}
|
||||
if (task.dispatch_state === 'not_dispatched') {
|
||||
return `任务 #${id} 已确认未派发到宿主机,但 PHP 本地账本收尾尚未完成;收尾成功前不能${action}。`;
|
||||
}
|
||||
return `任务 #${id} 尚在持续恢复,资源保持安全锁定;恢复收敛前不能${action}。`;
|
||||
}
|
||||
if (task.completed === true && task.status === 'failed') {
|
||||
return `任务 #${id} 已失败,资源安全锁定,需管理员人工处理后才能${action}。`;
|
||||
}
|
||||
return `任务 #${id} 状态协议无效,资源安全锁定,需管理员人工处理后才能${action}。`;
|
||||
}
|
||||
|
||||
function watch(receipt, { title, onResult, ...options }) {
|
||||
tasks.announceTaskAccepted(receipt, { title });
|
||||
return tasks.observeTask(receipt, {
|
||||
...options,
|
||||
onTerminal(task) {
|
||||
const succeeded = tasks.taskSucceededWithoutRecovery(task);
|
||||
const label = `${title}任务 #${receipt.task_id || '—'}`;
|
||||
onResult?.({ task, succeeded, message: succeeded ? `${label} 已成功。`
|
||||
: failureMessage(task, `${label} 执行失败。`) });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
read: (path, controller) => runtime.read(path, { signal: controller?.signal, timeoutMs: 30000 }),
|
||||
commit: (path, body, controller, method = 'POST') => runtime.mutate(path, {
|
||||
method, body, signal: controller?.signal, response: 'json',
|
||||
}),
|
||||
enqueue: (path, body, controller, method = 'PATCH') => runtime.mutate(path, {
|
||||
method, body, signal: controller?.signal, response: 'task',
|
||||
}),
|
||||
watch, blockMessage,
|
||||
});
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
export function createAdminInstanceTransport({
|
||||
taskUrl,
|
||||
fetchImpl = globalThis.fetch?.bind(globalThis),
|
||||
locationImpl = globalThis.location,
|
||||
csrfToken = () => globalThis.ADMIN_CSRF_TOKEN || '',
|
||||
timeoutMs = 30000,
|
||||
runtimeFactory = globalThis.VenixAdminRequestRuntime?.create,
|
||||
} = {}) {
|
||||
if (typeof taskUrl !== 'function') throw new TypeError('taskUrl is required');
|
||||
if (typeof runtimeFactory !== 'function') {
|
||||
throw new TypeError('administrator request runtime is unavailable');
|
||||
}
|
||||
|
||||
const runtime = runtimeFactory({
|
||||
fetchImpl, locationImpl, csrfToken, taskReceiptValidator: taskUrl,
|
||||
});
|
||||
|
||||
function read(path, controller) {
|
||||
return runtime.read(path, { signal: controller.signal, timeoutMs });
|
||||
}
|
||||
|
||||
function mutate(path, body, controller, method = 'PATCH') {
|
||||
return runtime.mutate(path, {
|
||||
method, body, signal: controller.signal, timeoutMs, response: 'task',
|
||||
});
|
||||
}
|
||||
|
||||
function mutateJson(path, body, controller, method = 'POST') {
|
||||
return runtime.mutate(path, {
|
||||
method, body, signal: controller.signal, timeoutMs, response: 'json',
|
||||
});
|
||||
}
|
||||
|
||||
return Object.freeze({ read, mutate, mutateJson });
|
||||
}
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026103125' scope='global'}
|
||||
{assign var=venix_asset_version value='2026103126' scope='global'}
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import vm from 'node:vm';
|
||||
|
||||
globalThis.location = new URL('https://panel.test/admin/instances');
|
||||
const tasks = await import('../public/cloud/task-observer.js');
|
||||
const { createAdminInstanceActions } = await import('../public/cloud/admin-instance-actions.js');
|
||||
const context = { Headers, AbortController, setTimeout, clearTimeout };
|
||||
vm.runInNewContext(await readFile(new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8'), context);
|
||||
|
||||
const calls = [];
|
||||
let response = { status: 202, ok: true, json: async () => ({ task_id: '42', status_url: '/api/v1/tasks/42' }) };
|
||||
let observation;
|
||||
let announced = 0;
|
||||
const actions = createAdminInstanceActions({
|
||||
runtimeFactory: context.VenixAdminRequestRuntime.create,
|
||||
fetchImpl: async (path, options) => { calls.push({ path, options }); return response; },
|
||||
locationImpl: globalThis.location,
|
||||
csrfToken: () => 'a'.repeat(64),
|
||||
tasks: { ...tasks, announceTaskAccepted() { announced += 1; },
|
||||
observeTask(receipt, options) { observation = options; return { url: receipt.status_url, stop() {} }; } },
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const receipt = await actions.enqueue('/api/v1/admin/instances/1/settings', { confirm_restart: true }, controller);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].options.method, 'PATCH');
|
||||
assert.equal(calls[0].options.headers.get('X-Admin-CSRF-Token'), 'a'.repeat(64));
|
||||
assert.ok(calls[0].options.headers.get('Idempotency-Key'));
|
||||
|
||||
let result;
|
||||
actions.watch(receipt, { title: '修改设置', onResult(value) { result = value; } });
|
||||
assert.equal(announced, 1);
|
||||
observation.onTerminal(tasks.normalizeTask({ id: '42', completed: true, status: 'succeeded' }));
|
||||
assert.equal(result.succeeded, true);
|
||||
observation.onTerminal(tasks.normalizeTask({ id: '42', completed: true, status: 'failed',
|
||||
effect_may_have_applied: true, safe_to_resubmit: false, error: '网络中断' }));
|
||||
assert.equal(result.succeeded, false);
|
||||
assert.match(result.message, /请勿再次提交/);
|
||||
observation.onTerminal(tasks.normalizeTask({ id: '42', completed: true, status: 'succeeded',
|
||||
recovery: { pending: true, message: '本地账本收尾中',
|
||||
last_checked_at: 1600000000, next_check_at: 1600000300 } }));
|
||||
assert.equal(result.succeeded, false, 'A successful host receipt with pending recovery must not unlock the UI.');
|
||||
|
||||
response = { status: 200, ok: true, json: async () => ({ task_id: '42', status_url: '/api/v1/tasks/42' }) };
|
||||
await assert.rejects(actions.enqueue('/api/task', {}, controller, 'POST'), error =>
|
||||
error.code === 'invalid_task_receipt' && error.mutationMayHaveApplied && !error.safeToRetry);
|
||||
assert.equal(calls.length, 2, 'A malformed receipt must not replay the mutation.');
|
||||
response = { status: 200, ok: true, json: async () => ({ deleted: true }) };
|
||||
assert.equal((await actions.commit('/api/backup/1', undefined, controller, 'DELETE')).deleted, true);
|
||||
assert.equal(calls[2].options.method, 'DELETE');
|
||||
await actions.read('/api/backup', controller);
|
||||
assert.equal(calls[3].options.method, 'GET');
|
||||
assert.equal(calls[3].options.headers.get('Idempotency-Key'), null);
|
||||
assert.equal(actions.blockMessage({ blocks_mutation: false }, '恢复'), '');
|
||||
assert.match(actions.blockMessage({ id: '42', blocks_mutation: true, completed: true,
|
||||
recovery: { pending: true }, dispatch_state: 'not_dispatched' }, '恢复'), /PHP 本地账本收尾尚未完成/);
|
||||
assert.match(actions.blockMessage({ id: '42', blocks_mutation: true, completed: false, status: 'active' }, '恢复'), /执行中/);
|
||||
console.log('Administrator instance action submission, observation and fence behavior passed.');
|
||||
Loading…
Reference in New Issue