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.
351 lines
15 KiB
JavaScript
351 lines
15 KiB
JavaScript
const TERMINAL_STATES = new Set(['succeeded', 'failed']);
|
|
// Administrator pages also use this transport module but deliberately do not
|
|
// load the user-locale runtime. Their Chinese-only fallback is not a target
|
|
// translation; ordinary user pages resolve these keys from the publication.
|
|
const adminFallback = Object.freeze({
|
|
'common.tasks.error.protocol': '任务状态协议无效,请联系管理员核查。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.error.invalid_response': '任务状态服务返回了无效数据。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.error.http': '任务状态读取失败(状态码 {status})。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.error.execution_failed': '任务执行失败。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.recovery.continuing': '持续自动核对', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.resolved.partial': '原任务失败;系统已确认部分宿主机已应用、部分未应用,未确认状态已收敛,资源锁已解除。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.resolved.applied': '原任务失败,但系统已确认操作已应用,资源锁已解除。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
'common.tasks.resolved.not_applied': '原任务失败,但系统已确认操作未应用,资源锁已解除。', // user-copy: allow admin-compatibility shared administrator task transport fallback
|
|
});
|
|
const hasUserCopyRuntime = typeof globalThis.VenixUserCopy?.text === 'function';
|
|
const i18n = hasUserCopyRuntime ? globalThis.VenixUserCopy : {
|
|
text(key, parameters = {}) {
|
|
return (adminFallback[key] || key).replace(/\{([a-z_]+)\}/g,
|
|
(match, name) => Object.prototype.hasOwnProperty.call(parameters, name)
|
|
? String(parameters[name]) : match);
|
|
},
|
|
};
|
|
const RESOLVED_EFFECT_STATES = new Set(['applied', 'not_applied']);
|
|
// The longest server-side absolute deadline is 145 minutes. Keep foreground
|
|
// GET observation finite while allowing enough time to receive that terminal
|
|
// result; this never retries the mutation itself.
|
|
const DEFAULT_OBSERVATION_BUDGET_MS = 9_300_000;
|
|
|
|
function asObject(value) {
|
|
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
}
|
|
|
|
function firstText(...values) {
|
|
for (const value of values) {
|
|
if (value !== null && value !== undefined && String(value).trim() !== '') return String(value).trim();
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function taskErrorText(raw, status) {
|
|
if (hasUserCopyRuntime) {
|
|
return status === 'failed' ? i18n.text('common.tasks.error.execution_failed') : '';
|
|
}
|
|
return firstText(raw.error); // user-copy: allow admin-compatibility shared administrator task diagnostics
|
|
}
|
|
|
|
function recoveryMessageText(candidate) {
|
|
if (hasUserCopyRuntime) return i18n.text('common.tasks.recovery.continuing');
|
|
return firstText(candidate.message); // user-copy: allow admin-compatibility shared administrator recovery diagnostics
|
|
}
|
|
|
|
function responseErrorText(payload, status) {
|
|
if (hasUserCopyRuntime) return i18n.text('common.tasks.error.http', { status });
|
|
return firstText(payload?.error, payload?.message, payload?.detail) // user-copy: allow admin-compatibility shared administrator HTTP diagnostics
|
|
|| i18n.text('common.tasks.error.http', { status });
|
|
}
|
|
|
|
function taskIdentifier(value) {
|
|
const normalized = typeof value === 'string' ? value.trim()
|
|
: (typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? String(value) : '');
|
|
return /^[1-9][0-9]{0,18}$/.test(normalized) ? normalized : '';
|
|
}
|
|
|
|
function protocolFailureTask(raw) {
|
|
return {
|
|
id: taskIdentifier(raw.id),
|
|
status: 'failed',
|
|
terminal: true,
|
|
completed: true,
|
|
effect_may_have_applied: true,
|
|
effect_resolution: null,
|
|
effect_scope: null,
|
|
recovery: null,
|
|
safe_to_resubmit: false,
|
|
error: i18n.text('common.tasks.error.protocol'),
|
|
error_code: 'task_protocol_invalid',
|
|
result: raw.result ?? null,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Validate the deliberately small public task contract without translating
|
|
* backend/internal workflow states. A non-terminal task is always represented
|
|
* locally as "running". Any malformed state is a protocol failure whose effect
|
|
* may already exist; it is never
|
|
* presented as an activity that the user should resubmit.
|
|
*/
|
|
export function normalizeTask(payload) {
|
|
const envelope = asObject(payload);
|
|
const raw = envelope;
|
|
const id = taskIdentifier(raw.id);
|
|
const rawStatus = typeof raw.status === 'string' ? raw.status : '';
|
|
const hasStatus = Object.prototype.hasOwnProperty.call(raw, 'status');
|
|
const validRunning = Boolean(id) && raw.completed === false && !hasStatus;
|
|
const validTerminal = Boolean(id) && raw.completed === true && TERMINAL_STATES.has(rawStatus);
|
|
const protocolFailure = !validRunning && !validTerminal;
|
|
if (protocolFailure) return protocolFailureTask(raw);
|
|
const terminal = !validRunning;
|
|
const status = validRunning ? 'running' : rawStatus;
|
|
|
|
const effectMayHaveApplied = raw.effect_may_have_applied === true;
|
|
let effectResolution = status === 'failed' && effectMayHaveApplied
|
|
&& Object.prototype.hasOwnProperty.call(raw, 'effect_resolution')
|
|
&& RESOLVED_EFFECT_STATES.has(raw.effect_resolution)
|
|
? raw.effect_resolution : null;
|
|
let effectScope = effectResolution === 'applied'
|
|
&& Object.prototype.hasOwnProperty.call(raw, 'effect_scope')
|
|
&& raw.effect_scope === 'partial' ? 'partial' : null;
|
|
const safeValue = raw.safe_to_resubmit;
|
|
const safeToResubmit = status === 'failed' && !effectMayHaveApplied && safeValue === true;
|
|
let recovery = null;
|
|
if (terminal && Object.prototype.hasOwnProperty.call(raw, 'recovery')) {
|
|
const candidate = asObject(raw.recovery);
|
|
const rawRecoveryMessage = typeof candidate.message === 'string'
|
|
? candidate.message.trim() : '';
|
|
const timestamp = value => value === null
|
|
? null
|
|
: (Number.isSafeInteger(value) && value > 0 ? value : undefined);
|
|
const lastCheckedAt = timestamp(candidate.last_checked_at);
|
|
const nextCheckAt = timestamp(candidate.next_check_at);
|
|
if (candidate.pending === true && rawRecoveryMessage
|
|
&& rawRecoveryMessage.length <= 400
|
|
&& lastCheckedAt !== undefined && nextCheckAt !== undefined) {
|
|
recovery = {
|
|
pending: true,
|
|
message: recoveryMessageText(candidate),
|
|
last_checked_at: lastCheckedAt,
|
|
next_check_at: nextCheckAt,
|
|
};
|
|
// A later dispatch-ledger or finalization incident can make an otherwise
|
|
// resolved failed task unsafe again. The live recovery fence is the
|
|
// authoritative UI state until the backend clears that incident.
|
|
effectResolution = null;
|
|
effectScope = null;
|
|
}
|
|
}
|
|
|
|
return {
|
|
id,
|
|
status,
|
|
terminal,
|
|
completed: terminal,
|
|
effect_may_have_applied: effectMayHaveApplied,
|
|
effect_resolution: effectResolution,
|
|
effect_scope: effectScope,
|
|
recovery,
|
|
safe_to_resubmit: safeToResubmit,
|
|
error: taskErrorText(raw, status),
|
|
error_code: firstText(raw.error_code),
|
|
result: raw.result ?? null,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Explain a converged effect without rewriting the immutable failed task.
|
|
* Callers still render its failed status, but use this notice instead of the
|
|
* now-stale unknown-effect error that said the resource fence was active.
|
|
*/
|
|
export function resolvedTaskFailureNotice(task) {
|
|
if (task?.status !== 'failed' || task?.effect_may_have_applied !== true
|
|
|| task?.recovery?.pending === true) return '';
|
|
if (task.effect_resolution === 'applied' && task.effect_scope === 'partial') {
|
|
return i18n.text('common.tasks.resolved.partial');
|
|
}
|
|
if (task.effect_resolution === 'applied') {
|
|
return i18n.text('common.tasks.resolved.applied');
|
|
}
|
|
if (task.effect_resolution === 'not_applied') {
|
|
return i18n.text('common.tasks.resolved.not_applied');
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/** Explain a pending recovery or fail-closed ledger incident safely. */
|
|
export function recoveryTaskFailureNotice(task) {
|
|
if (task?.terminal !== true || task?.recovery?.pending !== true) return '';
|
|
return firstText(task.recovery.message);
|
|
}
|
|
|
|
/** A terminal success is actionable only after every recovery fence clears. */
|
|
export function taskSucceededWithoutRecovery(task) {
|
|
return task?.terminal === true && task?.status === 'succeeded'
|
|
&& task?.recovery?.pending !== true;
|
|
}
|
|
|
|
export function taskUrl(receipt) {
|
|
const value = asObject(receipt);
|
|
const keys = Object.keys(value).sort();
|
|
if (keys.length !== 2 || keys[0] !== 'status_url' || keys[1] !== 'task_id') return '';
|
|
const id = taskIdentifier(value.task_id);
|
|
const supplied = firstText(value.status_url);
|
|
if (!id || !supplied) return '';
|
|
const expected = `/api/v1/tasks/${encodeURIComponent(id)}`;
|
|
if (typeof location === 'undefined') return '';
|
|
try {
|
|
const url = new URL(supplied, location.href);
|
|
if (url.origin !== location.origin || url.search || url.hash
|
|
|| !/^\/api\/v1\/tasks\/[^/]+$/.test(url.pathname)) return '';
|
|
if (expected && url.pathname !== expected) return '';
|
|
return url.pathname;
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
function directTaskUrl(value) {
|
|
const path = firstText(value);
|
|
return /^\/api\/v1\/tasks\/[1-9][0-9]{0,18}$/.test(path) ? path : '';
|
|
}
|
|
|
|
export async function readTask(url, { fetchImpl = fetch, signal } = {}) {
|
|
const response = await fetchImpl(url, {
|
|
method: 'GET', headers: { Accept: 'application/json' }, credentials: 'same-origin',
|
|
cache: 'no-store', signal,
|
|
});
|
|
let payload = null;
|
|
if (response.status !== 204) {
|
|
try { payload = await response.json(); }
|
|
catch { throw new Error(i18n.text('common.tasks.error.invalid_response')); }
|
|
}
|
|
if (!response.ok) {
|
|
const error = new Error(responseErrorText(payload, response.status));
|
|
error.status = response.status;
|
|
throw error;
|
|
}
|
|
const task = normalizeTask(payload);
|
|
if ((response.status === 202 && !task.terminal) || (response.status === 200 && task.terminal)) return task;
|
|
return protocolFailureTask(asObject(payload));
|
|
}
|
|
|
|
/**
|
|
* Observe one accepted task with GET only. Requests are serialized, bounded by
|
|
* an absolute deadline, aborted while the page is hidden, and stopped on
|
|
* pagehide. Stopping observation never changes or resubmits the server task.
|
|
*/
|
|
export function observeTask(receipt, options = {}) {
|
|
const url = typeof receipt === 'string' ? directTaskUrl(receipt) : taskUrl(receipt);
|
|
const documentRef = options.documentRef || (typeof document === 'undefined' ? null : document);
|
|
const windowRef = options.windowRef || (typeof window === 'undefined' ? null : window);
|
|
const fetchImpl = options.fetchImpl || fetch;
|
|
const delays = Array.isArray(options.delays) && options.delays.length
|
|
? options.delays.map(value => Math.max(0, Number(value) || 0)) : [2000, 5000, 15000, 30000];
|
|
const maxDurationMs = Math.max(1000,
|
|
Number(options.maxDurationMs) || DEFAULT_OBSERVATION_BUDGET_MS);
|
|
const requestTimeoutMs = Math.max(1000, Number(options.requestTimeoutMs) || 12000);
|
|
const startedAt = Date.now();
|
|
let attempt = 0;
|
|
let timer = null;
|
|
let request = null;
|
|
let stopped = false;
|
|
let inFlight = false;
|
|
let finishPromise;
|
|
let finish;
|
|
const done = new Promise(resolve => { finish = resolve; });
|
|
|
|
const hidden = () => documentRef?.visibilityState === 'hidden';
|
|
const clearTimer = () => {
|
|
if (timer !== null) (windowRef || globalThis).clearTimeout(timer);
|
|
timer = null;
|
|
};
|
|
const cleanup = () => {
|
|
clearTimer();
|
|
documentRef?.removeEventListener?.('visibilitychange', visibilityChanged);
|
|
windowRef?.removeEventListener?.('pagehide', pageHidden);
|
|
};
|
|
const stop = (reason = 'stopped') => {
|
|
if (stopped) return;
|
|
stopped = true;
|
|
request?.abort(reason);
|
|
request = null;
|
|
cleanup();
|
|
try { options.onStop?.(reason); }
|
|
finally { finish?.(null); }
|
|
};
|
|
const schedule = delay => {
|
|
clearTimer();
|
|
if (stopped || hidden()) return;
|
|
const elapsed = Date.now() - startedAt;
|
|
if (elapsed >= maxDurationMs) return stop('deadline');
|
|
const boundedDelay = Math.min(
|
|
Math.max(0, delay),
|
|
Math.max(0, maxDurationMs - elapsed),
|
|
);
|
|
timer = (windowRef || globalThis).setTimeout(() => {
|
|
timer = null;
|
|
void tick();
|
|
}, boundedDelay);
|
|
};
|
|
const visibilityChanged = () => {
|
|
if (hidden()) {
|
|
clearTimer();
|
|
request?.abort('hidden');
|
|
return;
|
|
}
|
|
if (!stopped && !inFlight) schedule(0);
|
|
};
|
|
const pageHidden = () => stop('pagehide');
|
|
|
|
async function tick() {
|
|
if (stopped || inFlight || hidden()) return;
|
|
if (!url) return stop('missing-task-id');
|
|
if (Date.now() - startedAt >= maxDurationMs) return stop('deadline');
|
|
inFlight = true;
|
|
const controller = new AbortController();
|
|
request = controller;
|
|
const timeout = (windowRef || globalThis).setTimeout(() => controller.abort('timeout'), requestTimeoutMs);
|
|
try {
|
|
const task = await readTask(url, { fetchImpl, signal: controller.signal });
|
|
if (stopped || controller.signal.aborted) return;
|
|
options.onUpdate?.(task);
|
|
if (task.terminal) {
|
|
stopped = true;
|
|
cleanup();
|
|
try { options.onTerminal?.(task); }
|
|
finally { finish?.(task); }
|
|
return;
|
|
}
|
|
const delay = delays[Math.min(attempt, delays.length - 1)];
|
|
attempt += 1;
|
|
schedule(delay);
|
|
} catch (error) {
|
|
if (stopped || (controller.signal.aborted && controller.signal.reason === 'hidden')) return;
|
|
options.onReadError?.(error);
|
|
if (error?.status === 401 || error?.status === 403 || error?.status === 404) return stop('unavailable');
|
|
const delay = delays[Math.min(attempt, delays.length - 1)];
|
|
attempt += 1;
|
|
schedule(delay);
|
|
} finally {
|
|
const resumeAfterHidden = controller.signal.aborted && controller.signal.reason === 'hidden';
|
|
(windowRef || globalThis).clearTimeout(timeout);
|
|
if (request === controller) request = null;
|
|
inFlight = false;
|
|
if (resumeAfterHidden && !stopped && !hidden() && timer === null) schedule(0);
|
|
}
|
|
}
|
|
|
|
documentRef?.addEventListener?.('visibilitychange', visibilityChanged);
|
|
windowRef?.addEventListener?.('pagehide', pageHidden, { once: true });
|
|
finishPromise = done;
|
|
schedule(0);
|
|
return { url, stop, done: finishPromise, get active() { return !stopped; } };
|
|
}
|
|
|
|
export function announceTaskAccepted(receipt, detail = {}) {
|
|
if (typeof window === 'undefined' || !taskUrl(receipt)) return false;
|
|
window.dispatchEvent(new CustomEvent('virt-cloud:task-accepted', {
|
|
detail: { id: firstText(receipt?.task_id), ...detail },
|
|
}));
|
|
return true;
|
|
}
|