import { useRef, useEffect } from "react"; import API_CONFIG from "../../../config/api"; export const useBenchmarkPolling = ( sessionId, setGenerationLogs, setGenerationComplete, onComplete ) => { const pollingIntervalRef = useRef(null); const startPolling = () => { if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); } pollingIntervalRef.current = setInterval(async () => { try { const logsResponse = await fetch( `${API_CONFIG.BASE_URL}/benchmark-progress/${sessionId}` ); if (logsResponse.ok) { const logsResult = await logsResponse.json(); if (logsResult.logs) { setGenerationLogs((prevLogs) => { if (logsResult.logs.length > prevLogs.length) { return logsResult.logs; } return prevLogs; }); } // Vérifier s'il y a des erreurs dans les logs const hasError = logsResult.logs.some( (log) => log.includes("Error") || log.includes("ERROR") || log.includes("Failed") || log.includes("RATE_LIMIT_EXCEEDED") || log.includes("heavy load") || log.includes("rate limit") ); if (hasError) { setGenerationComplete(true); clearInterval(pollingIntervalRef.current); if (onComplete) { onComplete({ success: false, error: "An error occurred during benchmark generation. Please try again later.", sessionId, }); } return; } if (logsResult.is_completed) { setGenerationComplete(true); clearInterval(pollingIntervalRef.current); if (onComplete) { onComplete({ success: true, sessionId, logs: logsResult.logs, }); } } } else { const errorData = await logsResponse.json(); setGenerationComplete(true); clearInterval(pollingIntervalRef.current); if (onComplete) { onComplete({ success: false, error: errorData.error || "Unknown error", sessionId, }); } } } catch (error) { setGenerationComplete(true); clearInterval(pollingIntervalRef.current); if (onComplete) { onComplete({ success: false, error: error.message, sessionId, }); } } }, 2000); }; useEffect(() => { return () => { if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); } }; }, []); return { startPolling }; };