Files
quality_analyse/web/src/useDataWorkflowOperation.ts
T

116 lines
5.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<DataWorkflowOperation | null>(null);
const [operationId, setOperationId] = useState('');
const [error, setError] = useState('');
const [starting, setStarting] = useState(false);
const callbackRef = useRef(onComplete);
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 {
if (value) localStorage.setItem(storageKey(slot), JSON.stringify(value));
else 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(current);
setError('');
const status = String(current.status || '').toUpperCase();
if (status === 'COMPLETED' || status === 'FAILED') {
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 (!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<DataWorkflowOperation>) => {
if (startPromiseRef.current) return startPromiseRef.current;
if (isPending(operation)) return operation;
const attempt = (async () => {
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++;
setOperation(null); setOperationId(''); setError(''); savePendingId(null);
}, [savePendingId]);
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
}