File size: 2,011 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
72
73
74
75
76
import { useCallback, useState } from "react";
import { waitForServerReady } from "../utils/healthCheck";

interface HealthCheckProgress {
  attempt: number;
  maxAttempts: number;
}

interface UseHealthCheckOptions {
  maxAttempts?: number;
  intervalMs?: number;
  onSuccess?: () => void;
  onError?: (error: Error) => void;
  logPrefix?: string;
}

interface UseHealthCheckReturn {
  healthCheckProgress: HealthCheckProgress | null;
  isHealthChecking: boolean;
  startHealthCheck: (healthUrl: string, options?: UseHealthCheckOptions) => Promise<void>;
  resetHealthCheck: () => void;
}

export const useHealthCheck = (): UseHealthCheckReturn => {
  const [healthCheckProgress, setHealthCheckProgress] = useState<HealthCheckProgress | null>(null);
  const [isHealthChecking, setIsHealthChecking] = useState<boolean>(false);

  const startHealthCheck = useCallback(async (
    healthUrl: string,
    options: UseHealthCheckOptions = {}
  ) => {
    const {
      maxAttempts = 60,
      intervalMs = 1000,
      onSuccess,
      onError,
      logPrefix = "Health check"
    } = options;

    setIsHealthChecking(true);
    setHealthCheckProgress({ attempt: 0, maxAttempts });

    try {
      await waitForServerReady(healthUrl, maxAttempts, intervalMs, (attempt, maxAttempts) => {
        console.log(`${logPrefix} progress: ${attempt}/${maxAttempts}`);
        setHealthCheckProgress({ attempt, maxAttempts });
      });

      console.log(`${logPrefix} completed successfully!`);
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      console.error(`${logPrefix} failed:`, error);
      if (onError) {
        onError(error as Error);
      }
    } finally {
      setIsHealthChecking(false);
      setHealthCheckProgress(null);
    }
  }, []);

  const resetHealthCheck = useCallback(() => {
    setHealthCheckProgress(null);
    setIsHealthChecking(false);
  }, []);

  return {
    healthCheckProgress,
    isHealthChecking,
    startHealthCheck,
    resetHealthCheck,
  };
};