-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathWebSocketService.ts
More file actions
423 lines (366 loc) · 14.2 KB
/
Copy pathWebSocketService.ts
File metadata and controls
423 lines (366 loc) · 14.2 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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import { createLogger, createErrorMetadata } from '../utils/logger';
import { debugState } from '../utils/debugState';
import { useSettingsStore } from '../store/settingsStore'; // Keep alias here for now, fix later if needed
import { graphDataManager } from '../features/graph/managers/graphDataManager';
const logger = createLogger('WebSocketService');
export interface WebSocketAdapter {
send: (data: ArrayBuffer) => void;
isReady: () => boolean;
}
export interface WebSocketMessage {
type: string;
data?: any;
}
type MessageHandler = (message: WebSocketMessage) => void;
type BinaryMessageHandler = (data: ArrayBuffer) => void;
type ConnectionStatusHandler = (connected: boolean) => void;
class WebSocketService {
private static instance: WebSocketService;
private socket: WebSocket | null = null;
private messageHandlers: MessageHandler[] = [];
private binaryMessageHandlers: BinaryMessageHandler[] = [];
private connectionStatusHandlers: ConnectionStatusHandler[] = [];
private reconnectInterval: number = 2000;
private maxReconnectAttempts: number = 10;
private reconnectAttempts: number = 0;
private reconnectTimeout: number | null = null;
private isConnected: boolean = false;
private isServerReady: boolean = false;
private url: string;
private constructor() {
// Default WebSocket URL
this.url = this.determineWebSocketUrl();
// Update URL when settings change
this.updateFromSettings();
// Subscribe to store changes and manually check customBackendUrl
let previousCustomBackendUrl = useSettingsStore.getState().settings.system.customBackendUrl;
useSettingsStore.subscribe((state) => {
const newCustomBackendUrl = state.settings.system.customBackendUrl;
if (newCustomBackendUrl !== previousCustomBackendUrl) {
if (debugState.isEnabled()) {
logger.info(`customBackendUrl setting changed from "${previousCustomBackendUrl}" to "${newCustomBackendUrl}", re-evaluating WebSocket URL.`);
}
previousCustomBackendUrl = newCustomBackendUrl; // Update for next comparison
this.updateFromSettings(); // Sets this.url based on the latest state
if (this.isConnected || (this.socket && this.socket.readyState === WebSocket.CONNECTING)) {
logger.info('Reconnecting WebSocket due to customBackendUrl change.');
this.close();
setTimeout(() => {
this.connect().catch(error => {
logger.error('Failed to reconnect WebSocket after URL change:', createErrorMetadata(error));
});
}, 100);
}
}
});
}
private updateFromSettings(): void {
const settings = useSettingsStore.getState().settings;
let newUrl = this.determineWebSocketUrl(); // Default to relative path
if (settings.system?.websocket) {
this.reconnectInterval = settings.system.websocket.reconnectDelay || 2000;
this.maxReconnectAttempts = settings.system.websocket.reconnectAttempts || 10;
}
if (settings.system?.customBackendUrl && settings.system.customBackendUrl.trim() !== '') {
const customUrl = settings.system.customBackendUrl.trim();
const protocol = customUrl.startsWith('https://') ? 'wss://' : 'ws://';
const hostAndPath = customUrl.replace(/^(https?:\/\/)?/, '');
newUrl = `${protocol}${hostAndPath.replace(/\/$/, '')}/wss`; // Ensure /wss and handle trailing slash
if (debugState.isEnabled()) {
logger.info(`Using custom backend WebSocket URL: ${newUrl}`);
}
} else {
if (debugState.isEnabled()) {
logger.info(`Using default WebSocket URL: ${newUrl}`);
}
}
this.url = newUrl;
}
public static getInstance(): WebSocketService {
if (!WebSocketService.instance) {
WebSocketService.instance = new WebSocketService();
}
return WebSocketService.instance;
}
private determineWebSocketUrl(): string {
// Always use a relative path. Nginx handles proxying in dev,
// and the browser resolves it correctly in production.
const url = '/wss'; // Changed from /ws to /wss
if (debugState.isEnabled()) { // Log only if debug is enabled
logger.info(`Determined WebSocket URL (relative): ${url}`);
}
return url;
}
/**
* Set a custom backend URL for WebSocket connections
* @param backendUrl The backend URL (e.g., 'http://192.168.0.51:8000' or just '192.168.0.51:8000')
*/
public setCustomBackendUrl(backendUrl: string | null): void {
if (!backendUrl) {
// Reset to default URL
this.url = this.determineWebSocketUrl();
if (debugState.isEnabled()) {
logger.info(`Reset to default WebSocket URL: ${this.url}`);
}
return;
}
// Determine protocol (ws or wss)
const protocol = backendUrl.startsWith('https://') ? 'wss://' : 'ws://';
// Extract host and port
const hostWithProtocol = backendUrl.replace(/^(https?:\/\/)?/, '');
// Set the WebSocket URL
this.url = `${protocol}${hostWithProtocol}/wss`; // Changed from /ws to /wss
if (debugState.isEnabled()) {
logger.info(`Set custom WebSocket URL: ${this.url}`);
}
// If already connected, reconnect with new URL
if (this.isConnected && this.socket) {
if (debugState.isEnabled()) {
logger.info('Reconnecting with new WebSocket URL');
}
this.close();
this.connect().catch(error => {
logger.error('Failed to reconnect with new URL:', createErrorMetadata(error));
});
}
}
public async connect(): Promise<void> {
// Don't try to connect if already connecting or connected
if (this.socket && (this.socket.readyState === WebSocket.CONNECTING || this.socket.readyState === WebSocket.OPEN)) {
return;
}
try {
if (debugState.isEnabled()) {
logger.info(`Connecting to WebSocket at ${this.url}`);
}
// Create a new WebSocket connection
this.socket = new WebSocket(this.url);
// Handle WebSocket events
this.socket.onopen = this.handleOpen.bind(this);
this.socket.onmessage = this.handleMessage.bind(this);
this.socket.onclose = this.handleClose.bind(this);
this.socket.onerror = this.handleError.bind(this);
// Create a promise that resolves when the connection opens or rejects on error
return new Promise<void>((resolve, reject) => {
if (!this.socket) {
reject(new Error('Socket initialization failed'));
return;
}
// Resolve when the socket successfully opens
this.socket.addEventListener('open', () => resolve(), { once: true });
// Reject if there's an error before the socket opens
this.socket.addEventListener('error', (event) => {
// Only reject if the socket hasn't opened yet
if (this.socket && this.socket.readyState !== WebSocket.OPEN) {
reject(new Error('WebSocket connection failed'));
}
}, { once: true });
});
} catch (error) {
logger.error('Error establishing WebSocket connection:', createErrorMetadata(error));
throw error;
}
}
private handleOpen(event: Event): void {
this.isConnected = true;
this.reconnectAttempts = 0;
if (debugState.isEnabled()) {
logger.info('WebSocket connection established');
}
this.notifyConnectionStatusHandlers(true);
}
private handleMessage(event: MessageEvent): void {
// Check for binary data first
if (event.data instanceof Blob) {
if (debugState.isDataDebugEnabled()) {
logger.debug('Received binary blob data');
}
// Convert Blob to ArrayBuffer
event.data.arrayBuffer().then(buffer => {
// Process the ArrayBuffer, with possible decompression
this.processBinaryData(buffer);
}).catch(error => {
logger.error('Error converting Blob to ArrayBuffer:', createErrorMetadata(error));
});
return;
}
if (event.data instanceof ArrayBuffer) {
if (debugState.isDataDebugEnabled()) {
logger.debug(`Received binary ArrayBuffer data: ${event.data.byteLength} bytes`);
}
// Process the ArrayBuffer directly, with possible decompression
this.processBinaryData(event.data);
return;
}
// If not binary, try to parse as JSON
try {
const message = JSON.parse(event.data) as WebSocketMessage;
if (debugState.isDataDebugEnabled()) {
logger.debug(`Received WebSocket message: ${message.type}`, message.data);
}
// Special handling for connection_established message
if (message.type === 'connection_established') {
this.isServerReady = true;
if (debugState.isEnabled()) {
logger.info('Server connection established and ready');
}
}
// Notify all message handlers
this.messageHandlers.forEach(handler => {
try {
handler(message);
} catch (error) {
logger.error('Error in message handler:', createErrorMetadata(error));
}
});
} catch (error) {
logger.error('Error parsing WebSocket message:', createErrorMetadata(error));
}
}
// Make the function async to handle graphDataManager processing
private async processBinaryData(data: ArrayBuffer): Promise<void> {
try {
if (debugState.isDataDebugEnabled()) {
logger.debug(`Processing binary data: ${data.byteLength} bytes`);
}
// Pass binary data to graphDataManager for processing in the worker
try {
await graphDataManager.updateNodePositions(data);
} catch (error) {
logger.error('Error processing binary data in graphDataManager:', createErrorMetadata(error));
}
// Notify binary message handlers
this.binaryMessageHandlers.forEach(handler => {
try {
handler(data);
} catch (error) {
logger.error('Error in binary message handler:', createErrorMetadata(error));
}
});
} catch (error) {
logger.error('Error processing binary data:', createErrorMetadata(error));
}
}
private handleClose(event: CloseEvent): void {
this.isConnected = false;
this.isServerReady = false;
if (debugState.isEnabled()) {
logger.info(`WebSocket connection closed: ${event.code} ${event.reason}`);
}
this.notifyConnectionStatusHandlers(false);
// Attempt to reconnect if it wasn't a normal closure
if (event.code !== 1000 && event.code !== 1001) {
this.attemptReconnect();
}
}
private handleError(event: Event): void {
logger.error('WebSocket error:', { event });
// The close handler will be called after this, which will handle reconnection
}
private attemptReconnect(): void {
// Clear any existing reconnect timeout
if (this.reconnectTimeout) {
window.clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = null;
}
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = this.reconnectInterval * Math.pow(1.5, this.reconnectAttempts - 1);
if (debugState.isEnabled()) {
logger.info(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
}
this.reconnectTimeout = window.setTimeout(() => {
this.connect().catch(error => {
logger.error('Reconnect attempt failed:', createErrorMetadata(error));
});
}, delay);
} else { // Added missing else block
logger.error(`Maximum reconnect attempts (${this.maxReconnectAttempts}) reached. Giving up.`);
}
}
public sendMessage(type: string, data?: any): void {
if (!this.isConnected || !this.socket) {
logger.warn('Cannot send message: WebSocket not connected');
return;
}
try {
const message: WebSocketMessage = { type, data };
this.socket.send(JSON.stringify(message));
if (debugState.isDataDebugEnabled()) {
logger.debug(`Sent message: ${type}`);
}
} catch (error) {
logger.error('Error sending WebSocket message:', createErrorMetadata(error));
}
}
public sendRawBinaryData(data: ArrayBuffer): void {
if (!this.isConnected || !this.socket) {
logger.warn('Cannot send binary data: WebSocket not connected');
return;
}
try {
this.socket.send(data);
if (debugState.isDataDebugEnabled()) {
logger.debug(`Sent binary data: ${data.byteLength} bytes`);
}
} catch (error) {
logger.error('Error sending binary data:', createErrorMetadata(error));
}
}
public onMessage(handler: MessageHandler): () => void {
this.messageHandlers.push(handler);
return () => {
this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
};
}
public onBinaryMessage(handler: BinaryMessageHandler): () => void {
this.binaryMessageHandlers.push(handler);
return () => {
this.binaryMessageHandlers = this.binaryMessageHandlers.filter(h => h !== handler);
};
}
public onConnectionStatusChange(handler: ConnectionStatusHandler): () => void {
this.connectionStatusHandlers.push(handler);
// Immediately notify of current status
handler(this.isConnected);
return () => {
this.connectionStatusHandlers = this.connectionStatusHandlers.filter(h => h !== handler);
};
}
private notifyConnectionStatusHandlers(connected: boolean): void {
this.connectionStatusHandlers.forEach(handler => {
try {
handler(connected);
} catch (error) {
logger.error('Error in connection status handler:', createErrorMetadata(error));
}
});
}
public isReady(): boolean {
return this.isConnected && this.isServerReady;
}
public close(): void {
if (this.socket) {
// Clear reconnection timeout
if (this.reconnectTimeout) {
window.clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = null;
}
try {
// Close the socket with a normal closure
this.socket.close(1000, 'Normal closure');
if (debugState.isEnabled()) {
logger.info('WebSocket connection closed by client');
}
} catch (error) {
logger.error('Error closing WebSocket:', createErrorMetadata(error));
} finally {
this.socket = null;
this.isConnected = false;
this.isServerReady = false;
this.notifyConnectionStatusHandlers(false);
}
}
}
}
export default WebSocketService;