Repository navigation
Expand file tree
/
Copy pathTelemetryNodeComponent.tsx
More file actions
144 lines (128 loc) · 3.86 KB
/
Copy pathTelemetryNodeComponent.tsx
File metadata and controls
144 lines (128 loc) · 3.86 KB
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
import { useEffect, useRef, useCallback } from 'react'
import { useTelemetryStore } from '@/store'
import type { WsMessage, TelemetryNode, TelemetryEdge, LogEntry, Alert, TelemetryEvent } from '@/types'
const WS_URL = process.env.NEXT_PUBLIC_WS_URL ?? 'ws://localhost:8000/ws/telemetry'
const RECONNECT_DELAY = 3000
const MAX_RECONNECT_ATTEMPTS = 10
export function useTelemetryWebSocket(projectId?: string) {
const wsRef = useRef<WebSocket | null>(null)
const reconnectAttempts = useRef(0)
const reconnectTimer = useRef<ReturnType<typeof setTimeout>>()
const mounted = useRef(true)
const {
setNodes,
updateNode,
addNode,
removeNode,
setEdges,
updateEdge,
addLog,
addEvent,
addAlert,
setConnectionStatus,
} = useTelemetryStore()
const handleMessage = useCallback(
(msg: WsMessage) => {
switch (msg.type) {
case 'node_update': {
const data = msg.payload as { id: string } & Partial<TelemetryNode>
updateNode(data.id, data)
break
}
case 'node_added': {
addNode(msg.payload as TelemetryNode)
break
}
case 'node_removed': {
removeNode((msg.payload as { id: string }).id)
break
}
case 'edge_update': {
const edge = msg.payload as { id: string } & Partial<TelemetryEdge>
updateEdge(edge.id, edge)
break
}
case 'log': {
addLog(msg.payload as LogEntry)
break
}
case 'event': {
addEvent(msg.payload as TelemetryEvent)
break
}
case 'alert': {
addAlert(msg.payload as Alert)
break
}
case 'crash': {
addEvent({
id: Math.random().toString(36).slice(2),
type: 'crash',
nodeId: (msg.payload as { nodeId: string }).nodeId,
timestamp: msg.timestamp,
payload: msg.payload as Record<string, unknown>,
severity: 'critical',
})
break
}
case 'ping': {
wsRef.current?.send(JSON.stringify({ type: 'pong', timestamp: new Date().toISOString() }))
break
}
}
},
[updateNode, addNode, removeNode, updateEdge, addLog, addEvent, addAlert]
)
const connect = useCallback(() => {
if (!mounted.current) return
setConnectionStatus('connecting')
const url = projectId ? `${WS_URL}/${projectId}` : WS_URL
const ws = new WebSocket(url)
wsRef.current = ws
ws.onopen = () => {
if (!mounted.current) return
reconnectAttempts.current = 0
setConnectionStatus('connected')
}
ws.onmessage = (event) => {
try {
const msg: WsMessage = JSON.parse(event.data)
handleMessage(msg)
} catch (err) {
console.error('[WS] Failed to parse message:', err)
}
}
ws.onerror = () => {
setConnectionStatus('error')
}
ws.onclose = () => {
if (!mounted.current) return
setConnectionStatus('disconnected')
if (reconnectAttempts.current < MAX_RECONNECT_ATTEMPTS) {
reconnectAttempts.current++
reconnectTimer.current = setTimeout(connect, RECONNECT_DELAY)
}
}
}, [projectId, handleMessage, setConnectionStatus])
const disconnect = useCallback(() => {
clearTimeout(reconnectTimer.current)
wsRef.current?.close()
wsRef.current = null
setConnectionStatus('disconnected')
}, [setConnectionStatus])
const send = useCallback((message: unknown) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(message))
}
}, [])
useEffect(() => {
mounted.current = true
connect()
return () => {
mounted.current = false
clearTimeout(reconnectTimer.current)
wsRef.current?.close()
}
}, [connect])
return { send, disconnect, reconnect: connect }
}