demo / frontend /src /utils /healthCheck.ts
Pierre Andrews
Initial commit
f52d137
raw
history blame
2.53 kB
/**
* Health check utilities for polling ARE server status
*/
/**
* Poll the health check endpoint until the server is ready
* @param healthUrl The health check URL to poll
* @param maxAttempts Maximum number of attempts (default: 60)
* @param intervalMs Interval between attempts in milliseconds (default: 1000)
* @param onProgress Optional callback for progress updates (attempt number, total attempts)
* @returns Promise that resolves when the server is healthy, rejects if max attempts reached
*/
export const pollHealthCheck = async (
healthUrl: string,
maxAttempts: number = 60,
intervalMs: number = 1000,
onProgress?: (attempt: number, maxAttempts: number) => void
): Promise<void> => {
console.log(`Starting health check for: ${healthUrl}`);
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
if (onProgress) {
onProgress(attempt, maxAttempts);
}
const response = await fetch(healthUrl, {
method: 'GET',
headers: {
'Cache-Control': 'no-cache',
},
// Add a timeout to prevent hanging requests
signal: AbortSignal.timeout(5000), // 5 second timeout per request
});
if (response.ok) {
console.log(`Health check passed on attempt ${attempt}`);
return; // Server is ready!
}
console.log(`Health check attempt ${attempt}/${maxAttempts} failed with status ${response.status}`);
} catch (error) {
console.log(`Health check attempt ${attempt}/${maxAttempts} failed:`, error instanceof Error ? error.message : error);
}
// Wait before next attempt (except on the last attempt)
if (attempt < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
}
throw new Error(`Health check failed after ${maxAttempts} attempts. Server may not be ready.`);
};
/**
* Convenience function for health checking using the health URL directly
* @param healthUrl The health check URL from start_demo API response
* @param maxAttempts Maximum number of health check attempts
* @param intervalMs Interval between health check attempts
* @param onProgress Optional progress callback
* @returns Promise that resolves when server is ready
*/
export const waitForServerReady = async (
healthUrl: string,
maxAttempts: number = 60,
intervalMs: number = 1000,
onProgress?: (attempt: number, maxAttempts: number) => void
): Promise<void> => {
return pollHealthCheck(healthUrl, maxAttempts, intervalMs, onProgress);
};