|
| 1 | +import { useEffect, useState, useRef } from 'react' |
| 2 | + |
| 3 | +interface SseMessage { |
| 4 | + from: string |
| 5 | + to: string |
| 6 | + content: string |
| 7 | +} |
| 8 | + |
| 9 | +interface SSEOptions { |
| 10 | + onUpdate?: (message: SseMessage) => void |
| 11 | + onConnect?: () => void |
| 12 | + onError?: (error: Event) => void |
| 13 | + autoReconnect?: boolean |
| 14 | + maxRetries?: number |
| 15 | +} |
| 16 | + |
| 17 | +export const useSimpleSSE = (url: string, options: SSEOptions = {}) => { |
| 18 | + const [connectionStatus, setConnectionStatus] = useState<'connecting' | 'connected' | 'disconnected'>('connecting') |
| 19 | + const [lastMessage, setLastMessage] = useState<SseMessage | null>(null) |
| 20 | + const [retryCount, setRetryCount] = useState(0) |
| 21 | + |
| 22 | + const eventSourceRef = useRef<EventSource | null>(null) |
| 23 | + const retryTimeoutRef = useRef<NodeJS.Timeout | null>(null) |
| 24 | + const optionsRef = useRef(options) |
| 25 | + const retryCountRef = useRef(0) |
| 26 | + const maxAttempts = optionsRef.current.maxRetries || 5 |
| 27 | + |
| 28 | + // Update options ref |
| 29 | + useEffect(() => { |
| 30 | + optionsRef.current = options |
| 31 | + }, [options]) |
| 32 | + |
| 33 | + // Update ref whenever state changes |
| 34 | + useEffect(() => { |
| 35 | + retryCountRef.current = retryCount |
| 36 | + }, [retryCount]) |
| 37 | + |
| 38 | + const connect = () => { |
| 39 | + // Clear any existing retry timeout |
| 40 | + if (retryTimeoutRef.current) { |
| 41 | + clearTimeout(retryTimeoutRef.current) |
| 42 | + } |
| 43 | + |
| 44 | + // Close existing connection |
| 45 | + if (eventSourceRef.current) { |
| 46 | + eventSourceRef.current.close() |
| 47 | + eventSourceRef.current = null |
| 48 | + } |
| 49 | + |
| 50 | + if (retryCountRef.current < maxAttempts) { |
| 51 | + eventSourceRef.current = new EventSource(url) |
| 52 | + |
| 53 | + eventSourceRef.current.onopen = () => { |
| 54 | + setConnectionStatus('connected') |
| 55 | + setRetryCount(0) // Reset retry count on successful connection |
| 56 | + optionsRef.current.onConnect?.() |
| 57 | + } |
| 58 | + |
| 59 | + eventSourceRef.current.addEventListener('connected', (event) => { |
| 60 | + const message: SseMessage = JSON.parse(event.data) |
| 61 | + setLastMessage(message) |
| 62 | + }) |
| 63 | + |
| 64 | + eventSourceRef.current.addEventListener('update', (event) => { |
| 65 | + const message: SseMessage = JSON.parse(event.data) |
| 66 | + setLastMessage(message) |
| 67 | + optionsRef.current.onUpdate?.(message) |
| 68 | + }) |
| 69 | + |
| 70 | + eventSourceRef.current.addEventListener('heartbeat', () => {}) |
| 71 | + |
| 72 | + eventSourceRef.current.onerror = (event) => { |
| 73 | + setConnectionStatus('disconnected') |
| 74 | + optionsRef.current.onError?.(event) |
| 75 | + |
| 76 | + // Auto-reconnect logic |
| 77 | + if (optionsRef.current.autoReconnect !== false) { |
| 78 | + console.error('SSE error:', event) |
| 79 | + |
| 80 | + const delay = Math.min(1000 * Math.pow(2, retryCount), 30000) |
| 81 | + console.warn(`Reconnecting in ${delay}ms (attempt ${retryCountRef.current + 1})`) |
| 82 | + setRetryCount((prev) => prev + 1) |
| 83 | + |
| 84 | + retryTimeoutRef.current = setTimeout(() => { |
| 85 | + connect() |
| 86 | + }, delay) |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + useEffect(() => { |
| 93 | + setConnectionStatus('connecting') |
| 94 | + connect() |
| 95 | + |
| 96 | + return () => { |
| 97 | + if (retryTimeoutRef.current) { |
| 98 | + clearTimeout(retryTimeoutRef.current) |
| 99 | + } |
| 100 | + if (eventSourceRef.current) { |
| 101 | + eventSourceRef.current.close() |
| 102 | + eventSourceRef.current = null |
| 103 | + } |
| 104 | + setConnectionStatus('disconnected') |
| 105 | + } |
| 106 | + }, [url]) // Only reconnect when URL |
| 107 | + |
| 108 | + return { |
| 109 | + connectionStatus, |
| 110 | + lastMessage, |
| 111 | + retryCount, |
| 112 | + maxAttempts, |
| 113 | + reconnect: connect, |
| 114 | + } |
| 115 | +} |
0 commit comments