All files / web/src/hooks use-sse.ts

0% Statements 0/167
100% Branches 1/1
100% Functions 1/1
0% Lines 0/167

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 247 248 249 250 251 252                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client';
 
import { info } from '@shared/console-logging';
import type {
  SSEConnectionOptions,
  SSEEventData,
  SSEEventType,
} from '@shared/types/sse';
import { useCallback, useEffect, useRef, useState } from 'react';
 
/**
 * SSE Event Handler
 * Callback function that handles SSE events
 */
export type SSEEventHandler = (event: SSEEventData) => void;
 
/**
 * SSE Connection State
 */
export interface SSEConnectionState {
  connected: boolean;
  connecting: boolean;
  error: Error | null;
  reconnectAttempts: number;
}
 
/**
 * useSSE Hook
 * Manages Server-Sent Events connection and event handling
 *
 * @param url - SSE endpoint URL
 * @param options - Connection options
 * @returns Connection state and event subscription methods
 */
export function useSSE(url: string, options: SSEConnectionOptions = {}) {
  const {
    reconnectDelay = 8787,
    maxReconnectAttempts = 5,
    pingInterval = 30000,
  } = options;
 
  const [connectionState, setConnectionState] = useState<SSEConnectionState>({
    connected: false,
    connecting: false,
    error: null,
    reconnectAttempts: 0,
  });
 
  const eventSourceRef = useRef<EventSource | null>(null);
  const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const eventHandlersRef = useRef<
    Map<SSEEventType | '*', Set<SSEEventHandler>>
  >(new Map());
  const lastPingRef = useRef<number>(Date.now());
 
  /**
   * Subscribe to specific event type
   */
  const subscribe = (
    eventType: SSEEventType | '*',
    handler: SSEEventHandler,
  ): (() => void) => {
    if (!eventHandlersRef.current.has(eventType)) {
      eventHandlersRef.current.set(eventType, new Set());
    }
    eventHandlersRef.current.get(eventType)?.add(handler);
 
    // Return unsubscribe function
    return () => {
      eventHandlersRef.current.get(eventType)?.delete(handler);
    };
  };
 
  /**
   * Connect to SSE endpoint
   */
  const connect = useCallback(() => {
    if (eventSourceRef.current) {
      return; // Already connected or connecting
    }
 
    setConnectionState((prev) => ({ ...prev, connecting: true, error: null }));
 
    try {
      const eventSource = new EventSource(url, {
        withCredentials: true, // Include cookies for authentication
      });
 
      eventSource.onopen = () => {
        info('[SSE Client] Connection established');
        setConnectionState({
          connected: true,
          connecting: false,
          error: null,
          reconnectAttempts: 0,
        });
        lastPingRef.current = Date.now();
      };
 
      eventSource.onmessage = (event) => {
        try {
          // Skip empty data (keep-alive messages, comments, etc.)
          if (!event.data || event.data.trim() === '') {
            return;
          }
 
          const data: SSEEventData = JSON.parse(event.data);
 
          // Update last ping time
          if (data.type === 'ping') {
            lastPingRef.current = Date.now();
            return;
          }
 
          // Log received event
          info('[SSE Client] Received event:', data.type);
 
          // Call specific event handlers
          const specificHandlers = eventHandlersRef.current.get(data.type);
          if (specificHandlers) {
            for (const handler of specificHandlers) {
              try {
                handler(data);
              } catch (error) {
                console.error('[SSE Client] Error in event handler:', error);
              }
            }
          }
 
          // Call wildcard handlers
          const wildcardHandlers = eventHandlersRef.current.get('*');
          if (wildcardHandlers) {
            for (const handler of wildcardHandlers) {
              try {
                handler(data);
              } catch (error) {
                console.error('[SSE Client] Error in wildcard handler:', error);
              }
            }
          }
        } catch (error) {
          console.error('[SSE Client] Error parsing event data:', error);
        }
      };
 
      eventSource.onerror = (error) => {
        console.error('[SSE Client] Connection error:', error);
 
        eventSource.close();
        eventSourceRef.current = null;
 
        const currentAttempts = connectionState.reconnectAttempts + 1;
 
        setConnectionState({
          connected: false,
          connecting: false,
          error: new Error('SSE connection failed'),
          reconnectAttempts: currentAttempts,
        });
 
        // Attempt to reconnect if under max attempts
        if (currentAttempts < maxReconnectAttempts) {
          info(
            `[SSE Client] Reconnecting in ${reconnectDelay}ms (attempt ${currentAttempts}/${maxReconnectAttempts})`,
          );
          reconnectTimeoutRef.current = setTimeout(() => {
            connect();
          }, reconnectDelay);
        } else {
          console.error('[SSE Client] Max reconnection attempts reached');
        }
      };
 
      eventSourceRef.current = eventSource;
    } catch (error) {
      console.error('[SSE Client] Error creating EventSource:', error);
      setConnectionState((prev) => ({
        ...prev,
        connecting: false,
        error: error as Error,
      }));
    }
  }, [
    url,
    connectionState.reconnectAttempts,
    maxReconnectAttempts,
    reconnectDelay,
  ]);
 
  /**
   * Disconnect from SSE endpoint
   */
  const disconnect = useCallback(() => {
    if (reconnectTimeoutRef.current) {
      clearTimeout(reconnectTimeoutRef.current);
      reconnectTimeoutRef.current = null;
    }
 
    if (eventSourceRef.current) {
      eventSourceRef.current.close();
      eventSourceRef.current = null;
    }
 
    setConnectionState({
      connected: false,
      connecting: false,
      error: null,
      reconnectAttempts: 0,
    });
 
    info('[SSE Client] Disconnected');
  }, []);
 
  /**
   * Check for stale connection (no ping received within interval)
   */
  useEffect(() => {
    const checkInterval = setInterval(() => {
      if (connectionState.connected) {
        const timeSinceLastPing = Date.now() - lastPingRef.current;
        if (timeSinceLastPing > pingInterval * 2) {
          console.warn(
            '[SSE Client] Connection appears stale, reconnecting...',
          );
          disconnect();
          connect();
        }
      }
    }, pingInterval);
 
    return () => clearInterval(checkInterval);
  }, [connectionState.connected, pingInterval, connect, disconnect]);
 
  /**
   * Auto-connect on mount, disconnect on unmount
   */
  useEffect(() => {
    connect();
 
    return () => {
      disconnect();
    };
  }, [connect, disconnect]);
 
  return {
    connectionState,
    subscribe,
    connect,
    disconnect,
  };
}