100 lines
4.4 KiB
TypeScript
100 lines
4.4 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react';
|
||
import { api } from './api';
|
||
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
||
|
||
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 : [];
|
||
return errors.map(item => item?.message).filter(Boolean).join(';') || '操作未完成,请重试';
|
||
}
|
||
|
||
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
|
||
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
|
||
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);
|
||
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
|
||
|
||
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(async (operationId: string) => {
|
||
const runId = ++activeRef.current;
|
||
setError('');
|
||
while (activeRef.current === runId) {
|
||
try {
|
||
const current = await api.dataWorkflowOperation(operationId);
|
||
if (activeRef.current !== runId) return;
|
||
setOperation(current);
|
||
const status = String(current.status || '').toUpperCase();
|
||
if (status === 'COMPLETED' || status === 'FAILED') {
|
||
if (status === 'COMPLETED') { savePendingId(null); callbackRef.current?.(current); }
|
||
else setError(operationError(current));
|
||
return;
|
||
}
|
||
} catch (value) {
|
||
if (activeRef.current !== runId) return;
|
||
setError(value instanceof Error ? value.message : '处理进度读取失败');
|
||
return;
|
||
}
|
||
await delay(900);
|
||
}
|
||
}, [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]);
|
||
|
||
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('服务端未返回操作编号');
|
||
setOperation(started);
|
||
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
|
||
void poll(started.operationId);
|
||
return started;
|
||
} catch (value) {
|
||
setError(value instanceof Error ? value.message : '操作未能开始');
|
||
throw value;
|
||
} finally {
|
||
startPromiseRef.current = null;
|
||
setStarting(false);
|
||
}
|
||
})();
|
||
startPromiseRef.current = attempt;
|
||
return attempt;
|
||
}, [operation, poll, 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);
|
||
}
|
||
}, [operation?.operationId, poll, slot]);
|
||
|
||
const clear = useCallback(() => { activeRef.current++; setOperation(null); setError(''); savePendingId(null); }, [savePendingId]);
|
||
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
|
||
}
|