All files / src/utils/components/backend-connection BackendConnectionBanner.jsx

98.14% Statements 53/54
96.66% Branches 29/30
85.71% Functions 6/7
100% Lines 51/51

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          3x 3x               3x 72x 72x 72x 72x 72x 72x 72x   72x 40x       40x 40x 40x 40x                 20x 14x 14x 14x       6x 2x 2x     4x 4x 4x     4x 4x 4x     34x 34x   34x     34x 34x 2x 32x 14x     34x 34x 34x   40x 40x       72x 19x 19x 19x 19x       72x   26x                 25x                                                                                                                                           2x                        
import { useEffect, useRef, useState } from "react";
import { Box, Button, CircularProgress, IconButton, Stack, Typography } from "@mui/material";
import { Iconify } from "@/utils/components";
import { API_ENDPOINTS } from "@/api/endpoints";
 
const POLL_INTERVAL_MS = 3_000;
const CHECK_TIMEOUT_MS = 5_000;
 
/**
 * Self-contained banner that polls the backend `/v1/health` endpoint every 3
 * seconds. Shows a sticky bottom banner when the backend is unreachable, and
 * reloads the page once it comes back online (cleanly re-triggers auth and
 * session initialization). Mounted once, globally, in App.jsx.
 */
const BackendConnectionBanner = () => {
    const [disconnected, setDisconnected] = useState(false);
    const [checking, setChecking] = useState(false);
    const [error, setError] = useState(null);
    const [dismissed, setDismissed] = useState(false);
    const wasDisconnectedRef = useRef(false);
    const retryCountRef = useRef(0);
    const timerRef = useRef(null);
 
    const check = async () => {
        setChecking(true);
        // Modified by Allan Ninal — the controller and its timer live out here so the
        // timer is cleared on EVERY path. It used to be cleared only on success, so a
        // failing check left a live 5s timer behind on every poll.
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);
        try {
            const response = await fetch(API_ENDPOINTS.system.health, { signal: controller.signal });
 
            // Modified by Allan Ninal — `fetch` resolves for ANY http status; it
            // rejects only on a network fault. Awaiting it was therefore treated as
            // proof of health, so a backend answering 502/503 behind a gateway — the
            // very thing this banner exists to announce — read as connected and the
            // banner stayed hidden. Worse, the recovery branch below shares this
            // path: a 502 counted as "back", so an outage reloaded the page every
            // three seconds.
            if (!response.ok) {
                const httpError = new Error(`Health check failed: HTTP ${response.status}`);
                httpError.status = response.status;
                throw httpError;
            }
 
            // Backend is back — reload if we were previously disconnected
            if (wasDisconnectedRef.current) {
                window.location.reload();
                return;
            }
 
            retryCountRef.current = 0;
            setDisconnected(false);
            setError(null);
 
            // Stop polling once connected
            Eif (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
        } catch (err) {
            retryCountRef.current += 1;
            wasDisconnectedRef.current = true;
 
            const isTimeout = err.name === "AbortError";
            // "Check your network connection" is wrong advice when the server
            // answered — it just answered with an error. Say which it was.
            let message = "Unable to reach the backend server. Check your network connection.";
            if (isTimeout) {
                message = "Connection timed out — the backend is not responding.";
            } else if (err.status) {
                message = `The backend responded with an error (HTTP ${err.status}).`;
            }
 
            setDisconnected(true);
            setDismissed(false);
            setError({ message, retryCount: retryCountRef.current, lastChecked: new Date() });
        } finally {
            clearTimeout(timeoutId);
            setChecking(false);
        }
    };
 
    useEffect(() => {
        check();
        timerRef.current = setInterval(check, POLL_INTERVAL_MS);
        return () => {
            if (timerRef.current) clearInterval(timerRef.current);
        };
    }, []);
 
    if (!disconnected || dismissed) return null;
 
    return (
        <Box
            role="alert"
            aria-live="assertive"
            sx={{
                position: "fixed",
                bottom: 0,
                left: 0,
                right: 0,
                zIndex: (theme) => theme.zIndex.snackbar + 1,
                bgcolor: "error.main",
                color: "error.contrastText",
                borderTop: "1px solid",
                borderColor: "error.dark",
                boxShadow: "0 -4px 16px rgba(0,0,0,0.25)",
            }}
        >
            <Stack
                direction={{ xs: "column", sm: "row" }}
                alignItems={{ xs: "flex-start", sm: "center" }}
                justifyContent="space-between"
                spacing={2}
                sx={{ maxWidth: 1280, mx: "auto", px: 2, py: 1.5 }}
            >
                <Stack direction="row" alignItems="center" spacing={1.5}>
                    {checking ? (
                        <CircularProgress size={18} sx={{ color: "inherit" }} />
                    ) : (
                        <Iconify icon="solar:danger-triangle-bold" width={20} />
                    )}
                    <Stack
                        direction={{ xs: "column", sm: "row" }}
                        spacing={{ xs: 0.25, sm: 1.5 }}
                        alignItems={{ sm: "center" }}
                    >
                        <Typography variant="subtitle2" component="span">
                            {checking ? "Reconnecting to server…" : "Backend server unreachable"}
                        </Typography>
                        {error && !checking && (
                            <Typography variant="caption" sx={{ opacity: 0.9 }}>
                                {error.message}
                            </Typography>
                        )}
                    </Stack>
                </Stack>
 
                <Stack direction="row" alignItems="center" spacing={1.5}>
                    {error && !checking && (
                        <Stack sx={{ display: { xs: "none", sm: "flex" } }} alignItems="flex-end" spacing={0.25}>
                            <Typography variant="caption" sx={{ opacity: 0.9 }}>
                                {error.retryCount} failed {error.retryCount === 1 ? "check" : "checks"}
                            </Typography>
                            <Typography variant="caption" sx={{ opacity: 0.9 }}>
                                Last attempt:{" "}
                                {error.lastChecked.toLocaleTimeString([], {
                                    hour: "2-digit",
                                    minute: "2-digit",
                                    second: "2-digit",
                                })}
                            </Typography>
                        </Stack>
                    )}
 
                    {!checking && (
                        <Button
                            onClick={check}
                            size="small"
                            variant="outlined"
                            color="inherit"
                            startIcon={<Iconify icon="solar:refresh-bold" width={16} />}
                            sx={{ borderColor: "rgba(255,255,255,0.5)", whiteSpace: "nowrap" }}
                        >
                            Retry now
                        </Button>
                    )}
 
                    <IconButton
                        aria-label="Dismiss"
                        size="small"
                        onClick={() => setDismissed(true)}
                        sx={{ color: "inherit" }}
                    >
                        <Iconify icon="solar:close-circle-bold" width={18} />
                    </IconButton>
                </Stack>
            </Stack>
        </Box>
    );
};
 
export default BackendConnectionBanner;