Files
supervisor-ui/lib/hooks/useEventSource.ts
Sebastian Krüger 95acf4542b feat(logging): add comprehensive client-side logging (Phase 5)
Created client-side logging infrastructure for React Query and hooks:

New Client Logger (lib/utils/client-logger.ts):
- Environment-aware logging (debug/info in dev, warn/error in prod)
- Structured logging with context objects
- Performance timing helpers (time/timeEnd)
- Group logging for related operations
- Factory functions for hook/query/mutation-specific loggers

React Query Configuration (components/providers/Providers.tsx):
- Added custom logger to QueryClient
- Integrated with client-side logger for consistent formatting
- Configured mutation retry defaults

SSE Hook Logging (lib/hooks/useEventSource.ts):
- Connection lifecycle logging (connect/disconnect/reconnect)
- Heartbeat and process update event logging
- Error tracking with reconnection attempt details
- Exponential backoff logging for reconnections

Supervisor Hooks Logging (lib/hooks/useSupervisor.ts):
- Added logging to all critical mutation hooks:
  - Process control (start/stop/restart)
  - Batch operations (start-all/stop-all/restart-all)
  - Configuration reload
  - Signal operations
- Logs mutation start, success, and error states
- Includes contextual metadata (process names, signals, etc.)

All client-side logs:
- Use structured format with timestamps
- Include relevant context for debugging
- Respect environment (verbose in dev, minimal in prod)
- Compatible with browser devtools

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 20:57:24 +01:00

166 lines
4.7 KiB
TypeScript

import { useEffect, useRef, useState, useCallback } from 'react';
import { createHookLogger } from '@/lib/utils/client-logger';
const logger = createHookLogger('useEventSource');
export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
export interface EventSourceMessage<T = any> {
event: string;
data: T;
}
export interface UseEventSourceOptions {
enabled?: boolean;
reconnectInterval?: number;
maxReconnectAttempts?: number;
onMessage?: (message: EventSourceMessage) => void;
onError?: (error: Event) => void;
onConnect?: () => void;
onDisconnect?: () => void;
}
export function useEventSource(url: string, options: UseEventSourceOptions = {}) {
const {
enabled = true,
reconnectInterval = 3000,
maxReconnectAttempts = 10,
onMessage,
onError,
onConnect,
onDisconnect,
} = options;
const [status, setStatus] = useState<ConnectionStatus>('disconnected');
const [reconnectAttempts, setReconnectAttempts] = useState(0);
const eventSourceRef = useRef<EventSource | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const connect = useCallback(() => {
if (!enabled || eventSourceRef.current) return;
logger.info('Connecting to SSE', { url });
setStatus('connecting');
try {
const eventSource = new EventSource(url);
eventSourceRef.current = eventSource;
eventSource.addEventListener('connected', () => {
logger.info('SSE connected successfully', { url });
setStatus('connected');
setReconnectAttempts(0);
onConnect?.();
});
eventSource.addEventListener('heartbeat', (event) => {
// Keep connection alive
if (status !== 'connected') {
logger.debug('SSE heartbeat received, updating status to connected');
setStatus('connected');
}
});
eventSource.addEventListener('process-update', (event) => {
try {
const data = JSON.parse(event.data);
logger.debug('Process update received', {
processCount: data.processes?.length,
timestamp: data.timestamp,
});
onMessage?.({ event: 'process-update', data });
} catch (error) {
logger.error('Failed to parse SSE message', error, { event: event.data });
}
});
eventSource.addEventListener('error', (event) => {
try {
const data = JSON.parse((event as MessageEvent).data);
logger.warn('SSE error event received', { error: data });
onMessage?.({ event: 'error', data });
} catch (error) {
// Not a message error, connection error
}
});
eventSource.onerror = (event) => {
logger.error('EventSource connection error', event);
setStatus('error');
onError?.(event);
// Close current connection
eventSource.close();
eventSourceRef.current = null;
// Attempt reconnection with exponential backoff
if (reconnectAttempts < maxReconnectAttempts) {
const delay = Math.min(reconnectInterval * Math.pow(2, reconnectAttempts), 30000);
logger.info('Scheduling reconnection', {
delay,
attempt: reconnectAttempts + 1,
maxAttempts: maxReconnectAttempts,
});
reconnectTimeoutRef.current = setTimeout(() => {
setReconnectAttempts((prev) => prev + 1);
connect();
}, delay);
} else {
logger.warn('Max reconnection attempts reached, disconnecting', {
maxAttempts: maxReconnectAttempts,
});
setStatus('disconnected');
onDisconnect?.();
}
};
} catch (error) {
logger.error('Failed to create EventSource', error, { url });
setStatus('error');
}
}, [url, enabled, status, reconnectAttempts, maxReconnectAttempts, reconnectInterval, onMessage, onError, onConnect, onDisconnect]);
const disconnect = useCallback(() => {
logger.info('Disconnecting from SSE');
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
setStatus('disconnected');
setReconnectAttempts(0);
}, []);
const reconnect = useCallback(() => {
logger.info('Manual reconnection requested');
disconnect();
setReconnectAttempts(0);
connect();
}, [disconnect, connect]);
useEffect(() => {
if (enabled) {
connect();
} else {
disconnect();
}
return () => {
disconnect();
};
}, [enabled, url]);
return {
status,
reconnectAttempts,
reconnect,
disconnect,
};
}