All files / src/utils/hooks useStudentDashboardWebSocket.js

95.31% Statements 61/64
81.48% Branches 22/27
100% Functions 10/10
100% Lines 57/57

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                                                                      2x           2x 25x 25x       46x 46x 46x 46x 46x 46x   46x 32x 32x 3x     29x 35x         35x 35x   1x 1x 1x   34x   34x 7x 7x 7x     34x 12x   11x 11x   1x   10x 7x 6x 5x       34x 6x 6x 6x     34x         29x 7x 7x 7x     29x   29x 29x 29x 5x 5x   29x 28x 28x       28x   29x       46x     2x  
/**
 * EI-2966 — Student Dashboard WebSocket hook.
 *
 * Opens a WebSocket to `/v1/student/dashboard/ws` and exposes
 * `lastEvent` + `connected` state.
 *
 * Behavior:
 *   - Opens the connection once on mount; re-opens with exponential
 *     backoff (1s, 2s, 4s, 8s, capped at 16 s) on unexpected closes.
 *   - Closes the connection cleanly on unmount.
 *   - Server pushes JSON `{ type, ts, ... }`.  Heartbeats are
 *     consumed to keep `connected` accurate but DO NOT bump
 *     `lastEvent` — only meaningful event types do.
 *   - The 30-second polling fallback in `Dashboard.jsx` stays in
 *     place; this hook is purely additive — if the WS drops, the
 *     dashboard still refreshes on poll.
 *
 * Auth (SEC-3): none, from this hook's point of view. The browser
 * attaches the HttpOnly `access_token` cookie the BFF already set,
 * exactly as it does for every REST call. There is nothing for the
 * hook to fetch, hold, or pass.
 *
 * This previously appended the raw Auth0 bearer token to the URL as
 * `?token=...`, which wrote a live credential into browser history,
 * the Referer header, and every proxy and nginx access log on the
 * path — defeating the point of the HttpOnly-cookie BFF design. The
 * server no longer accepts a query-param token at all, so re-adding
 * one here would not work even by accident.
 *
 * The URL must be same-site with the API (or the cookie must be
 * SameSite=none, which it is) or the browser will not attach it.
 */
 
import { useEffect, useRef, useState } from "react";
 
const EVENT_TYPES_TRIGGERING_REFRESH = new Set([
    "submission_submitted",
    "submission_graded",
    "assignment_created",
]);
 
const _backoffMs = (attempt) => {
    const base = Math.min(1000 * 2 ** attempt, 16000);
    return base;
};
 
export function useStudentDashboardWebSocket({ url }) {
    const [connected, setConnected] = useState(false);
    const [lastEvent, setLastEvent] = useState(null);
    const wsRef = useRef(null);
    const attemptRef = useRef(0);
    const cancelledRef = useRef(false);
    const reconnectTimerRef = useRef(null);
 
    useEffect(() => {
        cancelledRef.current = false;
        if (!url) {
            return undefined;
        }
 
        const connect = async () => {
            Iif (cancelledRef.current) return;
 
            // No token handling: the HttpOnly access_token cookie rides the
            // handshake automatically. See the SEC-3 note in the file header.
            let ws;
            try {
                ws = new WebSocket(url);
            } catch (err) {
                console.warn("EI-2966 WS construction failed:", err?.message || err);
                scheduleReconnect();
                return;
            }
            wsRef.current = ws;
 
            ws.onopen = () => {
                Iif (cancelledRef.current) return;
                attemptRef.current = 0;
                setConnected(true);
            };
 
            ws.onmessage = (msg) => {
                if (cancelledRef.current) return;
                let payload;
                try {
                    payload = JSON.parse(msg.data);
                } catch {
                    return;
                }
                if (!payload || typeof payload !== "object" || !payload.type) return;
                if (payload.type === "heartbeat") return;
                if (EVENT_TYPES_TRIGGERING_REFRESH.has(payload.type)) {
                    setLastEvent(payload);
                }
            };
 
            ws.onclose = () => {
                setConnected(false);
                wsRef.current = null;
                Eif (!cancelledRef.current) scheduleReconnect();
            };
 
            ws.onerror = () => {
                // onclose will fire afterwards — let it handle the reconnect.
            };
        };
 
        const scheduleReconnect = () => {
            Iif (cancelledRef.current) return;
            const delay = _backoffMs(attemptRef.current++);
            reconnectTimerRef.current = setTimeout(connect, delay);
        };
 
        connect();
 
        return () => {
            cancelledRef.current = true;
            if (reconnectTimerRef.current) {
                clearTimeout(reconnectTimerRef.current);
                reconnectTimerRef.current = null;
            }
            if (wsRef.current) {
                try {
                    wsRef.current.close();
                } catch {
                    // ignore — socket may already be in CLOSING/CLOSED
                }
                wsRef.current = null;
            }
            setConnected(false);
        };
    }, [url]);
 
    return { connected, lastEvent };
}
 
export const _eiInternals = { _backoffMs, EVENT_TYPES_TRIGGERING_REFRESH };