import { useCallback, useEffect, useRef, useState } from 'react'; import { api } from './api'; 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()); export function operationError(value: DataWorkflowOperation | null): string { const errors = Array.isArray(value?.errors) ? value.errors : []; return errors.map(item => item?.message).filter(Boolean).join(';') || '操作未完成,请重试'; } export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) { const { active } = usePageCache(); const [operation, setOperation] = useState(null); const [operationId, setOperationId] = useState(''); const [error, setError] = useState(''); const [starting, setStarting] = useState(false); const callbackRef = useRef(onComplete); const startPromiseRef = useRef | null>(null); const pollRequestRef = useRef | null>(null); const terminalHandledRef = useRef(new Set()); const generationRef = useRef(0); const mountedRef = useRef(false); const restoredIdRef = useRef(''); 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) { restoredIdRef.current = pending.operationId; setOperationId(pending.operationId); } return () => { mountedRef.current = false; generationRef.current++; }; }, [slot]); const savePendingId = useCallback((value: StoredOperation | null, expectedId?: string) => { try { if (value) localStorage.setItem(storageKey(slot), JSON.stringify(value)); else { // 另一个标签页可能已经启动新任务,旧任务结束不能清掉它的恢复入口。 const stored = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; if (!expectedId || stored?.operationId === expectedId) localStorage.removeItem(storageKey(slot)); } } catch { /* storage may be unavailable in a restricted browser context */ } }, [slot]); 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(id); if (!mountedRef.current || generation !== generationRef.current) return; setOperation(restoredIdRef.current === id ? { ...current, restoredFromPreviousVisit: true } : current); setError(''); const status = String(current.status || '').toUpperCase(); if (status === 'COMPLETED' || status === 'FAILED') { terminalHandledRef.current.add(id); generationRef.current++; setOperationId(''); // 只有未完成任务需要跨刷新恢复;失败详情仍留在本页和服务端历史记录。 savePendingId(null, id); if (status === 'COMPLETED') { 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 (!mountedRef.current || generation !== generationRef.current) return; setError(value instanceof Error ? value.message : '处理进度读取失败'); } })().finally(() => { if (pollRequestRef.current === attempt) pollRequestRef.current = null; }); pollRequestRef.current = attempt; return attempt; }, [savePendingId]); useVisiblePolling(() => poll(operationId), 2000, active && Boolean(operationId), true); const start = useCallback(async (create: () => Promise) => { if (startPromiseRef.current) return startPromiseRef.current; if (isPending(operation)) return operation; const attempt = (async () => { const previousId = operation?.operationId || restoredIdRef.current; if (previousId) savePendingId(null, previousId); generationRef.current++; restoredIdRef.current = ''; setOperation(null); setOperationId(''); setStarting(true); setError(''); 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() }); return started; } catch (value) { setError(value instanceof Error ? value.message : '操作未能开始'); throw value; } finally { startPromiseRef.current = null; setStarting(false); } })(); startPromiseRef.current = attempt; return attempt; }, [operation, savePendingId]); const resume = useCallback(() => { 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(() => { generationRef.current++; restoredIdRef.current = ''; setOperation(null); setOperationId(''); setError(''); savePendingId(null, operation?.operationId); }, [savePendingId, operation?.operationId]); return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear }; }