统一全系统资源加载、轻量趋势与缓存恢复

This commit is contained in:
2026-11-02 09:54:01 +08:00
parent 8b8f9b7728
commit b711327c8e
58 changed files with 3150 additions and 661 deletions
+48 -33
View File
@@ -1,12 +1,12 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { api } from './api';
import { WORKSPACE_INVALIDATED } from './pageCache';
import { WORKSPACE_INVALIDATED, usePageCache } from './pageCache';
import type { DataWorkflowOperation } from './NoCodeDataTypes';
import { useVisiblePolling } from './useVisiblePolling';
type StoredOperation = { operationId: string; startedAt: string };
const storageKey = (slot: string) => `quality-data-workflow:${slot}`;
const isPending = (value: DataWorkflowOperation | null) => value && ['QUEUED', 'RUNNING'].includes(String(value.status).toUpperCase());
const delay = (ms: number) => new Promise(resolve => window.setTimeout(resolve, ms));
export function operationError(value: DataWorkflowOperation | null): string {
const errors = Array.isArray(value?.errors) ? value.errors : [];
@@ -14,14 +14,25 @@ export function operationError(value: DataWorkflowOperation | null): string {
}
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
const { active } = usePageCache();
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
const [operationId, setOperationId] = useState('');
const [error, setError] = useState('');
const [pollRevision, setPollRevision] = useState(0);
const [starting, setStarting] = useState(false);
const callbackRef = useRef(onComplete);
const activeRef = useRef(0);
const startPromiseRef = useRef<Promise<DataWorkflowOperation> | null>(null);
const pollRequestRef = useRef<Promise<void> | null>(null);
const terminalHandledRef = useRef(new Set<string>());
const generationRef = useRef(0);
const mountedRef = useRef(false);
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
useEffect(() => {
mountedRef.current = true;
let pending: StoredOperation | null = null;
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
if (pending?.operationId) setOperationId(pending.operationId);
return () => { mountedRef.current = false; generationRef.current++; };
}, [slot]);
const savePendingId = useCallback((value: StoredOperation | null) => {
try {
@@ -30,35 +41,36 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
} catch { /* storage may be unavailable in a restricted browser context */ }
}, [slot]);
const poll = useCallback(async (operationId: string) => {
const runId = ++activeRef.current;
setError('');
while (activeRef.current === runId) {
const poll = useCallback((id: string) => {
if (!id || terminalHandledRef.current.has(id) || pollRequestRef.current) return pollRequestRef.current || Promise.resolve();
const generation = generationRef.current;
const attempt = (async () => {
try {
const current = await api.dataWorkflowOperation(operationId);
if (activeRef.current !== runId) return;
const current = await api.dataWorkflowOperation(id);
if (!mountedRef.current || generation !== generationRef.current) return;
setOperation(current);
setError('');
const status = String(current.status || '').toUpperCase();
if (status === 'COMPLETED' || status === 'FAILED') {
if (status === 'COMPLETED') { savePendingId(null); window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); callbackRef.current?.(current); }
else setError(operationError(current));
return;
terminalHandledRef.current.add(id);
generationRef.current++;
setOperationId('');
if (status === 'COMPLETED') {
savePendingId(null);
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration'] } }));
callbackRef.current?.(current);
} else setError(operationError(current));
}
} catch (value) {
if (activeRef.current !== runId) return;
if (!mountedRef.current || generation !== generationRef.current) return;
setError(value instanceof Error ? value.message : '处理进度读取失败');
return;
}
await delay(900);
}
})().finally(() => { if (pollRequestRef.current === attempt) pollRequestRef.current = null; });
pollRequestRef.current = attempt;
return attempt;
}, [savePendingId]);
useEffect(() => {
let pending: StoredOperation | null = null;
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
if (pending?.operationId) void poll(pending.operationId);
return () => { activeRef.current++; };
}, [poll, slot, pollRevision]);
useVisiblePolling(() => poll(operationId), 2000, active && Boolean(operationId), true);
const start = useCallback(async (create: () => Promise<DataWorkflowOperation>) => {
if (startPromiseRef.current) return startPromiseRef.current;
@@ -69,9 +81,11 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
try {
const started = await create();
if (!started?.operationId) throw new Error('服务端未返回操作编号');
generationRef.current++;
setOperation(started);
terminalHandledRef.current.delete(started.operationId);
setOperationId(started.operationId);
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
void poll(started.operationId);
return started;
} catch (value) {
setError(value instanceof Error ? value.message : '操作未能开始');
@@ -83,18 +97,19 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
})();
startPromiseRef.current = attempt;
return attempt;
}, [operation, poll, savePendingId]);
}, [operation, savePendingId]);
const resume = useCallback(() => {
if (operation?.operationId) void poll(operation.operationId);
else {
let pending: StoredOperation | null = null;
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
if (pending?.operationId) void poll(pending.operationId);
else setPollRevision(value => value + 1);
}
const id = operation?.operationId || (() => {
try { return (JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null)?.operationId || ''; }
catch { return ''; }
})();
if (id) { setError(''); setOperationId(id); void poll(id); }
}, [operation?.operationId, poll, slot]);
const clear = useCallback(() => { activeRef.current++; setOperation(null); setError(''); savePendingId(null); }, [savePendingId]);
const clear = useCallback(() => {
generationRef.current++;
setOperation(null); setOperationId(''); setError(''); savePendingId(null);
}, [savePendingId]);
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
}