File size: 2,527 Bytes
f52d137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * 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);
};