All files / src/hooks useRealtimeMetrics.ts

78.57% Statements 286/364
71.87% Branches 23/32
33.33% Functions 1/3
78.57% Lines 286/364

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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 3651x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 30x 30x 35x 35x 35x 35x 35x 35x 35x 35x 35x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 8x 1x 1x 8x     8x 1x 1x 1x 8x 5x 5x 5x 8x     8x 8x 8x 8x 8x     35x 35x 35x 35x 35x 35x 35x 35x                                               35x 35x 35x 35x 35x 35x                 35x 35x 35x 35x 35x 35x 17x       17x 35x 35x 35x 35x 35x 35x 14x 14x 14x 14x 14x     14x 14x 14x         14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 84x 14x 14x 14x                                     14x 35x 35x 35x 35x 35x 35x 16x 14x 14x 14x 16x       16x 16x 35x 35x 35x 35x 35x 35x 1x 1x 1x 35x 35x 35x 35x 35x 35x 22x                       22x 22x 22x 22x 35x 35x 35x 35x 35x 35x 13x 13x 13x 13x 13x 13x 35x 35x 35x 35x 35x 35x 35x 35x 35x 1x 1x  
'use client';
 
import { useState, useEffect, useCallback, useRef } from 'react';
import type { SLOResult } from '@/lib/observability';
import { clientLogger } from '@/lib/logging/clientLogger';
 
/**
 * Metrics summary from the stream
 */
export interface MetricsSummary {
  totalRequests: number;
  successRate: number;
  avgDuration: number;
  errorCount: number;
}
 
/**
 * Error log entry
 */
export interface ErrorLogEntry {
  id: string;
  category: string;
  message: string;
  createdAt: string;
}
 
/**
 * Alert entry
 */
export interface Alert {
  sloName: string;
  status: string;
}
 
/**
 * Connection status
 */
export type ConnectionStatus = 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'polling';
 
/**
 * SSE Message structure
 */
interface SSEMessage {
  type: string;
  data: unknown;
  timestamp: number;
}
 
/**
 * Real-time metrics state
 */
export interface RealtimeMetricsState {
  slos: SLOResult[];
  metrics: MetricsSummary | null;
  recentErrors: ErrorLogEntry[];
  alerts: Alert[];
  lastUpdate: Date | null;
  status: ConnectionStatus;
  error: string | null;
}
 
/**
 * Hook options
 */
export interface UseRealtimeMetricsOptions {
  /** Enable incident mode (faster updates) */
  incidentMode?: boolean;
  /** Polling fallback interval in ms (default: 30000) */
  pollingInterval?: number;
  /** Auto-reconnect on disconnect */
  autoReconnect?: boolean;
  /** Max reconnection attempts */
  maxReconnectAttempts?: number;
  /** Callback when alerts are received */
  onAlert?: (alerts: Alert[]) => void;
  /** Callback when connection status changes */
  onStatusChange?: (status: ConnectionStatus) => void;
}
 
/**
 * Hook return type
 */
export interface UseRealtimeMetricsReturn extends RealtimeMetricsState {
  /** Manually reconnect */
  reconnect: () => void;
  /** Disconnect from stream */
  disconnect: () => void;
  /** Check if using polling fallback */
  isPolling: boolean;
}
 
/**
 * Default state
 */
const defaultState: RealtimeMetricsState = {
  slos: [],
  metrics: null,
  recentErrors: [],
  alerts: [],
  lastUpdate: null,
  status: 'connecting',
  error: null,
};
 
/**
 * useRealtimeMetrics Hook
 *
 * Provides real-time metrics updates via Server-Sent Events (SSE)
 * with automatic fallback to polling if SSE is not supported.
 */
export function useRealtimeMetrics(
  options: UseRealtimeMetricsOptions = {}
): UseRealtimeMetricsReturn {
  const {
    incidentMode = false,
    pollingInterval = 30000,
    autoReconnect = true,
    maxReconnectAttempts = 5,
    onAlert,
    onStatusChange,
  } = options;
 
  const [state, setState] = useState<RealtimeMetricsState>(defaultState);
  const [isPolling, setIsPolling] = useState(false);
 
  const eventSourceRef = useRef<EventSource | null>(null);
  const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const reconnectAttemptsRef = useRef(0);
  const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isVisibleRef = useRef(true);
 
  /**
   * Update connection status
   */
  const updateStatus = useCallback(
    (status: ConnectionStatus) => {
      setState((prev) => ({ ...prev, status }));
      onStatusChange?.(status);
    },
    [onStatusChange]
  );
 
  /**
   * Handle incoming SSE message
   */
  const handleMessage = useCallback(
    (event: MessageEvent) => {
      try {
        const message: SSEMessage = JSON.parse(event.data);
        const { type, data, timestamp } = message;
 
        setState((prev) => {
          const updates: Partial<RealtimeMetricsState> = {
            lastUpdate: new Date(timestamp),
            error: null,
          };
 
          switch (type) {
            case 'slo_update':
              updates.slos = data as SLOResult[];
              break;
            case 'metrics_update':
              updates.metrics = data as MetricsSummary;
              break;
            case 'error_update':
              updates.recentErrors = data as ErrorLogEntry[];
              break;
            case 'alert':
              updates.alerts = data as Alert[];
              onAlert?.(data as Alert[]);
              break;
            case 'connected':
              updates.status = 'connected';
              reconnectAttemptsRef.current = 0;
              break;
            case 'heartbeat':
              // Just update timestamp
              break;
          }
 
          return { ...prev, ...updates };
        });
      } catch (error) {
        clientLogger.error('Failed to parse realtime metrics message', error instanceof Error ? error : new Error(String(error)));
      }
    },
    [onAlert]
  );
 
  /**
   * Fallback polling fetch
   */
  const fetchMetrics = useCallback(async () => {
    try {
      const response = await fetch('/api/admin/monitoring/stream?poll=true');
      if (!response.ok) throw new Error('Failed to fetch metrics');

      // For polling, we need to fetch data differently
      // This is a simplified approach - in production you'd have a separate endpoint
      const slosRes = await fetch('/api/admin/monitoring/slo-history?mode=trends');

      if (slosRes.ok) {
        const slosData = await slosRes.json();
        setState((prev) => ({
          ...prev,
          slos: slosData.slos || [],
          lastUpdate: new Date(),
          error: null,
        }));
      }
    } catch (error) {
      setState((prev) => ({
        ...prev,
        error: error instanceof Error ? error.message : 'Failed to fetch metrics',
      }));
    }
  }, []);
 
  /**
   * Start polling fallback
   */
  const startPolling = useCallback(() => {
    setIsPolling(true);
    updateStatus('polling');

    // Initial fetch
    fetchMetrics();

    // Set up interval
    pollingIntervalRef.current = setInterval(fetchMetrics, pollingInterval);
  }, [fetchMetrics, pollingInterval, updateStatus]);
 
  /**
   * Stop polling
   */
  const stopPolling = useCallback(() => {
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
      pollingIntervalRef.current = null;
    }
    setIsPolling(false);
  }, []);
 
  /**
   * Connect to SSE stream
   */
  const connect = useCallback(() => {
    // Don't connect if page is not visible
    if (!isVisibleRef.current) return;
 
    // Clean up existing connection
    if (eventSourceRef.current) {
      eventSourceRef.current.close();
    }
 
    // Check if SSE is supported
    if (typeof EventSource === 'undefined') {
      clientLogger.warn('SSE not supported, falling back to polling');
      startPolling();
      return;
    }
 
    updateStatus('connecting');
 
    const url = `/api/admin/monitoring/stream${incidentMode ? '?incident=true' : ''}`;
    const eventSource = new EventSource(url);
    eventSourceRef.current = eventSource;
 
    // Handle all event types
    const eventTypes = ['slo_update', 'metrics_update', 'error_update', 'alert', 'heartbeat', 'connected'];
    eventTypes.forEach((eventType) => {
      eventSource.addEventListener(eventType, handleMessage);
    });
 
    eventSource.onerror = () => {
      eventSource.close();
      eventSourceRef.current = null;

      if (autoReconnect && reconnectAttemptsRef.current < maxReconnectAttempts) {
        reconnectAttemptsRef.current++;
        updateStatus('reconnecting');

        // Exponential backoff
        const delay = Math.min(1000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
        reconnectTimeoutRef.current = setTimeout(connect, delay);
      } else if (reconnectAttemptsRef.current >= maxReconnectAttempts) {
        // Fall back to polling
        clientLogger.warn('Max reconnect attempts reached, falling back to polling');
        startPolling();
      } else {
        updateStatus('disconnected');
        setState((prev) => ({ ...prev, error: 'Connection lost' }));
      }
    };
  }, [autoReconnect, handleMessage, incidentMode, maxReconnectAttempts, startPolling, updateStatus]);
 
  /**
   * Disconnect from stream
   */
  const disconnect = useCallback(() => {
    if (eventSourceRef.current) {
      eventSourceRef.current.close();
      eventSourceRef.current = null;
    }
    if (reconnectTimeoutRef.current) {
      clearTimeout(reconnectTimeoutRef.current);
      reconnectTimeoutRef.current = null;
    }
    stopPolling();
    updateStatus('disconnected');
  }, [stopPolling, updateStatus]);
 
  /**
   * Manual reconnect
   */
  const reconnect = useCallback(() => {
    reconnectAttemptsRef.current = 0;
    stopPolling();
    connect();
  }, [connect, stopPolling]);
 
  /**
   * Handle visibility change
   */
  useEffect(() => {
    const handleVisibilityChange = () => {
      isVisibleRef.current = document.visibilityState === 'visible';

      if (isVisibleRef.current) {
        // Reconnect when page becomes visible
        if (state.status === 'disconnected' || !eventSourceRef.current) {
          reconnect();
        }
      } else {
        // Disconnect when page is hidden to save resources
        disconnect();
      }
    };
 
    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
  }, [disconnect, reconnect, state.status]);
 
  /**
   * Initial connection
   */
  useEffect(() => {
    connect();
 
    return () => {
      disconnect();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [incidentMode]);
 
  return {
    ...state,
    reconnect,
    disconnect,
    isPolling,
  };
}
 
export default useRealtimeMetrics;