All files / client/src/hooks use-backend-health.ts

100% Statements 104/104
88.88% Branches 48/54
100% Functions 22/22
100% Lines 94/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246                                            2x               44x 44x 44x 44x       44x     44x 20x 20x 20x 20x 15x 14x 12x           20x       44x   44x 20x 20x       44x     44x   44x 44x     44x 2x 2x 2x         44x 20x   20x 43x 43x 43x 43x           32x 31x 29x 29x     11x 11x 11x     42x       20x 20x   20x 20x 20x         44x 20x   20x 26x 26x 26x 26x 21x 20x 14x 13x         25x       20x 20x   20x 20x 20x         44x 30x 8x 1x         7x 1x                       44x 36x 7x 7x 2x           29x   2x 2x 2x                 44x 33x 33x     33x   33x   2x       44x   3x 2x               2x   1x         44x 5x 5x               44x                    
import { useState, useEffect, useRef, useCallback } from "react";
import { useToast } from "@/hooks/use-toast";
import { useWebSocket } from "@/hooks/use-websocket";
import type { QueryClient } from "@tanstack/react-query";
import type { ServerStatusEventData } from "@/types/external-api";
 
type PoolStats = ServerStatusEventData["sandboxRunners"];
type CompileStats = ServerStatusEventData["compileSlots"];
 
type ServerStatus = {
  sandboxRunners: PoolStats;
  compileSlots: CompileStats;
} | null;
 
/** Polling intervals fetched from /api/config (fallbacks match server defaults) */
interface ClientConfig {
  healthPollIntervalMs: number;
  statusPollIntervalMs: number;
  startupGraceMs: number;
  fetchTimeoutMs: number;
}
 
const DEFAULT_CLIENT_CONFIG: ClientConfig = {
  healthPollIntervalMs: 5_000,
  statusPollIntervalMs: 15_000,
  startupGraceMs: 5_000,
  fetchTimeoutMs: 2_000,
};
 
export function useBackendHealth(queryClient: QueryClient) {
  const [backendReachable, setBackendReachable] = useState(true);
  const [backendPingError, setBackendPingError] = useState<string | null>(null);
  const [showErrorGlitch, setShowErrorGlitch] = useState(false);
  const [serverStatus, setServerStatus] = useState<ServerStatus>(null);
 
  // Store polling config in a ref so effect callbacks always read current values
  // without re-triggering interval setup when /api/config responds.
  const configRef = useRef<ClientConfig>(DEFAULT_CLIENT_CONFIG);
 
  // Fetch dynamic config from server once on mount
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch("/api/config", { cache: "no-store" });
        if (res.ok) {
          const data = await res.json();
          if (!cancelled) configRef.current = { ...DEFAULT_CLIENT_CONFIG, ...data };
        }
      } catch {
        // Use defaults on failure
      }
    })();
    return () => { cancelled = true; };
  }, []);
 
  // Startup grace period: suppress error toasts during initial connection phase.
  const [startupGraceOver, setStartupGraceOver] = useState(false);
 
  useEffect(() => {
    const timer = setTimeout(() => setStartupGraceOver(true), configRef.current.startupGraceMs);
    return () => clearTimeout(timer);
  }, []);
 
  // Ref to track if backend was ever unreachable (for recovery toast)
  const wasBackendUnreachableRef = useRef(false);
 
  // Ref to track previous backend reachable state for detecting transitions
  const prevBackendReachableRef = useRef(true);
 
  const { toast } = useToast();
  const { isConnected, connectionError, hasEverConnected } = useWebSocket();
 
  // Trigger visual glitch effect on compilation error
  const triggerErrorGlitch = useCallback((duration = 600) => {
    try {
      setShowErrorGlitch(true);
      globalThis.setTimeout(() => setShowErrorGlitch(false), duration);
    } catch {}
  }, []);
 
  // Lightweight backend ping
  useEffect(() => {
    let cancelled = false;
 
    const ping = async () => {
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), configRef.current.fetchTimeoutMs);
      try {
        const res = await fetch("/api/health", {
          method: "GET",
          cache: "no-store",
          headers: { Connection: "close" },
          signal: controller.signal,
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        if (!cancelled) {
          setBackendReachable(true);
          setBackendPingError(null);
        }
      } catch (err) {
        Eif (!cancelled) {
          setBackendReachable(false);
          setBackendPingError((err as Error)?.message || "Health check failed");
        }
      } finally {
        clearTimeout(timeout);
      }
    };
 
    const interval = setInterval(ping, configRef.current.healthPollIntervalMs);
    ping();
 
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);
 
  // Poll /api/status for pool / compile-queue stats
  useEffect(() => {
    let cancelled = false;
 
    const fetchStatus = async () => {
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), configRef.current.fetchTimeoutMs);
      try {
        const res = await fetch("/api/status", { cache: "no-store", headers: { Connection: "close" }, signal: controller.signal });
        if (!res.ok) return;
        const data = await res.json() as { sandboxRunners: PoolStats; compileSlots: CompileStats };
        if (!cancelled) {
          setServerStatus({ sandboxRunners: data.sandboxRunners, compileSlots: data.compileSlots });
        }
      } catch {
        // status fetch failure is non-critical – silently ignore
      } finally {
        clearTimeout(timeout);
      }
    };
 
    const interval = setInterval(fetchStatus, configRef.current.statusPollIntervalMs);
    fetchStatus();
 
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);
 
  // WebSocket reachability notifications (suppressed during startup grace period)
  useEffect(() => {
    if (!startupGraceOver) return;
    if (connectionError) {
      toast({
        title: "Backend unreachable",
        description: connectionError,
        variant: "destructive",
      });
    } else if (!isConnected && hasEverConnected) {
      toast({
        title: "Connection lost",
        description: "Trying to re-establish backend connection...",
        variant: "destructive",
      });
    }
  }, [startupGraceOver, connectionError, isConnected, hasEverConnected, toast]);
 
  // Show toast when HTTP backend becomes unreachable or recovers
  // Toast display is suppressed during startup grace period, but the
  // wasBackendUnreachableRef tracking always runs so that post-grace
  // transitions are detected correctly.
  useEffect(() => {
    if (!backendReachable) {
      wasBackendUnreachableRef.current = true;
      if (startupGraceOver) {
        toast({
          title: "Backend unreachable",
          description: backendPingError || "Could not reach API server.",
          variant: "destructive",
        });
      }
    } else if (backendReachable && wasBackendUnreachableRef.current) {
      // Backend recovered after being unreachable
      wasBackendUnreachableRef.current = false;
      Eif (startupGraceOver) {
        toast({
          title: "Backend reachable again",
          description: "Connection restored.",
        });
      }
    }
  }, [startupGraceOver, backendReachable, backendPingError, toast]);
 
  // Refetch sketches when backend becomes reachable again (false -> true transition)
  useEffect(() => {
    const wasUnreachable = !prevBackendReachableRef.current;
    const isNowReachable = backendReachable;
 
    // Update the ref for next check
    prevBackendReachableRef.current = backendReachable;
 
    if (wasUnreachable && isNowReachable) {
      // Backend just transitioned from unreachable to reachable
      queryClient.refetchQueries({ queryKey: ["/api/sketches"] });
    }
  }, [backendReachable, queryClient]);
 
  const ensureBackendConnected = useCallback(
    (actionLabel: string) => {
      if (!backendReachable || !isConnected) {
        toast({
          title: "Backend unreachable",
          description:
            backendPingError ||
            connectionError ||
            `${actionLabel} failed because the backend is not reachable. Please check the server or retry in a moment.`,
          variant: "destructive",
        });
        return false;
      }
      return true;
    },
    [backendReachable, isConnected, backendPingError, connectionError, toast],
  );
 
  const isBackendUnreachableError = useCallback((error: unknown) => {
    const message = (error as Error | undefined)?.message || "";
    return (
      message.includes("Failed to fetch") ||
      message.includes("NetworkError") ||
      message.includes("ERR_CONNECTION") ||
      message.includes("Network request failed")
    );
  }, []);
 
  return {
    backendReachable,
    backendPingError,
    showErrorGlitch,
    serverStatus,
    ensureBackendConnected,
    isBackendUnreachableError,
    triggerErrorGlitch,
  };
}