Spaces:
Running
Running
File size: 6,209 Bytes
c2ea5ed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
import { useState, useCallback, useRef } from "react";
import { api } from "@/lib/api";
interface TaskStatus {
status:
| "pending"
| "running"
| "completed"
| "failed"
| "COMPLETED"
| "FAILED";
progress?: number;
message?: string;
error?: string;
}
interface UseTaskPollingOptions {
onSuccess?: (taskId: string) => void;
onError?: (error: string, taskId: string) => void;
onProgress?: (progress: number, message?: string) => void;
maxAttempts?: number;
interval?: number;
enableExponentialBackoff?: boolean;
}
interface UseTaskPollingReturn {
pollTaskStatus: (taskId: string) => void;
stopPolling: () => void;
isPolling: boolean;
currentAttempts: number;
}
export function useTaskPolling(
options: UseTaskPollingOptions = {}
): UseTaskPollingReturn {
const {
onSuccess,
onError,
onProgress,
maxAttempts = 180, // Maximum 15 minutes with exponential backoff
interval = 5000,
enableExponentialBackoff = true,
} = options;
const [isPolling, setIsPolling] = useState(false);
const [currentAttempts, setCurrentAttempts] = useState(0);
const pollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const attemptsRef = useRef(0);
const consecutiveErrorsRef = useRef(0);
const stopPolling = useCallback(() => {
if (pollTimeoutRef.current) {
clearTimeout(pollTimeoutRef.current);
pollTimeoutRef.current = null;
}
setIsPolling(false);
setCurrentAttempts(0);
attemptsRef.current = 0;
consecutiveErrorsRef.current = 0;
}, []);
const getPollingInterval = useCallback(
(attempt: number): number => {
if (!enableExponentialBackoff) {
return interval;
}
// Exponential backoff: start with 5s, max out at 30s
// First 12 attempts: 5s
// Next 18 attempts: 10s
// Next 30 attempts: 15s
// Remaining attempts: 30s
if (attempt <= 12) {
return 5000;
} else if (attempt <= 30) {
return 10000;
} else if (attempt <= 60) {
return 15000;
} else {
return 30000;
}
},
[interval, enableExponentialBackoff]
);
const pollTaskStatus = useCallback(
async (taskId: string) => {
setIsPolling(true);
attemptsRef.current = 0;
consecutiveErrorsRef.current = 0;
setCurrentAttempts(0);
const poll = async () => {
try {
const taskStatus: TaskStatus = await api.tasks.get(taskId);
// Reset consecutive errors on successful request
consecutiveErrorsRef.current = 0;
// Update progress if available
if (taskStatus.progress && onProgress) {
onProgress(taskStatus.progress, taskStatus.message);
}
// Check for completion
if (
taskStatus.status === "completed" ||
taskStatus.status === "COMPLETED"
) {
stopPolling();
if (onSuccess) {
onSuccess(taskId);
}
return;
}
// Check for failure
if (
taskStatus.status === "failed" ||
taskStatus.status === "FAILED"
) {
stopPolling();
if (onError) {
onError(taskStatus.error || "Task failed", taskId);
}
return;
}
// Continue polling if still running
attemptsRef.current++;
setCurrentAttempts(attemptsRef.current);
if (attemptsRef.current < maxAttempts) {
const nextInterval = getPollingInterval(attemptsRef.current);
pollTimeoutRef.current = setTimeout(poll, nextInterval);
} else {
// Timeout reached - provide more helpful message based on last known progress
stopPolling();
if (onError) {
let timeoutMessage = "Task polling timeout after 15 minutes";
if (taskStatus.progress && taskStatus.progress > 0) {
timeoutMessage = `Task was ${Math.round(
taskStatus.progress
)}% complete when polling timed out. The process may still be running in the background. You can refresh the page or try again in a few minutes.`;
} else {
timeoutMessage =
"Task polling timed out. The process may still be running in the background. Please refresh the page or check your task manually.";
}
onError(timeoutMessage, taskId);
}
}
} catch (error) {
console.error("Error polling task status:", error);
consecutiveErrorsRef.current++;
// If we have too many consecutive errors, stop polling
if (consecutiveErrorsRef.current >= 5) {
stopPolling();
if (onError) {
onError(
"Multiple polling errors occurred. Please check your connection and try again.",
taskId
);
}
return;
}
// On error, continue polling for a few more attempts with exponential backoff
attemptsRef.current++;
setCurrentAttempts(attemptsRef.current);
if (attemptsRef.current < maxAttempts) {
// Use longer interval after errors
const errorInterval = Math.min(
getPollingInterval(attemptsRef.current) * 2,
60000
);
pollTimeoutRef.current = setTimeout(poll, errorInterval);
} else {
stopPolling();
if (onError) {
onError(
error instanceof Error
? `Polling failed: ${error.message}`
: "Unknown polling error",
taskId
);
}
}
}
};
// Start polling with a 2-second delay to give the task time to start
pollTimeoutRef.current = setTimeout(poll, 2000);
},
[
maxAttempts,
getPollingInterval,
onSuccess,
onError,
onProgress,
stopPolling,
]
);
return {
pollTaskStatus,
stopPolling,
isPolling,
currentAttempts,
};
}
|